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
main
lyingbug 2026-10-15 14:54:40 +08:00 committed by GitHub
parent 1b24132566
commit a131efa5e0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 1274 additions and 170 deletions

View File

@ -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';

View File

@ -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 = {

View File

@ -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'),

View File

@ -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'"),

View File

@ -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 },

View File

@ -248,7 +248,7 @@ const sharedAgentKbList = ref<Array<{ id: string; name: string; type?: string; k
// 知识库:用新智能体配置的列表替换当前选中,使已选与可@列表一致(含共享智能体)
watch([selectedAgentId, agentKnowledgeBases, agentKBSelectionMode], ([newAgentId, newAgentKbs, newKbMode], [oldAgentId]) => {
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<SteerQueueItem[]>,
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<string | number> | 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" />
<!-- 选中的知识库和文件标签(显示在输入框内顶部) -->
<div v-if="allSelectedItems.length > 0" class="selected-tags-inline">
<span v-for="item in allSelectedItems" :key="`${item.type}:${item.id}`" class="mention-chip" :class="[
<div v-if="$slots.chips || (!embeddedMode && allSelectedItems.length > 0)" class="selected-tags-inline">
<slot name="chips" />
<span v-for="item in (embeddedMode ? [] : allSelectedItems)" :key="`${item.type}:${item.id}`" class="mention-chip" :class="[
getMentionChipClass(item),
{ 'mention-chip--agent': item.isAgentConfigured }
]">
@ -2792,7 +2833,9 @@ defineExpose({
<!-- 控制栏按文档流排列,换行时自动撑开容器 -->
<div class="control-bar" :class="{ 'is-embedded': embeddedMode }">
<!-- 左侧控制按钮 -->
<div class="control-left" v-if="!embeddedMode">
<div class="control-left">
<!-- 嵌入时宿主已定好 agent/KB,只保留模型选择 -->
<template v-if="!embeddedMode">
<!-- Agent 模式切换按钮 -->
<div ref="agentModeButtonRef" class="control-btn agent-mode-btn" :class="{
'is-normal': !isCustomAgent && !isAgentEnabled,
@ -2931,10 +2974,10 @@ defineExpose({
</svg>
</div>
</t-tooltip>
</template>
<!-- 模型显示 -->
<t-tooltip :content="isModelLockedByAgent ? $t('input.modelLockedByAgent') : ''"
:disabled="!isModelLockedByAgent">
<t-tooltip :content="modelTriggerTooltip" :disabled="!modelTriggerTooltip">
<div class="model-display" :class="{ 'agent-controlled': isModelLockedByAgent }">
<div ref="modelButtonRef" class="model-selector-trigger" @click.stop="toggleModelSelector">
<span class="model-selector-name">
@ -2953,7 +2996,7 @@ defineExpose({
</div>
</div>
</t-tooltip>
<t-popup v-if="reasoningLevels.length > 0" v-model:visible="showReasoningSelector"
<t-popup v-if="!embeddedMode && reasoningLevels.length > 0" v-model:visible="showReasoningSelector"
trigger="click" placement="top-right" :disabled="composerLocked"
:overlay-inner-style="{ padding: '4px', borderRadius: 'var(--app-radius-lg)' }"
@visible-change="handleReasoningVisibleChange">
@ -2994,8 +3037,19 @@ defineExpose({
</button>
</div>
<div class="model-selector-content">
<div v-if="embeddedMode" class="model-option" :class="{ selected: !composerModelId }"
:title="$t('input.modelAutoHint')" @click="handleModelChange(EMBEDDED_AUTO_MODEL)">
<div class="model-option-left">
<div class="model-option-name-wrap">
<span class="model-option-name">{{ $t('input.modelAuto') }}</span>
</div>
</div>
<span class="model-option-check">
<t-icon v-if="!composerModelId" name="check" size="14px" />
</span>
</div>
<div v-for="model in availableModels" :key="model.id" class="model-option"
:class="{ selected: model.id === selectedModelId }" @click="handleModelChange(model.id || '')">
:class="{ selected: model.id === composerModelId }" @click="handleModelChange(model.id || '')">
<div class="model-option-left">
<div class="model-option-name-wrap">
<span class="model-option-name">{{ modelDisplayName(model) }}</span>
@ -3008,7 +3062,7 @@ defineExpose({
:title="contextWindowTitle(model.parameters?.context_window)"
>{{ formatContextWindow(model.parameters?.context_window) }}</span>
<span class="model-option-check">
<t-icon v-if="model.id === selectedModelId" name="check" size="14px" />
<t-icon v-if="model.id === composerModelId" name="check" size="14px" />
</span>
</div>
<div v-if="availableModels.length === 0" class="model-option empty">

View File

@ -0,0 +1,123 @@
<template>
<t-tooltip v-if="context" :content="tooltip" placement="top">
<span v-if="assistant.contextAttached" class="assistant-context-chip">
<t-icon :name="icon" class="assistant-context-chip__icon" />
<span class="assistant-context-chip__name">{{ label }}</span>
<span class="assistant-context-chip__remove" role="button" :aria-label="t('assistant.context.detach')"
@click.stop="assistant.dismissPageContext()">×</span>
</span>
<button v-else type="button" class="assistant-context-chip is-detached" @click="assistant.restorePageContext()">
<t-icon name="add" class="assistant-context-chip__icon" />
<span class="assistant-context-chip__name">{{ label }}</span>
</button>
</t-tooltip>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAssistantStore } from '@/stores/assistant'
const { t } = useI18n()
const assistant = useAssistantStore()
const context = computed(() => assistant.pageContext)
const icon = computed(() => {
if (context.value?.wikiSlug) return 'book-open'
if (context.value?.knowledgeId) return 'file'
return 'folder'
})
const label = computed(() => {
const c = context.value
if (!c) return ''
return c.wikiTitle || c.wikiSlug || c.knowledgeTitle || c.knowledgeBaseName || t('assistant.context.currentPage')
})
const tooltip = computed(() => {
const c = context.value
if (!c) return ''
const path = [c.knowledgeBaseName, c.knowledgeTitle, c.wikiTitle || c.wikiSlug].filter(Boolean).join(' / ')
return assistant.contextAttached
? t('assistant.context.attachedTip', { path })
: t('assistant.context.detachedTip', { path })
})
</script>
<style lang="less" scoped>
@import '@/components/css/chat-resource-chips.less';
.assistant-context-chip {
.chat-resource-chip-surface();
display: inline-flex;
align-items: center;
gap: 5px;
min-height: 26px;
max-width: 260px;
padding: 3px 6px;
border-radius: var(--td-radius-medium);
box-sizing: border-box;
font-size: var(--app-text-sm);
font-weight: 500;
line-height: 18px;
transition: background var(--app-motion-fast), border-color var(--app-motion-fast);
&:hover {
.chat-resource-chip-hover();
}
&.is-detached {
border-style: dashed;
background: transparent;
box-shadow: none;
color: var(--td-text-color-secondary);
cursor: pointer;
font-family: inherit;
}
}
.assistant-context-chip__icon {
flex-shrink: 0;
font-size: var(--app-text-base);
color: var(--td-brand-color);
.is-detached & {
color: inherit;
}
}
.assistant-context-chip__name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.assistant-context-chip__remove {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
margin-left: 1px;
border-radius: 50%;
font-size: var(--app-text-base);
line-height: 1;
font-weight: 400;
cursor: pointer;
opacity: 0.5;
transition: opacity var(--app-motion-fast), background var(--app-motion-fast), color var(--app-motion-fast);
color: currentColor;
flex-shrink: 0;
.assistant-context-chip:hover & {
opacity: 0.8;
}
&:hover {
opacity: 1;
background: var(--td-bg-color-component);
color: var(--td-text-color-primary);
}
}
</style>

View File

@ -0,0 +1,171 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import { compileScript, parse } from '@vue/compiler-sfc'
import * as vue from 'vue'
import * as pinia from 'pinia'
import ts from 'typescript'
const filename = fileURLToPath(new URL('./AssistantDrawer.vue', import.meta.url))
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
const drawerScript = compileScript(descriptor, { id: 'assistant-drawer-test', inlineTemplate: true }).content
const storeScript = readFileSync(new URL('../../stores/assistant.ts', import.meta.url), 'utf8')
function evaluate(source: string, dependencies: Record<string, unknown>, globals = {}) {
const exports: any = {}
runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText, {
exports, console, ...globals,
require(name: string) {
if (name in dependencies) return dependencies[name]
throw new Error(`Unexpected component dependency: ${name}`)
},
})
return exports
}
function storage() {
const values = new Map<string, string>()
return {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => { values.set(key, value) },
removeItem: (key: string) => { values.delete(key) },
}
}
const flush = async () => {
await new Promise(resolve => setImmediate(resolve))
await vue.nextTick()
}
async function fixture(createSession = async () => ({ data: { id: 'new-session' } })) {
const auth = vue.reactive({ user: { id: 'user-a' }, effectiveTenantId: 1 })
const sessionStorage = storage()
sessionStorage.setItem('weknora:assistant-session:user-a:2', 'workspace-b-session')
sessionStorage.setItem('weknora:assistant-session:user-b:1', 'user-b-session')
const stores = evaluate(storeScript, {
vue, pinia, './auth': { useAuthStore: () => auth },
}, { sessionStorage, localStorage: storage() })
const storeRoot = pinia.createPinia()
pinia.setActivePinia(storeRoot)
const assistant = stores.useAssistantStore()
const mounted: Array<{ sessionId: string; query: string }> = []
const sent: Array<{ sessionId: string; query: string; scope: any }> = []
const menuEntries: unknown[] = []
const emptyComponent = vue.defineComponent({ inheritAttrs: false, render: () => null })
const ChatView = vue.defineComponent({
inheritAttrs: false,
props: ['session_id', 'initialQuery', 'hostScope'],
setup(props) {
vue.onMounted(() => {
mounted.push({ sessionId: props.session_id, query: props.initialQuery })
// ChatView sends initialQuery on mount and reads hostScope during send.
if (props.initialQuery) {
sent.push({ sessionId: props.session_id, query: props.initialQuery, scope: props.hostScope() })
}
})
return () => null
},
})
const component = evaluate(drawerScript, {
vue,
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
'@/views/chat/index.vue': ChatView,
'@/components/Input-field.vue': emptyComponent,
'./AssistantContextChip.vue': emptyComponent,
'@/api/chat': { createSessions: createSession },
'@/api/agent': { BUILTIN_WEKNORA_ASSISTANT_ID: 'builtin-weknora-assistant' },
'@/stores/menu': { useMenuStore: () => ({ updataMenuChildren: (entry: unknown) => menuEntries.push(entry) }) },
'@/stores/auth': { useAuthStore: () => auth },
'@/stores/assistant': stores,
'@/components/sessionMutations': { SESSION_MUTATION_EVENT: 'session-mutation' },
}, { window: { addEventListener() {}, removeEventListener() {} } }).default
type HostNode = { children: HostNode[]; parent?: HostNode }
const node = (): HostNode => ({ children: [] })
const remove = (child: HostNode) => {
if (child.parent) child.parent.children.splice(child.parent.children.indexOf(child), 1)
child.parent = undefined
}
const renderer = vue.createRenderer<HostNode, HostNode>({
createElement: node, createText: node, createComment: node,
insert(child, parent, anchor) {
remove(child)
const index = anchor ? parent.children.indexOf(anchor) : -1
parent.children.splice(index < 0 ? parent.children.length : index, 0, child)
child.parent = parent
},
remove, setElementText() {}, setText() {}, patchProp() {},
parentNode: child => child.parent ?? null,
nextSibling: child => child.parent?.children[child.parent.children.indexOf(child) + 1] ?? null,
})
const app = renderer.createApp(component)
app.use(storeRoot)
// TDrawer retains its content when hidden, which is essential to this regression.
app.component('t-drawer', vue.defineComponent({
inheritAttrs: false,
setup: (_, { slots }) => () => slots.default?.(),
}))
for (const name of ['t-tooltip', 't-button', 't-icon']) app.component(name, emptyComponent)
app.mount(node())
await flush()
return { auth, assistant, mounted, sent, menuEntries, sessionStorage, close: () => app.unmount() }
}
for (const identity of ['workspace', 'user']) {
test(`restoring another ${identity}'s session does not resend the old first message`, async () => {
const f = await fixture()
try {
f.assistant.publishPageContext(Symbol(), { knowledgeBaseId: 'kb-a', wikiIssueIds: ['issue-1', 'issue-2'] })
f.assistant.open({ query: 'Fix this issue', focus: { wikiIssueIds: ['issue-2'] } })
await flush()
assert.equal(f.sent.length, 1)
assert.equal(f.sent[0].query, 'Fix this issue')
assert.deepEqual(Array.from(f.sent[0].scope.pageContext.wiki_issue_ids), ['issue-2'])
f.assistant.close()
if (identity === 'workspace') f.auth.effectiveTenantId = 2
else f.auth.user = { id: 'user-b' }
await flush()
const restored = identity === 'workspace' ? 'workspace-b-session' : 'user-b-session'
assert.deepEqual(f.mounted.at(-1), { sessionId: restored, query: '' })
assert.equal(f.sent.length, 1, 'restoring a session must load history instead of sending')
f.assistant.open()
await flush()
assert.equal(f.sent.length, 1, 'reopening the retained drawer must not resend either')
} finally { f.close() }
})
}
test('a new conversation still sends its own first message after restoring a session', async () => {
const f = await fixture()
try {
f.auth.effectiveTenantId = 2
await flush()
f.assistant.open({ query: 'New request' })
await flush()
assert.equal(f.sent.length, 1)
assert.equal(f.sent[0].sessionId, 'new-session')
assert.equal(f.sent[0].query, 'New request')
assert.equal(f.sessionStorage.getItem('weknora:assistant-session:user-a:2'), 'new-session')
} finally { f.close() }
})
test('session creation finishing after a workspace switch cannot replace the restored session', async () => {
let resolve!: (value: { data: { id: string } }) => void
const f = await fixture(() => new Promise(done => { resolve = done }))
try {
f.assistant.open({ query: 'Old workspace request' })
await flush()
f.auth.effectiveTenantId = 2
await flush()
resolve({ data: { id: 'old-workspace-session' } })
await flush()
assert.equal(f.assistant.sessionId, 'workspace-b-session')
assert.equal(f.sessionStorage.getItem('weknora:assistant-session:user-a:2'), 'workspace-b-session')
assert.equal(f.sent.length, 0)
assert.equal(f.menuEntries.length, 0)
} finally { f.close() }
})

View File

@ -0,0 +1,316 @@
<template>
<t-drawer v-model:visible="assistant.visible" size="700px" :z-index="2100" :footer="false" :close-btn="true"
class="assistant-drawer">
<template #header>
<div class="assistant-drawer-header">
<div class="assistant-drawer-header-icon">
<t-icon name="compass" />
</div>
<div class="assistant-drawer-header-title">{{ t('assistant.title') }}</div>
<t-tooltip :content="t('assistant.newConversation')" placement="bottom">
<t-button class="assistant-drawer-header-action" size="small" variant="text" shape="square"
:disabled="!assistant.sessionId || starting" :aria-label="t('assistant.newConversation')"
@click="assistant.startNewConversation()">
<template #icon><t-icon name="chat-add" size="16px" /></template>
</t-button>
</t-tooltip>
</div>
</template>
<ChatView v-if="assistant.sessionId" :key="assistant.sessionId" :session_id="assistant.sessionId"
:agent-id="BUILTIN_WEKNORA_ASSISTANT_ID" :embedded-mode="true" :initial-query="initialQuery"
:host-scope="hostScope" :model-id="assistant.modelId" @update:model-id="assistant.setModel">
<template v-if="assistant.pageContext" #composer-chips>
<AssistantContextChip />
</template>
</ChatView>
<div v-else class="assistant-welcome">
<div class="assistant-welcome-body">
<div class="assistant-welcome-icon">
<t-icon name="compass" size="22px" />
</div>
<h3 class="assistant-welcome-title">{{ t('assistant.welcomeTitle') }}</h3>
<p class="assistant-welcome-desc">{{ t('assistant.welcomeDesc') }}</p>
<div class="assistant-starters">
<button v-for="starter in starters" :key="starter" type="button" class="assistant-starter"
:disabled="starting" @click="startConversation(starter)">
{{ starter }}
</button>
</div>
</div>
<div class="assistant-welcome-composer">
<InputField :embedded-mode="true" :auto-focus="assistant.visible" :model-id="assistant.modelId"
@update:model-id="assistant.setModel" @send-msg="(query) => startConversation(query)">
<template v-if="assistant.pageContext" #chips>
<AssistantContextChip />
</template>
</InputField>
</div>
</div>
</t-drawer>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import ChatView from '@/views/chat/index.vue'
import InputField from '@/components/Input-field.vue'
import AssistantContextChip from './AssistantContextChip.vue'
import { createSessions } from '@/api/chat'
import { BUILTIN_WEKNORA_ASSISTANT_ID } from '@/api/agent'
import { useMenuStore } from '@/stores/menu'
import { useAuthStore } from '@/stores/auth'
import { toPageContextPayload, useAssistantStore, type AssistantOpenRequest } from '@/stores/assistant'
import { SESSION_MUTATION_EVENT, type SessionMutationDetail } from '@/components/sessionMutations'
const { t } = useI18n()
const assistant = useAssistantStore()
const menuStore = useMenuStore()
const auth = useAuthStore()
const conversationOwner = computed(() => `${auth.user?.id}:${auth.effectiveTenantId}`)
const starting = ref(false)
// A first message belongs to the session we created, never a restored one.
const initialMessage = ref<{
sessionId: string
query: string
focus?: AssistantOpenRequest['focus']
} | null>(null)
const initialQuery = computed(() => initialMessage.value?.sessionId === assistant.sessionId
? initialMessage.value.query : '')
const starters = computed(() => {
const c = assistant.contextAttached ? assistant.pageContext : null
if (c?.wikiSlug) return [t('assistant.starters.wikiIssues'), t('assistant.starters.wikiSummary')]
if (c?.knowledgeId) return [t('assistant.starters.documentStatus'), t('assistant.starters.documentSummary')]
if (c) return [t('assistant.starters.failedDocuments'), t('assistant.starters.recentActivity')]
return [t('assistant.starters.formats'), t('assistant.starters.createWiki')]
})
// The backend only honours a page context inside the run's search scope, so
// the page's knowledge base travels with it.
const hostScope = () => {
const context = assistant.contextAttached ? assistant.pageContext : null
const focus = initialMessage.value?.sessionId === assistant.sessionId ? initialMessage.value.focus : undefined
initialMessage.value = null
if (!context) return { knowledgeBaseIds: [], pageContext: null }
return {
knowledgeBaseIds: [context.knowledgeBaseId],
pageContext: toPageContextPayload(focus ? { ...context, ...focus } : context),
}
}
async function startConversation(query: string, focus?: AssistantOpenRequest['focus']) {
const text = query.trim()
if (!text || starting.value) return
const owner = conversationOwner.value
starting.value = true
try {
const res: any = await createSessions({})
// A workspace switch can complete while session creation is in flight.
if (conversationOwner.value !== owner) return
const sessionId = res?.data?.id
if (!sessionId) throw new Error('missing session id')
const now = new Date().toISOString()
menuStore.updataMenuChildren({
title: t('assistant.title'),
path: `chat/${sessionId}`,
id: sessionId,
isMore: false,
isNoTitle: true,
created_at: now,
updated_at: now,
})
initialMessage.value = { sessionId, query: text, focus }
assistant.setSession(sessionId)
} catch (e) {
console.error('[Assistant] Failed to start a conversation', e)
MessagePlugin.error(t('assistant.startFailed'))
} finally {
starting.value = false
}
}
watch(() => [assistant.visible, assistant.pendingRequest] as const, ([visible, request]) => {
if (!visible || !request) return
const { query, focus } = assistant.takePendingRequest() || {}
assistant.restorePageContext()
if (query) void startConversation(query, focus)
}, { immediate: true })
watch(() => assistant.sessionId, (id) => {
if (id !== initialMessage.value?.sessionId) initialMessage.value = null
})
const handleSessionMutation = (event: Event) => {
const detail = (event as CustomEvent<SessionMutationDetail>).detail
if (detail?.removed && detail.sessionId === assistant.sessionId) assistant.startNewConversation()
}
onMounted(() => window.addEventListener(SESSION_MUTATION_EVENT, handleSessionMutation))
onUnmounted(() => window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation))
</script>
<style lang="less">
.assistant-drawer {
.t-drawer__body {
padding: 20px !important;
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.chat {
max-width: 100% !important;
min-width: 100% !important;
padding: 0 !important;
height: 100% !important;
flex: 1 !important;
border-radius: 0 !important;
}
.chat_scroll_box {
padding: 0 !important;
}
.chat>.input-container {
padding: 16px 0 0 0 !important;
box-sizing: border-box;
width: 100% !important;
max-width: 100% !important;
margin: 0 !important;
overflow-x: hidden;
}
.msg_list {
max-width: 100% !important;
padding-bottom: 0 !important;
margin: 0 !important;
}
}
.assistant-drawer-header {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
width: 100%;
padding-right: 32px;
}
.assistant-drawer-header-icon {
flex-shrink: 0;
width: 24px;
height: 24px;
border-radius: var(--app-radius-sm);
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
font-size: var(--app-text-lg);
}
.assistant-drawer-header-title {
flex: 1 1 auto;
min-width: 0;
font-size: var(--app-text-base);
font-weight: 500;
line-height: 20px;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.assistant-drawer-header-action {
width: 28px;
min-width: 28px;
height: 28px;
padding: 0;
color: var(--td-text-color-secondary);
}
.assistant-welcome {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.assistant-welcome-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 0 24px;
text-align: center;
}
.assistant-welcome-icon {
width: 40px;
height: 40px;
border-radius: var(--app-radius-md, 8px);
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
}
.assistant-welcome-title {
margin: 4px 0 0;
font-size: var(--app-text-lg);
font-weight: 600;
color: var(--td-text-color-primary);
}
.assistant-welcome-desc {
margin: 0;
max-width: 420px;
font-size: var(--app-text-md);
line-height: 1.6;
color: var(--td-text-color-secondary);
}
.assistant-starters {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
margin-top: 12px;
}
.assistant-starter {
padding: 6px 12px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--td-radius-medium);
background: var(--td-bg-color-container);
color: var(--td-text-color-primary);
font-family: inherit;
font-size: var(--app-text-sm);
line-height: 18px;
cursor: pointer;
transition: background var(--app-motion-fast), border-color var(--app-motion-fast);
&:hover:not(:disabled) {
background: var(--td-bg-color-container-hover);
border-color: var(--td-component-border);
}
&:disabled {
cursor: not-allowed;
color: var(--td-text-color-disabled);
}
}
.assistant-welcome-composer {
flex-shrink: 0;
padding-top: 16px;
}
</style>

View File

@ -22,6 +22,7 @@ import { openMermaidFullscreen } from '@/utils/mermaidViewer';
import { diffWikiLines, type WikiDiffLine } from '@/utils/wikiLineDiff';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';
import { useAssistantStore } from '@/stores/assistant';
import DocumentPreview from '@/components/document-preview.vue';
import DocumentFileIcon from '@/views/knowledge/components/DocumentFileIcon.vue';
import KnowledgeProcessingTimeline from '@/components/knowledge-processing-timeline.vue';
@ -241,6 +242,7 @@ mermaid.initialize({
});
const props = defineProps(["visible", "details", "knowledgeType", "sourceInfo", "canEditKB", "canDownloadKB", "parse_status", "kbId"]);
const emit = defineEmits(["closeDoc", "getDoc", "questionDeleted", "summaryStateChange"]);
const assistant = useAssistantStore();
const applySummaryState = (summaryStatus?: string, description?: string) => {
if (typeof summaryStatus === 'string' && summaryStatus) {
@ -1603,6 +1605,12 @@ const handleChunkPageChange = (pageInfo: { current: number }) => {
<t-icon name="chart-line" size="16px" />
</template>
</t-button>
<t-button v-if="details.id" class="header-action-btn" size="small" variant="text" shape="square"
theme="default" :title="$t('assistant.askAboutDocument')" @click="assistant.open()">
<template #icon>
<t-icon name="compass" size="16px" />
</template>
</t-button>
</div>
</div>
</template>

View File

@ -7,6 +7,12 @@
<sup v-if="isLiteEdition" class="lite-badge">Lite</sup>
</div>
<div class="logo_actions">
<t-tooltip :content="t('assistant.title')" placement="bottom">
<div class="header-icon-btn" :class="{ 'is-active': assistantStore.visible }"
:aria-label="t('assistant.title')" @click="assistantStore.toggle()">
<t-icon name="compass" size="18px" />
</div>
</t-tooltip>
<t-tooltip placement="bottom">
<template #content>
<span class="cmdk-tip">
@ -77,6 +83,16 @@
</div>
</div>
</t-tooltip>
<t-tooltip :content="t('assistant.title')" placement="right">
<div class="menu_item menu_item--cmdk" :class="{ 'menu_item_active': assistantStore.visible }"
:aria-label="t('assistant.title')" @click="assistantStore.toggle()">
<div class="menu_item-box">
<div class="menu_icon">
<t-icon name="compass" size="18px" />
</div>
</div>
</div>
</t-tooltip>
</div>
<div class="menu_box" :class="{ 'menu_box--sticky': item.children && !uiStore.sidebarCollapsed }"
v-for="(item, index) in topMenuItems" :key="index">
@ -274,6 +290,7 @@ import { useBrowserConnectionStore } from '@/stores/browserConnection';
import { useOrganizationStore } from '@/stores/organization';
import { useUIStore } from '@/stores/ui';
import { useCommandPaletteStore } from '@/stores/commandPalette';
import { useAssistantStore } from '@/stores/assistant';
import { MessagePlugin, DialogPlugin, Icon as TIcon } from "tdesign-vue-next";
import UserMenu from '@/components/UserMenu.vue';
import TenantSelector from '@/components/TenantSelector.vue';
@ -333,6 +350,7 @@ watch(() => uiStore.sidebarBrowserStatus && toolboxPreview.value.some((tool) =>
if (visible && !browserConnection.loaded) browserConnection.refresh().catch(() => {});
}, { immediate: true });
const commandPaletteStore = useCommandPaletteStore();
const assistantStore = useAssistantStore();
// Platform-aware label for the ⌘K hint. navigator.platform is deprecated but
// the alternatives (userAgentData.platform) aren't universally available yet;
@ -1836,6 +1854,11 @@ const resizeSidebar = (delta: number, keyboard: boolean) => {
background: var(--td-bg-color-container-hover);
}
&.is-active {
background: var(--td-bg-color-container-hover);
color: var(--td-brand-color);
}
.header-icon-img {
width: 18px;
height: 18px;

View File

@ -0,0 +1,17 @@
import { onBeforeUnmount, watch } from 'vue'
import { useAssistantStore, type AssistantPageContext } from '@/stores/assistant'
/**
* Publishes what this page has open to the WeKnora assistant for as long as
* the component is mounted. Return null while nothing is open. A component
* mounted inside another publisher refines it: fields it sets win.
*/
export function useAssistantPageContext(source: () => Partial<AssistantPageContext> | null) {
const assistant = useAssistantStore()
const owner = Symbol('assistant-page-context')
watch(source, (context) => {
if (context) assistant.publishPageContext(owner, context)
else assistant.retractPageContext(owner)
}, { immediate: true, deep: true })
onBeforeUnmount(() => assistant.retractPageContext(owner))
}

View File

@ -2955,6 +2955,8 @@ export default {
notConfigured: 'Not configured',
sharedAgentModelLabel: 'Model from shared agent',
noModel: 'No available models',
modelAuto: 'Auto',
modelAutoHint: 'Uses the current knowledge base\'s chat model, or the system default if it has none',
stopGeneration: 'Stop Generation',
send: 'Send',
steerCurrent: 'Supplement current task',
@ -3226,6 +3228,8 @@ export default {
actorId: 'Initiator ID',
apiKeyName: 'API key name',
apiKeyId: 'API key ID',
agentSessionId: 'Assistant conversation ID',
agentOperation: 'Assistant operation',
details: 'Details'
},
drawer: {
@ -3237,6 +3241,7 @@ export default {
systemActor: 'System',
actorWithAPIKey: '{actor} · API Key · {name}',
actorAPIKey: 'API Key · {name}',
viaAssistant: 'Via WeKnora Assistant',
knowledgeBase: 'Knowledge base',
countItems: '{count} items',
titleWithCount: '{title} and {count} more',
@ -3684,12 +3689,10 @@ export default {
globalIssuesEmpty: 'No pending content issues',
issuePagePrefix: 'Page: ',
issueGoFix: 'Go to fix',
fixAssistantTitle: 'Wiki Smart Fix Assistant',
issueFixSuggestions: 'Content Optimization Suggestions ({count})',
issueFixSingle: 'Fix',
fixStartError: 'Failed to start fix assistant',
issueFixPromptSingle: 'Please fix the issue (ID: {id}) on page [[{slug}]].',
issueFixPromptAutoStart: 'Please fix the following issues on page [[{slug}]]:'
issueFixPromptSingle: 'Fix this Wiki issue: {description}',
issueFixPromptAll: 'Fix the {count} open issues on this page'
},
buttons: {
create: 'Create Knowledge Base',
@ -6100,6 +6103,30 @@ export default {
audioNotSupported: 'Your browser does not support audio playback',
videoNotSupported: 'Your browser does not support video playback'
},
assistant: {
title: 'WeKnora Assistant',
newConversation: 'New conversation',
welcomeTitle: 'How can I help?',
welcomeDesc: 'Ask how WeKnora works, or have me check and handle document parsing, knowledge base activity and Wiki issues in your workspace. I ask before anything like a deletion.',
startFailed: 'Failed to start the assistant. Please try again.',
askAboutDocument: 'Ask WeKnora Assistant',
context: {
currentPage: 'Current page',
detach: 'Don\'t include the current page',
attachedTip: 'Including the current page: {path}',
detachedTip: 'Click to include the current page: {path}'
},
starters: {
wikiIssues: 'What issues are open on this page?',
wikiSummary: 'Summarize this Wiki page',
documentStatus: 'How did this document parse?',
documentSummary: 'Summarize this document',
failedDocuments: 'Which documents in this knowledge base failed to parse?',
recentActivity: 'What changed in this knowledge base recently?',
formats: 'Which document formats does WeKnora support?',
createWiki: 'How do I create a Wiki knowledge base?'
}
},
commandPalette: {
placeholder: 'Search knowledge bases, files, conversations…',
clearRecent: 'Clear',
@ -6129,7 +6156,8 @@ export default {
agents: 'Open agents',
organizations: 'Open shared spaces',
settings: 'Open settings',
productTour: 'Product tour'
productTour: 'Product tour',
assistant: 'Open WeKnora Assistant'
},
empty: {
noResults: 'No matches found',

View File

@ -2955,6 +2955,8 @@ export default {
notConfigured: '未設定',
sharedAgentModelLabel: '共有エージェントのモデル',
noModel: '利用可能なモデルがありません',
modelAuto: '自動',
modelAutoHint: '現在のナレッジベースのチャットモデルを使用し、未設定の場合はシステムの既定モデルを使用します',
stopGeneration: '生成を停止',
send: '送信',
steerCurrent: '現在のタスクに追加',
@ -3226,6 +3228,8 @@ export default {
actorId: '実行者ID',
apiKeyName: 'APIキー名',
apiKeyId: 'APIキーID',
agentSessionId: 'アシスタント会話 ID',
agentOperation: 'アシスタントの操作',
details: '詳細'
},
drawer: {
@ -3237,6 +3241,7 @@ export default {
systemActor: 'システム',
actorWithAPIKey: '{actor} · API Key · {name}',
actorAPIKey: 'API Key · {name}',
viaAssistant: 'WeKnora アシスタント経由',
knowledgeBase: 'ナレッジベース',
countItems: '{count}件',
titleWithCount: '{title}ほか{count}件',
@ -3684,12 +3689,10 @@ export default {
globalIssuesEmpty: '未処理のコンテンツ問題はありません',
issuePagePrefix: 'ページ: ',
issueGoFix: '修正に移動',
fixAssistantTitle: 'Wikiスマート修正アシスタント',
issueFixSuggestions: 'コンテンツ最適化の提案({count})',
issueFixSingle: '修正',
fixStartError: '修正アシスタントの起動に失敗しました',
issueFixPromptSingle: 'ページ [[{slug}]] の問題(ID: {id})を修正してください。',
issueFixPromptAutoStart: 'ページ [[{slug}]] の次の問題を修正してください:'
issueFixPromptSingle: 'この Wiki の問題を修正して:{description}',
issueFixPromptAll: 'このページの未対応の問題 {count} 件を修正して'
},
buttons: {
create: 'ナレッジベースを作成',
@ -6100,6 +6103,30 @@ export default {
audioNotSupported: 'お使いのブラウザは音声再生に対応していません',
videoNotSupported: 'お使いのブラウザは動画再生に対応していません'
},
assistant: {
title: 'WeKnora アシスタント',
newConversation: '新しい会話',
welcomeTitle: '何をお手伝いしましょうか?',
welcomeDesc: 'WeKnora の使い方にお答えするほか、ワークスペースのドキュメント解析、ナレッジベースの履歴、Wiki の問題を確認・対応できます。削除などの操作は事前に確認します。',
startFailed: 'アシスタントを起動できませんでした。もう一度お試しください。',
askAboutDocument: 'WeKnora アシスタントに聞く',
context: {
currentPage: '現在のページ',
detach: '現在のページを含めない',
attachedTip: '現在のページを含めています:{path}',
detachedTip: 'クリックして現在のページを含める:{path}'
},
starters: {
wikiIssues: 'このページの未対応の問題は?',
wikiSummary: 'この Wiki ページを要約して',
documentStatus: 'このドキュメントの解析状況は?',
documentSummary: 'このドキュメントを要約して',
failedDocuments: 'このナレッジベースで解析に失敗したドキュメントは?',
recentActivity: 'このナレッジベースの最近の変更は?',
formats: 'WeKnora はどのドキュメント形式に対応していますか?',
createWiki: 'Wiki ナレッジベースの作り方は?'
}
},
commandPalette: {
placeholder: 'ナレッジベース、ファイル、会話を検索…',
clearRecent: 'クリア',
@ -6129,7 +6156,8 @@ export default {
agents: 'エージェントを開く',
organizations: '共有スペースを開く',
settings: '設定を開く',
productTour: 'プロダクトツアー'
productTour: 'プロダクトツアー',
assistant: 'WeKnora アシスタントを開く'
},
empty: {
noResults: '一致する項目がありません',

View File

@ -2048,6 +2048,30 @@ export default {
todoWrite: '계획 수립',
askUser: '사용자에게 질문'
},
assistant: {
title: 'WeKnora 어시스턴트',
newConversation: '새 대화',
welcomeTitle: '무엇을 도와드릴까요?',
welcomeDesc: 'WeKnora 사용법을 안내하고, 워크스페이스의 문서 파싱, 지식 베이스 활동, Wiki 문제를 확인하고 처리할 수 있습니다. 삭제 같은 작업은 먼저 확인을 요청합니다.',
startFailed: '어시스턴트를 시작하지 못했습니다. 다시 시도해 주세요.',
askAboutDocument: 'WeKnora 어시스턴트에게 묻기',
context: {
currentPage: '현재 페이지',
detach: '현재 페이지 포함하지 않기',
attachedTip: '현재 페이지 포함됨: {path}',
detachedTip: '클릭하여 현재 페이지 포함: {path}'
},
starters: {
wikiIssues: '이 페이지에 처리할 문제가 있나요?',
wikiSummary: '이 Wiki 페이지를 요약해 줘',
documentStatus: '이 문서의 파싱 상태는 어떤가요?',
documentSummary: '이 문서를 요약해 줘',
failedDocuments: '이 지식 베이스에서 파싱에 실패한 문서는?',
recentActivity: '이 지식 베이스에 최근 어떤 변경이 있었나요?',
formats: 'WeKnora는 어떤 문서 형식을 지원하나요?',
createWiki: 'Wiki 지식 베이스는 어떻게 만드나요?'
}
},
commandPalette: {
placeholder: '지식베이스, 파일, 대화 검색…',
clearRecent: '지우기',
@ -2071,7 +2095,8 @@ export default {
agents: '에이전트 열기',
organizations: '공유 공간 열기',
settings: '설정 열기',
productTour: '사용 가이드'
productTour: '사용 가이드',
assistant: 'WeKnora 어시스턴트 열기'
},
match: {
vector: '벡터',
@ -4762,12 +4787,10 @@ export default {
globalIssuesEmpty: '보류 중인 콘텐츠 문제가 없습니다',
issuePagePrefix: '페이지: ',
issueGoFix: '수정하러 가기',
fixAssistantTitle: 'Wiki 스마트 수정 도우미',
issueFixSuggestions: '콘텐츠 최적화 제안 ({count})',
issueFixSingle: '수정',
fixStartError: '수정 도우미 시작 실패',
issueFixPromptSingle: '페이지 [[{slug}]] 의 문제(ID: {id})를 수정해 주세요.',
issueFixPromptAutoStart: '페이지 [[{slug}]] 의 다음 문제들을 수정해 주세요:'
issueFixPromptSingle: '이 Wiki 문제를 수정해 줘: {description}',
issueFixPromptAll: '이 페이지의 처리할 문제 {count}개를 수정해 줘'
},
indexing: {
title: '인덱싱 전략',
@ -4877,6 +4900,7 @@ export default {
systemActor: '시스템',
actorWithAPIKey: '{actor} · API Key · {name}',
actorAPIKey: 'API Key · {name}',
viaAssistant: 'WeKnora 어시스턴트 경유',
knowledgeBase: '지식 베이스',
countItems: '{count}개 항목',
titleWithCount: '{title} 외 {count}개',
@ -4982,6 +5006,8 @@ export default {
actorId: '시작자 ID',
apiKeyName: 'API 키 이름',
apiKeyId: 'API 키 ID',
agentSessionId: '어시스턴트 대화 ID',
agentOperation: '어시스턴트 작업',
details: '상세'
},
columns: {
@ -5219,6 +5245,8 @@ export default {
notConfigured: '구성되지 않음',
sharedAgentModelLabel: '공유 에이전트에 구성된 모델',
noModel: '사용 가능한 모델 없음',
modelAuto: '자동',
modelAutoHint: '현재 지식 베이스의 대화 모델을 사용하고, 설정되지 않은 경우 시스템 기본 모델을 사용합니다',
stopGeneration: '생성 중지',
send: '전송',
steerCurrent: '현재 작업에 추가',

View File

@ -2048,6 +2048,30 @@ export default {
todoWrite: 'Составить план',
askUser: 'Вопрос пользователю'
},
assistant: {
title: 'Ассистент WeKnora',
newConversation: 'Новый диалог',
welcomeTitle: 'Чем помочь?',
welcomeDesc: 'Я отвечаю на вопросы о WeKnora, а также проверяю и обрабатываю разбор документов, активность баз знаний и проблемы Wiki в вашем пространстве. Перед удалением и подобными действиями я спрошу подтверждение.',
startFailed: 'Не удалось запустить ассистента. Попробуйте ещё раз.',
askAboutDocument: 'Спросить ассистента WeKnora',
context: {
currentPage: 'Текущая страница',
detach: 'Не прикладывать текущую страницу',
attachedTip: 'Приложена текущая страница: {path}',
detachedTip: 'Нажмите, чтобы приложить текущую страницу: {path}'
},
starters: {
wikiIssues: 'Какие открытые проблемы есть на этой странице?',
wikiSummary: 'Кратко изложи эту страницу Wiki',
documentStatus: 'Как прошёл разбор этого документа?',
documentSummary: 'Кратко изложи этот документ',
failedDocuments: 'Какие документы этой базы знаний не удалось разобрать?',
recentActivity: 'Что недавно менялось в этой базе знаний?',
formats: 'Какие форматы документов поддерживает WeKnora?',
createWiki: 'Как создать базу знаний Wiki?'
}
},
commandPalette: {
placeholder: 'Поиск по базам знаний, файлам, диалогам…',
clearRecent: 'Очистить',
@ -2071,7 +2095,8 @@ export default {
agents: 'Открыть агенты',
organizations: 'Открыть общие пространства',
settings: 'Открыть настройки',
productTour: 'Обучение'
productTour: 'Обучение',
assistant: 'Открыть ассистента WeKnora'
},
match: {
vector: 'Вектор',
@ -4762,12 +4787,10 @@ export default {
globalIssuesEmpty: 'Нет ожидающих проблем содержимого',
issuePagePrefix: 'Страница: ',
issueGoFix: 'Исправить',
fixAssistantTitle: 'Wiki Умный помощник исправления',
issueFixSuggestions: 'Предложения по оптимизации ({count})',
issueFixSingle: 'Исправить',
fixStartError: 'Не удалось запустить помощник исправления',
issueFixPromptSingle: 'Пожалуйста, исправьте проблему (ID: {id}) на странице [[{slug}]].',
issueFixPromptAutoStart: 'Пожалуйста, исправьте следующие проблемы на странице [[{slug}]]:'
issueFixPromptSingle: 'Исправь эту проблему Wiki: {description}',
issueFixPromptAll: 'Исправь {count} открытых проблем на этой странице'
},
indexing: {
title: 'Стратегия индексации',
@ -4877,6 +4900,7 @@ export default {
systemActor: 'Система',
actorWithAPIKey: '{actor} · API Key · {name}',
actorAPIKey: 'API Key · {name}',
viaAssistant: 'Через ассистента WeKnora',
knowledgeBase: 'База знаний',
countItems: '{count} элем.',
titleWithCount: '{title} и ещё {count}',
@ -4982,6 +5006,8 @@ export default {
actorId: 'ID инициатора',
apiKeyName: 'Имя API-ключа',
apiKeyId: 'ID API-ключа',
agentSessionId: 'ID диалога ассистента',
agentOperation: 'Операция ассистента',
details: 'Подробности'
},
columns: {
@ -5219,6 +5245,8 @@ export default {
notConfigured: 'Не настроено',
sharedAgentModelLabel: 'Модель из общего агента',
noModel: 'Нет доступных моделей',
modelAuto: 'Авто',
modelAutoHint: 'Используется модель чата текущей базы знаний, а если она не задана — модель по умолчанию',
stopGeneration: 'Остановить генерацию',
send: 'Отправить',
steerCurrent: 'Дополнить текущую задачу',

View File

@ -2050,6 +2050,30 @@ export default {
todoWrite: '制定计划',
askUser: '向用户提问'
},
assistant: {
title: 'WeKnora 助手',
newConversation: '新对话',
welcomeTitle: '有什么可以帮你?',
welcomeDesc: '我可以解答 WeKnora 的用法,也可以查看和处理你空间里的文档解析、知识库动态和 Wiki 问题。删除等操作会先请你确认。',
startFailed: '启动助手失败,请重试',
askAboutDocument: '问 WeKnora 助手',
context: {
currentPage: '当前页面',
detach: '不附带当前页面',
attachedTip: '已附带当前页面:{path}',
detachedTip: '点击附带当前页面:{path}'
},
starters: {
wikiIssues: '这个页面有哪些待处理的问题?',
wikiSummary: '总结一下这个 Wiki 页面',
documentStatus: '这个文档的解析状态怎么样?',
documentSummary: '总结一下这个文档',
failedDocuments: '这个知识库有哪些解析失败的文档?',
recentActivity: '这个知识库最近有哪些变动?',
formats: 'WeKnora 支持哪些文档格式?',
createWiki: '怎样创建 Wiki 知识库?'
}
},
commandPalette: {
placeholder: '搜索知识库、文件、对话…',
clearRecent: '清除',
@ -2073,7 +2097,8 @@ export default {
agents: '打开智能体',
organizations: '打开共享空间',
settings: '打开设置',
productTour: '新手引导'
productTour: '新手引导',
assistant: '打开 WeKnora 助手'
},
match: {
vector: '向量',
@ -4764,12 +4789,10 @@ export default {
globalIssuesEmpty: '暂无待处理的内容问题',
issuePagePrefix: '页面: ',
issueGoFix: '去处理',
fixAssistantTitle: 'Wiki 智能修复助手',
issueFixSuggestions: '内容优化建议 ({count})',
issueFixSingle: '修复',
fixStartError: '启动修复助手失败',
issueFixPromptSingle: '请修复页面 [[{slug}]] 上的问题 (ID: {id})。',
issueFixPromptAutoStart: '请修复页面 [[{slug}]] 上的以下问题:'
issueFixPromptSingle: '修复这个 Wiki 问题:{description}',
issueFixPromptAll: '修复当前页面的 {count} 个待处理问题'
},
indexing: {
title: '索引策略',
@ -4879,6 +4902,7 @@ export default {
systemActor: '系统触发',
actorWithAPIKey: '{actor} · API Key · {name}',
actorAPIKey: 'API Key · {name}',
viaAssistant: '经 WeKnora 助手',
knowledgeBase: '知识库',
countItems: '共 {count} 项',
titleWithCount: '{title} 等 {count} 项',
@ -4984,6 +5008,8 @@ export default {
actorId: '发起人 ID',
apiKeyName: 'API Key 名称',
apiKeyId: 'API Key ID',
agentSessionId: '助手会话 ID',
agentOperation: '助手操作',
details: '详情'
},
columns: {
@ -5221,6 +5247,8 @@ export default {
notConfigured: '未配置',
sharedAgentModelLabel: '共享智能体配置的模型',
noModel: '暂无可用模型',
modelAuto: '自动',
modelAutoHint: '使用当前知识库配置的对话模型,未配置时使用系统默认模型',
stopGeneration: '停止生成',
send: '发送',
steerCurrent: '补充当前任务',

View File

@ -2050,6 +2050,30 @@ export default {
todoWrite: '制定計劃',
askUser: '向使用者提問'
},
assistant: {
title: 'WeKnora 助手',
newConversation: '新對話',
welcomeTitle: '有什麼可以幫你?',
welcomeDesc: '我可以解答 WeKnora 的用法,也可以檢視和處理你空間裡的文件解析、知識庫動態和 Wiki 問題。刪除等操作會先請你確認。',
startFailed: '啟動助手失敗,請重試',
askAboutDocument: '問 WeKnora 助手',
context: {
currentPage: '目前頁面',
detach: '不附帶目前頁面',
attachedTip: '已附帶目前頁面:{path}',
detachedTip: '點擊附帶目前頁面:{path}'
},
starters: {
wikiIssues: '這個頁面有哪些待處理的問題?',
wikiSummary: '總結一下這個 Wiki 頁面',
documentStatus: '這個文件的解析狀態如何?',
documentSummary: '總結一下這個文件',
failedDocuments: '這個知識庫有哪些解析失敗的文件?',
recentActivity: '這個知識庫最近有哪些變動?',
formats: 'WeKnora 支援哪些文件格式?',
createWiki: '怎樣建立 Wiki 知識庫?'
}
},
commandPalette: {
placeholder: '搜尋知識庫、檔案、對話…',
clearRecent: '清除',
@ -2073,7 +2097,8 @@ export default {
agents: '打開智慧代理',
organizations: '打開共享空間',
settings: '打開設定',
productTour: '新手引導'
productTour: '新手引導',
assistant: '開啟 WeKnora 助手'
},
match: {
vector: '向量',
@ -4764,12 +4789,10 @@ export default {
globalIssuesEmpty: '暫無待處理的內容問題',
issuePagePrefix: '頁面: ',
issueGoFix: '去處理',
fixAssistantTitle: 'Wiki 智慧修復助手',
issueFixSuggestions: '內容最佳化建議 ({count})',
issueFixSingle: '修復',
fixStartError: '啟動修復助手失敗',
issueFixPromptSingle: '請修復頁面 [[{slug}]] 上的問題 (ID: {id})。',
issueFixPromptAutoStart: '請修復頁面 [[{slug}]] 上的以下問題:'
issueFixPromptSingle: '修復這個 Wiki 問題:{description}',
issueFixPromptAll: '修復目前頁面的 {count} 個待處理問題'
},
indexing: {
title: '索引策略',
@ -4879,6 +4902,7 @@ export default {
systemActor: '系統觸發',
actorWithAPIKey: '{actor} · API Key · {name}',
actorAPIKey: 'API Key · {name}',
viaAssistant: '經 WeKnora 助手',
knowledgeBase: '知識庫',
countItems: '共 {count} 項',
titleWithCount: '{title} 等 {count} 項',
@ -4984,6 +5008,8 @@ export default {
actorId: '發起人 ID',
apiKeyName: 'API Key 名稱',
apiKeyId: 'API Key ID',
agentSessionId: '助手對話 ID',
agentOperation: '助手操作',
details: '詳情'
},
columns: {
@ -5221,6 +5247,8 @@ export default {
notConfigured: '未設定',
sharedAgentModelLabel: '共享智慧代理設定的模型',
noModel: '暫無可用模型',
modelAuto: '自動',
modelAutoHint: '使用目前知識庫設定的對話模型,未設定時使用系統預設模型',
stopGeneration: '停止生成',
send: '傳送',
steerCurrent: '補充當前任務',

View File

@ -0,0 +1,161 @@
import { defineStore } from 'pinia'
import { computed, ref, shallowReactive, watch } from 'vue'
import type { PageContextPayload } from '@/api/chat/streame'
import { useAuthStore } from './auth'
/** What the user has open, as published by the pages that know it. */
export interface AssistantPageContext {
knowledgeBaseId: string
knowledgeBaseName?: string
knowledgeId?: string
knowledgeTitle?: string
wikiSlug?: string
wikiTitle?: string
wikiIssueIds?: string[]
}
export interface AssistantOpenRequest {
/** Sent as the first message of a new conversation. */
query?: string
/** Narrows the page context for that first message only. */
focus?: Pick<AssistantPageContext, 'wikiIssueIds'>
}
const SESSION_KEY_PREFIX = 'weknora:assistant-session'
const MODEL_KEY_PREFIX = 'weknora:assistant-model'
export function toPageContextPayload(context: AssistantPageContext): PageContextPayload {
return {
knowledge_base_id: context.knowledgeBaseId,
knowledge_id: context.knowledgeId || undefined,
wiki_slug: context.wikiSlug || undefined,
wiki_issue_ids: context.wikiIssueIds?.length ? [...context.wikiIssueIds] : undefined,
}
}
function contextKey(context: AssistantPageContext | null): string {
if (!context) return ''
return [context.knowledgeBaseId, context.knowledgeId || '', context.wikiSlug || ''].join('|')
}
/**
* Pinia store behind the global WeKnora assistant drawer (rendered once in
* platform/index.vue). Pages publish what is open through
* useAssistantPageContext; anything can open the drawer with open().
*/
export const useAssistantStore = defineStore('assistant', () => {
const visible = ref(false)
const sessionId = ref('')
const pendingRequest = ref<AssistantOpenRequest | null>(null)
// Publishers in mount order, so a nested page (Wiki) refines its parent (KB).
const layers = shallowReactive(new Map<symbol, Partial<AssistantPageContext>>())
const dismissedKey = ref('')
const pageContext = computed<AssistantPageContext | null>(() => {
const merged: Partial<AssistantPageContext> = {}
for (const layer of layers.values()) Object.assign(merged, layer)
return merged.knowledgeBaseId ? (merged as AssistantPageContext) : null
})
const contextAttached = computed(() => !!pageContext.value && dismissedKey.value !== contextKey(pageContext.value))
// '' leaves the choice to the run: the knowledge base's chat model, then
// the system default.
const modelId = ref('')
// The conversation survives reloads within the tab and the model choice
// persists, both scoped like the command palette's history so another user
// or workspace never inherits them.
const storageKey = (prefix: string): string => {
const auth = useAuthStore()
return `${prefix}:${auth.user?.id || 'anon'}:${auth.effectiveTenantId ?? 'none'}`
}
const restore = () => {
try {
sessionId.value = sessionStorage.getItem(storageKey(SESSION_KEY_PREFIX)) || ''
modelId.value = localStorage.getItem(storageKey(MODEL_KEY_PREFIX)) || ''
} catch {
sessionId.value = ''
modelId.value = ''
}
}
const setSession = (id: string) => {
sessionId.value = id
try {
if (id) sessionStorage.setItem(storageKey(SESSION_KEY_PREFIX), id)
else sessionStorage.removeItem(storageKey(SESSION_KEY_PREFIX))
} catch {
// Storage can throw in private mode; the in-memory value still works.
}
}
const setModel = (id: string) => {
modelId.value = id
try {
if (id) localStorage.setItem(storageKey(MODEL_KEY_PREFIX), id)
else localStorage.removeItem(storageKey(MODEL_KEY_PREFIX))
} catch {
// See setSession.
}
}
restore()
watch(() => {
const auth = useAuthStore()
return `${auth.user?.id}:${auth.effectiveTenantId}`
}, restore)
const open = (request?: AssistantOpenRequest) => {
if (request?.query) {
setSession('')
pendingRequest.value = request
}
visible.value = true
}
const close = () => {
visible.value = false
}
const toggle = () => {
if (visible.value) close()
else open()
}
const startNewConversation = () => {
pendingRequest.value = null
setSession('')
}
const takePendingRequest = (): AssistantOpenRequest | null => {
const request = pendingRequest.value
pendingRequest.value = null
return request
}
const publishPageContext = (owner: symbol, context: Partial<AssistantPageContext>) => {
layers.set(owner, context)
}
const retractPageContext = (owner: symbol) => {
layers.delete(owner)
}
const dismissPageContext = () => {
dismissedKey.value = contextKey(pageContext.value)
}
const restorePageContext = () => {
dismissedKey.value = ''
}
return {
visible,
sessionId,
modelId,
pendingRequest,
pageContext,
contextAttached,
open,
close,
toggle,
setSession,
setModel,
startNewConversation,
takePendingRequest,
publishPageContext,
retractPageContext,
dismissPageContext,
restorePageContext,
}
})

View File

@ -171,7 +171,10 @@
@stop-confirmed="handleStopConfirmed"
@stop-failed="handleStopFailed" :isReplying="isReplying" :composer-locked="composerLocked" :sessionId="session_id"
:assistantMessageId="currentAssistantMessageId" :embeddedMode="embeddedMode"
:queuedSteers="steerQueue.filter(item => item.delivery === 'after')" :canSteer="isAgentStreamSession()"></InputField>
:model-id="modelId" @update:model-id="(id) => emit('update:modelId', id)"
:queuedSteers="steerQueue.filter(item => item.delivery === 'after')" :canSteer="isAgentStreamSession()">
<template v-if="$slots['composer-chips']" #chips><slot name="composer-chips" /></template>
</InputField>
</div>
</div>
<div v-if="!embeddedMode" class="chat_overlays">
@ -181,7 +184,7 @@
</div>
</div>
</div>
<KnowledgeBaseEditorModal :visible="uiStore.showKBEditorModal" :mode="uiStore.kbEditorMode"
<KnowledgeBaseEditorModal v-if="!embeddedMode" :visible="uiStore.showKBEditorModal" :mode="uiStore.kbEditorMode"
:kb-id="uiStore.currentKBId || undefined" :initial-type="uiStore.kbEditorType"
@update:visible="(val) => val ? null : uiStore.closeKBEditor()" @success="handleKBEditorSuccess" />
<ChatReferencesDrawer />
@ -258,9 +261,18 @@ const { visible: referencesDrawerVisible, panelWidth: referencesPanelWidth } = r
const props = defineProps({
session_id: { type: String, default: '' },
agentId: { type: String, default: '' },
kbIds: { type: Array, default: () => [] },
embeddedMode: { type: Boolean, default: false },
// Embedded only: sent once on mount, instead of the menu store's firstQuery
// that belongs to the main chat.
initialQuery: { type: String, default: '' },
// Embedded only: returns { knowledgeBaseIds, pageContext } for each send,
// read at send time so the host can follow the page the user is on.
hostScope: { type: Function, default: null },
// Embedded only: the host's model choice (v-model:model-id), '' for the
// agent's own.
modelId: { type: String, default: '' },
});
const emit = defineEmits(['update:modelId']);
const usemenuStore = useMenuStore();
const useSettingsStoreInstance = useSettingsStore();
@ -278,7 +290,7 @@ const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
const { t } = useI18n();
const { firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles, firstQuestionOrigin } = storeToRefs(usemenuStore);
// Capture before the initial send consumes firstQuery; the child focuses after mounting.
const focusComposerOnMount = Boolean(firstQuery.value);
const focusComposerOnMount = Boolean(props.embeddedMode ? props.initialQuery : firstQuery.value);
const { onChunk, error, isStreaming, startStream, stopStream, lastStreamRequest } = useStream();
/** Snapshot of the in-flight HTTP request for attaching to the next assistant message. */
const pendingStreamDebug = ref(null);
@ -804,6 +816,8 @@ const getUserQuery = (index) => {
};
watch([() => route.params], async (newvalue) => {
// The host owns an embedded view's session; the route belongs to the page behind it.
if (props.embeddedMode) return;
isFirstEnter.value = true;
if (newvalue[0].chatid) {
if (!firstQuery.value) {
@ -1513,7 +1527,8 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
// Merge @mentioned KB/file IDs so retrieval uses the same targets user @mentioned (including shared KBs)
const sidebarKbIds = props.embeddedMode ? props.kbIds : (useSettingsStoreInstance.settings.selectedKnowledgeBases || []);
const hostScope = props.embeddedMode && props.hostScope ? props.hostScope() : null;
const sidebarKbIds = props.embeddedMode ? (hostScope?.knowledgeBaseIds || []) : (useSettingsStoreInstance.settings.selectedKnowledgeBases || []);
const sidebarFileIds = props.embeddedMode ? [] : (useSettingsStoreInstance.settings.selectedFiles || []);
const kbIdSet = new Set(sidebarKbIds);
const fileIdSet = new Set(sidebarFileIds);
@ -1563,6 +1578,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
query: value,
suggestion_attribution: suggestionAttribution || undefined,
question_origin: options?.questionOrigin,
page_context: agentEnabled ? (hostScope?.pageContext || undefined) : undefined,
method: 'POST',
url: endpoint,
});
@ -1715,8 +1731,10 @@ const handleSessionMutation = (event) => {
};
onBeforeMount(async () => {
// 嵌入式的 agent / 知识库由宿主随请求传入,不能写进主对话的 settings store。
if (props.embeddedMode) return;
// 若从智能体列表点击共享智能体进入,URL 带 agent_id 与 source_tenant_id,同步到 store
const agentIdFromQuery = props.agentId || (route.query.agent_id && String(route.query.agent_id));
const agentIdFromQuery = route.query.agent_id && String(route.query.agent_id);
const sourceTenantIdFromQuery = route.query.source_tenant_id && String(route.query.source_tenant_id);
if (agentIdFromQuery && sourceTenantIdFromQuery) {
useSettingsStoreInstance.selectAgent(agentIdFromQuery, sourceTenantIdFromQuery);
@ -1724,10 +1742,6 @@ onBeforeMount(async () => {
useSettingsStoreInstance.selectAgent(agentIdFromQuery, null);
}
if (props.kbIds && props.kbIds.length > 0) {
useSettingsStoreInstance.selectKnowledgeBases(props.kbIds);
}
// 必须在 Input-field onMounted 之前完成:按 session.last_request_state 恢复输入栏
await loadSessionAndHydrate(session_id.value);
});
@ -1741,7 +1755,11 @@ onMounted(async () => {
loading.value = false;
isReplying.value = false;
if (firstQuery.value) {
if (props.embeddedMode && props.initialQuery) {
scrollLock.value = true;
historyLoading.value = false;
sendMsg(props.initialQuery, props.modelId);
} else if (!props.embeddedMode && firstQuery.value) {
scrollLock.value = true;
historyLoading.value = false;
if (firstModelId.value) {
@ -1782,13 +1800,17 @@ onUnmounted(() => {
window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
});
// An embedded view outlives the page behind it: a route change must not stop
// its stream or restore the main chat's defaults.
onBeforeRouteLeave((to, from, next) => {
if (props.embeddedMode) return next()
clearData()
// 离开聊天会话 → 还原"用户全局默认",避免旧会话的请求态泄漏到新建对话。
useSettingsStoreInstance.restoreDefaultsIfSnapshotted();
next()
})
onBeforeRouteUpdate((to, from, next) => {
if (props.embeddedMode) return next()
clearData()
// 仅"会话 → 会话"会落到这里;跨会话覆盖的还原放到 route.params 的 watch 里,
// 因为新会话的 getSession 也在那边触发,便于保证 restore→snapshot→apply 顺序。

View File

@ -82,6 +82,7 @@ import {
} from './documentSorting';
import { useI18n } from 'vue-i18n';
import { useMarqueeSelect } from '@/hooks/useMarqueeSelect';
import { useAssistantPageContext } from '@/composables/useAssistantPageContext';
import type { ParserEngineInfo } from '@/api/system';
const route = useRoute();
const { t } = useI18n();
@ -433,6 +434,16 @@ const onCardMoreVisibleChange = (visible: boolean, item: KnowledgeCard) => {
}
};
let isCardDetails = ref(false);
useAssistantPageContext(() => {
if (!kbId.value) return null;
const docOpen = isCardDetails.value && !!details.id;
return {
knowledgeBaseId: kbId.value,
knowledgeBaseName: kbInfo.value?.id === kbId.value ? kbInfo.value?.name : undefined,
knowledgeId: docOpen ? details.id : undefined,
knowledgeTitle: docOpen ? details.title : undefined,
};
});
let timeout: ReturnType<typeof setTimeout> | null = null;
let knowledgeScroll = ref()
let page = 1;

View File

@ -166,6 +166,9 @@
<span v-if="activityAPIKeyName(row)" class="audit-actor-key">
{{ actorAPIKeyLabel(row) }}
</span>
<span v-if="activityViaAssistant(row)" class="audit-actor-key">
{{ t('knowledgeEditor.activity.viaAssistant') }}
</span>
</div>
</template>
<template #outcome="{ row }">
@ -523,10 +526,14 @@ function actorAPIKeyLabel(entry: KnowledgeBaseActivity): string {
function actorLabel(entry: KnowledgeBaseActivity): string {
const person = actorPersonLabel(entry)
const keyName = activityAPIKeyName(entry)
if (keyName) {
return t('knowledgeEditor.activity.actorWithAPIKey', { actor: person, name: keyName })
}
return person
const label = keyName
? t('knowledgeEditor.activity.actorWithAPIKey', { actor: person, name: keyName })
: person
return activityViaAssistant(entry) ? `${label} · ${t('knowledgeEditor.activity.viaAssistant')}` : label
}
function activityViaAssistant(entry: KnowledgeBaseActivity): boolean {
return details(entry).via === 'agent'
}
function activityAPIKeyName(entry: KnowledgeBaseActivity): string {
@ -657,6 +664,21 @@ function identifierFields(entry: KnowledgeBaseActivity): DetailField[] {
value: keyId,
})
}
const value = details(entry)
if (value.via === 'agent' && value.agent_session_id) {
fields.push({
key: 'agentSessionId',
label: t('knowledgeEditor.activity.expanded.agentSessionId'),
value: String(value.agent_session_id),
})
}
if (value.via === 'agent' && value.agent_operation) {
fields.push({
key: 'agentOperation',
label: t('knowledgeEditor.activity.expanded.agentOperation'),
value: String(value.agent_operation),
})
}
return fields
}

View File

@ -746,13 +746,6 @@
</div>
</t-drawer>
<!-- Fix Chat Drawer -->
<t-drawer v-model:visible="showFixDrawer" :header="$t('knowledgeEditor.wikiBrowser.fixAssistantTitle')" size="700px"
:footer="false" class="wiki-fix-drawer">
<ChatView v-if="showFixDrawer" :session_id="currentFixSessionId" agentId="builtin-wiki-fixer"
:kbIds="[props.knowledgeBaseId]" :embeddedMode="true" />
</t-drawer>
<!-- Revision history drawer -->
<WikiRevisionDrawer v-model:visible="showRevisionDrawer" :kb-id="props.knowledgeBaseId"
:slug="selectedPage?.slug || ''" :current-page="selectedPage" :can-edit="props.canEdit"
@ -821,7 +814,6 @@
<script setup lang="ts">
import { ref, computed, reactive, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMenuStore } from '@/stores/menu'
import { useSettingsStore } from '@/stores/settings'
import { useI18n } from 'vue-i18n'
import { marked } from 'marked'
@ -840,8 +832,8 @@ import {
import { resolveWikiBacklinkTitle } from './wikiBacklinkTitles'
import { buildGraphLayout, graphNodeRadius, stepGraphLayout, visibleGraphLabels, graphPointBounds, initialGraphViewport, graphClusterOutline, graphLandmarkTitle, type GraphBounds, type GraphCluster } from './wikiGraphLayout'
import { getKnowledgeDetails } from '@/api/knowledge-base'
import { createSessions } from '@/api/chat'
import ChatView from '@/views/chat/index.vue'
import { useAssistantStore } from '@/stores/assistant'
import { useAssistantPageContext } from '@/composables/useAssistantPageContext'
import {
listWikiPages,
listWikiFolders,
@ -870,7 +862,7 @@ import {
const router = useRouter()
const route = useRoute()
const menuStore = useMenuStore()
const assistant = useAssistantStore()
const settingsStore = useSettingsStore()
ensureLiteralSingleTildeOnGlobalMarked()
@ -1011,10 +1003,18 @@ const activeSystemView = ref<'' | 'index'>('')
const searchResults = ref<WikiPage[] | null>(null)
const pageIssues = ref<WikiPageIssue[]>([])
const showIssuesBox = ref(false)
const showFixDrawer = ref(false)
useAssistantPageContext(() => {
const page = selectedPage.value
if (!page) return null
return {
knowledgeBaseId: props.knowledgeBaseId,
wikiSlug: page.slug,
wikiTitle: page.title,
wikiIssueIds: pageIssues.value.map(issue => issue.id),
}
})
const showGlobalIssuesDrawer = ref(false)
const globalIssues = ref<WikiPageIssue[]>([])
const currentFixSessionId = ref('')
const stats = ref<WikiStats | null>(null)
const graphData = ref<WikiGraphData | null>(null)
const searchQuery = ref('')
@ -3700,58 +3700,31 @@ async function handleIssueIgnore(issueId: string) {
}
}
async function startFixSession(prompt: string) {
try {
const res = await createSessions({})
if (res && (res as any).data && (res as any).data.id) {
const sessionId = (res as any).data.id
const now = new Date().toISOString()
menuStore.updataMenuChildren({
title: t('knowledgeEditor.wikiBrowser.fixAssistantTitle'),
path: `chat/${sessionId}`,
id: sessionId,
isMore: false,
isNoTitle: true,
created_at: now,
updated_at: now
})
menuStore.changeIsFirstSession(true)
menuStore.changeFirstQuery(prompt, [], '', [])
currentFixSessionId.value = sessionId
showFixDrawer.value = true
showIssuesBox.value = false // Hide issues box
} else {
MessagePlugin.error(t('knowledgeEditor.wikiBrowser.fixStartError'))
}
} catch (e) {
console.error('Failed to create fix session', e)
MessagePlugin.error(t('knowledgeEditor.wikiBrowser.fixStartError'))
}
}
function triggerFixIssue(issue: WikiPageIssue) {
if (!selectedPage.value) return
const prompt = t('knowledgeEditor.wikiBrowser.issueFixPromptSingle', {
slug: selectedPage.value.slug,
id: issue.id
showIssuesBox.value = false
assistant.open({
query: t('knowledgeEditor.wikiBrowser.issueFixPromptSingle', { description: issue.description }),
focus: { wikiIssueIds: [issue.id] },
})
startFixSession(prompt)
}
function triggerAutoFix() {
if (!selectedPage.value || pageIssues.value.length === 0) return
let prompt = t('knowledgeEditor.wikiBrowser.issueFixPromptAutoStart', { slug: selectedPage.value.slug }) + '\n\n'
pageIssues.value.forEach((issue, idx) => {
prompt += `${idx + 1}. Issue ID: ${issue.id}\n`
showIssuesBox.value = false
assistant.open({
query: t('knowledgeEditor.wikiBrowser.issueFixPromptAll', { count: pageIssues.value.length }),
focus: { wikiIssueIds: pageIssues.value.map(issue => issue.id) },
})
startFixSession(prompt)
}
// The assistant may have rewritten the page or resolved its issues.
watch(() => assistant.visible, (visible, wasVisible) => {
if (!wasVisible || visible || editingPage.value) return
void refreshSelectedPage()
void loadStats()
})
async function doSearch() {
if (!searchQuery.value.trim()) {
searchResults.value = null
@ -7008,44 +6981,4 @@ span.graph-focus-name {
}
</style>
<style lang="less">
/* Fix Embedded Chat UI (unscoped because drawer attaches to body) */
.wiki-fix-drawer {
.t-drawer__body {
padding: 20px !important;
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.chat {
max-width: 100% !important;
min-width: 100% !important;
padding: 0 !important;
height: 100% !important;
flex: 1 !important;
border-radius: 0 !important;
}
.chat_scroll_box {
padding: 0 !important;
}
.chat>.input-container {
padding: 16px 0 0 0 !important;
box-sizing: border-box;
width: 100% !important;
max-width: 100% !important;
margin: 0 !important;
overflow-x: hidden;
}
.msg_list {
max-width: 100% !important;
padding-bottom: 0 !important;
margin: 0 !important;
}
}
</style>
<style lang="less" src="@/components/css/wiki-graph-drawer.less"></style>

View File

@ -53,7 +53,8 @@ async function fixture() {
if (name === 'vue' || name === 'marked') return require(name)
if (name === 'vue-router') return { useRouter: () => ({}), useRoute: () => ({ query: {} }) }
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
if (name === '@/stores/menu') return { useMenuStore: () => ({}) }
if (name === '@/stores/assistant') return { useAssistantStore: () => ({ visible: false }) }
if (name === '@/composables/useAssistantPageContext') return { useAssistantPageContext() {} }
if (name === '@/stores/settings') return { useSettingsStore: () => ({}) }
if (name === '@/api/wiki') return api
if (name === 'tdesign-vue-next') return { MessagePlugin: { success() {}, error() {} } }

View File

@ -11,6 +11,8 @@
<Settings />
<!-- 全局命令面板 (⌘K),随 platform 路由存活 -->
<GlobalCommandPalette />
<!-- WeKnora 助手抽屉:跨页面保留会话,从侧栏或命令面板唤出 -->
<AssistantDrawer />
<!-- 全局右上角"待处理邀请"铃铛。固定定位,z-index 低于抽屉,业务页面
右侧抽屉弹出时会自然覆盖;仅在有待处理邀请时渲染。 -->
<GlobalInvitationBell />
@ -27,6 +29,7 @@ import { useRoute, useRouter } from 'vue-router'
import UploadMask from '@/components/upload-mask.vue'
import Settings from '@/views/settings/Settings.vue'
import GlobalCommandPalette from '@/components/GlobalCommandPalette.vue'
import AssistantDrawer from '@/components/assistant/AssistantDrawer.vue'
import GlobalInvitationBell from '@/components/GlobalInvitationBell.vue'
import UploadTasksPanel from '@/components/upload-tasks/UploadTasksPanel.vue'
import NewUserGuide from '@/components/NewUserGuide.vue'