From e7dead14f92998bf4f12dbcd78292645660b894d Mon Sep 17 00:00:00 2001 From: LamXwah <137157815+zh769394@users.noreply.github.com> Date: Fri, 21 Aug 2026 15:58:26 +0800 Subject: [PATCH] fix(chat): prune deleted knowledge base references from sessions (#936) * fix(chat): prune deleted knowledge base references from sessions * style(chat): drop the unrelated reformat from the KB-pruning change ChatMessages.tsx arrived with ~50 lines of prettier output that the fix does not need: `.map()` arrow bodies unwrapped for bookReferences, notebookReferences, historyReferences and memoryReferences, plus a union type joined onto one line. `dev` does not follow prettier for this file (`prettier --check` flags it on `dev` too), and CI gates neither prettier nor tsc for web, so the churn would have landed silently. Restore those hunks and keep only what threads `availableKbNames` through: the two prop declarations, the two destructures, the pass-down, and the `.filter()` in front of the knowledge-base context items. The remaining reindent inside that `.map()` is intrinsic to inserting the filter ahead of it. --------- Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com> --- .../home/[[...sessionId]]/page.tsx | 27 +++++++++++- web/components/chat/home/ChatMessages.tsx | 44 ++++++++++++------- web/lib/session-activity.ts | 10 ++++- web/tests/session-activity.test.ts | 35 +++++++++++++++ 4 files changed, 96 insertions(+), 20 deletions(-) diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx index c1d234f10..3960e56ea 100644 --- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx +++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx @@ -400,6 +400,11 @@ export default function ChatPage() { } = useUnifiedChat(); const [knowledgeBases, setKnowledgeBases] = useState([]); + const [knowledgeBasesLoaded, setKnowledgeBasesLoaded] = useState(false); + const availableKbNames = useMemo( + () => new Set(knowledgeBases.map((kb) => kb.name)), + [knowledgeBases], + ); // A connected agent to preselect once it loads, from `?agent=` on the // URL (the partner list page links here to drop straight into a chat with a // partner). Captured once at first client render — the URL is rewritten to @@ -1190,7 +1195,9 @@ export default function ChatPage() { try { const list = await listKnowledgeBases({ force: options?.force }); setKnowledgeBases(list); + setKnowledgeBasesLoaded(true); } catch { + setKnowledgeBasesLoaded(false); setKnowledgeBases([]); } }, @@ -1211,6 +1218,16 @@ export default function ChatPage() { void refreshKnowledgeBases(); }, [refreshKnowledgeBases]); + // A physical KB delete does not cascade into persisted session preferences. + // Reconcile only after a successful fetch: an empty result then means every + // KB was deleted, while a failed request must keep the existing selection. + useEffect(() => { + if (!knowledgeBasesLoaded) return; + const selected = state.knowledgeBases; + const pruned = selected.filter((name) => availableKbNames.has(name)); + if (pruned.length !== selected.length) setKBs(pruned); + }, [availableKbNames, knowledgeBasesLoaded, state.knowledgeBases, setKBs]); + const refreshUserEnabledTools = useCallback( async (options?: { force?: boolean }) => { try { @@ -1465,8 +1482,11 @@ export default function ChatPage() { // Fold all messages once per state.messages change to power the // SessionActivityPanel on the right (tools, KBs, space refs, attachments). const sessionActivity = useMemo( - () => buildSessionActivity(state.messages), - [state.messages], + () => + buildSessionActivity(state.messages, { + availableKbNames: knowledgeBasesLoaded ? availableKbNames : undefined, + }), + [state.messages, availableKbNames, knowledgeBasesLoaded], ); // Context-window readout for the composer chip: the newest turn that was @@ -2200,6 +2220,9 @@ export default function ChatPage() { onEditMessage={editMessage} onSwitchBranch={switchBranch} onSubmitUserReply={submitUserReply} + availableKbNames={ + knowledgeBasesLoaded ? availableKbNames : undefined + } />
void; + /** Names of KBs confirmed to exist. Omitted when the KB list is unavailable. */ + availableKbNames?: Set; }) { const { t } = useTranslation(); const [editing, setEditing] = useState(false); @@ -956,25 +959,30 @@ const UserMessage = memo(function UserMessage({ onClick: onPreviewAttachment ? () => onPreviewAttachment(a) : undefined, }; }), - ...(snap?.knowledgeBases ?? []).map((name): ContextTreeItem => { - const agentKind = agentKinds[name]; - if (agentKind) { + ...(snap?.knowledgeBases ?? []) + .filter( + (name) => + !availableKbNames || availableKbNames.has(name) || agentKinds[name], + ) + .map((name): ContextTreeItem => { + const agentKind = agentKinds[name]; + if (agentKind) { + return { + key: `agent-${name}`, + // Brand SVG marks share the lucide call signature (size/strokeWidth/ + // className); cast bridges the structural-variance gap. + icon: (agentGlyph(agentKind) ?? Bot) as unknown as LucideIcon, + kind: t("Agent"), + label: name, + }; + } return { - key: `agent-${name}`, - // Brand SVG marks share the lucide call signature (size/strokeWidth/ - // className); cast bridges the structural-variance gap. - icon: (agentGlyph(agentKind) ?? Bot) as unknown as LucideIcon, - kind: t("Agent"), + key: `kb-${name}`, + icon: Database, + kind: t("Knowledge"), label: name, }; - } - return { - key: `kb-${name}`, - icon: Database, - kind: t("Knowledge"), - label: name, - }; - }), + }), ...(snap?.bookReferences ?? []).map( (ref): ContextTreeItem => ({ key: `book-${ref.book_id}`, @@ -1165,6 +1173,7 @@ export const ChatMessageList = memo(function ChatMessageList({ selectedBranches, onEditMessage, onSwitchBranch, + availableKbNames, onSubmitUserReply, }: { messages: ChatMessageItem[]; @@ -1201,6 +1210,8 @@ export const ChatMessageList = memo(function ChatMessageList({ answers?: Array<{ questionId: string; text: string }>; }, ) => void; + /** Names of KBs confirmed to exist. Omitted when the KB list is unavailable. */ + availableKbNames?: Set; }) { const { t } = useTranslation(); // Visible path: when no branching has happened the result is identical @@ -1381,6 +1392,7 @@ export const ChatMessageList = memo(function ChatMessageList({ editDisabled={isStreaming} siblingInfo={sib} onSwitchBranch={onSwitchBranch} + availableKbNames={availableKbNames} /> ); } diff --git a/web/lib/session-activity.ts b/web/lib/session-activity.ts index c9a4e29a0..ebbe815b2 100644 --- a/web/lib/session-activity.ts +++ b/web/lib/session-activity.ts @@ -70,7 +70,11 @@ export interface SessionActivity { isEmpty: boolean; } -export function buildSessionActivity(messages: MessageItem[]): SessionActivity { +export function buildSessionActivity( + messages: MessageItem[], + options?: { availableKbNames?: Set }, +): SessionActivity { + const availableKbNames = options?.availableKbNames; const toolCounts = new Map(); const kbs = new Set(); const historySessionIds = new Set(); @@ -106,7 +110,9 @@ export function buildSessionActivity(messages: MessageItem[]): SessionActivity { const snap: MessageRequestSnapshot | undefined = msg.requestSnapshot; if (snap) { - snap.knowledgeBases?.forEach((k) => kbs.add(k)); + snap.knowledgeBases?.forEach((k) => { + if (!availableKbNames || availableKbNames.has(k)) kbs.add(k); + }); snap.historyReferences?.forEach((s) => historySessionIds.add(s)); snap.bookReferences?.forEach((b) => { bookIds.add(b.book_id); diff --git a/web/tests/session-activity.test.ts b/web/tests/session-activity.test.ts index 7ac1c9d8d..1c149fa44 100644 --- a/web/tests/session-activity.test.ts +++ b/web/tests/session-activity.test.ts @@ -164,6 +164,41 @@ test("dedupes knowledge bases across turns", () => { assert.deepEqual(activity.knowledgeBases, ["KB"]); }); +test("hides deleted knowledge bases when an available set is given", () => { + const activity = buildSessionActivity( + messages({ + role: "user", + requestSnapshot: snapshot({ knowledgeBases: ["gone", "alive"] }), + }), + { availableKbNames: new Set(["alive"]) }, + ); + + assert.deepEqual(activity.knowledgeBases, ["alive"]); +}); + +test("hides every stale knowledge base when the confirmed set is empty", () => { + const activity = buildSessionActivity( + messages({ + role: "user", + requestSnapshot: snapshot({ knowledgeBases: ["last-deleted-kb"] }), + }), + { availableKbNames: new Set() }, + ); + + assert.deepEqual(activity.knowledgeBases, []); +}); + +test("keeps knowledge bases when availability could not be loaded", () => { + const activity = buildSessionActivity( + messages({ + role: "user", + requestSnapshot: snapshot({ knowledgeBases: ["unconfirmed"] }), + }), + ); + + assert.deepEqual(activity.knowledgeBases, ["unconfirmed"]); +}); + /* ------------------------------------------------------------------ */ /* artifactDiskPath */ /* ------------------------------------------------------------------ */