Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf6b2bee

Browse files
Shared conversation redirect (#1968)
* redirect to the convo* backend redirect to the convo* fix: fetch url logs* server side redirect* require a query only for the get* fix error type* fix: fetch url logs---------Co-authored-by: rtrm <remy.trompier@gmail.com>
1 parent4d98b15 commitf6b2bee

File tree

8 files changed

+138
-86
lines changed

8 files changed

+138
-86
lines changed

‎src/lib/components/BackgroundGenerationPoller.svelte‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
log("poll",id);
6565
6666
try {
67-
const response=awaitclient.conversations({id }).get();
67+
const response=awaitclient.conversations({id }).get({ query: {} });
6868
const conversation=handleResponse(response);
6969
const messages=conversation?.messages?? [];
7070
const lastAssistant= [...messages]

‎src/lib/server/api/routes/groups/conversations.ts‎

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -72,18 +72,17 @@ export const conversationGroup = new Elysia().use(authPlugin).group("/conversati
7272
},
7373
(app)=>{
7474
returnapp
75-
.derive(async({ locals, params})=>{
75+
.derive(async({ locals, params, query})=>{
7676
letconversation;
7777
letshared=false;
7878

79-
// if theconver
79+
// if theconversation is shared
8080
if(params.id.length===7){
8181
// shared link of length 7
8282
conversation=awaitcollections.sharedConversations.findOne({
8383
_id:params.id,
8484
});
8585
shared=true;
86-
8786
if(!conversation){
8887
thrownewError("Conversation not found");
8988
}
@@ -113,6 +112,9 @@ export const conversationGroup = new Elysia().use(authPlugin).group("/conversati
113112

114113
thrownewError("Conversation not found.");
115114
}
115+
if(query.fromShare&&conversation.meta?.fromShareId===query.fromShare){
116+
shared=true;
117+
}
116118
}
117119

118120
constconvertedConv={
@@ -123,19 +125,29 @@ export const conversationGroup = new Elysia().use(authPlugin).group("/conversati
123125

124126
return{conversation:convertedConv};
125127
})
126-
.get("",async({ conversation})=>{
127-
return{
128-
messages:conversation.messages,
129-
title:conversation.title,
130-
model:conversation.model,
131-
preprompt:conversation.preprompt,
132-
rootMessageId:conversation.rootMessageId,
133-
id:conversation._id.toString(),
134-
updatedAt:conversation.updatedAt,
135-
modelId:conversation.model,
136-
shared:conversation.shared,
137-
};
138-
})
128+
.get(
129+
"",
130+
async({ conversation})=>{
131+
return{
132+
messages:conversation.messages,
133+
title:conversation.title,
134+
model:conversation.model,
135+
preprompt:conversation.preprompt,
136+
rootMessageId:conversation.rootMessageId,
137+
id:conversation._id.toString(),
138+
updatedAt:conversation.updatedAt,
139+
modelId:conversation.model,
140+
shared:conversation.shared,
141+
};
142+
},
143+
{
144+
query:t.Optional(
145+
t.Object({
146+
fromShare:t.Optional(t.String()),
147+
})
148+
),
149+
}
150+
)
139151
.post("",()=>{
140152
// todo: post new message
141153
thrownewError("Not implemented");

‎src/lib/server/conversation.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import{collections}from"$lib/server/database";
2+
import{MetricsServer}from"$lib/server/metrics";
3+
import{error}from"@sveltejs/kit";
4+
import{ObjectId}from"mongodb";
5+
import{authCondition}from"$lib/server/auth";
6+
7+
/**
8+
* Create a new conversation from a shared conversation ID.
9+
* If the conversation already exists for the user/session, return the existing conversation ID.
10+
* returns the conversation ID.
11+
*/
12+
exportasyncfunctioncreateConversationFromShare(
13+
fromShareId:string,
14+
locals:App.Locals,
15+
userAgent?:string
16+
):Promise<string>{
17+
constconversation=awaitcollections.sharedConversations.findOne({
18+
_id:fromShareId,
19+
});
20+
21+
if(!conversation){
22+
error(404,"Conversation not found");
23+
}
24+
25+
// Check if shared conversation exists already for this user/session
26+
constexistingConversation=awaitcollections.conversations.findOne({
27+
"meta.fromShareId":fromShareId,
28+
...authCondition(locals),
29+
});
30+
31+
if(existingConversation){
32+
returnexistingConversation._id.toString();
33+
}
34+
35+
// Create new conversation from shared conversation
36+
constres=awaitcollections.conversations.insertOne({
37+
_id:newObjectId(),
38+
title:conversation.title.replace(/<\/?think>/gi,"").trim(),
39+
rootMessageId:conversation.rootMessageId,
40+
messages:conversation.messages,
41+
model:conversation.model,
42+
preprompt:conversation.preprompt,
43+
createdAt:newDate(),
44+
updatedAt:newDate(),
45+
userAgent,
46+
...(locals.user ?{userId:locals.user._id} :{sessionId:locals.sessionId}),
47+
meta:{ fromShareId},
48+
});
49+
50+
if(MetricsServer.isEnabled()){
51+
MetricsServer.getMetrics().model.conversationsTotal.inc({model:conversation.model});
52+
}
53+
returnres.insertedId.toString();
54+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import{redirect}from"@sveltejs/kit";
2+
importtype{PageServerLoad}from"./$types";
3+
import{loginEnabled}from"$lib/server/auth";
4+
import{createConversationFromShare}from"$lib/server/conversation";
5+
6+
exportconstload:PageServerLoad=async({ url, params, locals, request})=>{
7+
/// if logged in and valid share ID, create conversation from share, usually occurs after login
8+
if(loginEnabled&&locals.user&&params.id.length===7){
9+
constleafId=url.searchParams.get("leafId");
10+
constconversationId=awaitcreateConversationFromShare(
11+
params.id,
12+
locals,
13+
request.headers.get("User-Agent")??undefined
14+
);
15+
16+
returnredirect(
17+
302,
18+
`../conversation/${conversationId}?leafId=${leafId}&fromShare=${params.id}`
19+
);
20+
}
21+
};

‎src/routes/conversation/[id]/+page.svelte‎

Lines changed: 7 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import {isAborted }from"$lib/stores/isAborted";
55
import {onMount }from"svelte";
66
import {page }from"$app/state";
7-
import {beforeNavigate,goto,invalidateAll }from"$app/navigation";
7+
import {beforeNavigate,invalidateAll }from"$app/navigation";
88
import {base }from"$app/paths";
99
import {ERROR_MESSAGES,error }from"$lib/stores/errors";
1010
import {findCurrentModel }from"$lib/utils/models";
@@ -95,35 +95,6 @@
9595
returnalternatives;
9696
}
9797
98-
asyncfunction convFromShared() {
99-
try {
100-
$loading=true;
101-
const res=awaitfetch(`${base}/conversation`, {
102-
method:"POST",
103-
headers: {
104-
"Content-Type":"application/json",
105-
},
106-
body:JSON.stringify({
107-
fromShare:page.params.id,
108-
model:data.model,
109-
}),
110-
});
111-
112-
if (!res.ok) {
113-
error.set(awaitres.text());
114-
console.error("Error while creating conversation:"+ (awaitres.text()));
115-
return;
116-
}
117-
118-
const { conversationId }=awaitres.json();
119-
120-
returnconversationId;
121-
}catch (err) {
122-
error.set(ERROR_MESSAGES.default);
123-
console.error(String(err));
124-
throwerr;
125-
}
126-
}
12798
// this function is used to send new message to the backends
12899
asyncfunction writeMessage({
129100
prompt,
@@ -381,16 +352,7 @@
381352
});
382353
383354
asyncfunction onMessage(content:string) {
384-
if (!data.shared) {
385-
awaitwriteMessage({ prompt:content });
386-
}else {
387-
awaitconvFromShared()
388-
.then(async (convId)=> {
389-
awaitgoto(`${base}/conversation/${convId}`, { invalidateAll:true });
390-
})
391-
.then(async ()=>awaitwriteMessage({ prompt:content }))
392-
.finally(()=> ($loading=false));
393-
}
355+
awaitwriteMessage({ prompt:content });
394356
}
395357
396358
asyncfunction onRetry(payload: { id:Message["id"]; content?:string }) {
@@ -399,27 +361,11 @@
399361
const lastMsgId=payload.id;
400362
messagesPath=createMessagesPath(messages,lastMsgId);
401363
402-
if (!data.shared) {
403-
awaitwriteMessage({
404-
prompt:payload.content,
405-
messageId:payload.id,
406-
isRetry:true,
407-
});
408-
}else {
409-
awaitconvFromShared()
410-
.then(async (convId)=> {
411-
awaitgoto(`${base}/conversation/${convId}`, { invalidateAll:true });
412-
})
413-
.then(
414-
async ()=>
415-
awaitwriteMessage({
416-
prompt:payload.content,
417-
messageId:payload.id,
418-
isRetry:true,
419-
})
420-
)
421-
.finally(()=> ($loading=false));
422-
}
364+
awaitwriteMessage({
365+
prompt:payload.content,
366+
messageId:payload.id,
367+
isRetry:true,
368+
});
423369
}
424370
425371
asyncfunction onShowAlternateMsg(payload: { id:Message["id"] }) {

‎src/routes/conversation/[id]/+page.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ export const load = async ({ params, depends, fetch, url }) => {
88
constclient=useAPIClient({ fetch,origin:url.origin});
99

1010
try{
11-
returnawaitclient.conversations({id:params.id}).get().then(handleResponse);
11+
returnawaitclient
12+
.conversations({id:params.id})
13+
.get({query:{fromShare:url.searchParams.get("fromShare")??undefined}})
14+
.then(handleResponse);
1215
}catch{
1316
redirect(302,"/");
1417
}

‎src/routes/r/[id]/+page.server.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import{redirect}from"@sveltejs/kit";
2+
importtype{PageServerLoad}from"./$types";
3+
import{loginEnabled}from"$lib/server/auth";
4+
import{createConversationFromShare}from"$lib/server/conversation";
5+
6+
exportconstload:PageServerLoad=async({ url, params, locals, request})=>{
7+
constleafId=url.searchParams.get("leafId");
8+
9+
/// if logged in and valid share ID, create conversation from share
10+
if(loginEnabled&&locals.user&&params.id){
11+
constconversationId=awaitcreateConversationFromShare(
12+
params.id,
13+
locals,
14+
request.headers.get("User-Agent")??undefined
15+
);
16+
17+
returnredirect(
18+
302,
19+
`../conversation/${conversationId}?leafId=${leafId}&fromShare=${params.id}`
20+
);
21+
}
22+
returnredirect(302,`../conversation/${params.id}?leafId=${leafId}`);
23+
};

‎src/routes/r/[id]/+page.ts‎

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp