Skip to content

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

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
oobabooga:worktree-kb-upload-discoverability
Oct 6, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
oobabooga:worktree-kb-upload-discoverability

Conversation

@oobabooga

@oobabooga oobabooga commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

In the desktop app, dropping files onto a chat that retrieves from a knowledge base shows:

This chat retrieves from a knowledge base. Add these files to the knowledge base instead.

The toast gives no way to do that, and the dropped files are discarded. The only route to a knowledge base's files is the RAG pill's "Manage knowledge bases…", where the knowledge base name is an unstyled button next to a pencil that renames it.

Reported on Reddit: the reporter searched Settings and both sidebars, then found it by trial and error.

Fix

  • The toast now asks Add "release-notes.md" to "Product docs"? with an "Add" action. "Add" opens that knowledge base's documents and uploads the dropped files there, through the same native path upload the dialog already uses. The toast is neutral rather than an error and stays up for as long as the dropped files can still be added. Nothing goes to the thread, as before.
  • The "Knowledge base: " chip above the composer is now a button that opens the same view. Closing the dialog returns focus to it.
  • Knowledge base rows get a chevron, a hover background, a focus ring and a tooltip.
  • Creating a knowledge base opens it on its documents view instead of going back to the list.
  • Creating, renaming or deleting a knowledge base now makes the composer's source menu and the chip refetch, so deleting the active knowledge base from the chip's dialog moves the chat back to its own files.

In the browser, a dropped file is still attached to the message, so the toast only appears in the desktop app. The other changes apply to both.

Validation

Live A/B in headless Chromium against one backend on a fresh profile. The desktop drop was simulated with the Tauri bridge stubbed; its path leases were signed with a test secret and verified by the real backend upload route.

Step main This PR
Drop a file on a chat using an empty knowledge base Error toast with no action, gone after about 5 s; file discarded Toast with "Add"; the file is indexed in the knowledge base, with one upload request even after closing and reopening
Click the knowledge base chip Nothing Opens that knowledge base's documents
Knowledge base row No chevron, hover change or focus ring All three
Create a knowledge base Back to the list Opens the new knowledge base with Upload

Before (main) and after (this PR):

Dropping a file on a chat that uses a knowledge base (desktop app):

4_drop_toast

Clicking the "Knowledge base: Product docs" chip:

3_chip_click

The list in "Manage knowledge bases…", row hovered:

1_list_row

Right after creating a knowledge base:

2_after_create
  • 11 new tests cover the drop offer and its handoff to the dialog, uploading the files exactly once (including under StrictMode and after closing and reopening), and the refetch after create, rename and delete. All 11 fail on main.
  • Frontend: 10,542 of 10,555 tests passed. The 13 failures also fail on main.
  • Typecheck passed. ESLint found nothing new in changed files.

Limitations

  • Knowledge bases are still managed only from the composer's RAG menu. The reporter looked in Settings first, and Settings has no knowledge base entry; that is left for a follow-up.
  • A real desktop window with an OS drop was not tested, and neither were Windows or macOS.

Before / after (Studio, merge base vs this PR)

Two isolated Studio installs built from the merge base (6f4d997) and this branch (856e96d), driven in headless Chromium with a knowledge base "Product docs" selected as the chat's retrieval source.

Clicking the "Knowledge base: Product docs" chip: before it is a plain label and nothing opens; after it opens that knowledge base's documents with Upload.

chip click

"Manage knowledge bases..." with the row hovered: the row gains a chevron, a hover background and a tooltip.

list row

Right after creating "Release notes": before, back to the list; after, the new knowledge base's documents view with Upload.

after create

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#335.

@danielhanchen

Copy link
Copy Markdown
Member

Two red checks here:

  1. Frontend build + bundle sanity is from main (the branch picker chevrons in the user message footer measure 20px against the 24px floor). It is being fixed in Branch picker chevrons: give back the 24px hit target in the same 20px slot #12781 and needs no change here.
  2. Parity verdict, scored against the null is from this PR. delete_message and thread_reopen at the 100K rung differ in the thread scaffolding outside any message (13636 to 11595 characters). The evidence artifact (studiobench-parity-evidence on run 37374435518) shows the one on-screen difference: the merge base draws an empty card above the composer, and this branch does not. That card is the thread documents bar this PR changes. If dropping the empty card is intended, that is the deliberate difference the parity policy asks to be called out; if not, the documents bar is no longer rendering for a thread that had it.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 6, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 6, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #12779, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#459.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror dcda487e0 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx (on the mirror)

@@ -84,24 +97,58 @@ 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);
     }
   }, []);
 
   useEffect(() => {
-    if (!open) return;
+    if (!open) {
+      handoffRef.current = [];
+      handedFocusRef.current = null;
+      return;
+    }
+    // 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;
     setView({ kind: "list" });
-    void refresh();
-  }, [open, refresh]);
+    void refresh().then((rows) => {

P1 Badge Preserve an active upload when another handoff arrives

If a user accepts a second dropped-file toast while the first handoff is still uploading, changing focus reruns this effect and switches the dialog to the list view. That unmounts KnowledgeBaseDocuments, whose useRagDocuments cleanup invalidates the active upload, while takeUploads has already removed the first batch from the dialog; depending on which await it reached, those files are either never uploaded or their completed upload is no longer tracked. Keep the documents view mounted while folding in the new batch, or explicitly queue the handoff until the current upload finishes.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 856e96d: a handoff into the knowledge base already on screen keeps the documents view mounted, and its files wait until the running upload finishes.

chatgpt-codex-connector[bot] on studio/frontend/src/features/rag/api/rag-api.ts (on the mirror)

@@ -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));
+}

P2 Badge Broadcast knowledge-base mutations across tabs

This DOM event reaches only the window that performed the mutation. If a knowledge base is renamed or deleted in another Studio tab, this tab's composer and source chip receive no notification, so the composer can retain and send the deleted kb_id until the user manually reopens the source menu. The same module already uses BroadcastChannel for project-source mutations; knowledge-base changes need an equivalent cross-tab notification.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not introduced here: on main the composer never heard about mutations from other tabs either, and it still refetches whenever its menu opens. Cross-tab sync is a separate change.

Round 2: reviewed mirror 10dbc913a (this PR's 856e96d56)

chatgpt-codex-connector[bot] on studio/frontend/src/features/rag/components/thread-documents-bar.tsx (on the mirror)

@@ -559,32 +617,48 @@ 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,

P2 Badge Expire the drop action by wall-clock time

When the app is hidden or the pointer remains over the toast, Sonner pauses its duration countdown, so this offer can remain clickable after expiresAtMs. Clicking it then hands an expired native token to consumeNativePathToken; because the batch was already removed from the native-intent queue, the upload fails and the user must drop the files again. Dismiss or disable the action based on the absolute expiry timestamp rather than relying only on the toast duration.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

An expired token fails the upload with a visible "Couldn't upload " toast and the files stay on disk to drop again; on main the drop was discarded outright, so nothing is lost relative to today.

chatgpt-codex-connector[bot] on studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx (on the mirror)

@@ -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);

P1 Badge Keep handed-off batches until every upload has started

When a handed-off native batch contains multiple files and the user closes the dialog or clicks “All knowledge bases” while the first file is uploading, this call clears the entire handoff before upload() completes. Unmounting KnowledgeBaseDocuments then triggers useRagDocuments cleanup, increments its generation, and causes the sequential upload loop to exit before starting the remaining files; reopening cannot retry them because handoffRef is already empty. Retain the batch until the upload promise settles, or prevent the documents view from unmounting while it is active.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Pre-existing: closing the knowledge base dialog mid-upload abandons the rest of any batch started there on main too (picker or drop), through the same useRagDocuments unmount path this PR does not change. Out of scope here.

chatgpt-codex-connector[bot] on studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx (on the mirror)

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

P1 Badge Queue handoffs targeting a different knowledge base

When two outstanding drop offers target different knowledge bases, clicking the second offer while the first multi-file batch is uploading takes this fallback because the IDs differ, unmounting the first KnowledgeBaseDocuments; its useRagDocuments cleanup invalidates the sequential upload loop, and takeUploads has already cleared that batch, so the remaining files are never started or recoverable from the dialog. The fresh evidence beyond the prior same-KB finding is that the new preservation guard applies only when current.kb.id === focus.kbId; keep the active view mounted or queue cross-KB handoffs until its upload settles.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Needs two live offers for different knowledge bases from one chat (switch its retrieval source between two drops) plus a click on the second during the first batch's upload; the realistic same-KB case is handled in 856e96d.

Round 3: reviewed mirror 10dbc913a1 (this PR's 856e96d56)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 10dbc913a1

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 10dbc913a1 (this PR's 856e96d56).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit c94eecd into unslothai:main Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants