fix: ai chat session handling (#6751)

fix AFF-999
upstream: https://github.com/toeverything/blocksuite/pull/6932
This commit is contained in:
pengx17 2024-04-30 15:08:26 +00:00
parent 0c175ada31
commit 91ee5e05bb
No known key found for this signature in database
GPG Key ID: 23F23D9E8B3971ED
2 changed files with 30 additions and 13 deletions

View File

@ -3,6 +3,7 @@ import { authAtom, openSettingModalAtom } from '@affine/core/atoms';
import { mixpanel } from '@affine/core/utils';
import { getBaseUrl } from '@affine/graphql';
import { Trans } from '@affine/i18n';
import { UnauthorizedError } from '@blocksuite/blocks';
import { assertExists } from '@blocksuite/global/utils';
import { AIProvider } from '@blocksuite/presets';
import { getCurrentStore } from '@toeverything/infra';
@ -71,11 +72,17 @@ const provideAction = <T extends AIAction>(
export function setupAIProvider() {
// a single workspace should have only a single chat session
// workspace-id:doc-id -> chat session id
// user-id:workspace-id:doc-id -> chat session id
const chatSessions = new Map<string, Promise<string>>();
async function getChatSessionId(workspaceId: string, docId: string) {
const storeKey = `${workspaceId}:${docId}`;
const userId = (await AIProvider.userInfo)?.id;
if (!userId) {
throw new UnauthorizedError();
}
const storeKey = `${userId}:${workspaceId}:${docId}`;
if (!chatSessions.has(storeKey)) {
chatSessions.set(
storeKey,
@ -85,9 +92,15 @@ export function setupAIProvider() {
})
);
}
const sessionId = await chatSessions.get(storeKey);
assertExists(sessionId);
return sessionId;
try {
const sessionId = await chatSessions.get(storeKey);
assertExists(sessionId);
return sessionId;
} catch (err) {
// do not cache the error
chatSessions.delete(storeKey);
throw err;
}
}
//#region actions

View File

@ -24,6 +24,16 @@ export const AccountLoggedIn = createEvent<AuthAccountInfo>('AccountLoggedIn');
export const AccountLoggedOut =
createEvent<AuthAccountInfo>('AccountLoggedOut');
function toAIUserInfo(account: AuthAccountInfo | null) {
if (!account) return null;
return {
avatarUrl: account.avatar ?? '',
email: account.email ?? '',
id: account.id,
name: account.label,
};
}
@OnEvent(ApplicationStarted, e => e.onApplicationStart)
@OnEvent(ApplicationFocused, e => e.onApplicationFocused)
export class AuthService extends Service {
@ -36,14 +46,7 @@ export class AuthService extends Service {
super();
AIProvider.provide('userInfo', () => {
const account = this.session.account$.value;
if (!account) return null;
return {
avatarUrl: account.avatar ?? '',
email: account.email ?? '',
id: account.id,
name: account.label,
};
return toAIUserInfo(this.session.account$.value);
});
this.session.account$
@ -62,6 +65,7 @@ export class AuthService extends Service {
this.eventBus.emit(AccountLoggedIn, account);
}
this.eventBus.emit(AccountChanged, account);
AIProvider.slots.userInfo.emit(toAIUserInfo(account));
});
}