diff --git a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts --- a/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts +++ b/packages/frontend/core/src/blocksuite/ai/components/ai-chat-input/ai-chat-input.ts @@ -860,7 +860,7 @@ control: this.trackOptions?.control, reasoning: this._isReasoningActive, toolsConfig: this.aiToolsConfigService.config.value, - routeTargetId: this.aiModelService.modelId.value, + ...this.aiModelService.getSelection(), userInfo: { userId: userInfo?.id, userName: userInfo?.name, diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts --- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts +++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/runtime.ts @@ -30,6 +30,10 @@ private createSessionPromise: Promise< CopilotChatHistoryFragment | null | undefined > | null = null; + private readonly sessionSelections = new Map< + string, + Pick + >(); private snapshot: AIChatSnapshot; constructor(private readonly options: RuntimeOptions) { @@ -69,6 +73,7 @@ this.createSessionPromise = null; this.createSessionPromiseKey = null; this.streamAbortController?.abort(); + this.sessionSelections.clear(); this.listeners.clear(); } @@ -389,6 +394,10 @@ this.updateScopeSelection({ syncing: false }); } + const selection = options.profileId && options.modelId + ? { profileId: options.profileId, modelId: options.modelId } + : { routeTargetId: options.routeTargetId ?? this.snapshot.composer.routeTargetId }; + this.sessionSelections.set(session.sessionId, selection); const stream = (await this.options.request.executeAction('chat', { workspaceId: this.snapshot.scope.workspaceId, docId: @@ -407,8 +416,7 @@ ], reasoning: options.reasoning ?? this.snapshot.composer.reasoning, toolsConfig: options.toolsConfig ?? this.snapshot.composer.toolsConfig, - routeTargetId: - options.routeTargetId ?? this.snapshot.composer.routeTargetId, + ...selection, isRootSession: options.isRootSession, where: options.where, control: options.control, @@ -474,6 +482,7 @@ workspaceId: this.snapshot.scope.workspaceId, sessionId: this.snapshot.activeSessionId, liveEditorContext, + ...this.sessionSelections.get(this.snapshot.activeSessionId), retry: true, stream: true, signal: this.streamAbortController.signal, diff --git a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts --- a/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts +++ b/packages/frontend/core/src/blocksuite/ai/runtime/chat/actions.ts @@ -16,6 +16,8 @@ reasoning?: boolean; toolsConfig?: unknown; routeTargetId?: string; + profileId?: string; + modelId?: string; userInfo?: { userId?: string; userName?: string; diff --git a/packages/frontend/core/src/modules/ai-button/services/models.ts b/packages/frontend/core/src/modules/ai-button/services/models.ts --- a/packages/frontend/core/src/modules/ai-button/services/models.ts +++ b/packages/frontend/core/src/modules/ai-button/services/models.ts @@ -1,4 +1,7 @@ -import { getCopilotRouteOptionsQuery } from '@affine/graphql'; +import { + getCopilotRouteOptionsQuery, + workspaceByokSettingsQuery, +} from '@affine/graphql'; import { signal } from '@preact/signals-core'; import { Service } from '@toeverything/infra'; @@ -13,7 +16,24 @@ category: string; version: string; available: boolean; + profileId?: string; + modelId?: string; } + +export type AIModelSelection = + | { routeTargetId?: undefined; profileId?: undefined; modelId?: undefined } + | { routeTargetId: string; profileId?: undefined; modelId?: undefined } + | { routeTargetId?: undefined; profileId: string; modelId: string }; + +const isPermissionDenied = (error: unknown) => + typeof error === 'object' && + error !== null && + 'isStatus' in error && + typeof error.isStatus === 'function' && + error.isStatus(403); + +const supportsText = (capability: { input: string[]; output: string[] }) => + capability.input.includes('text') && capability.output.includes('text'); export class AIModelService extends Service { readonly modelId = signal(undefined); @@ -31,7 +51,9 @@ export class AIModelService extends Service { super(); const subscription = subscriptionService.subscription.ai$.subscribe(() => { if (this.workspaceId && this.routeId) { - this.load(this.workspaceId, this.routeId).catch(console.error); + this.load(this.workspaceId, this.routeId).catch(() => + console.error('Failed to load AI models') + ); } }); this.disposables.push(() => subscription.unsubscribe()); @@ -43,13 +65,26 @@ export class AIModelService extends Service { this.routeId = routeId; this.models.value = []; this.modelId.value = undefined; - this.load(workspaceId, routeId).catch(console.error); + this.load(workspaceId, routeId).catch(() => + console.error('Failed to load AI models') + ); } resetModel() { this.setModel(undefined); } + getSelection(): AIModelSelection { + const model = this.models.value.find( + candidate => candidate.id === this.modelId.value && candidate.available + ); + if (!model) return {}; + if (model.profileId && model.modelId) { + return { profileId: model.profileId, modelId: model.modelId }; + } + return { routeTargetId: model.id }; + } + setModel(modelId: string | undefined) { if (!this.workspaceId || !this.routeId) return; if ( @@ -67,18 +102,42 @@ private async load(workspaceId: string, routeId: string) { const requestId = ++this.requestId; - const result = await this.gqlService.gql({ - query: getCopilotRouteOptionsQuery, - variables: { promptName: routeId }, - }); + const to = new Date(); + const from = new Date(to.getTime()); + from.setDate(from.getDate() - 30); + const [managedResponse, byokResponse] = await Promise.allSettled([ + this.gqlService.gql({ + query: getCopilotRouteOptionsQuery, + variables: { promptName: routeId }, + }), + this.gqlService + .gql({ + query: workspaceByokSettingsQuery, + variables: { + id: workspaceId, + from: from.toISOString(), + to: to.toISOString(), + }, + }) + .catch(error => { + if (isPermissionDenied(error)) return undefined; + throw error; + }), + ]); if (requestId !== this.requestId) return; - const options = result.currentUser?.copilot?.routeOptions; - if (!options) { - this.models.value = []; - this.modelId.value = undefined; - return; - } - this.models.value = options.choices.map(choice => { + if (byokResponse.status === 'rejected') { + console.error('Failed to load workspace BYOK models'); + throw byokResponse.reason; + } + if (managedResponse.status === 'rejected') { + console.error('Failed to load managed AI models'); + } + const managedResult = + managedResponse.status === 'fulfilled' ? managedResponse.value : undefined; + const byokResult = + byokResponse.status === 'fulfilled' ? byokResponse.value : undefined; + const options = managedResult?.currentUser?.copilot?.routeOptions; + const managedModels = options?.choices.map(choice => { const [category] = choice.displayName.split(' '); return { id: choice.id, @@ -87,7 +146,31 @@ version: choice.displayName.slice(category.length + 1), available: choice.available, }; - }); + }) ?? []; + const settings = byokResult?.workspace?.byokSettings; + const byokModels = + settings?.serverEntitled && settings.policy.enabled + ? settings.profiles.flatMap(profile => { + if ( + !profile.enabled || + !settings.policy.allowedProviders.includes(profile.provider) + ) { + return []; + } + return profile.definition.models + .filter(model => model.enabled && model.capabilities.some(supportsText)) + .map(model => ({ + id: `byok:${profile.profileId}:${encodeURIComponent(model.modelId)}`, + name: model.modelId, + category: model.modelId, + version: profile.name, + available: true, + profileId: profile.profileId, + modelId: model.modelId, + })); + }) + : []; + this.models.value = [...managedModels, ...byokModels]; const selected = this.globalStateService.globalState.get( this.storageKey(workspaceId, routeId) );