Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: make adding files to a knowledge base discoverable from the chat (#12779)

oobaboogac94eecd70a2d
diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.ts
index fa43f948599..6c0105a44fe 100644
--- a/studio/frontend/src/features/rag/api/rag-api.ts
+++ b/studio/frontend/src/features/rag/api/rag-api.ts
@@ -110,17 +110,34 @@ export async function listKnowledgeBases(): Promise<KnowledgeBase[]> {
return data.knowledgeBases ?? [];
}
+/** Readers keep their own KB list; one that misses a delete keeps sending the deleted kb_id. */
+export const KNOWLEDGE_BASES_CHANGED_EVENT = "unsloth-knowledge-bases-changed";
+
+// Also on failure: a delete can fail because the row is already gone.
+function announceKnowledgeBasesChanged(): void {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(new Event(KNOWLEDGE_BASES_CHANGED_EVENT));
+}
+
+export function subscribeKnowledgeBasesChanged(
+ onChanged: () => void,
+): () => void {
+ if (typeof window === "undefined") return () => undefined;
+ window.addEventListener(KNOWLEDGE_BASES_CHANGED_EVENT, onChanged);
+ return () => window.removeEventListener(KNOWLEDGE_BASES_CHANGED_EVENT, onChanged);
+}
+
export function createKnowledgeBase(payload: {
name: string;
description?: string;
}): Promise<{ id: string; name: string }> {
- return ragRequest("/knowledge-bases", {
+ return ragRequest<{ id: string; name: string }>("/knowledge-bases", {
method: "POST",
body: {
name: payload.name,
...(payload.description ? { description: payload.description } : {}),
},
- });
+ }).finally(announceKnowledgeBasesChanged);
}
export function updateKnowledgeBase(
@@ -130,16 +147,17 @@ export function updateKnowledgeBase(
const body: Record<string, unknown> = {};
if (payload.name !== undefined) body.name = payload.name;
if (payload.description !== undefined) body.description = payload.description;
- return ragRequest(`/knowledge-bases/${encodeURIComponent(kbId)}`, {
- method: "PATCH",
- body,
- });
+ return ragRequest<{ ok: boolean }>(
+ `/knowledge-bases/${encodeURIComponent(kbId)}`,
+ { method: "PATCH", body },
+ ).finally(announceKnowledgeBasesChanged);
}
export function deleteKnowledgeBase(kbId: string): Promise<{ ok: boolean }> {
- return ragRequest(`/knowledge-bases/${encodeURIComponent(kbId)}`, {
- method: "DELETE",
- });
+ return ragRequest<{ ok: boolean }>(
+ `/knowledge-bases/${encodeURIComponent(kbId)}`,
+ { method: "DELETE" },
+ ).finally(announceKnowledgeBasesChanged);
}
export async function listKnowledgeBaseDocuments(
diff --git a/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx b/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx
index f16aa0bf947..bc0e89cef27 100644
--- a/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx
+++ b/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx
@@ -8,7 +8,7 @@ import {
import { Tick02Icon } from "@/lib/tick-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import { FileDatabaseIcon } from "@hugeicons/core-free-icons";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import {
DropdownMenu,
@@ -21,7 +21,10 @@ import {
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
-import { listKnowledgeBases } from "../api/rag-api";
+import {
+ listKnowledgeBases,
+ subscribeKnowledgeBasesChanged,
+} from "../api/rag-api";
import type { KnowledgeBase } from "../types/rag";
import { KnowledgeBaseDialog } from "./knowledge-base-dialog";
@@ -43,20 +46,24 @@ export function KnowledgeBaseComposerButton({
const [menuOpen, setMenuOpen] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
+ // Refreshes overlap; an older answer landing last would restore a deleted KB.
+ const latestRefreshRef = useRef(0);
const refresh = useCallback(async () => {
+ const request = ++latestRefreshRef.current;
try {
const rows = await listKnowledgeBases();
- setKbs(rows);
+ if (request === latestRefreshRef.current) setKbs(rows);
} catch {
// Keep prior state on failure.
} finally {
- setKbsLoaded(true);
+ if (request === latestRefreshRef.current) setKbsLoaded(true);
}
}, []);
// Load on mount so newly created KBs show up.
useEffect(() => {
void refresh();
+ return subscribeKnowledgeBasesChanged(() => void refresh());
}, [refresh]);
// If the selected KB was deleted, fall back to thread source so we never send a
@@ -182,10 +189,7 @@ export function KnowledgeBaseComposerButton({
</DropdownMenu>
<KnowledgeBaseDialog
open={dialogOpen}
- onOpenChange={(next) => {
- setDialogOpen(next);
- if (!next) void refresh();
- }}
+ onOpenChange={setDialogOpen}
/>
</>
);
diff --git a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
index 725ab8f5a08..5fbb6bc780c 100644
--- a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
+++ b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
@@ -7,7 +7,7 @@ import {
PlusSignIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { ChevronLeftIcon, UploadIcon } from "lucide-react";
+import { ChevronLeftIcon, ChevronRightIcon, UploadIcon } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
@@ -47,27 +47,40 @@ import { type KnowledgeBase, isLinkedFolderManaged } from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
import { LinkedFoldersManager } from "./linked-folders-manager";
import { RAG_SOURCE_UPLOAD_ACCEPT } from "./source-drop-policy";
-import { useRagDocuments } from "./use-rag-documents";
+import { type RagUploadItem, useRagDocuments } from "./use-rag-documents";
import { useSourceDrop } from "./use-source-drop";
type View =
| { kind: "list" }
| { kind: "create" }
| { kind: "edit"; kb: KnowledgeBase }
- | { kind: "documents"; kb: KnowledgeBase };
+ | { kind: "documents"; kb: KnowledgeBase; uploads?: RagUploadItem[] };
+
+export interface KnowledgeBaseFocus {
+ kbId: string;
+ uploads?: RagUploadItem[];
+}
export interface KnowledgeBaseDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
+ focus?: KnowledgeBaseFocus | null;
+ /** Without a Radix trigger, focus would land on the body on close. */
+ onCloseAutoFocus?: (event: Event) => void;
}
export function KnowledgeBaseDialog({
open,
onOpenChange,
+ focus = null,
+ onCloseAutoFocus,
}: KnowledgeBaseDialogProps) {
const [kbs, setKbs] = useState<KnowledgeBase[]>([]);
const [loading, setLoading] = useState(false);
const [view, setView] = useState<View>({ kind: "list" });
+ // Handed-over files not yet uploading; nothing else holds them.
+ const handoffRef = useRef<RagUploadItem[]>([]);
+ const handedFocusRef = useRef<KnowledgeBaseFocus | null>(null);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [saving, setSaving] = useState(false);
@@ -84,24 +97,75 @@ export function KnowledgeBaseDialog({
? (ragUnavailableReason ?? undefined)
: undefined;
- const refresh = useCallback(async () => {
+ const refresh = useCallback(async (): Promise<KnowledgeBase[] | null> => {
setLoading(true);
try {
- setKbs(await listKnowledgeBases());
+ const rows = await listKnowledgeBases();
+ setKbs(rows);
+ return rows;
} catch (err) {
toast.error("Failed to load knowledge bases", {
description: err instanceof Error ? err.message : String(err),
});
+ return null;
} finally {
setLoading(false);
}
}, []);
+ const wasOpenRef = useRef(false);
useEffect(() => {
- if (!open) return;
- setView({ kind: "list" });
- void refresh();
- }, [open, refresh]);
+ if (!open) {
+ handoffRef.current = [];
+ handedFocusRef.current = null;
+ wasOpenRef.current = false;
+ return;
+ }
+ const wasOpen = wasOpenRef.current;
+ wasOpenRef.current = true;
+ // Once per handoff, though StrictMode runs this twice for the same one.
+ if (focus !== handedFocusRef.current) {
+ handedFocusRef.current = focus;
+ handoffRef.current = [...handoffRef.current, ...(focus?.uploads ?? [])];
+ }
+ const uploads = handoffRef.current;
+ let cancelled = false;
+ // A handoff into the KB already on screen keeps its view mounted: unmounting it
+ // abandons the rest of a batch still uploading there.
+ setView((current) =>
+ wasOpen &&
+ focus &&
+ current.kind === "documents" &&
+ current.kb.id === focus.kbId
+ ? {
+ kind: "documents",
+ kb: current.kb,
+ uploads: uploads.length ? uploads : undefined,
+ }
+ : { kind: "list" },
+ );
+ void refresh().then((rows) => {
+ if (cancelled || !focus) return;
+ const kb = rows?.find((row) => row.id === focus.kbId);
+ if (!kb) {
+ // A failed load already said so.
+ if (uploads.length && rows) {
+ toast.error("Knowledge base not found", {
+ description: "Open or create one below and the files go there.",
+ });
+ }
+ return;
+ }
+ setView({
+ kind: "documents",
+ kb,
+ uploads: uploads.length ? uploads : undefined,
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, focus, refresh]);
function startCreate() {
setName("");
@@ -119,6 +183,25 @@ export function KnowledgeBaseDialog({
setView({ kind: "list" });
}
+ function openDocuments(kb: KnowledgeBase) {
+ const uploads = handoffRef.current;
+ setView({
+ kind: "documents",
+ kb,
+ uploads: uploads.length ? uploads : undefined,
+ });
+ }
+
+ // The view outlives a close, so the files leave it as soon as they start.
+ const takeUploads = useCallback(() => {
+ handoffRef.current = [];
+ setView((current) =>
+ current.kind === "documents" && current.uploads
+ ? { kind: "documents", kb: current.kb }
+ : current,
+ );
+ }, []);
+
async function submitForm() {
// The button is disabled for this, but the form is also reachable by keyboard and
// the verdict can land while it is open. A 503 toast is not an explanation.
@@ -135,6 +218,7 @@ export function KnowledgeBaseDialog({
}
setSaving(true);
try {
+ let createdId: string | null = null;
if (view.kind === "edit") {
await updateKnowledgeBase(view.kb.id, {
name: trimmed,
@@ -142,14 +226,17 @@ export function KnowledgeBaseDialog({
});
toast.success("Knowledge base updated");
} else {
- await createKnowledgeBase({
- name: trimmed,
- description: description.trim() || undefined,
- });
+ createdId = (
+ await createKnowledgeBase({
+ name: trimmed,
+ description: description.trim() || undefined,
+ })
+ ).id;
toast.success("Knowledge base created");
}
- backToList();
- await refresh();
+ const created = (await refresh())?.find((row) => row.id === createdId);
+ if (created) openDocuments(created);
+ else setView({ kind: "list" });
} catch (err) {
toast.error("Save failed", {
description: err instanceof Error ? err.message : String(err),
@@ -174,7 +261,7 @@ export function KnowledgeBaseDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-2xl">
+ <DialogContent className="max-w-2xl" onCloseAutoFocus={onCloseAutoFocus}>
<DialogHeader>
<DialogTitle>
{view.kind === "documents" ? view.kb.name : "Knowledge bases"}
@@ -187,7 +274,12 @@ export function KnowledgeBaseDialog({
</DialogHeader>
{view.kind === "documents" ? (
- <KnowledgeBaseDocuments kb={view.kb} onBack={backToList} />
+ <KnowledgeBaseDocuments
+ kb={view.kb}
+ uploads={view.uploads}
+ onUploadsStarted={takeUploads}
+ onBack={backToList}
+ />
) : showForm ? (
<div className="flex flex-col gap-4">
<div className="grid gap-2">
@@ -254,15 +346,24 @@ export function KnowledgeBaseDialog({
>
<button
type="button"
- onClick={() => setView({ kind: "documents", kb })}
- className="min-w-0 flex-1 text-left"
+ onClick={() => openDocuments(kb)}
+ title="Open to add or remove documents"
+ className="-my-1 -ml-2 flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
- <div className="truncate font-medium">{kb.name}</div>
- <div className="truncate text-xs text-muted-foreground">
- {kb.documentCount ?? 0} document
- {(kb.documentCount ?? 0) === 1 ? "" : "s"}
- {kb.description ? ` · ${kb.description}` : ""}
- </div>
+ <span className="block min-w-0 flex-1">
+ <span className="block truncate font-medium">
+ {kb.name}
+ </span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {kb.documentCount ?? 0} document
+ {(kb.documentCount ?? 0) === 1 ? "" : "s"}
+ {kb.description ? ` · ${kb.description}` : ""}
+ </span>
+ </span>
+ <ChevronRightIcon
+ strokeWidth={1.5}
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
</button>
<div className="flex items-center gap-1">
<Button
@@ -329,9 +430,13 @@ export function KnowledgeBaseDialog({
function KnowledgeBaseDocuments({
kb,
+ uploads,
+ onUploadsStarted,
onBack,
}: {
kb: KnowledgeBase;
+ uploads?: RagUploadItem[];
+ onUploadsStarted: () => void;
onBack: () => void;
}) {
const lister = useCallback(() => listKnowledgeBaseDocuments(kb.id), [kb.id]);
@@ -350,6 +455,18 @@ function KnowledgeBaseDocuments({
: undefined,
});
+ // Deferred a tick: the hook's unmount cleanup aborts an upload started on StrictMode's
+ // first mount. Taking the files off the view, not the deps, stops a rerun.
+ // A batch already uploading here goes first: upload() tracks one run at a time.
+ useEffect(() => {
+ if (!uploads?.length || uploading) return;
+ const timer = window.setTimeout(() => {
+ onUploadsStarted();
+ void upload(uploads);
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, [uploads, uploading, onUploadsStarted, upload]);
+
return (
<div
className="flex min-w-0 flex-col gap-3"
diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
index 9cd48c31996..f8b30a6818e 100644
--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
@@ -1,7 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ type RefObject,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
import { HugeiconsIcon } from "@hugeicons/react";
import {
AttachmentIcon,
@@ -41,6 +47,7 @@ import {
announceProjectSourcesUpdated,
invalidateProjectSources,
listKnowledgeBases,
+ subscribeKnowledgeBasesChanged,
listProjectDocuments,
listThreadDocuments,
} from "../api/rag-api";
@@ -62,37 +69,72 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { DocumentStatusChip } from "./document-status-chip";
-import { useRagDocuments } from "./use-rag-documents";
+import {
+ type KnowledgeBaseFocus,
+ KnowledgeBaseDialog,
+} from "./knowledge-base-dialog";
+import { EXPIRY_GRACE_MS } from "./staged-source";
+import { uploadItemFromIntent, useRagDocuments } from "./use-rag-documents";
-// Read-only chip shown when retrieval comes from a KB, so the source isn't invisible.
-function KnowledgeBaseSourceChip({ kbId }: { kbId: string }) {
- const [name, setName] = useState<string | null>(null);
+// Refetched after any KB mutation so a rename shows at once.
+function useKnowledgeBaseName(kbId: string | null): string | null {
+ // Keyed by id: a drop during a switch must not name one KB and add to another.
+ const [known, setKnown] = useState<{ kbId: string; name: string | null } | null>(
+ null,
+ );
useEffect(() => {
+ if (!kbId) return;
let cancelled = false;
- listKnowledgeBases()
- .then((rows) => {
- if (!cancelled) setName(rows.find((kb) => kb.id === kbId)?.name ?? null);
- })
- .catch(() => {
- if (!cancelled) setName(null);
- });
+ let latest = 0;
+ const load = () => {
+ const request = ++latest;
+ listKnowledgeBases()
+ .then((rows) => {
+ if (cancelled || request !== latest) return;
+ setKnown({ kbId, name: rows.find((kb) => kb.id === kbId)?.name ?? null });
+ })
+ .catch(() => {
+ // A failed refetch says nothing about the KB.
+ });
+ };
+ load();
+ const unsubscribe = subscribeKnowledgeBasesChanged(load);
return () => {
cancelled = true;
+ unsubscribe();
};
}, [kbId]);
+ return known !== null && known.kbId === kbId ? known.name : null;
+}
+
+// Shown when retrieval comes from a KB, so the source isn't invisible.
+function KnowledgeBaseSourceChip({
+ name,
+ onOpen,
+ buttonRef,
+}: {
+ name: string | null;
+ onOpen: () => void;
+ buttonRef: RefObject<HTMLButtonElement | null>;
+}) {
return (
<div className="mb-2 flex w-full flex-row items-center gap-1.5 pl-0.5 pr-1.5 pt-0.5 pb-1">
- <span
- className="composer-pill-btn shrink-0 cursor-default"
- title="This chat retrieves from a knowledge base. Change the source in RAG retrieval settings."
+ <button
+ ref={buttonRef}
+ type="button"
+ onClick={onOpen}
+ className="composer-pill-btn min-w-0 max-w-full"
+ title="Add or remove documents"
>
<HugeiconsIcon
icon={FileDatabaseIcon}
strokeWidth={2}
- className="size-3.5"
+ className="size-3.5 shrink-0"
/>
- <span>{name ? `Knowledge base: ${name}` : "Knowledge base"}</span>
- </span>
+ <span className="min-w-0 truncate">
+ {name ? `Knowledge base: ${name}` : "Knowledge base"}
+ </span>
+ </button>
</div>
);
}
@@ -537,6 +579,22 @@ export function ThreadDocumentsBar({
// Desktop drops land in the native-intent store because the drop listener lives on
// the chat page; only the chat that received the OS drop may drain its batch.
const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();
+ const [kbDialogFocus, setKbDialogFocus] = useState<KnowledgeBaseFocus | null>(
+ null,
+ );
+ const kbChipRef = useRef<HTMLButtonElement>(null);
+ // The toaster outlives this bar; an "Add" after unmount would open nothing.
+ const kbDropOffersRef = useRef(new Set<string | number>());
+ useEffect(() => {
+ const offers = kbDropOffersRef.current;
+ return () => {
+ for (const id of offers) toast.dismiss(id);
+ offers.clear();
+ };
+ }, []);
+ const activeKbName = useKnowledgeBaseName(
+ ragEnabled && ragSource.type === "kb" ? ragSource.kbId : null,
+ );
const hasPendingAttachments = useNativeIntentStore((s) =>
Boolean(
nativeAttachmentTargetKey &&
@@ -559,9 +617,32 @@ export function ThreadDocumentsBar({
// A KB-scoped chat uploads through the KB dialog, so a thread upload here would
// index into something this bar never shows.
if (ragEnabled && ragSource.type === "kb") {
- toast.error("This chat retrieves from a knowledge base", {
- description: "Add these files to the knowledge base instead.",
+ const kbId = ragSource.kbId;
+ const files =
+ intents.length === 1
+ ? `"${intents[0].displayLabel}"`
+ : `${intents.length} files`;
+ const target = activeKbName
+ ? `"${activeKbName}"`
+ : "this chat's knowledge base";
+ // Nothing else holds these files: keep the offer while their path tokens are readable.
+ const expiresAt = Math.min(...intents.map((intent) => intent.path.expiresAtMs));
+ const offer = toast(`Add ${files} to ${target}?`, {
+ description:
+ "This chat retrieves from that knowledge base, not from files dropped in the chat.",
+ duration: Number.isFinite(expiresAt)
+ ? Math.max(8_000, expiresAt - EXPIRY_GRACE_MS - Date.now())
+ : Infinity,
+ action: {
+ label: "Add",
+ onClick: () =>
+ setKbDialogFocus({
+ kbId,
+ uploads: intents.map(uploadItemFromIntent),
+ }),
+ },
});
+ kbDropOffersRef.current.add(offer);
return;
}
// A stale KB preference is inactive while RAG is off; use thread retrieval.
@@ -569,15 +650,7 @@ export function ThreadDocumentsBar({
setRagSource({ type: "thread" });
setRagEnabled(true);
}
- attach(
- intents.map((intent) => ({
- kind: "native" as const,
- token: intent.path.token,
- name: intent.displayLabel,
- sizeBytes: intent.path.sizeBytes,
- modifiedMs: intent.path.modifiedMs,
- })),
- );
+ attach(intents.map(uploadItemFromIntent));
}, [
hasPendingAttachments,
projectUnresolved,
@@ -585,6 +658,7 @@ export function ThreadDocumentsBar({
attach,
ragEnabled,
ragSource,
+ activeKbName,
setRagSource,
setRagEnabled,
]);
@@ -610,17 +684,51 @@ export function ThreadDocumentsBar({
fileInputRef.current?.click();
}, []);
+ // Every branch, always the first fragment child: an "Add" must open after the source
+ // moves, and deleting the active KB in it must not remount it.
+ const kbDialog = (
+ <KnowledgeBaseDialog
+ open={kbDialogFocus !== null}
+ onOpenChange={(next) => {
+ if (!next) setKbDialogFocus(null);
+ }}
+ focus={kbDialogFocus}
+ onCloseAutoFocus={(event) => {
+ const chip = kbChipRef.current;
+ if (chip?.isConnected) {
+ event.preventDefault();
+ chip.focus({ preventScroll: true });
+ }
+ }}
+ />
+ );
+
// A KB source uploads via the KB dialog, not here; show which KB is active.
if (ragEnabled && ragSource.type === "kb") {
- return <KnowledgeBaseSourceChip kbId={ragSource.kbId} />;
+ const kbId = ragSource.kbId;
+ return (
+ <>
+ {kbDialog}
+ <KnowledgeBaseSourceChip
+ name={activeKbName}
+ onOpen={() => setKbDialogFocus({ kbId })}
+ buttonRef={kbChipRef}
+ />
+ </>
+ );
}
// Project sources retrieve whether the Docs pill is on or not (chat-adapter's projectRagEnabled),
// so list them either way rather than letting the model answer from files the user cannot see.
// The attach controls stay behind the pill: with it off, thread scope is inert.
if (!ragEnabled) {
- return projectDocuments.length > 0 ? (
- <InheritedProjectSources documents={projectDocuments} />
- ) : null;
+ return (
+ <>
+ {kbDialog}
+ {projectDocuments.length > 0 ? (
+ <InheritedProjectSources documents={projectDocuments} />
+ ) : null}
+ </>
+ );
}
// Attaching before the chat's project is known would file the file by guess.
@@ -628,107 +736,110 @@ export function ThreadDocumentsBar({
const chipCount = documents.length + projectDocuments.length;
return (
- <div className="mb-2 flex w-full flex-row items-start gap-1.5 pl-0.5 pr-1.5 pt-0.5 pb-1">
- <AttachFilesButton
- disabled={busy}
- compact={chipCount > 0}
- sharesWithProject={sharesWithProject}
- onClick={handleAddDocs}
- />
- {/* Only a project chat has two scopes to choose between. */}
- {projectId ? (
- <AttachmentTargetMenu
+ <>
+ {kbDialog}
+ <div className="mb-2 flex w-full flex-row items-start gap-1.5 pl-0.5 pr-1.5 pt-0.5 pb-1">
+ <AttachFilesButton
disabled={busy}
+ compact={chipCount > 0}
sharesWithProject={sharesWithProject}
- onSelect={(target) =>
- setThreadProjectAttachmentTarget(effectiveThreadId, target)
- }
+ onClick={handleAddDocs}
/>
- ) : null}
- <input
- ref={fileInputRef}
- type="file"
- multiple
- accept={RAG_UPLOAD_ACCEPT}
- className="hidden"
- onChange={(e) => {
- const files = Array.from(e.target.files ?? []);
- e.target.value = "";
- if (files.length === 0) return;
- attach(files);
- }}
- />
- {/* Cap height so a large set scrolls; fade the cut-off row. */}
- <div
- ref={chipScrollRef}
- onScroll={updateChipFade}
- className={cn(
- "flex max-h-24 flex-1 flex-row flex-wrap items-center gap-1.5 overflow-y-auto",
- chipsOverflow && "rag-docs-bottom-fade",
- )}
- >
- {/* Project sources first: inherited context, and it outlives this chat. */}
- {projectDocuments.map((doc) => (
- <DocumentStatusChip
- key={`project:${doc.id}`}
- filename={doc.filename}
- status={doc.status}
- progress={doc.progress}
- stage={doc.stage}
- error={doc.error}
- shared={true}
- onRemove={
- doc.id.startsWith("pending_") || isLinkedFolderManaged(doc)
- ? undefined
- : () => setRemovingShared(doc)
- }
- />
- ))}
- {documents.map((doc) => (
- <DocumentStatusChip
- key={doc.id}
- filename={doc.filename}
- status={doc.status}
- progress={doc.progress}
- stage={doc.stage}
- error={doc.error}
- onRemove={
- doc.id.startsWith("pending_")
- ? undefined
- : () => void remove(doc.id)
+ {/* Only a project chat has two scopes to choose between. */}
+ {projectId ? (
+ <AttachmentTargetMenu
+ disabled={busy}
+ sharesWithProject={sharesWithProject}
+ onSelect={(target) =>
+ setThreadProjectAttachmentTarget(effectiveThreadId, target)
}
/>
- ))}
+ ) : null}
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={RAG_UPLOAD_ACCEPT}
+ className="hidden"
+ onChange={(e) => {
+ const files = Array.from(e.target.files ?? []);
+ e.target.value = "";
+ if (files.length === 0) return;
+ attach(files);
+ }}
+ />
+ {/* Cap height so a large set scrolls; fade the cut-off row. */}
+ <div
+ ref={chipScrollRef}
+ onScroll={updateChipFade}
+ className={cn(
+ "flex max-h-24 flex-1 flex-row flex-wrap items-center gap-1.5 overflow-y-auto",
+ chipsOverflow && "rag-docs-bottom-fade",
+ )}
+ >
+ {/* Project sources first: inherited context, and it outlives this chat. */}
+ {projectDocuments.map((doc) => (
+ <DocumentStatusChip
+ key={`project:${doc.id}`}
+ filename={doc.filename}
+ status={doc.status}
+ progress={doc.progress}
+ stage={doc.stage}
+ error={doc.error}
+ shared={true}
+ onRemove={
+ doc.id.startsWith("pending_") || isLinkedFolderManaged(doc)
+ ? undefined
+ : () => setRemovingShared(doc)
+ }
+ />
+ ))}
+ {documents.map((doc) => (
+ <DocumentStatusChip
+ key={doc.id}
+ filename={doc.filename}
+ status={doc.status}
+ progress={doc.progress}
+ stage={doc.stage}
+ error={doc.error}
+ onRemove={
+ doc.id.startsWith("pending_")
+ ? undefined
+ : () => void remove(doc.id)
+ }
+ />
+ ))}
+ </div>
+ <AlertDialog
+ open={removingShared !== null}
+ onOpenChange={(open) => {
+ if (!open) setRemovingShared(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove from project sources</AlertDialogTitle>
+ <AlertDialogDescription>
+ Remove "{removingShared?.filename}"? Every chat in this project
+ loses it, and the file and its indexed content are deleted. This
+ cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ const doc = removingShared;
+ setRemovingShared(null);
+ if (doc) void removeFromProject(doc.id);
+ }}
+ >
+ Remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
- <AlertDialog
- open={removingShared !== null}
- onOpenChange={(open) => {
- if (!open) setRemovingShared(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Remove from project sources</AlertDialogTitle>
- <AlertDialogDescription>
- Remove "{removingShared?.filename}"? Every chat in this project
- loses it, and the file and its indexed content are deleted. This
- cannot be undone.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- const doc = removingShared;
- setRemovingShared(null);
- if (doc) void removeFromProject(doc.id);
- }}
- >
- Remove
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
+ </>
);
}
diff --git a/studio/frontend/tests/knowledge-base-composer-refresh.test.ts b/studio/frontend/tests/knowledge-base-composer-refresh.test.ts
new file mode 100644
index 00000000000..f04dd14a970
--- /dev/null
+++ b/studio/frontend/tests/knowledge-base-composer-refresh.test.ts
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { loadWithStubs, stubJsxRuntime } from "./helpers/module-stubs.ts";
+
+// The source menu refetches on mount, on open and after every mutation, so its fetches
+// overlap. Its fallback moves a chat off a deleted KB, which only works if an answer
+// from before the delete cannot land after the one from after it.
+
+type Rows = Array<{ id: string; name: string }>;
+
+function harness() {
+ const slots: unknown[] = [];
+ let cursor = 0;
+ const effects: Array<() => unknown> = [];
+ const pending: Array<(rows: Rows) => void> = [];
+ const listeners: Array<() => void> = [];
+ const sources: unknown[] = [];
+ const state = {
+ ragEnabled: true,
+ ragSource: { type: "kb", kbId: "kb-1" } as unknown,
+ setRagEnabled() {},
+ setRagSource(source: unknown) {
+ state.ragSource = source;
+ sources.push(source);
+ },
+ };
+ const { KnowledgeBaseComposerButton } = loadWithStubs<{
+ KnowledgeBaseComposerButton: () => unknown;
+ }>(
+ new URL(
+ "../src/features/rag/components/knowledge-base-composer-button.tsx",
+ import.meta.url,
+ ),
+ {
+ react: {
+ useRef(value: unknown) {
+ const index = cursor++;
+ slots[index] ??= { current: value };
+ return slots[index];
+ },
+ useState(value: unknown) {
+ const index = cursor++;
+ if (!(index in slots)) slots[index] = value;
+ return [
+ slots[index],
+ (next: unknown) => {
+ slots[index] = next;
+ },
+ ];
+ },
+ useCallback(fn: unknown) {
+ const index = cursor++;
+ slots[index] ??= fn;
+ return slots[index];
+ },
+ useEffect(effect: () => unknown, deps: unknown[]) {
+ const index = cursor++;
+ const previous = slots[index] as unknown[] | undefined;
+ if (previous && deps.every((dep, i) => Object.is(dep, previous[i])))
+ return;
+ slots[index] = deps;
+ effects.push(effect);
+ },
+ },
+ "react/jsx-runtime": stubJsxRuntime(),
+ "lucide-react": {},
+ "@/lib/tick-icon": {},
+ "@hugeicons/react": {},
+ "@hugeicons/core-free-icons": {},
+ "@/components/ui/dropdown-menu": {},
+ "@/features/chat/hooks/use-rag-tool-disabled": {
+ useRagToolDisabled: () => false,
+ },
+ "@/features/chat/stores/chat-runtime-store": {
+ useChatRuntimeStore: (select: (s: typeof state) => unknown) =>
+ select(state),
+ },
+ "../api/rag-api": {
+ listKnowledgeBases: () =>
+ new Promise<Rows>((resolve) => pending.push(resolve)),
+ subscribeKnowledgeBasesChanged: (onChanged: () => void) => {
+ listeners.push(onChanged);
+ return () => {};
+ },
+ },
+ "./knowledge-base-dialog": { KnowledgeBaseDialog: "KnowledgeBaseDialog" },
+ },
+ );
+ function render() {
+ cursor = 0;
+ KnowledgeBaseComposerButton();
+ effects.splice(0).forEach((effect) => effect());
+ }
+ return { render, pending, listeners, sources };
+}
+
+const flush = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+test("a list fetched before a delete cannot land after the one fetched after it", async () => {
+ const app = harness();
+ app.render();
+ assert.equal(app.pending.length, 1);
+ // The active KB is deleted while the mount fetch is still out.
+ app.listeners.forEach((onChanged) => onChanged());
+ assert.equal(app.pending.length, 2);
+
+ // Both answers arrive before the next render, so React batches them and the fallback
+ // sees only whichever landed last.
+ app.pending[1]([]);
+ app.pending[0]([{ id: "kb-1", name: "Product docs" }]);
+ await flush();
+ app.render();
+ await flush();
+ app.render();
+
+ assert.deepEqual(app.sources, [{ type: "thread" }]);
+});
diff --git a/studio/frontend/tests/knowledge-base-dialog-focus.test.ts b/studio/frontend/tests/knowledge-base-dialog-focus.test.ts
new file mode 100644
index 00000000000..377908ba1b1
--- /dev/null
+++ b/studio/frontend/tests/knowledge-base-dialog-focus.test.ts
@@ -0,0 +1,391 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ loadWithStubs,
+ stubJsxRuntime,
+ type StubElement,
+} from "./helpers/module-stubs.ts";
+
+// Runs the real KnowledgeBaseDialog and its documents view on a small hook host. Each
+// component instance keeps its own hook slots, and a StrictMode mount runs its effects,
+// their cleanups, and the effects again on the same state and refs, as React 19 does.
+
+type Effect = {
+ deps?: unknown[];
+ cleanup?: (() => void) | void;
+ run?: () => (() => void) | void;
+};
+
+class Host {
+ slots: unknown[] = [];
+ cursor = 0;
+ queued: number[] = [];
+
+ begin() {
+ this.cursor = 0;
+ this.queued = [];
+ }
+
+ flushEffects() {
+ for (const index of this.queued.splice(0)) {
+ const effect = this.slots[index] as Effect;
+ effect.cleanup?.();
+ effect.cleanup = effect.run?.();
+ }
+ }
+
+ strictRemount() {
+ for (const slot of this.slots) {
+ const effect = slot as Effect | undefined;
+ if (effect && "run" in effect) effect.cleanup?.();
+ }
+ for (const slot of this.slots) {
+ const effect = slot as Effect | undefined;
+ if (effect && "run" in effect) effect.cleanup = effect.run?.();
+ }
+ }
+
+ unmount() {
+ for (const slot of this.slots) {
+ const effect = slot as Effect | undefined;
+ if (effect && "run" in effect) effect.cleanup?.();
+ }
+ }
+}
+
+const sameDeps = (a?: unknown[], b?: unknown[]) =>
+ Boolean(a && b && a.length === b.length && a.every((v, i) => Object.is(v, b[i])));
+
+let current: Host;
+const react = {
+ useState(initial: unknown) {
+ const host = current;
+ const index = host.cursor++;
+ if (!(index in host.slots)) host.slots[index] = initial;
+ return [
+ host.slots[index],
+ (next: unknown) => {
+ host.slots[index] =
+ typeof next === "function"
+ ? (next as (prev: unknown) => unknown)(host.slots[index])
+ : next;
+ },
+ ];
+ },
+ useRef(initial: unknown) {
+ const index = current.cursor++;
+ current.slots[index] ??= { current: initial };
+ return current.slots[index];
+ },
+ useCallback(fn: unknown, deps: unknown[]) {
+ const index = current.cursor++;
+ const prev = current.slots[index] as { fn: unknown; deps: unknown[] } | undefined;
+ if (prev && sameDeps(prev.deps, deps)) return prev.fn;
+ current.slots[index] = { fn, deps };
+ return fn;
+ },
+ useEffect(run: () => (() => void) | void, deps?: unknown[]) {
+ const index = current.cursor++;
+ const prev = current.slots[index] as Effect | undefined;
+ if (prev && sameDeps(prev.deps, deps)) return;
+ current.slots[index] = { ...prev, deps, run };
+ current.queued.push(index);
+ },
+};
+
+// The documents view defers its upload with window.setTimeout.
+globalThis.window = { setTimeout, clearTimeout } as unknown as Window &
+ typeof globalThis;
+
+const KB = { id: "kb-1", name: "Product docs", documentCount: 0 };
+const ITEM = { kind: "native", token: "tok-notes", name: "notes.md" };
+
+function harness(rows: Array<typeof KB> = [KB]) {
+ const state = { uploading: false };
+ const uploads: unknown[][] = [];
+ const abandoned: unknown[][] = [];
+ const errors: string[] = [];
+ const { KnowledgeBaseDialog } = loadWithStubs<{
+ KnowledgeBaseDialog: (props: Record<string, unknown>) => StubElement;
+ }>(
+ new URL(
+ "../src/features/rag/components/knowledge-base-dialog.tsx",
+ import.meta.url,
+ ),
+ {
+ react,
+ "react/jsx-runtime": stubJsxRuntime(),
+ "@hugeicons/core-free-icons": {},
+ "@hugeicons/react": {},
+ "lucide-react": {},
+ "@/components/ui/alert-dialog": {},
+ "@/components/ui/button": { Button: "Button" },
+ "@/components/ui/dialog": {
+ Dialog: "Dialog",
+ DialogContent: "DialogContent",
+ DialogDescription: "DialogDescription",
+ DialogHeader: "DialogHeader",
+ DialogTitle: "DialogTitle",
+ },
+ "@/components/ui/input": {},
+ "@/components/ui/label": {},
+ "@/components/ui/spinner": {},
+ "@/components/ui/textarea": {},
+ "@/lib/toast": {
+ toast: { error: (message: string) => errors.push(message) },
+ },
+ "@/lib/utils": { cn: () => "" },
+ "../api/rag-api": {
+ listKnowledgeBases: async () => rows,
+ listKnowledgeBaseDocuments: async () => [],
+ },
+ "../api/rag-availability": {
+ useRagAvailabilityStore: (
+ select: (s: {
+ isUnavailable: () => boolean;
+ unavailableReason: () => string | null;
+ }) => unknown,
+ ) =>
+ select({ isUnavailable: () => false, unavailableReason: () => null }),
+ },
+ "../types/rag": { isLinkedFolderManaged: () => false },
+ "./document-status-chip": {},
+ "./linked-folders-manager": {},
+ "./source-drop-policy": { RAG_SOURCE_UPLOAD_ACCEPT: "" },
+ "./use-rag-documents": {
+ // Like the real hook: a fresh `upload` every render (its scope argument is a new
+ // object each time), and an unmount cleanup that abandons uploads already running.
+ useRagDocuments: () => {
+ const generation = react.useRef(0) as { current: number };
+ react.useEffect(
+ () => () => {
+ generation.current += 1;
+ },
+ [],
+ );
+ return {
+ documents: [],
+ loading: false,
+ uploading: state.uploading,
+ refresh: async () => {},
+ upload: async (items: unknown[]) => {
+ const started = generation.current;
+ await Promise.resolve();
+ (started === generation.current ? uploads : abandoned).push(items);
+ },
+ remove: async () => {},
+ };
+ },
+ },
+ "./use-source-drop": {
+ useSourceDrop: () => ({
+ dragging: false,
+ dropProps: {},
+ nativeDropTarget: () => {},
+ }),
+ },
+ },
+ );
+
+ const dialog = new Host();
+ let documents: Host | null = null;
+ let documentsMounts = 0;
+ let tree: StubElement;
+ let props: Record<string, unknown> = {};
+
+ function find(
+ node: unknown,
+ match: (element: StubElement) => boolean,
+ ): StubElement | undefined {
+ if (Array.isArray(node)) {
+ for (const child of node) {
+ const hit = find(child, match);
+ if (hit) return hit;
+ }
+ return undefined;
+ }
+ if (!node || typeof node !== "object" || !("props" in node)) return undefined;
+ const element = node as StubElement;
+ if (match(element)) return element;
+ return find(element.props.children, match);
+ }
+
+ // Radix renders DialogContent only while the dialog is open, so a closed dialog has no
+ // documents view mounted, whatever its view state says.
+ const documentsView = () =>
+ props.open
+ ? find(
+ tree,
+ (e) =>
+ typeof e.type === "function" && e.type.name === "KnowledgeBaseDocuments",
+ )
+ : undefined;
+
+ // One render pass: the dialog, then its documents view if it shows one. A view that
+ // just appeared mounts the way StrictMode mounts it.
+ function render() {
+ current = dialog;
+ dialog.begin();
+ tree = KnowledgeBaseDialog(props);
+ dialog.flushEffects();
+ const view = documentsView();
+ if (!view) {
+ documents?.unmount();
+ documents = null;
+ return;
+ }
+ const mounting = documents === null;
+ if (mounting) documentsMounts += 1;
+ documents ??= new Host();
+ current = documents;
+ documents.begin();
+ (view.type as (p: Record<string, unknown>) => StubElement)(view.props);
+ documents.flushEffects();
+ if (mounting) documents.strictRemount();
+ }
+
+ async function settle() {
+ for (let i = 0; i < 4; i++) {
+ render();
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ }
+ }
+
+ return {
+ uploads,
+ abandoned,
+ errors,
+ async open(focus: Record<string, unknown> | null) {
+ props = { open: true, onOpenChange() {}, focus };
+ await settle();
+ },
+ async close() {
+ props = { ...props, open: false, focus: null };
+ await settle();
+ },
+ settle,
+ get title() {
+ return find(tree, (e) => e.type === "DialogTitle")?.props.children;
+ },
+ get documentsView() {
+ return documentsView();
+ },
+ get documentsMounts() {
+ return documentsMounts;
+ },
+ set uploading(value: boolean) {
+ state.uploading = value;
+ },
+ openRow() {
+ const row = find(tree, (e) => e.props.title === "Open to add or remove documents");
+ (row!.props.onClick as () => void)();
+ },
+ back() {
+ (documentsView()!.props.onBack as () => void)();
+ },
+ };
+}
+
+test("files handed to a knowledge base upload once, on the StrictMode mount that stays", async () => {
+ const app = harness();
+ await app.open({ kbId: KB.id, uploads: [ITEM] });
+ assert.equal(app.title, KB.name);
+ assert.deepEqual(app.uploads, [[ITEM]]);
+ assert.deepEqual(app.abandoned, []);
+
+ // Later renders hand the view a new `upload` each time; the batch must not go again.
+ await app.settle();
+ assert.deepEqual(app.uploads, [[ITEM]]);
+});
+
+test("going back and opening the knowledge base again does not upload the files twice", async () => {
+ const app = harness();
+ await app.open({ kbId: KB.id, uploads: [ITEM] });
+ app.back();
+ await app.settle();
+ assert.equal(app.documentsView, undefined);
+ app.openRow();
+ await app.settle();
+ assert.equal(app.title, KB.name);
+ assert.deepEqual(app.uploads, [[ITEM]]);
+});
+
+test("reopening the dialog on the same knowledge base without files uploads nothing more", async () => {
+ const app = harness();
+ await app.open({ kbId: KB.id, uploads: [ITEM] });
+ await app.close();
+ assert.equal(app.documentsView, undefined);
+ await app.open({ kbId: KB.id });
+ assert.equal(app.title, KB.name);
+ // Closing unmounted the view, so this is a fresh mount. The host lets that mount's timer
+ // fire before the open effect's reset renders, which is stricter than React's ordering.
+ assert.equal(app.documentsMounts, 2);
+ assert.deepEqual(app.uploads, [[ITEM]]);
+});
+
+test("a missing knowledge base says so only when files were handed over", async () => {
+ const withFiles = harness([]);
+ await withFiles.open({ kbId: KB.id, uploads: [ITEM] });
+ assert.equal(withFiles.title, "Knowledge bases");
+ assert.deepEqual(withFiles.errors, ["Knowledge base not found"]);
+ assert.deepEqual(withFiles.uploads, []);
+
+ const fromChip = harness([]);
+ await fromChip.open({ kbId: KB.id });
+ assert.equal(fromChip.title, "Knowledge bases");
+ assert.deepEqual(fromChip.errors, []);
+});
+
+test("files handed to a missing knowledge base go to the one opened next, once", async () => {
+ const app = harness();
+ await app.open({ kbId: "kb-deleted", uploads: [ITEM] });
+ assert.equal(app.title, "Knowledge bases");
+ assert.deepEqual(app.errors, ["Knowledge base not found"]);
+ assert.deepEqual(app.uploads, []);
+
+ app.openRow();
+ await app.settle();
+ assert.equal(app.title, KB.name);
+ assert.deepEqual(app.uploads, [[ITEM]]);
+
+ app.back();
+ await app.settle();
+ app.openRow();
+ await app.settle();
+ assert.deepEqual(app.uploads, [[ITEM]]);
+});
+
+test("a handoff that arrives while another waits joins it instead of replacing it", async () => {
+ const app = harness();
+ await app.open({ kbId: "kb-deleted", uploads: [ITEM] });
+ assert.deepEqual(app.uploads, []);
+ // The chat's next drop is handed over while the first batch is still waiting here.
+ const LATER = { kind: "native", token: "tok-faq", name: "faq.md" };
+ await app.open({ kbId: KB.id, uploads: [LATER] });
+ assert.equal(app.title, KB.name);
+ assert.deepEqual(app.uploads, [[ITEM, LATER]]);
+
+ // Once uploading, the batch is no longer waiting, so a later handoff goes alone.
+ const LAST = { kind: "native", token: "tok-last", name: "last.md" };
+ await app.open({ kbId: KB.id, uploads: [LAST] });
+ assert.deepEqual(app.uploads, [[ITEM, LATER], [LAST]]);
+});
+
+test("a handoff into the knowledge base on screen waits for its running upload without remounting", async () => {
+ const app = harness();
+ await app.open({ kbId: KB.id, uploads: [ITEM] });
+ assert.deepEqual(app.uploads, [[ITEM]]);
+ app.uploading = true;
+ // A second drop's "Add" while the first batch is still uploading in this view.
+ const LATER = { kind: "native", token: "tok-faq", name: "faq.md" };
+ await app.open({ kbId: KB.id, uploads: [LATER] });
+ assert.equal(app.documentsMounts, 1);
+ assert.deepEqual(app.uploads, [[ITEM]]);
+ app.uploading = false;
+ await app.settle();
+ assert.deepEqual(app.uploads, [[ITEM], [LATER]]);
+ assert.deepEqual(app.abandoned, []);
+});
diff --git a/studio/frontend/tests/knowledge-bases-changed-event.test.ts b/studio/frontend/tests/knowledge-bases-changed-event.test.ts
new file mode 100644
index 00000000000..76a8a088007
--- /dev/null
+++ b/studio/frontend/tests/knowledge-bases-changed-event.test.ts
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+// Every reader of the knowledge base list keeps its own copy: the composer's source menu,
+// whose fallback drops a deleted KB from the chat, and the source chip, which shows the
+// name. They stay right only if every create, rename and delete announces itself.
+
+type RagApi = {
+ createKnowledgeBase: (payload: { name: string }) => Promise<unknown>;
+ updateKnowledgeBase: (kbId: string, payload: { name: string }) => Promise<unknown>;
+ deleteKnowledgeBase: (kbId: string) => Promise<unknown>;
+ listKnowledgeBases: () => Promise<unknown>;
+ subscribeKnowledgeBasesChanged: (onChanged: () => void) => () => void;
+};
+
+function load(responses: Response[]) {
+ const requests: string[] = [];
+ const api = loadWithStubs<RagApi>(
+ new URL("../src/features/rag/api/rag-api.ts", import.meta.url),
+ {
+ "@/features/auth": {
+ authFetch: async (url: string, init?: { method?: string }) => {
+ requests.push(`${init?.method ?? "GET"} ${url}`);
+ return responses.shift()!;
+ },
+ },
+ "@/lib/api-base": { apiUrl: (path: string) => path },
+ "@/lib/format-fastapi-error": { formatFastApiDetail: () => null },
+ "@/lib/open-stream-response": {},
+ "@/lib/sse-json-events": {},
+ "./rag-availability": {
+ noteRagAvailability() {},
+ noteRagResponse() {},
+ },
+ },
+ );
+ return { api, requests };
+}
+
+globalThis.window = new EventTarget() as unknown as Window & typeof globalThis;
+
+test("create, rename and delete announce the change; listing does not", async () => {
+ const { api } = load([
+ Response.json({ id: "kb-1", name: "Product docs" }),
+ Response.json({ ok: true }),
+ Response.json({ ok: true }),
+ Response.json({ knowledgeBases: [], ragAvailable: true }),
+ ]);
+ let changes = 0;
+ const unsubscribe = api.subscribeKnowledgeBasesChanged(() => changes++);
+
+ await api.createKnowledgeBase({ name: "Product docs" });
+ assert.equal(changes, 1);
+ await api.updateKnowledgeBase("kb-1", { name: "Handbook" });
+ assert.equal(changes, 2);
+ await api.deleteKnowledgeBase("kb-1");
+ assert.equal(changes, 3);
+ await api.listKnowledgeBases();
+ assert.equal(changes, 3);
+
+ unsubscribe();
+});
+
+test("a delete that fails still announces, so readers refetch and see what is there", async () => {
+ const { api } = load([Response.json({ detail: "Not found" }, { status: 404 })]);
+ let changes = 0;
+ const unsubscribe = api.subscribeKnowledgeBasesChanged(() => changes++);
+ await assert.rejects(api.deleteKnowledgeBase("kb-gone"));
+ assert.equal(changes, 1);
+ unsubscribe();
+});
+
+test("an unsubscribed reader hears nothing more", async () => {
+ const { api } = load([Response.json({ id: "kb-2", name: "Notes" })]);
+ let changes = 0;
+ api.subscribeKnowledgeBasesChanged(() => changes++)();
+ await api.createKnowledgeBase({ name: "Notes" });
+ assert.equal(changes, 0);
+});
diff --git a/studio/frontend/tests/rag-thread-initialization.test.ts b/studio/frontend/tests/rag-thread-initialization.test.ts
index 90ffd75a755..2fd2b6936ee 100644
--- a/studio/frontend/tests/rag-thread-initialization.test.ts
+++ b/studio/frontend/tests/rag-thread-initialization.test.ts
@@ -24,6 +24,7 @@ function harness(
persist?: Promise<void>;
itemId?: string;
storedIds?: string[];
+ ragSource?: { type: "thread" } | { type: "kb"; kbId: string };
} = {},
) {
let initialized = options.initialized ?? false;
@@ -33,14 +34,20 @@ function harness(
let cursor = 0;
const slots: unknown[] = [];
const effects: Array<() => void> = [];
+ const cleanups: Array<() => void> = [];
const uploads: Scope[] = [];
const errors: string[] = [];
+ const toasts: Array<{
+ title: string;
+ data: { duration?: number; action?: { label: string; onClick: () => void } };
+ }> = [];
+ const dismissed: number[] = [];
const adopted: string[] = [];
const itemId = options.itemId ?? ID;
const storedIds = new Set(options.storedIds ?? []);
const state = {
ragEnabled: true,
- ragSource: { type: "thread" },
+ ragSource: options.ragSource ?? { type: "thread" },
activeProjectId: null,
projectAttachmentTarget: "thread",
projectAttachmentTargetByThread: {},
@@ -73,7 +80,12 @@ function harness(
nativePending = false;
return [
{
- path: { token: "native-docx", sizeBytes: 20, modifiedMs: 1 },
+ path: {
+ token: "native-docx",
+ sizeBytes: 20,
+ modifiedMs: 1,
+ expiresAtMs: Date.now() + 900_000,
+ },
displayLabel: "report.docx",
},
];
@@ -143,11 +155,21 @@ function harness(
useNativeIntentStore: nativeStore,
},
"@/lib/toast": {
- toast: { error: (message: string) => errors.push(message) },
+ toast: Object.assign(
+ (title: string, data: (typeof toasts)[number]["data"]) =>
+ toasts.push({ title, data }) - 1,
+ {
+ error: (message: string) => errors.push(message),
+ dismiss: (id: number) => dismissed.push(id),
+ },
+ ),
},
"@/components/ui/dropdown-menu": {},
"@/components/ui/alert-dialog": {},
- "../api/rag-api": {},
+ "../api/rag-api": {
+ listKnowledgeBases: async () => [{ id: "kb-1", name: "Product docs" }],
+ subscribeKnowledgeBasesChanged: () => () => {},
+ },
"../api/rag-availability": {
useRagAvailabilityStore: (
select: (s: { isUnavailable: () => boolean }) => unknown,
@@ -155,7 +177,17 @@ function harness(
},
"../types/rag": { RAG_UPLOAD_ACCEPT: ".docx" },
"./document-status-chip": {},
+ "./knowledge-base-dialog": { KnowledgeBaseDialog: "KnowledgeBaseDialog" },
+ "./staged-source": { EXPIRY_GRACE_MS: 30_000 },
"./use-rag-documents": {
+ uploadItemFromIntent: (intent: {
+ path: { token: string };
+ displayLabel: string;
+ }) => ({
+ kind: "native",
+ token: intent.path.token,
+ name: intent.displayLabel,
+ }),
useRagDocuments: () => ({
documents: [],
uploading: false,
@@ -178,12 +210,13 @@ function harness(
tree = ThreadDocumentsBar({
threadId: options.propId === undefined ? ID : options.propId,
});
- effects.splice(0).forEach((effect) => effect());
+ effects.splice(0).forEach((effect) => {
+ const cleanup = (effect as () => unknown)();
+ if (typeof cleanup === "function") cleanups.push(cleanup as () => void);
+ });
}
function pick() {
- const input = (tree.props.children as StubElement[]).find(
- (child) => child?.type === "input",
- )!;
+ const input = findElement(tree, "input")!;
const onChange = input.props.onChange as (event: unknown) => void;
onChange({
target: {
@@ -197,7 +230,18 @@ function harness(
pick,
uploads,
errors,
+ toasts,
+ dismissed,
adopted,
+ unmount() {
+ cleanups.splice(0).forEach((cleanup) => cleanup());
+ },
+ setRagSource(source: { type: "thread" } | { type: "kb"; kbId: string }) {
+ state.ragSource = source;
+ },
+ get tree() {
+ return tree;
+ },
drop() {
nativePending = true;
render();
@@ -297,3 +341,126 @@ test("initialization tags a temporary chat before the persistence check", async
assert.equal(app.initializeCalls, 1);
assert.equal(app.uploads[0]?.threadId, ID);
});
+
+function findElement(node: unknown, type: string): StubElement | undefined {
+ if (Array.isArray(node)) {
+ for (const child of node) {
+ const hit = findElement(child, type);
+ if (hit) return hit;
+ }
+ return undefined;
+ }
+ if (!node || typeof node !== "object" || !("props" in node)) return undefined;
+ const element = node as StubElement;
+ if (element.type === type) return element;
+ return findElement(element.props.children, type);
+}
+
+function kbDialog(tree: StubElement): StubElement | undefined {
+ return findElement(tree, "KnowledgeBaseDialog");
+}
+
+test("a native drop into a knowledge base chat offers to add the files to that knowledge base", async () => {
+ const app = harness({ ragSource: { type: "kb", kbId: "kb-1" } });
+ app.render();
+ await flush();
+ app.render();
+ app.drop();
+ await flush();
+ // Nothing goes to the thread: a thread upload would index somewhere this chat never reads.
+ assert.deepEqual(app.uploads, []);
+ assert.equal(app.initializeCalls, 0);
+ assert.deepEqual(app.errors, []);
+ assert.equal(kbDialog(app.tree)!.props.open, false);
+
+ // Names the file and the knowledge base, and stays while the dropped paths are readable.
+ assert.equal(app.toasts.length, 1);
+ const [{ title, data }] = app.toasts;
+ assert.equal(title, 'Add "report.docx" to "Product docs"?');
+ assert.equal(data.action?.label, "Add");
+ assert.ok(data.duration! > 60_000, `duration ${data.duration}`);
+ data.action!.onClick();
+ app.render();
+ const dialog = kbDialog(app.tree)!;
+ assert.equal(dialog.props.open, true);
+ assert.deepEqual(dialog.props.focus, {
+ kbId: "kb-1",
+ uploads: [{ kind: "native", token: "native-docx", name: "report.docx" }],
+ });
+
+ (dialog.props.onOpenChange as (open: boolean) => void)(false);
+ app.render();
+ assert.equal(kbDialog(app.tree)!.props.open, false);
+});
+
+test("the drop's Add still opens its knowledge base after the chat's source moves", async () => {
+ const app = harness({ ragSource: { type: "kb", kbId: "kb-1" } });
+ app.render();
+ await flush();
+ app.render();
+ app.drop();
+ await flush();
+ app.setRagSource({ type: "thread" });
+ app.render();
+ app.toasts[0].data.action!.onClick();
+ app.render();
+ const dialog = kbDialog(app.tree)!;
+ assert.equal(dialog.props.open, true);
+ assert.deepEqual(dialog.props.focus, {
+ kbId: "kb-1",
+ uploads: [{ kind: "native", token: "native-docx", name: "report.docx" }],
+ });
+ assert.deepEqual(app.uploads, []);
+});
+
+test("the knowledge base chip opens that knowledge base without uploading anything", () => {
+ const app = harness({ ragSource: { type: "kb", kbId: "kb-1" } });
+ app.render();
+ const chip = (app.tree.props.children as StubElement[]).find(
+ (child) => typeof child?.type === "function",
+ )!;
+ (chip.props.onOpen as () => void)();
+ app.render();
+ const dialog = kbDialog(app.tree)!;
+ assert.equal(dialog.props.open, true);
+ assert.deepEqual(dialog.props.focus, { kbId: "kb-1" });
+});
+
+test("an open dialog keeps its place when deleting the active knowledge base moves the source", () => {
+ // React keeps an instance only at the same type and position. Deleting the active KB
+ // inside the dialog switches the chat to its own files, and a dialog that moved in the
+ // tree would remount, replaying its animation and dropping its state.
+ const app = harness({ ragSource: { type: "kb", kbId: "kb-1" } });
+ app.render();
+ const chip = (app.tree.props.children as StubElement[]).find(
+ (child) => typeof child?.type === "function",
+ )!;
+ (chip.props.onOpen as () => void)();
+ app.render();
+ const place = (tree: StubElement) => ({
+ root: tree.type,
+ first: (tree.props.children as StubElement[])[0]?.type,
+ });
+ const before = place(app.tree);
+ app.setRagSource({ type: "thread" });
+ app.render();
+ assert.deepEqual(place(app.tree), before);
+ assert.deepEqual(before, {
+ root: Symbol.for("Fragment"),
+ first: "KnowledgeBaseDialog",
+ });
+ assert.equal(kbDialog(app.tree)!.props.open, true);
+});
+
+test("leaving the chat dismisses a drop's offer, whose Add could no longer open anything", async () => {
+ const app = harness({ ragSource: { type: "kb", kbId: "kb-1" } });
+ app.render();
+ await flush();
+ app.render();
+ app.drop();
+ await flush();
+ assert.equal(app.toasts.length, 1);
+ assert.deepEqual(app.dismissed, []);
+ app.unmount();
+ assert.deepEqual(app.dismissed, [0]);
+});