Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(chat): preselect the answer's knowledge base when saving to a KB (#3853)

yi11107e6a06d76a2
diff --git a/frontend/src/components/manual-knowledge-editor.vue b/frontend/src/components/manual-knowledge-editor.vue
index 7b91edd02..01318ce45 100644
--- a/frontend/src/components/manual-knowledge-editor.vue
+++ b/frontend/src/components/manual-knowledge-editor.vue
@@ -5,6 +5,7 @@ import { marked } from 'marked'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { registerUnsavedChanges } from '@/utils/unsavedChanges'
import { useUIStore } from '@/stores/ui'
+import { resolvePreferredKnowledgeBaseId } from '@/utils/manualKnowledgeDraft'
import {
getKnowledgeDetails,
getKnowledgeBaseById,
@@ -633,6 +634,9 @@ const loadKnowledgeBases = async () => {
kbOptions.value = list
if (mode.value === 'create') {
+ // Explicit kbId (KB-page callers) keeps the historical force-insert path.
+ // Chat preferences are soft: only select an id already in the writable
+ // candidate list, otherwise fall back to list[0].
const presetKbId = uiStore.manualEditorKBId
if (presetKbId) {
const exists = list.find((item) => item.value === presetKbId)
@@ -644,7 +648,10 @@ const loadKnowledgeBases = async () => {
}
form.kbId = presetKbId
} else {
- form.kbId = list[0]?.value ?? ''
+ form.kbId = resolvePreferredKnowledgeBaseId(
+ uiStore.manualEditorPreferredKbIds,
+ list.map((item) => item.value),
+ )
}
}
} catch (error) {
@@ -751,8 +758,13 @@ const initialize = async () => {
const presetKbId = uiStore.manualEditorKBId
if (presetKbId) {
form.kbId = presetKbId
- } else if (!form.kbId && kbOptions.value.length) {
- form.kbId = kbOptions.value[0].value
+ } else {
+ // Re-resolve preferences against the loaded candidates (resetForm may have
+ // left form.kbId empty; do not re-apply a preferred id missing from the list).
+ form.kbId = resolvePreferredKnowledgeBaseId(
+ uiStore.manualEditorPreferredKbIds,
+ kbOptions.value.map((item) => item.value),
+ )
}
form.title = form.title || generateDefaultTitle()
form.content = form.content || ''
diff --git a/frontend/src/stores/ui.ts b/frontend/src/stores/ui.ts
index 9c6be1f0b..6fa6eb92b 100644
--- a/frontend/src/stores/ui.ts
+++ b/frontend/src/stores/ui.ts
@@ -16,6 +16,8 @@ export const useUIStore = defineStore('ui', {
manualEditorVisible: false,
manualEditorMode: 'create' as 'create' | 'edit',
manualEditorKBId: null as string | null,
+ // Soft chat preference: resolved against the writable candidate list.
+ manualEditorPreferredKbIds: [] as string[],
manualEditorKnowledgeId: null as string | null,
manualEditorInitialTitle: '',
manualEditorInitialContent: '',
@@ -78,6 +80,8 @@ export const useUIStore = defineStore('ui', {
openManualEditor(options: {
mode?: 'create' | 'edit'
kbId?: string | null
+ /** Soft preference from chat citations; resolved against writable candidates. */
+ preferredKbIds?: string[] | null
knowledgeId?: string | null
title?: string
content?: string
@@ -86,6 +90,9 @@ export const useUIStore = defineStore('ui', {
} = {}) {
this.manualEditorMode = options.mode || 'create'
this.manualEditorKBId = options.kbId ?? null
+ this.manualEditorPreferredKbIds = (options.preferredKbIds || []).filter(
+ (id): id is string => typeof id === 'string' && !!id.trim(),
+ )
this.manualEditorKnowledgeId = options.knowledgeId ?? null
this.manualEditorInitialTitle = options.title || ''
this.manualEditorInitialContent = options.content || ''
@@ -96,6 +103,8 @@ export const useUIStore = defineStore('ui', {
closeManualEditor() {
this.manualEditorVisible = false
+ this.manualEditorKBId = null
+ this.manualEditorPreferredKbIds = []
this.manualEditorKnowledgeId = null
this.manualEditorInitialContent = ''
this.manualEditorInitialTitle = ''
diff --git a/frontend/src/utils/chatMessageShared.ts b/frontend/src/utils/chatMessageShared.ts
index 96b0b253a..bbd588854 100644
--- a/frontend/src/utils/chatMessageShared.ts
+++ b/frontend/src/utils/chatMessageShared.ts
@@ -1,6 +1,6 @@
import i18n from '@/i18n';
import { buildMermaidBlockHtml, buildMermaidLoadingHtml } from '@/utils/markdownEnhancements';
-import { buildManualDraft, deriveManualTitle } from './manualKnowledgeDraft';
+import { buildManualDraft, collectManualDraftPreferredKbIds, deriveManualTitle } from './manualKnowledgeDraft';
import {
injectCachedMermaidSvg as injectCachedMermaidSvgHtml,
maskMermaidBlocksForStreaming as maskMermaidBlocks,
@@ -77,3 +77,13 @@ export const buildManualMarkdown = (_question: string, answer: string): string =
sourcesHeading: i18n.global.t('chat.manualSourcesHeading'),
});
};
+
+/**
+ * Soft knowledge-base preferences for the manual editor, in citation order.
+ * The editor resolves the first id that is already in its writable candidate
+ * list; nothing is force-inserted. Empty when the answer has no retrievable
+ * provenance (plain chat / missing references).
+ */
+export const collectManualPreferredKbIds = (
+ references?: { knowledge_base_id?: string }[] | null,
+): string[] => collectManualDraftPreferredKbIds(references);
diff --git a/frontend/src/utils/manualKnowledgeDraft.test.ts b/frontend/src/utils/manualKnowledgeDraft.test.ts
index 9f3ad338f..bfe59031e 100644
--- a/frontend/src/utils/manualKnowledgeDraft.test.ts
+++ b/frontend/src/utils/manualKnowledgeDraft.test.ts
@@ -1,6 +1,13 @@
import assert from 'node:assert/strict'
import test from 'node:test'
-import { buildManualDraft, deriveManualTitle } from './manualKnowledgeDraft'
+import {
+ buildManualDraft,
+ collectManualDraftPreferredKbIds,
+ deriveManualTitle,
+ resolveManualDraftKnowledgeBaseId,
+ resolvePreferredKnowledgeBaseId,
+ type ManualDraftReference,
+} from './manualKnowledgeDraft'
const labels = { emptyAnswer: '(无内容)', sourcesHeading: '参考来源' }
@@ -65,3 +72,83 @@ test('an English question is cut on a word boundary', () => {
const title = deriveManualTitle('How does a binary view of technology hurt diversity?', '对话摘录')
assert.equal(title, 'How does a binary view of')
})
+
+// Soft preference for the chat "add to knowledge base" action: collect cited
+// KB ids in order, then resolve against the editor's writable candidate list.
+
+test('cited answers collect preferred knowledge-base ids in reference order', () => {
+ assert.deepEqual(
+ collectManualDraftPreferredKbIds([
+ { knowledge_base_id: '441ee604-a04d-4c9a-a4bd-1c4e198e6226' },
+ ]),
+ ['441ee604-a04d-4c9a-a4bd-1c4e198e6226'],
+ )
+ const refs = [
+ { knowledge_base_id: 'kb-first' },
+ { knowledge_base_id: 'kb-second' },
+ ]
+ assert.deepEqual(collectManualDraftPreferredKbIds(refs), ['kb-first', 'kb-second'])
+ assert.deepEqual(collectManualDraftPreferredKbIds([...refs].reverse()), [
+ 'kb-second',
+ 'kb-first',
+ ])
+})
+
+test('blank references are skipped and do not mask a later usable one', () => {
+ assert.deepEqual(collectManualDraftPreferredKbIds([]), [])
+ assert.deepEqual(collectManualDraftPreferredKbIds(undefined), [])
+ assert.deepEqual(collectManualDraftPreferredKbIds(null), [])
+ assert.deepEqual(collectManualDraftPreferredKbIds([{}]), [])
+ assert.deepEqual(collectManualDraftPreferredKbIds([{ knowledge_base_id: '' }]), [])
+ assert.deepEqual(collectManualDraftPreferredKbIds([{ knowledge_base_id: ' ' }]), [])
+ // A web-only reference carries no knowledge_base_id field.
+ const webOnly: ManualDraftReference = {}
+ assert.deepEqual(collectManualDraftPreferredKbIds([webOnly]), [])
+ assert.deepEqual(
+ collectManualDraftPreferredKbIds([
+ { knowledge_base_id: '' },
+ { knowledge_base_id: 'kb-real' },
+ ]),
+ ['kb-real'],
+ )
+ // Duplicates stay once, in first-seen order.
+ assert.deepEqual(
+ collectManualDraftPreferredKbIds([
+ { knowledge_base_id: 'kb-a' },
+ { knowledge_base_id: 'kb-a' },
+ { knowledge_base_id: 'kb-b' },
+ ]),
+ ['kb-a', 'kb-b'],
+ )
+})
+
+test('resolveManualDraftKnowledgeBaseId still returns the first preferred id', () => {
+ assert.equal(
+ resolveManualDraftKnowledgeBaseId([{ knowledge_base_id: 'kb-first' }]),
+ 'kb-first',
+ )
+ assert.equal(resolveManualDraftKnowledgeBaseId([]), null)
+})
+
+test('a rejected preference falls through to a later eligible reference', () => {
+ // Viewer-only / FAQ / unknown first citation must not win over a writable later one.
+ assert.equal(
+ resolvePreferredKnowledgeBaseId(['viewer-only', 'writable-doc'], ['writable-doc', 'other']),
+ 'writable-doc',
+ )
+})
+
+test('when no preferred target matches, keep the first-option fallback', () => {
+ assert.equal(
+ resolvePreferredKnowledgeBaseId(['viewer-only', 'faq-kb'], ['my-doc', 'shared-doc']),
+ 'my-doc',
+ )
+ assert.equal(resolvePreferredKnowledgeBaseId(['missing'], ['only']), 'only')
+})
+
+test('an empty candidate list yields an empty selection', () => {
+ assert.equal(resolvePreferredKnowledgeBaseId(['kb-a'], []), '')
+ assert.equal(resolvePreferredKnowledgeBaseId([], []), '')
+ assert.equal(resolvePreferredKnowledgeBaseId(undefined, []), '')
+ assert.equal(resolvePreferredKnowledgeBaseId(null, ['x']), 'x')
+})
diff --git a/frontend/src/utils/manualKnowledgeDraft.ts b/frontend/src/utils/manualKnowledgeDraft.ts
index b8298e960..f4ff44eb2 100644
--- a/frontend/src/utils/manualKnowledgeDraft.ts
+++ b/frontend/src/utils/manualKnowledgeDraft.ts
@@ -34,6 +34,68 @@ export function deriveManualTitle(question: string, fallback: string): string {
return cut.replace(TRAILING_PUNCTUATION_RE, '').trim() || head.trim()
}
+/** A retrieved chunk reference, as persisted on an assistant message. */
+export interface ManualDraftReference {
+ knowledge_base_id?: string
+}
+
+/**
+ * Collect knowledge-base ids cited by a chat answer, in reference order.
+ *
+ * Used as a soft preference when opening the manual editor from chat: the
+ * editor resolves the first id that appears in its writable candidate list,
+ * and otherwise keeps the existing first-option fallback. Viewer-only shares,
+ * FAQ bases, and unknown ids are never force-inserted — those would reject
+ * a save or create an invisible FAQ document.
+ */
+export function collectManualDraftPreferredKbIds(
+ references?: ManualDraftReference[] | null,
+): string[] {
+ if (!Array.isArray(references)) return []
+ const ids: string[] = []
+ const seen = new Set<string>()
+ for (const reference of references) {
+ const kbId = reference?.knowledge_base_id
+ if (typeof kbId !== 'string') continue
+ const trimmed = kbId.trim()
+ if (!trimmed || seen.has(trimmed)) continue
+ seen.add(trimmed)
+ ids.push(trimmed)
+ }
+ return ids
+}
+
+/**
+ * Pick a preferred knowledge base that is already in the editor's candidates.
+ *
+ * Returns the first preferred id that appears in `candidateIds`, or the first
+ * candidate (or '') when nothing matches — matching the editor's historical
+ * `list[0]?.value ?? ''` fallback.
+ */
+export function resolvePreferredKnowledgeBaseId(
+ preferredIds: string[] | null | undefined,
+ candidateIds: string[],
+): string {
+ if (candidateIds.length === 0) return ''
+ const candidates = new Set(candidateIds)
+ for (const id of preferredIds || []) {
+ if (candidates.has(id)) return id
+ }
+ return candidateIds[0] ?? ''
+}
+
+/**
+ * @deprecated Prefer {@link collectManualDraftPreferredKbIds} + editor-side
+ * resolution against the writable candidate list. Kept as a thin first-id
+ * helper for call sites that only need the raw citation order.
+ */
+export function resolveManualDraftKnowledgeBaseId(
+ references?: ManualDraftReference[] | null,
+): string | null {
+ const ids = collectManualDraftPreferredKbIds(references)
+ return ids[0] ?? null
+}
+
/**
* Build the Markdown body seeded into the manual editor from a chat answer.
*
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 6d73129db..b3844bde7 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -813,6 +813,7 @@ import { parseWikiToolReferences } from '@/utils/wikiToolReferences';
import {
buildManualMarkdown,
formatManualTitle,
+ collectManualPreferredKbIds,
replaceIncompleteMermaidWithPlaceholder,
prepareStreamingMermaidMarkdown,
extractMermaidCodes,
@@ -3430,6 +3431,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
uiStore.openManualEditor({
mode: 'create',
+ preferredKbIds: collectManualPreferredKbIds(props.session?.knowledge_references),
title: manualTitle,
content: manualContent,
status: 'draft',
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index e217608a6..125bce475 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -178,6 +178,7 @@ import { useAssistantStore } from '@/stores/assistant';
import {
buildManualMarkdown,
formatManualTitle,
+ collectManualPreferredKbIds,
} from '@/utils/chatMessageShared';
import { copyWithToast } from '@/utils/clipboard';
import {
@@ -497,6 +498,7 @@ const handleAddToKnowledge = () => {
``
uiStore.openManualEditor({
mode: 'create',
+ preferredKbIds: collectManualPreferredKbIds(props.session?.knowledge_references),
title: manualTitle,
content: manualContent,
status: 'draft',