Skip to content

Commit

Permalink
feat: add chat session limit
Browse files Browse the repository at this point in the history
  • Loading branch information
darkskygit committed Apr 10, 2024
1 parent ebbdcea commit b04f5e1
Showing 1 changed file with 54 additions and 30 deletions.
84 changes: 54 additions & 30 deletions packages/backend/server/src/plugins/copilot/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,36 +111,56 @@ export class ChatSessionService {
private readonly prompt: PromptService
) {}

private async setSession(state: ChatSessionState): Promise<void> {
await this.db.aiSession.upsert({
where: {
id: state.sessionId,
userId: state.userId,
},
update: {
messages: {
// delete old messages
deleteMany: {},
create: state.messages.map(m => ({
...m,
params: m.params || undefined,
})),
private async setSession(state: ChatSessionState): Promise<string> {
return await this.db.$transaction(async tx => {
let sessionId = state.sessionId;

// find existing session if session is chat session
if (!state.prompt.action) {
const { id } =
(await tx.aiSession.findFirst({
where: {
userId: state.userId,
workspaceId: state.workspaceId,
docId: state.docId,
prompt: { action: { equals: null } },
},
select: { id: true },
})) || {};
if (id) sessionId = id;
}

await tx.aiSession.upsert({
where: {
id: sessionId,
userId: state.userId,
},
update: {
messages: {
// delete old messages
deleteMany: {},
create: state.messages.map(m => ({
...m,
params: m.params || undefined,
})),
},
},
},
create: {
id: state.sessionId,
workspaceId: state.workspaceId,
docId: state.docId,
messages: {
create: state.messages.map(m => ({
...m,
params: m.params || undefined,
})),
create: {
id: sessionId,
workspaceId: state.workspaceId,
docId: state.docId,
messages: {
create: state.messages.map(m => ({
...m,
params: m.params || undefined,
})),
},
// connect
user: { connect: { id: state.userId } },
prompt: { connect: { name: state.prompt.name } },
},
// connect
user: { connect: { id: state.userId } },
prompt: { connect: { name: state.prompt.name } },
},
});
return sessionId;
});
}

Expand Down Expand Up @@ -293,8 +313,12 @@ export class ChatSessionService {
this.logger.error(`Prompt not found: ${options.promptName}`);
throw new Error('Prompt not found');
}
await this.setSession({ ...options, sessionId, prompt, messages: [] });
return sessionId;
return await this.setSession({
...options,
sessionId,
prompt,
messages: [],
});
}

/**
Expand Down

0 comments on commit b04f5e1

Please sign in to comment.