diff --git a/frontend/src/api/chat/streame.test.ts b/frontend/src/api/chat/streame.test.ts index f0226024..204986c8 100644 --- a/frontend/src/api/chat/streame.test.ts +++ b/frontend/src/api/chat/streame.test.ts @@ -40,6 +40,23 @@ after(async () => { else Reflect.deleteProperty(globalThis, 'localStorage') }) +for (const effort of [undefined, '', 'off', 'auto', 'high', 'max']) { + test(`SSE body carries only explicit reasoning overrides: ${effort}`, async () => { + let stream!: ReturnType + await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } })) + try { + await stream.startStream({ + session_id: 'session', query: 'question', method: 'POST', url: '/api/v1/agent-chat', + reasoning_effort: effort, + }) + assert.equal(stream.error.value, null) + const body = JSON.parse(transport.requests.at(-1)!.options.body) + assert.equal(body.reasoning_effort, effort || undefined) + assert.equal(Object.hasOwn(body, 'reasoning_effort'), !!effort) + } finally { stream.stopStream() } + }) +} + for (const selected of [true, false, undefined]) { test(`SSE HTTP body preserves browser selection ${selected} alongside other tools`, async () => { let stream!: ReturnType diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts index eccd3b69..8590b4a0 100644 --- a/frontend/src/api/chat/streame.ts +++ b/frontend/src/api/chat/streame.ts @@ -40,7 +40,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; 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 }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => { const myGeneration = ++streamGeneration const streamAbort = controller // 重置状态 @@ -119,6 +119,10 @@ export function useStream() { if (params.summary_model_id) { postBody.summary_model_id = params.summary_model_id; } + // Omit inheritance so the agent's current default remains authoritative. + if (params.reasoning_effort) { + postBody.reasoning_effort = params.reasoning_effort; + } // Include mcp_service_ids if provided (for Agent mode) if (params.mcp_service_ids !== undefined && params.mcp_service_ids.length > 0) { postBody.mcp_service_ids = params.mcp_service_ids; diff --git a/frontend/src/components/Input-field.reasoning.test.ts b/frontend/src/components/Input-field.reasoning.test.ts new file mode 100644 index 00000000..24a0fca6 --- /dev/null +++ b/frontend/src/components/Input-field.reasoning.test.ts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' +import test from 'node:test' +import ts from 'typescript' +import { computed, effectScope, reactive, ref, watch } from 'vue' +import { supportedLevels, levelLabelKey, levelFromLegacy, clampLevel } from '../utils/reasoningEffort' + +const source = readFileSync(new URL('./Input-field.vue', import.meta.url), 'utf8') +const start = source.indexOf('const selectedModel = computed(') +const end = source.indexOf('// 模型展示名', start) +assert.ok(start > 0 && end > start) +const compiled = ts.transpileModule(source.slice(start, end), { + compilerOptions: { target: ts.ScriptTarget.ES2022 }, +}).outputText + +function fixture() { + const availableModels = ref([]) + const selectedModelId = ref('model-a') + const settingsStore = reactive({ reasoningEffortOverride: '', _isApplyingSessionState: false }) + const currentAgentConfig = ref({ thinking: true, reasoning_effort: 'high' }) + const scope = effectScope() + const output: any = {} + scope.run(() => runInNewContext(compiled + '\nObject.assign(output, { reasoningLevels, displayedReasoningLevel, selectReasoningLevel });', { + computed, ref, watch, supportedLevels, levelLabelKey, levelFromLegacy, clampLevel, currentAgentConfig, availableModels, selectedModelId, settingsStore, output, t: (key: string) => key, + })) + return { availableModels, selectedModelId, settingsStore, currentAgentConfig, ...output, close: () => scope.stop() } +} + +test('composer reasoning follows model capabilities and discards incompatible overrides', () => { + const f = fixture() + try { + assert.equal(f.reasoningLevels.value.length, 0, 'unknown model hides reasoning') + f.availableModels.value = [ + { id: 'model-a', capabilities: { thinking_levels: ['off', 'auto', 'low', 'high'] } }, + { id: 'model-b', capabilities: { thinking_levels: ['auto', 'medium', 'max'] } }, + { id: 'model-c', capabilities: { thinking_levels: [] } }, + ] + assert.deepEqual(Array.from(f.reasoningLevels.value), ['off', 'auto', 'low', 'high']) + assert.equal(f.displayedReasoningLevel.value, 'high') + assert.equal(f.settingsStore.reasoningEffortOverride, '', 'agent default stays inherited') + f.settingsStore.reasoningEffortOverride = 'high' + f.selectedModelId.value = 'model-b' + assert.equal(f.settingsStore.reasoningEffortOverride, '') + assert.deepEqual(Array.from(f.reasoningLevels.value), ['auto', 'medium', 'max'], 'always-on models offer no Off') + f.settingsStore.reasoningEffortOverride = 'auto' + f.selectedModelId.value = 'model-a' + assert.equal(f.settingsStore.reasoningEffortOverride, 'auto', 'supported choices survive a model switch') + f.selectedModelId.value = 'model-c' + assert.equal(f.reasoningLevels.value.length, 0) + assert.equal(f.settingsStore.reasoningEffortOverride, '') + } finally { f.close() } +}) + +test('session restoration waits for model data and does not validate against the previous session model', () => { + const f = fixture() + try { + f.settingsStore.reasoningEffortOverride = 'high' + assert.equal(f.settingsStore.reasoningEffortOverride, 'high') + f.availableModels.value = [{ id: 'model-a', capabilities: { thinking_levels: ['auto', 'high'] } }] + assert.equal(f.settingsStore.reasoningEffortOverride, 'high') + f.settingsStore._isApplyingSessionState = true + f.settingsStore.reasoningEffortOverride = 'max' + f.availableModels.value.push({ id: 'model-b', capabilities: { thinking_levels: ['auto', 'max'] } }) + f.selectedModelId.value = 'model-b' + f.settingsStore._isApplyingSessionState = false + assert.equal(f.settingsStore.reasoningEffortOverride, 'max') + } finally { f.close() } +}) + +test('default displays the agent level without sending an override, and selection can restore inheritance', () => { + const f = fixture() + try { + f.availableModels.value = [{ id: 'model-a', capabilities: { thinking_levels: ['off', 'auto', 'low', 'high'] } }] + assert.equal(f.displayedReasoningLevel.value, 'high') + assert.equal(f.settingsStore.reasoningEffortOverride, '') + f.currentAgentConfig.value = { thinking: true, reasoning_effort: 'low' } + assert.equal(f.displayedReasoningLevel.value, 'low') + f.selectReasoningLevel('high') + assert.equal(f.settingsStore.reasoningEffortOverride, 'high') + assert.equal(f.displayedReasoningLevel.value, 'high') + f.selectReasoningLevel('low') + assert.equal(f.settingsStore.reasoningEffortOverride, '') + f.currentAgentConfig.value = { thinking: false, reasoning_effort: '' } + assert.equal(f.displayedReasoningLevel.value, 'off', 'legacy boolean still supplies the default') + f.currentAgentConfig.value.thinking = true + assert.equal(f.displayedReasoningLevel.value, 'auto') + } finally { f.close() } +}) diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 51285d8f..64f1e12e 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -52,6 +52,7 @@ import { } from '@/utils/agent-readiness'; import { formatLocalizedList } from '@/utils/format-list'; import { SKILL_ICON, type MentionItem, type MentionItemType, type MentionRequestItem } from '@/types/mention'; +import { supportedLevels, levelLabelKey, levelFromLegacy, clampLevel, type ReasoningLevel } from '@/utils/reasoningEffort'; const route = useRoute(); const router = useRouter(); @@ -1098,6 +1099,28 @@ const selectedModel = computed(() => { return availableModels.value.find(model => model.id === selectedModelId.value); }); +const reasoningLevels = computed(() => supportedLevels(selectedModel.value?.capabilities)); +const agentReasoningLevel = computed(() => clampLevel( + levelFromLegacy(currentAgentConfig.value?.thinking, currentAgentConfig.value?.reasoning_effort), + reasoningLevels.value, +)); +// Show the effective level while leaving the request unset until the user +// chooses a different level. Selecting the agent's level restores inheritance. +const displayedReasoningLevel = computed(() => settingsStore.reasoningEffortOverride || agentReasoningLevel.value); +const showReasoningSelector = ref(false); +const selectReasoningLevel = (level: ReasoningLevel) => { + settingsStore.reasoningEffortOverride = level === agentReasoningLevel.value ? '' : level; + showReasoningSelector.value = false; +}; +watch([selectedModel, reasoningLevels, () => settingsStore.reasoningEffortOverride, () => settingsStore._isApplyingSessionState], () => { + // Wait for model resources during session restoration. Once known, an + // unsupported override returns to inheritance instead of inventing a level. + if (!settingsStore._isApplyingSessionState && selectedModel.value && settingsStore.reasoningEffortOverride + && !reasoningLevels.value.includes(settingsStore.reasoningEffortOverride)) { + settingsStore.reasoningEffortOverride = ''; + } +}, { immediate: true, flush: 'sync' }); + // 模型展示名:本空间列表中有则用名称;若为共享智能体且其 model_id 不在本空间列表中则显示“共享智能体配置的模型” const selectedModelDisplayName = computed(() => { if (selectedModel.value) return modelDisplayName(selectedModel.value); @@ -1789,6 +1812,7 @@ const removeFile = (id: string) => { }; const toggleModelSelector = () => { + showReasoningSelector.value = false; // 如果智能体锁定了模型,不允许打开选择器 if (isModelLockedByAgent.value) { MessagePlugin.warning(t('input.modelLockedByAgent')); @@ -1821,6 +1845,13 @@ const closeModelSelector = () => { showModelSelector.value = false; }; +const handleReasoningVisibleChange = (visible: boolean) => { + if (!visible) return; + closeModelSelector(); + showMention.value = false; + showAgentModeSelector.value = false; +}; + // 关闭 Agent 模式选择器(点击外部) const closeAgentModeSelector = () => { showAgentModeSelector.value = false; @@ -2885,6 +2916,34 @@ defineExpose({ + + + + @@ -3736,6 +3795,58 @@ const getImgSrc = (url: string) => { } /* 模型显示样式 */ +.model-selector-trigger.reasoning-effort-trigger { + flex-shrink: 0; + min-width: 0; + box-sizing: content-box; + background: transparent; + font: inherit; +} + +.reasoning-effort-menu { + min-width: 120px; + display: flex; + flex-direction: column; + gap: 2px; +} + +.reasoning-effort-title { + padding: 6px 8px; + margin-bottom: 2px; + border-bottom: .5px solid var(--td-component-stroke); + color: var(--td-text-color-secondary); + font-size: var(--app-text-sm); + font-weight: 500; + line-height: 20px; +} + +.reasoning-effort-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + min-height: 30px; + padding: 4px 8px; + border: 0; + border-radius: var(--app-radius-sm); + background: transparent; + color: var(--td-text-color-secondary); + font: inherit; + font-size: var(--app-text-sm); + line-height: 20px; + text-align: left; + cursor: pointer; + + &:hover, &:focus-visible { + background: var(--td-bg-color-secondarycontainer-hover); + } + + &.selected { + background: var(--td-bg-color-secondarycontainer); + color: var(--td-brand-color); + } +} + .model-display { display: flex; align-items: center; diff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vue index de2ea533..8c468dad 100644 --- a/frontend/src/components/ModelEditorDialog.vue +++ b/frontend/src/components/ModelEditorDialog.vue @@ -333,7 +333,7 @@ :meta="credentialMeta" @changed="invalidateConnectionTest()" /> + class="api-key-input" autocomplete="new-password" spellcheck="false">

{{ apiKeyHint }}

@@ -346,7 +346,7 @@
+ :placeholder="secretExtraField.placeholder || ''" autocomplete="new-password" spellcheck="false">

{{ secretExtraField.placeholder }}

@@ -370,7 +370,7 @@ type="number" :placeholder="extraFieldDisplayPlaceholder(field)" @update:model-value="(v: string | number) => setExtraConfig(field.key, String(v ?? ''))" /> @@ -639,6 +639,7 @@ import CredentialResource, { type CredentialResourceApi, } from '@/components/credentials/CredentialResource.vue' import { shouldShowOllamaUnavailableTip } from '@/components/modelEditorSourceState' +import { WEKNORA_CLOUD_PROVIDER, WKC_MODEL_KINDS, WKC_MODEL_NAME_BY_KIND } from '@/utils/weknoraCloudModels' interface CustomHeaderItem { key: string @@ -879,12 +880,23 @@ interface CatalogModelOption { } const catalogEntries = computed(() => { + const entries = selectedProvider.value?.models || [] + // Managed aliases are already used by the cloud setup page. They have no + // published limits, so the backend catalog is empty, but they can still be + // offered by name without inventing context windows or embedding dimensions. + if (formData.value.provider === WEKNORA_CLOUD_PROVIDER && entries.length === 0) { + const kind = WKC_MODEL_KINDS.find(kind => kind === activeModelType.value) + if (kind) { + const name = WKC_MODEL_NAME_BY_KIND[kind] + return [{ id: name, name, type: kind === 'vllm' ? 'chat' : kind, input: kind === 'vllm' ? ['text', 'image'] : ['text'] }] + } + } // The list is already scoped: providers are fetched per model type, so the // backend returned exactly the entries that type can use. Filtering again // here on entry.type was wrong for 视觉 — a VLM entry is a chat model that // accepts images, so it arrives typed "chat" and every one of them was // dropped, leaving the picker empty for every vendor. - return selectedProvider.value?.models || [] + return entries }) const catalogModelOptions = computed(() => { diff --git a/frontend/src/components/ResourceListToolbar.vue b/frontend/src/components/ResourceListToolbar.vue index 02131887..18b41de2 100644 --- a/frontend/src/components/ResourceListToolbar.vue +++ b/frontend/src/components/ResourceListToolbar.vue @@ -86,7 +86,7 @@ onMounted(() => { if (!props.hideScopes) orgStore.fetchOrganizations() }) min-width: 0; } .category-tabs { .artifact-filter-tabs(); } -.scope-count { margin-left: 5px; font-size: var(--app-text-xs); opacity: 0.65; font-variant-numeric: tabular-nums; } +.scope-count { margin-left: 5px; font-size: var(--app-text-xs); font-variant-numeric: tabular-nums; } .space-filter { width: 180px; } .space-filter-icon-active { color: var(--td-brand-color); } .search-input { width: 260px; max-width: 100%; margin-left: auto; } diff --git a/frontend/src/components/modelEditorFlow.test.ts b/frontend/src/components/modelEditorFlow.test.ts index ffa68ac2..bb6c1679 100644 --- a/frontend/src/components/modelEditorFlow.test.ts +++ b/frontend/src/components/modelEditorFlow.test.ts @@ -82,6 +82,8 @@ async function fixture(options: { } }, } if (name === '@/stores/modelProviders') return { useModelProvidersStore: () => providersStore } + if (name === '@/api/model') return { getWeKnoraCloudStatus: async () => ({ has_models: true, needs_reinit: false }) } + if (name === '@/utils/weknoraCloudModels') return require('../utils/weknoraCloudModels.ts') if (name === '@/stores/modelProvidersState') return require('../stores/modelProvidersState.ts') if (name === '@/utils/reasoningEffort') return require('../utils/reasoningEffort.ts') if (name === '@/utils/contextWindow') return require('../utils/contextWindow.ts') @@ -767,6 +769,49 @@ test('the vision picker lists the vendor models the backend scoped to it', async } finally { f.close() } }) +const cloudProvider = { + value: 'weknoracloud', label: 'WeKnora Cloud', description: '', order: 1, + modelTypes: ['chat', 'embedding', 'rerank', 'vllm'], + defaultUrls: Object.fromEntries(['chat', 'embedding', 'rerank', 'vllm'].map(type => [type, 'https://weknora.weixin.qq.com'])), + models: [], +} + +for (const [type, modelName] of [['chat', 'chat'], ['embedding', 'embedding'], ['rerank', 'rerank'], ['vllm', 'vlm']]) { + test(`WeKnora Cloud ${type}: an empty catalog still offers the managed model`, async () => { + const f = await fixture({ type, providers: [cloudProvider] }) + try { + f.vm.formData.provider = 'weknoracloud' + f.vm.handleProviderChange('weknoracloud') + await nextTick() + await f.vm.checkWkcCredentialStatus() + assert.equal(f.vm.wkcCredentialState, 'configured') + assert.deepEqual(Array.from(f.vm.catalogModelOptions, (o: any) => o.value), [modelName]) + assert.equal(f.vm.catalogModelOptions[0].vision, type === 'vllm') + f.vm.formData.modelName = modelName + f.vm.handleCatalogModelChange(modelName) + await nextTick() + await f.vm.checkRemoteAPI() + assert.equal(f.requests[0].modelName, modelName) + assert.equal(f.requests[0].provider, 'weknoracloud') + assert.equal(f.vm.formData.contextWindow, undefined) + assert.equal(f.vm.formData.dimension, undefined) + } finally { f.close() } + }) +} + +test('switching WeKnora Cloud model types updates the managed choices', async () => { + const f = await fixture({ providers: [cloudProvider] }) + try { + f.vm.formData.provider = 'weknoracloud' + f.vm.handleProviderChange('weknoracloud') + await nextTick() + f.vm.formData.modelName = 'chat' + await f.vm.selectModelType('vllm') + assert.equal(f.vm.formData.modelName, '') + assert.deepEqual(Array.from(f.vm.catalogModelOptions, (o: any) => o.value), ['vlm']) + } finally { f.close() } +}) + test('rerank and asr pickers list their own entries', async () => { for (const [type, id] of [['rerank', 'the-reranker'], ['asr', 'the-transcriber']]) { const providers = [{ diff --git a/frontend/src/stores/browserSource.test.ts b/frontend/src/stores/browserSource.test.ts index 97d9224d..a374c124 100644 --- a/frontend/src/stores/browserSource.test.ts +++ b/frontend/src/stores/browserSource.test.ts @@ -46,6 +46,32 @@ test('browser and web search selections are independent and persisted', () => { assert.equal(store.isLocalBrowserEnabled, false) assert.equal(store.settings.webSearchEnabled, true) }) + +test('reasoning overrides belong to the session, restore on reload and never become global defaults', () => { + items.clear() + const store = useSettingsStore(createPinia()) + assert.equal(store.reasoningEffortOverride, '') + store.reasoningEffortOverride = 'high' + store.toggleWebSearch(true) + assert.equal(JSON.stringify(JSON.parse(items.get('WeKnora_settings')!)).includes('high'), false) + store.hydrateSessionInputState({}, true) + assert.equal(store.reasoningEffortOverride, 'high', 'first send keeps the createChat choice') + store.restoreDefaultsIfSnapshotted() + assert.equal(store.reasoningEffortOverride, '', 'leaving even a new session clears the choice') + store.hydrateSessionInputState({ reasoning_effort: 'off' }) + assert.equal(store.reasoningEffortOverride, 'off') + store.restoreDefaultsIfSnapshotted() + assert.equal(store.reasoningEffortOverride, '') + store.applyLastRequestState({ reasoning_effort: 'max' }) + assert.equal(store.reasoningEffortOverride, 'max') + store.applyLastRequestState({}) + assert.equal(store.reasoningEffortOverride, '', 'old sessions inherit') + store.applyLastRequestState({ reasoning_effort: 'unsupported' }) + assert.equal(store.reasoningEffortOverride, '') + store.reasoningEffortOverride = 'high' + store.selectAgent('another-agent') + assert.equal(store.reasoningEffortOverride, '') +}) test('session restore follows saved browser choice and clears it for older sessions', () => { const store = useSettingsStore(createPinia()) store.applyLastRequestState({ local_browser_enabled: true, web_search_enabled: true }) diff --git a/frontend/src/stores/settings.ts b/frontend/src/stores/settings.ts index 684f7702..41aa0751 100644 --- a/frontend/src/stores/settings.ts +++ b/frontend/src/stores/settings.ts @@ -4,6 +4,7 @@ import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent import { getApiBaseUrl } from "@/utils/api-base"; import { isAgentStreamAgentId } from "@/utils/agent-mode"; import { loadAndReconcileSettings } from "@/stores/settingsStorage"; +import { isReasoningLevel, type ReasoningLevel } from "@/utils/reasoningEffort"; // 定义设置接口 interface Settings { @@ -119,6 +120,8 @@ export const useSettingsStore = defineStore("settings", { _defaultsSnapshot: null as Settings | null, /** 正在从 session.last_request_state 恢复输入栏,避免 agent 切换 watch 覆盖 KB 选择 */ _isApplyingSessionState: false, + // Session-only preference: never written into global settings/localStorage. + reasoningEffortOverride: '' as ReasoningLevel | '', }), getters: { @@ -456,6 +459,7 @@ export const useSettingsStore = defineStore("settings", { // 选择智能体(sourceTenantId 仅在使用共享智能体时传入) selectAgent(agentId: string, sourceTenantId?: string | null) { + this.reasoningEffortOverride = ''; this.settings.selectedAgentId = agentId; this.settings.selectedAgentSourceTenantId = (sourceTenantId != null && sourceTenantId !== "") ? sourceTenantId : null; // 智能体配置只决定是否具备网络搜索能力,不替用户决定是否在本轮使用。 @@ -504,6 +508,7 @@ export const useSettingsStore = defineStore("settings", { // 还原默认(如果有快照),用于离开会话或跨会话切换时。 restoreDefaultsIfSnapshotted() { + this.reasoningEffortOverride = ''; if (!this._defaultsSnapshot) return; this.settings = this._defaultsSnapshot; this._defaultsSnapshot = null; @@ -526,6 +531,7 @@ export const useSettingsStore = defineStore("settings", { if (!state) return; this._isApplyingSessionState = true; try { + this.reasoningEffortOverride = isReasoningLevel(state.reasoning_effort) ? state.reasoning_effort : ''; if (typeof state.agent_enabled === "boolean") { this.settings.isAgentEnabled = state.agent_enabled; } @@ -601,6 +607,7 @@ export const useSettingsStore = defineStore("settings", { // 后端 sessions.last_request_state JSON 形状(与 SessionLastRequestState 对齐)。 // 字段全部可选——历史会话或新建会话首发前的请求没有这条记录。 export interface SessionLastRequestStatePayload { + reasoning_effort?: string; agent_id?: string; agent_enabled?: boolean; model_id?: string; diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 6d71a099..b5cbe91c 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -566,9 +566,11 @@ const isFirstEnter = ref(true); const loading = ref(false); const sessionActivity = useSessionActivityStore(); const activitySessionId = ref(''); -watch([activitySessionId, isReplying, isStreaming, isImRecovering, currentAssistantMessageId], () => { +watch([activitySessionId, isReplying, isImRecovering, currentAssistantMessageId], () => { if (props.embeddedMode || !activitySessionId.value) return; - sessionActivity.update(activitySessionId.value, isReplying.value || isStreaming.value || isImRecovering.value, currentAssistantMessageId.value); + // SSE may stay connected after a stop/complete event. The sidebar tracks + // generation, not the transport, just like the composer's Stop button. + sessionActivity.update(activitySessionId.value, isReplying.value || isImRecovering.value, currentAssistantMessageId.value); }, { flush: 'sync' }); const historyLoading = ref(true); const historyLoadingMore = ref(false); @@ -948,7 +950,7 @@ const { const lastMessage = findLastMessage( (message) => message.role === 'assistant' && !message.is_completed ); - const locallyRunning = isReplying.value || isStreaming.value || isImRecovering.value; + const locallyRunning = isReplying.value || isImRecovering.value; // History reload can finish after sendMsg already marked this session // running. Do not clear that marker just because the snapshot's last // message still looks completed. A scanned incomplete assistant counts: a @@ -1367,6 +1369,7 @@ const attachSteerFollowUp = async (completedAssistantId) => { const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [], attachmentFiles = [], options = {}) => { if (composerLocked.value) return + const reasoningEffort = props.embeddedMode ? undefined : (useSettingsStoreInstance.reasoningEffortOverride || undefined); stopStream(); prepareForNewOutgoingMessage(); activitySessionId.value = String(session_id.value); @@ -1536,6 +1539,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [] web_search_enabled: webSearchEnabled, local_browser_enabled: !props.embeddedMode && agentEnabled && useSettingsStoreInstance.isLocalBrowserEnabled && !useBrowserConnectionStore().knownOffline, summary_model_id: modelId, + reasoning_effort: reasoningEffort, mcp_service_ids: requestMcpServiceIds, skill_names: requestSkillNames, tag_ids: tagIds, diff --git a/frontend/src/views/chat/sessionActivity.test.ts b/frontend/src/views/chat/sessionActivity.test.ts new file mode 100644 index 00000000..cee5d987 --- /dev/null +++ b/frontend/src/views/chat/sessionActivity.test.ts @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' +import test from 'node:test' +import { effectScope, reactive, ref, watch } from 'vue' +import { createSessionActivityState, type SessionActivity } from '../../stores/sessionActivityState' + +const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8') +const start = source.indexOf('watch([activitySessionId,') +const end = source.indexOf('const historyLoading =', start) +assert.ok(start > 0 && end > start) + +function fixture() { + const entries = reactive>({}) + const sessionActivity = createSessionActivityState(entries, async () => []) + const refs = { + activitySessionId: ref('session-a'), isReplying: ref(false), isStreaming: ref(false), + isImRecovering: ref(false), currentAssistantMessageId: ref('reply-a'), + } + const scope = effectScope() + scope.run(() => runInNewContext(source.slice(start, end), { ...refs, sessionActivity, watch, props: { embeddedMode: false } })) + return { ...refs, entries, sessionActivity, close: () => scope.stop() } +} + +test('a terminal reply clears the sidebar even while its SSE connection remains open', () => { + const f = fixture() + try { + f.isReplying.value = true + f.isStreaming.value = true + assert.ok(f.entries['session-a']) + f.isReplying.value = false + f.currentAssistantMessageId.value = '' + assert.equal(f.entries['session-a'], undefined) + f.isStreaming.value = false + f.isStreaming.value = true + assert.equal(f.entries['session-a'], undefined, 'transport changes cannot restart the turn indicator') + } finally { f.close() } +}) + +test('generation remains active during connection setup and IM recovery', () => { + const f = fixture() + try { + f.isReplying.value = true + assert.ok(f.entries['session-a'], 'waiting for headers still counts as generating') + f.isReplying.value = false + f.isImRecovering.value = true + assert.ok(f.entries['session-a'], 'IM polling counts as active without an SSE connection') + f.isImRecovering.value = false + assert.equal(f.entries['session-a'], undefined) + } finally { f.close() } +}) + +test('stopping the current conversation does not clear a detached conversation', () => { + const f = fixture() + try { + f.isReplying.value = true + f.sessionActivity.detach('session-a') + f.activitySessionId.value = '' + f.isReplying.value = false + assert.equal(f.entries['session-a']?.detached, true) + f.activitySessionId.value = 'session-b' + f.isReplying.value = true + f.isStreaming.value = true + f.isReplying.value = false + assert.equal(f.entries['session-b'], undefined) + assert.ok(f.entries['session-a']) + f.isReplying.value = true + assert.ok(f.entries['session-b'], 'a new turn starts the indicator again') + } finally { f.close() } +}) diff --git a/frontend/src/views/creatChat/creatChat.vue b/frontend/src/views/creatChat/creatChat.vue index c11fa170..6f8ddfd8 100644 --- a/frontend/src/views/creatChat/creatChat.vue +++ b/frontend/src/views/creatChat/creatChat.vue @@ -83,7 +83,7 @@ import { useMenuStore } from '@/stores/menu'; import { useSettingsStore } from '@/stores/settings'; import { useUIStore } from '@/stores/ui'; import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'; -import { useRoute, useRouter } from 'vue-router'; +import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'; import { MessagePlugin } from 'tdesign-vue-next'; import { useI18n } from 'vue-i18n'; import KnowledgeBaseEditorModal from '@/views/knowledge/KnowledgeBaseEditorModal.vue'; @@ -93,6 +93,13 @@ const router = useRouter(); const route = useRoute(); const usemenuStore = useMenuStore(); const settingsStore = useSettingsStore(); +onBeforeRouteLeave((to) => { + // The first send carries the draft into its new session; abandoning the + // composer must not make this a default for the next conversation. + if (!to.path.startsWith('/platform/chat/') || !usemenuStore.isFirstSession) { + settingsStore.reasoningEffortOverride = ''; + } +}); const uiStore = useUIStore(); const deploymentCapabilities = useDeploymentCapabilitiesStore(); const { t } = useI18n(); @@ -485,4 +492,4 @@ async function openProjectDir() { } } - \ No newline at end of file + diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vue index 7e8f9203..48955db6 100644 --- a/frontend/src/views/knowledge/KnowledgeBaseList.vue +++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue @@ -220,7 +220,7 @@ placement="top">
- + {{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }} @@ -297,7 +297,7 @@ placement="top">
- + {{ kb.type === 'faq' ? (kb.chunk_count || '-') : (kb.knowledge_count || '-') }} @@ -451,7 +451,7 @@ placement="top">
- + {{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }} @@ -577,7 +577,7 @@ placement="top">
- {{ shared.knowledge_base.type === 'faq' ? (shared.knowledge_base.chunk_count ?? diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go index 9eaad9d5..e546ee86 100644 --- a/internal/application/service/session_agent_qa.go +++ b/internal/application/service/session_agent_qa.go @@ -344,6 +344,7 @@ func (s *sessionService) buildAgentConfig( RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory, SharedAgentReadOnly: req.SharedAgentReadOnly, } + applyRequestReasoningEffort(req.ReasoningEffort, &agentConfig.Thinking, &agentConfig.ReasoningEffort) // An unset MCP mode means "all" at runtime, but the share scope and the // agent UI both present it as none. A shared run must not hand receivers // every MCP service (with the owner's credentials) that its owner believes diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go index d9bdc162..2c468c5b 100644 --- a/internal/application/service/session_knowledge_qa.go +++ b/internal/application/service/session_knowledge_qa.go @@ -171,6 +171,9 @@ func (s *sessionService) KnowledgeQA( // Apply custom agent overrides (system prompt, temperature, retrieval params, // rewrite, fallback, FAQ strategy, history turns) s.applyAgentOverridesToChatManage(ctx, req.CustomAgent, chatManage) + applyRequestReasoningEffort( + req.ReasoningEffort, &chatManage.SummaryConfig.Thinking, &chatManage.SummaryConfig.ReasoningEffort, + ) // An agent may opt out of long-term memory. The preference is per-request // rather than per-user, so it travels in the context that the recall diff --git a/internal/application/service/session_qa_helpers.go b/internal/application/service/session_qa_helpers.go index 11484b82..f06a6be3 100644 --- a/internal/application/service/session_qa_helpers.go +++ b/internal/application/service/session_qa_helpers.go @@ -7,10 +7,23 @@ import ( "strings" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/models/api" "github.com/Tencent/WeKnora/internal/types" secutils "github.com/Tencent/WeKnora/internal/utils" ) +// applyRequestReasoningEffort only changes runtime options, never the saved agent. +// Empty requests preserve both the graded default and legacy Thinking boolean. +func applyRequestReasoningEffort(override string, thinking **bool, effort *string) { + level, ok := api.ParseReasoningEffort(override) + if !ok || level == "" { + return + } + enabled := level.Enabled() + *thinking = &enabled + *effort = string(level) +} + // --------------------------------------------------------------------------- // Shared QA helpers: KB resolution, model resolution, retrieval tenant // --------------------------------------------------------------------------- diff --git a/internal/application/service/session_reasoning_effort_test.go b/internal/application/service/session_reasoning_effort_test.go new file mode 100644 index 00000000..56c31b62 --- /dev/null +++ b/internal/application/service/session_reasoning_effort_test.go @@ -0,0 +1,55 @@ +package service + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +func TestRequestReasoningEffortPrecedence(t *testing.T) { + for _, tc := range []struct { + override, want string + enabled bool + }{ + {"", "high", true}, {"off", "off", false}, {"auto", "auto", true}, {"max", "max", true}, + } { + t.Run("override="+tc.override, func(t *testing.T) { + enabled := true + agent := &types.CustomAgent{Config: types.CustomAgentConfig{ + Thinking: &enabled, ReasoningEffort: "high", WebSearchProviderID: "provider", + }} + svc := newTagTargetSessionService() + req := &types.QARequest{ + Session: &types.Session{ID: "session", TenantID: 100}, + CustomAgent: agent, ReasoningEffort: tc.override, + } + cfg, err := svc.buildAgentConfig(tagTargetContext(), req, &types.Tenant{ID: 100}, 100) + require.NoError(t, err) + require.Equal(t, tc.want, cfg.ReasoningEffort) + require.NotNil(t, cfg.Thinking) + require.Equal(t, tc.enabled, *cfg.Thinking) + require.Equal(t, "high", agent.Config.ReasoningEffort) + require.True(t, *agent.Config.Thinking, "runtime override must not mutate the agent") + + // The RAG pipeline starts with the agent defaults and applies the same + // request override to its summary options. + cm := &types.ChatManage{} + svc.applyAgentOverridesToChatManage(tagTargetContext(), agent, cm) + applyRequestReasoningEffort( + req.ReasoningEffort, &cm.SummaryConfig.Thinking, &cm.SummaryConfig.ReasoningEffort, + ) + require.Equal(t, tc.want, cm.SummaryConfig.ReasoningEffort) + require.Equal(t, tc.enabled, *cm.SummaryConfig.Thinking) + }) + } +} + +func TestRequestReasoningEffortPreservesLegacyDefaults(t *testing.T) { + for _, original := range []*bool{nil, new(bool)} { + thinking, effort := original, "" + applyRequestReasoningEffort("", &thinking, &effort) + require.True(t, original == thinking) + require.Empty(t, effort) + } +} diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 8c49eb53..46b7a2aa 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -19,6 +19,7 @@ import ( "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/models/api" "github.com/Tencent/WeKnora/internal/sandbox" "github.com/Tencent/WeKnora/internal/storageurl" "github.com/Tencent/WeKnora/internal/stream" @@ -53,6 +54,7 @@ type qaRequestContext struct { mcpServiceIDs []string skillNames []string summaryModelID string + reasoningEffort string localBrowserEnabled bool webSearchEnabled bool mentionedItems types.MentionedItems @@ -107,6 +109,7 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest { Query: rc.query, AssistantMessageID: rc.assistantMessage.ID, SummaryModelID: rc.summaryModelID, + ReasoningEffort: rc.reasoningEffort, CustomAgent: rc.customAgent, SharedAgentReadOnly: rc.sharedAgentReadOnly, KnowledgeBaseIDs: rc.knowledgeBaseIDs, @@ -151,6 +154,14 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo return nil, nil, errors.NewBadRequestError(err.Error()) } + level, validEffort := api.ParseReasoningEffort(request.ReasoningEffort) + if !validEffort { + return nil, nil, errors.NewBadRequestError( + fmt.Sprintf("reasoning_effort must be one of %v", api.AllReasoningEfforts), + ) + } + request.ReasoningEffort = string(level) + // Validate syntax before session lookup or QA work, preserving the original // query text. KnowledgeQA applies its XSS-pattern check later in the chat // pipeline; AgentQA must allow frontend code in conversation text. @@ -431,6 +442,7 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo mcpServiceIDs: secutils.SanitizeForLogArray(mcpServiceIDs), skillNames: secutils.SanitizeForLogArray(skillNames), summaryModelID: secutils.SanitizeForLog(request.SummaryModelID), + reasoningEffort: request.ReasoningEffort, webSearchEnabled: request.WebSearchEnabled, localBrowserEnabled: request.LocalBrowserEnabled, mentionedItems: convertMentionedItems(request.MentionedItems), @@ -1765,6 +1777,7 @@ func (h *Handler) persistLastRequestState(parentCtx context.Context, reqCtx *qaR AgentID: reqCtx.reqAgentID, AgentEnabled: agentEnabled, ModelID: reqCtx.summaryModelID, + ReasoningEffort: reqCtx.reasoningEffort, KnowledgeBaseIDs: reqCtx.knowledgeBaseIDs, KnowledgeIDs: reqCtx.knowledgeIDs, TagIDs: reqCtx.tagIDs, diff --git a/internal/handler/session/qa_reasoning_effort_test.go b/internal/handler/session/qa_reasoning_effort_test.go new file mode 100644 index 00000000..531b6021 --- /dev/null +++ b/internal/handler/session/qa_reasoning_effort_test.go @@ -0,0 +1,78 @@ +package session + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestQAReasoningEffortValidation(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"knowledge-chat", "agent-chat"} { + for _, effort := range []string{"", "off", "auto", "high", "max", "unknown"} { + t.Run(endpoint+"/"+effort, func(t *testing.T) { + sessions := &queryValidationSessionStub{} + h := &Handler{sessionService: sessions} + router := gin.New() + router.Use(middleware.ErrorHandler()) + router.POST("/knowledge-chat/:session_id", h.KnowledgeQA) + router.POST("/agent-chat/:session_id", h.AgentQA) + body, err := json.Marshal(CreateKnowledgeQARequest{Query: "question", ReasoningEffort: effort}) + require.NoError(t, err) + request := httptest.NewRequest(http.MethodPost, "/"+endpoint+"/session", bytes.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if effort == "unknown" { + require.Equal(t, http.StatusBadRequest, response.Code) + require.Contains(t, response.Body.String(), "reasoning_effort") + require.Zero(t, sessions.lookupCalls) + } else { + require.Equal(t, 1, sessions.lookupCalls) + } + }) + } + } +} + +type reasoningSessionStub struct { + interfaces.SessionService + state *types.SessionLastRequestState +} + +func (s *reasoningSessionStub) UpdateSessionLastRequestState( + _ context.Context, _ string, state *types.SessionLastRequestState, +) error { + s.state = state + return nil +} + +func TestQAReasoningEffortPropagationAndRestore(t *testing.T) { + for _, effort := range []string{"", "off", "high"} { + t.Run(effort, func(t *testing.T) { + rc := &qaRequestContext{ + sessionID: "session", session: &types.Session{ID: "session"}, + assistantMessage: &types.Message{ID: "answer"}, reasoningEffort: effort, + } + require.Equal(t, effort, rc.buildQARequest().ReasoningEffort) + sessions := &reasoningSessionStub{} + h := &Handler{sessionService: sessions} + h.persistLastRequestState(context.Background(), rc, qaModeAgent) + require.NotNil(t, sessions.state) + raw, err := sessions.state.Value() + require.NoError(t, err) + var restored types.SessionLastRequestState + require.NoError(t, restored.Scan(raw)) + require.Equal(t, effort, restored.ReasoningEffort) + }) + } +} diff --git a/internal/handler/session/types.go b/internal/handler/session/types.go index d30a2752..4d9e046a 100644 --- a/internal/handler/session/types.go +++ b/internal/handler/session/types.go @@ -67,6 +67,9 @@ type CreateKnowledgeQARequest struct { SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"` // QuestionOrigin is the knowledge source of a picked suggested question. QuestionOrigin *types.QuestionOrigin `json:"question_origin,omitempty"` + + // ReasoningEffort overrides thinking for this request; empty inherits the agent configuration. + ReasoningEffort string `json:"reasoning_effort,omitempty"` } // AttachmentUpload represents a file attachment upload from the client diff --git a/internal/types/qa_request.go b/internal/types/qa_request.go index bb8b2655..e6ffa58c 100644 --- a/internal/types/qa_request.go +++ b/internal/types/qa_request.go @@ -56,6 +56,7 @@ type QARequest struct { Query string // User query text AssistantMessageID string // Pre-created assistant message ID SummaryModelID string // Optional model override; empty = use agent/KB default + ReasoningEffort string // Optional per-request override; empty = use agent default CustomAgent *CustomAgent // Optional custom agent for config override SharedAgentReadOnly bool // True only when access came from an agent share; source-workspace writes are forbidden KnowledgeBaseIDs []string // Knowledge base IDs to search (from request + @mentions) diff --git a/internal/types/session.go b/internal/types/session.go index 11a25bbd..1b5ce7cb 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -335,6 +335,7 @@ type SessionLastRequestState struct { AgentID string `json:"agent_id,omitempty"` AgentEnabled bool `json:"agent_enabled"` ModelID string `json:"model_id,omitempty"` + ReasoningEffort string `json:"reasoning_effort,omitempty"` KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` KnowledgeIDs []string `json:"knowledge_ids,omitempty"` TagIDs []string `json:"tag_ids,omitempty"`