From a131efa5e037040cc690f25a02e2f33dd0f6f1ce Mon Sep 17 00:00:00 2001 From: lyingbug Date: Thu, 15 Oct 2026 14:54:40 +0800 Subject: [PATCH] feat(frontend): open the WeKnora assistant from anywhere with page context (#4314) * feat(frontend): open the WeKnora assistant from anywhere with page context - Global drawer hosting the built-in assistant, opened from the sidebar, the command palette or the document drawer. The conversation survives navigation and reloads within the tab. - Pages publish what is open (knowledge base, document, Wiki page and its pending issues). It travels as page_context with the page's knowledge base in scope, shown as a chip the user can detach. - Wiki fix buttons now hand the issue to the assistant; the wiki fixer drawer is gone. - Embedded ChatView no longer writes the main chat's agent, knowledge bases or model, ignores route changes, and keeps its stream when the page behind it navigates. - Knowledge base activity marks entries performed via the assistant. * feat(frontend): let users pick the WeKnora assistant's model The assistant's composer shows the same model picker as the main chat, plus an Auto entry (the default) that keeps today's behaviour: the knowledge base's chat model, then the system default. The choice is the user's own, kept per user and workspace in localStorage and sent as the request's model override; the main chat's pick is neither read nor changed. A pick that is no longer available falls back to Auto. * fix(frontend): isolate assistant sessions and steer resources --- frontend/src/api/agent/index.ts | 1 + frontend/src/api/chat/streame.ts | 13 +- .../GlobalCommandPalette/commands.ts | 11 + .../Input-field.agent-switch.test.mjs | 5 +- .../src/components/Input-field.focus.test.mjs | 51 ++- frontend/src/components/Input-field.vue | 102 ++++-- .../assistant/AssistantContextChip.vue | 123 +++++++ .../assistant/AssistantDrawer.test.ts | 171 ++++++++++ .../components/assistant/AssistantDrawer.vue | 316 ++++++++++++++++++ frontend/src/components/doc-content.vue | 8 + frontend/src/components/menu.vue | 23 ++ .../composables/useAssistantPageContext.ts | 17 + frontend/src/i18n/locales/en-US.ts | 38 ++- frontend/src/i18n/locales/ja-JP.ts | 38 ++- frontend/src/i18n/locales/ko-KR.ts | 38 ++- frontend/src/i18n/locales/ru-RU.ts | 38 ++- frontend/src/i18n/locales/zh-CN.ts | 38 ++- frontend/src/i18n/locales/zh-TW.ts | 38 ++- frontend/src/stores/assistant.ts | 161 +++++++++ frontend/src/views/chat/index.vue | 44 ++- .../src/views/knowledge/KnowledgeBase.vue | 11 + .../KnowledgeBaseActivitySettings.vue | 30 +- .../src/views/knowledge/wiki/WikiBrowser.vue | 123 ++----- .../wiki/wikiBacklinkBrowser.test.ts | 3 +- frontend/src/views/platform/index.vue | 3 + 25 files changed, 1274 insertions(+), 170 deletions(-) create mode 100644 frontend/src/components/assistant/AssistantContextChip.vue create mode 100644 frontend/src/components/assistant/AssistantDrawer.test.ts create mode 100644 frontend/src/components/assistant/AssistantDrawer.vue create mode 100644 frontend/src/composables/useAssistantPageContext.ts create mode 100644 frontend/src/stores/assistant.ts diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 5303bfd9..954dfb57 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -178,6 +178,7 @@ export interface UpdateAgentRequest { // 内置智能体 ID(常用的保留常量,便于代码引用) export const BUILTIN_QUICK_ANSWER_ID = 'builtin-quick-answer'; export const BUILTIN_SMART_REASONING_ID = 'builtin-smart-reasoning'; +export const BUILTIN_WEKNORA_ASSISTANT_ID = 'builtin-weknora-assistant'; // AgentMode 常量 export const AGENT_MODE_QUICK_ANSWER = 'quick-answer'; diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts index 998e8af4..ff0e6407 100644 --- a/frontend/src/api/chat/streame.ts +++ b/frontend/src/api/chat/streame.ts @@ -14,6 +14,14 @@ import { runStreamWithAuthRetry, } from '@/utils/authRefresh'; +/** The WeKnora page the user has open; agent-chat only. */ +export interface PageContextPayload { + knowledge_base_id: string + knowledge_id?: string + wiki_slug?: string + wiki_issue_ids?: string[] +} + interface StreamOptions { // 请求方法 (默认POST) method?: 'GET' | 'POST' @@ -40,7 +48,7 @@ export function useStream() { let renderTimer: number | null = null // 启动流式请求 - const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; reasoning_effort?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; question_origin?: { knowledge_base_id: string; knowledge_id?: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => { + const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; reasoning_effort?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; question_origin?: { knowledge_base_id: string; knowledge_id?: string }; page_context?: PageContextPayload; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => { const myGeneration = ++streamGeneration const streamAbort = controller // 重置状态 @@ -154,6 +162,9 @@ export function useStream() { if (params.question_origin) { postBody.question_origin = params.question_origin; } + if (params.page_context) { + postBody.page_context = params.page_context; + } postBody.channel = embedToken ? "embed" : "web"; lastStreamRequest.value = { diff --git a/frontend/src/components/GlobalCommandPalette/commands.ts b/frontend/src/components/GlobalCommandPalette/commands.ts index 4db0f49b..94da0a5d 100644 --- a/frontend/src/components/GlobalCommandPalette/commands.ts +++ b/frontend/src/components/GlobalCommandPalette/commands.ts @@ -1,6 +1,7 @@ import type { Router } from 'vue-router' import type { Composer } from 'vue-i18n' import { openNewUserGuide } from '@/config/contextualGuides' +import { useAssistantStore } from '@/stores/assistant' /** * A single command that can be searched and invoked from the palette. @@ -33,6 +34,16 @@ export interface CommandContext { export function buildCommands(ctx: CommandContext): CmdkCommand[] { const { router, t, close } = ctx return [ + { + id: 'open-assistant', + label: t('commandPalette.quick.assistant'), + icon: 'compass', + keywords: ['assistant', 'help', 'weknora', '助手', '帮助', 'ассистент'], + run: () => { + close() + useAssistantStore().open() + }, + }, { id: 'new-chat', label: t('commandPalette.quick.newChat'), diff --git a/frontend/src/components/Input-field.agent-switch.test.mjs b/frontend/src/components/Input-field.agent-switch.test.mjs index 571f0bbd..deaefad0 100644 --- a/frontend/src/components/Input-field.agent-switch.test.mjs +++ b/frontend/src/components/Input-field.agent-switch.test.mjs @@ -91,9 +91,12 @@ test('mid-run send is limited to agent sessions', () => { assert.match(chatView, /:canSteer="isAgentStreamSession\(\)"/) const fnStart = inputField.indexOf('const createSession = async') - const fn = inputField.slice(fnStart, fnStart + 1600) + const fnEnd = inputField.indexOf('const updateAgentModeDropdownPosition =', fnStart) + const fn = inputField.slice(fnStart, fnEnd) assert.notEqual(fnStart, -1) + assert.ok(fnEnd > fnStart) assert.match(fn, /if \(!props\.canSteer\)/) + assert.ok(fn.includes("emit('steer-msg'")) // The guard must come before anything queues the message. assert.ok( fn.indexOf('props.canSteer') < fn.indexOf("emit('steer-msg'"), diff --git a/frontend/src/components/Input-field.focus.test.mjs b/frontend/src/components/Input-field.focus.test.mjs index 7ad4751d..e7f5d873 100644 --- a/frontend/src/components/Input-field.focus.test.mjs +++ b/frontend/src/components/Input-field.focus.test.mjs @@ -11,6 +11,7 @@ const sendCode = source.slice(source.indexOf('const createSession ='), source.in for (const mode of ['normal', 'embedded', 'after', 'inject']) { test(`${mode} send clears the draft and restores focus after the DOM update`, async () => { const effects = [], ticks = [] + let sentModel const textarea = { isConnected: true, focus: options => effects.push(['focus', options.preventScroll]), @@ -20,11 +21,15 @@ for (const mode of ['normal', 'embedded', 'after', 'inject']) { props: { isReplying: ['after', 'inject'].includes(mode), canSteer: true, embeddedMode: mode === 'embedded' }, uploadedAttachments: { value: [] }, uploadedImages: { value: [] }, allSelectedItems: { value: [] }, selectedModelId: { value: 'model' }, + composerModelId: { value: 'host-model' }, selectedAgent: { value: { config: {} } }, settingsStore: {}, chatResources: { isLoaded: () => true }, collectAgentNotReadyReasons: () => ({ keys: [], labels: [] }), attachmentUploadRef: { value: null }, - emit: name => effects.push([name]), + emit: (name, _query, model) => { + effects.push([name]) + if (name === 'send-msg') sentModel = model + }, clearvalue: () => effects.push(['clear']), getTextareaEl: () => textarea, nextTick: () => new Promise(resolve => ticks.push(resolve)), @@ -32,6 +37,9 @@ for (const mode of ['normal', 'embedded', 'after', 'inject']) { const send = vm.runInNewContext(ts.transpile(`${focusCode}\n${sendCode}\ncreateSession`), context) await send('hello', mode === 'inject' ? 'inject' : 'after') assert.deepEqual(effects, [[context.props.isReplying ? 'steer-msg' : 'send-msg'], ['clear']]) + // Embedded, the host's model goes out, never the main chat's pick. + if (mode === 'embedded') assert.equal(sentModel, 'host-model') + if (mode === 'normal') assert.equal(sentModel, 'model') for (const resolve of ticks) resolve() await new Promise(setImmediate) assert.deepEqual(effects.at(-1), ['focus', true]) @@ -51,6 +59,35 @@ test('a queued focus does not focus a textarea removed during navigation', async assert.equal(focused, false) }) +for (const embeddedMode of [false, true]) { + for (const delivery of ['after', 'inject']) { + test(`${embeddedMode ? 'embedded' : 'main'} ${delivery} steer respects the composer's resource scope`, async () => { + const selected = [ + { id: 'main-kb', name: 'Main KB', type: 'kb' }, + { id: 'main-file', name: 'Main file', type: 'file', kbId: 'main-kb' }, + { id: 'main-tag', name: 'Main tag', type: 'tag', kbId: 'main-kb' }, + { id: 'main-mcp', name: 'Main MCP', type: 'mcp' }, + { id: 'main-skill', name: 'Main skill', type: 'skill', skillName: 'main-skill' }, + ] + let emitted + const send = vm.runInNewContext(ts.transpile(`${sendCode}\ncreateSession`), { + props: { embeddedMode, isReplying: true, canSteer: true }, + uploadedAttachments: { value: [] }, uploadedImages: { value: [] }, + allSelectedItems: { value: selected }, + emit: (...args) => { emitted = args }, + clearvalue() {}, focusInput: async () => {}, + }) + await send(' continue ', delivery) + const [event, query, mentions, mode] = emitted + assert.equal(event, 'steer-msg') + assert.equal(query, 'continue') + assert.equal(mode, delivery) + assert.deepEqual(Array.from(mentions, item => item.id), embeddedMode ? [] : selected.map(item => item.id)) + assert.equal(selected.length, 5, 'sending must not clear the main composer selection') + }) + } +} + test('teardown blurs the active textarea before it is detached', () => { const code = source.slice(source.indexOf('onBeforeUnmount(() =>'), source.indexOf('onUnmounted(() =>')) let teardown, blurred = false @@ -67,10 +104,18 @@ test('new-session focus survives consumption of the first query and runs on chil const page = readFileSync(new URL('../views/chat/index.vue', import.meta.url), 'utf8') const snapshot = page.match(/const focusComposerOnMount = [^;]+;/)[0] const firstQuery = { value: 'initial question' } - const autoFocus = vm.runInNewContext(`${snapshot}\nfirstQuery.value = ''; focusComposerOnMount`, { firstQuery }) + const autoFocus = vm.runInNewContext(`${snapshot}\nfirstQuery.value = ''; focusComposerOnMount`, { + firstQuery, props: { embeddedMode: false, initialQuery: '' }, + }) assert.equal(autoFocus, true) + // An embedded host passes its own first message; the main chat's draft is not its. + const embedded = { embeddedMode: true, initialQuery: 'host question' } + assert.equal(vm.runInNewContext(`${snapshot}\nfocusComposerOnMount`, { firstQuery, props: embedded }), true) + assert.equal(vm.runInNewContext(`${snapshot}\nfocusComposerOnMount`, { + firstQuery: { value: 'main draft' }, props: { embeddedMode: true, initialQuery: '' }, + }), false) assert.match(page, /:auto-focus="focusComposerOnMount"/) - const mountStart = source.slice(source.indexOf('onMounted(() => {'), source.indexOf('// Embed 渠道')) + const mountStart = source.slice(source.indexOf('onMounted(() => {'), source.indexOf('// 嵌入时 agent/KB 由宿主注入,只需')) let mounted, focused = false vm.runInNewContext(`${mountStart}\n});`, { props: { autoFocus }, onMounted: fn => { mounted = fn }, focusInput: () => { focused = true }, diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 2e3b2f5b..7cbb741b 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -248,7 +248,7 @@ const sharedAgentKbList = ref { if (settingsStore._isApplyingSessionState) return; - if (newAgentId !== oldAgentId && oldAgentId !== undefined) { + if (newAgentId !== oldAgentId && oldAgentId !== undefined && !props.embeddedMode) { if (newKbMode === 'none') { settingsStore.selectKnowledgeBases([]); } else { @@ -312,6 +312,8 @@ const isKnowledgeBaseDisabledByAgent = computed(() => { return agentKBSelectionMode.value === 'none'; }); const isMentionDisabled = computed(() => { + // The host pins the scope; @-mentions would edit the main chat's selection. + if (props.embeddedMode) return true; if (settingsStore.isAgentStreamMode && isKnowledgeBaseDisabledByAgent.value) { return agentMCPSelectionMode.value === 'none' && agentSkillsSelectionMode.value === 'none'; } @@ -379,7 +381,7 @@ const isSkillAllowedByAgent = (skillName: string) => { // 切换智能体时清理不允许的 MCP / Skill @mention watch([selectedAgentId, agentMCPSelectionMode, agentSkillsSelectionMode], ([newAgentId], [oldAgentId]) => { - if (settingsStore._isApplyingSessionState) return; + if (props.embeddedMode || settingsStore._isApplyingSessionState) return; if (newAgentId === oldAgentId || oldAgentId === undefined) return; const mcpMode = agentMCPSelectionMode.value; @@ -540,6 +542,13 @@ const props = defineProps({ type: Boolean, default: false }, + // Embedded only: the host owns the model choice (v-model:model-id) so the + // main chat's pick is neither read nor overwritten. '' lets the agent + // resolve its own model. + modelId: { + type: String, + default: '' + }, queuedSteers: { type: Array as PropType, default: () => [] @@ -1005,7 +1014,7 @@ const loadChatModels = async (force = false) => { modelsLoading.value = true; try { await chatResources.ensureChatModels(force); - ensureModelSelection(); + if (!props.embeddedMode) ensureModelSelection(); } catch (error) { console.error('Failed to load chat models:', error); chatResources.invalidate('models'); @@ -1036,7 +1045,7 @@ const ensureModelSelection = () => { watch( [selectedAgentId, () => settingsStore.selectedAgentSourceTenantId, agentModelId], ([, sourceTenantId, newModelId]) => { - if (!newModelId || newModelId.trim() === '') return; + if (props.embeddedMode || !newModelId || newModelId.trim() === '') return; const lastPick = readLastChatModelID(); const isSharedAgent = !!sourceTenantId; @@ -1078,10 +1087,15 @@ const handleModelChange = (value: string | number | Array | und return; } if (val === '__add_model__') { - selectedModelId.value = readLastChatModelID(); + if (!props.embeddedMode) selectedModelId.value = readLastChatModelID(); handleGoToConversationModels(); return; } + if (props.embeddedMode) { + emit('update:modelId', val === EMBEDDED_AUTO_MODEL ? '' : val); + showModelSelector.value = false; + return; + } // The chat-level model picker now persists per-user-per-browser via // localStorage instead of writing to the tenant-shared KV. This is what @@ -1103,6 +1117,18 @@ const selectedModel = computed(() => { return availableModels.value.find(model => model.id === selectedModelId.value); }); +// What the composer shows and sends. Embedded, a pick that is no longer +// available falls back to auto instead of failing the run. +const EMBEDDED_AUTO_MODEL = '__auto__'; +const composerModel = computed(() => { + if (!props.embeddedMode) return selectedModel.value; + return props.modelId ? availableModels.value.find(model => model.id === props.modelId) : undefined; +}); +const composerModelId = computed(() => { + if (!props.embeddedMode) return selectedModelId.value; + return composerModel.value?.id || ''; +}); + const reasoningLevels = computed(() => supportedLevels(selectedModel.value?.capabilities)); const agentReasoningLevel = computed(() => clampLevel( levelFromLegacy(currentAgentConfig.value?.thinking, currentAgentConfig.value?.reasoning_effort), @@ -1127,7 +1153,8 @@ watch([selectedModel, reasoningLevels, () => settingsStore.reasoningEffortOverri // 模型展示名:本空间列表中有则用名称;若为共享智能体且其 model_id 不在本空间列表中则显示“共享智能体配置的模型” const selectedModelDisplayName = computed(() => { - if (selectedModel.value) return modelDisplayName(selectedModel.value); + if (composerModel.value) return modelDisplayName(composerModel.value); + if (props.embeddedMode) return t('input.modelAuto'); if (!selectedModelId.value) return t('input.notConfigured'); const isSharedAgent = !!settingsStore.selectedAgentSourceTenantId; const modelFromAgent = agentModelId.value && agentModelId.value === selectedModelId.value; @@ -1135,6 +1162,12 @@ const selectedModelDisplayName = computed(() => { return t('input.notConfigured'); }); +const modelTriggerTooltip = computed(() => { + if (isModelLockedByAgent.value) return t('input.modelLockedByAgent'); + if (props.embeddedMode && !composerModel.value) return t('input.modelAutoHint'); + return ''; +}); + const modelDisplayName = (model: ModelConfig) => { const displayName = model.display_name?.trim(); return displayName || model.name; @@ -1148,17 +1181,17 @@ const contextWindowTitle = (tokens?: number) => { }; const selectedModelContextLabel = computed(() => { - if (!selectedModel.value) return ''; - return formatContextWindow(selectedModel.value.parameters?.context_window); + if (!composerModel.value) return ''; + return formatContextWindow(composerModel.value.parameters?.context_window); }); const selectedModelContextIsDefault = computed(() => { - return isDefaultContextWindow(selectedModel.value?.parameters?.context_window); + return isDefaultContextWindow(composerModel.value?.parameters?.context_window); }); const selectedModelContextTitle = computed(() => { - if (!selectedModel.value) return ''; - return contextWindowTitle(selectedModel.value.parameters?.context_window); + if (!composerModel.value) return ''; + return contextWindowTitle(composerModel.value.parameters?.context_window); }); const updateModelDropdownPosition = () => { @@ -1911,8 +1944,11 @@ let scrollHandler: (() => void) | null = null; onMounted(() => { if (props.autoFocus) void focusInput(); - // Embed 渠道由宿主注入 agent/KB,勿拉取需 JWT 的平台资源 - if (props.embeddedMode) return; + // 嵌入时 agent/KB 由宿主注入,只需模型列表供宿主选择 + if (props.embeddedMode) { + void loadChatModels(); + return; + } browserConnection.watchStatus(); @@ -2003,6 +2039,7 @@ onUnmounted(() => { // 监听路由变化 watch(() => route.params.kbId, (newKbId) => { + if (props.embeddedMode) return; if (newKbId && typeof newKbId === 'string' && !selectedKbIds.value.includes(newKbId)) { settingsStore.addKnowledgeBase(newKbId); } @@ -2025,6 +2062,7 @@ watch([selectedKbIds, selectedFileIds], ([kbIds, fileIds]) => { const emit = defineEmits<{ (e: 'send-msg', query: string, modelId: string, mentionedItems: MentionRequestItem[], imageFiles: File[], attachmentFiles: AttachmentFile[], options: SendMessageOptions): void; + (e: 'update:modelId', modelId: string): void; (e: 'stop-generation'): void; (e: 'stop-confirmed'): void; (e: 'stop-failed'): void; @@ -2069,7 +2107,8 @@ const createSession = async ( MessagePlugin.warning(t('input.messages.steerHasAttachments')); return; } - const steerMentions: MentionRequestItem[] = allSelectedItems.value.map(item => ({ + // Embedded scope belongs to the host, including queued and injected turns. + const steerMentions: MentionRequestItem[] = (props.embeddedMode ? [] : allSelectedItems.value).map(item => ({ id: item.id, name: item.name, type: item.type, @@ -2100,9 +2139,10 @@ const createSession = async ( return; } - // Embed 渠道由后端绑定 agent/KB,勿走平台侧 agent 列表与就绪校验 + // 嵌入时 agent/KB 由宿主注入,勿走平台侧 agent 列表与就绪校验。 + // 模型只用宿主的选择,不能把主对话里选的模型带进来。 if (props.embeddedMode) { - emit('send-msg', val, selectedModelId.value || '', [], [], [], options); + emit('send-msg', val, composerModelId.value, [], [], [], options); clearvalue(); void focusInput(); return; @@ -2763,8 +2803,9 @@ defineExpose({ @update:files="uploadedAttachments = $event" /> -
- 0)" class="selected-tags-inline"> + + @@ -2792,7 +2833,9 @@ defineExpose({
-
+
+ + + + +
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index b76f9d8e..0cc23663 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -7,6 +7,12 @@ Lite
+ +
+ +
+