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>
This commit is contained in:
LamXwah
2026-08-21 15:58:26 +08:00
committed by GitHub
parent 7411315b6b
commit e7dead14f9
4 changed files with 96 additions and 20 deletions

View File

@@ -400,6 +400,11 @@ export default function ChatPage() {
} = useUnifiedChat();
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
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=<name>` 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
}
/>
<div
ref={messagesEndRef}

View File

@@ -891,6 +891,7 @@ const UserMessage = memo(function UserMessage({
editDisabled,
siblingInfo,
onSwitchBranch,
availableKbNames,
}: {
msg: ChatMessageItem;
index: number;
@@ -900,6 +901,8 @@ const UserMessage = memo(function UserMessage({
editDisabled?: boolean;
siblingInfo?: SiblingInfo;
onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;
/** Names of KBs confirmed to exist. Omitted when the KB list is unavailable. */
availableKbNames?: Set<string>;
}) {
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<string>;
}) {
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}
/>
);
}

View File

@@ -70,7 +70,11 @@ export interface SessionActivity {
isEmpty: boolean;
}
export function buildSessionActivity(messages: MessageItem[]): SessionActivity {
export function buildSessionActivity(
messages: MessageItem[],
options?: { availableKbNames?: Set<string> },
): SessionActivity {
const availableKbNames = options?.availableKbNames;
const toolCounts = new Map<string, number>();
const kbs = new Set<string>();
const historySessionIds = new Set<string>();
@@ -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);

View File

@@ -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 */
/* ------------------------------------------------------------------ */