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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: attach saved Library files to the current chat (#16522)
Daniel Han220719e1ec70
diff --git a/studio/frontend/scripts/check-library-picker.py b/studio/frontend/scripts/check-library-picker.pynew file mode 100644index 00000000000..078014b47f2--- /dev/null+++ b/studio/frontend/scripts/check-library-picker.py@@ -0,0 +1,184 @@+# 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 json+import os+import re+import time+import uuid+from pathlib import Path+from urllib.parse import urlsplit+from urllib.request import Request, urlopen++from playwright.sync_api import expect, sync_playwright+++def main():+ base = os.environ["BASE_URL"].rstrip("/")+ out = Path(os.environ["PW_ART_DIR"])+ out.mkdir(parents = True, exist_ok = True)+ token = ""++ def api(+ path,+ body = None,+ method = "POST",+ content_type = "application/json",+ ):+ data = body if isinstance(body, bytes) else json.dumps(body).encode()+ request = Request(base + path, data = None if method == "GET" else data, method = method)+ request.add_header("Content-Type", content_type)+ if token:+ request.add_header("Authorization", "Bearer " + token)+ with urlopen(request, timeout = 30) as response:+ return json.load(response)++ auth = api("/api/auth/login", {"username": "unsloth", "password": os.environ["STUDIO_PW"]})+ token = auth["access_token"]+ ident = uuid.uuid4().hex+ thread = "library-picker-" + ident+ name = f"picker-note-{ident[:8]}.txt"+ note = b"Saved Library report: revenue grew by 12 percent.\n"+ boundary = "picker-" + ident+ multipart = (+ (+ f'--{boundary}\r\nContent-Disposition: form-data; name="files"; filename="{name}"\r\n'+ "Content-Type: text/plain\r\n\r\n"+ ).encode()+ + note+ + f"\r\n--{boundary}--\r\n".encode()+ )+ api("/api/library/uploads", multipart, content_type = "multipart/form-data; boundary=" + boundary)+ saved = next(+ item for item in api("/api/library", method = "GET")["items"] if item["name"] == name+ )+ now = int(time.time() * 1000)+ api(+ "/api/chat/threads",+ {+ "id": thread,+ "title": "Library picker regression",+ "modelType": "base",+ "modelId": "",+ "createdAt": now,+ "updatedAt": now,+ },+ )+ parent = None+ for role, text in [+ ("user", "Please review a saved file."),+ ("assistant", "Attach your Library report."),+ ]:+ message = ident + "-" + role+ api(+ f"/api/chat/threads/{thread}/messages/{message}",+ {+ "id": message,+ "threadId": thread,+ "parentId": parent,+ "role": role,+ "content": [{"type": "text", "text": text}],+ "createdAt": now,+ },+ method = "PUT",+ )+ parent = message+ seed = {+ "unsloth_auth_token": token,+ "unsloth_refresh_token": auth.get("refresh_token", ""),+ "unsloth_chat_connections_enabled": "false",+ "unsloth_chat_external_providers": "[]",+ "unsloth_chat_external_provider_keys": "{}",+ }+ facts = {"passed": False, "attachment_counts": [], "pointer_events": []}+ with sync_playwright() as pw:+ browser = pw.chromium.launch()+ context = browser.new_context(viewport = {"width": 1280, "height": 900})+ context.add_init_script(+ "for (const [k,v] of Object.entries("+ + json.dumps(seed)+ + ")) localStorage.setItem(k,v);"+ )+ page = context.new_page()+ page.set_default_timeout(15_000)+ try:+ page.goto(f"{base}/chat?thread={thread}", wait_until = "domcontentloaded")+ expect(page.get_by_text("Attach your Library report.", exact = True)).to_be_visible(+ timeout = 60_000+ )+ composer = page.locator("form:has(textarea)").filter(visible = True).first+ text = composer.locator("textarea").first+ draft = "Summarize the attached report without leaving this conversation."+ text.fill(draft)+ original_url = page.url+ plus = composer.get_by_role("button", name = "Tools and attachments", exact = True)+ dialog = page.get_by_role("dialog", name = "Attach from Library", exact = True)+ remove = composer.get_by_role("button", name = "Remove file", exact = True)+ for attempt in range(2):+ plus.click()+ expect(+ page.get_by_role("menuitem", name = "Attach from Library", exact = True)+ ).to_have_count(0)+ page.get_by_role("menuitem", name = "More", exact = True).click()+ page.get_by_role("menuitem", name = "Attach from Library", exact = True).click()+ expect(dialog).to_be_visible()+ dialog.get_by_placeholder("Search Library files...", exact = True).fill(name)+ with page.expect_response(+ lambda response: urlsplit(response.url).path == urlsplit(saved["fileUrl"]).path+ and response.request.method == "GET"+ ) as response:+ dialog.get_by_role("option").filter(has_text = name).click()+ assert response.value.ok and response.value.body() == note, "Library bytes changed"+ expect(dialog).to_be_hidden()+ expect(remove).to_have_count(1)+ expect(text).to_have_value(draft)+ assert page.url == original_url, "Attaching changed the conversation"+ page.wait_for_function("getComputedStyle(document.body).pointerEvents !== 'none'")+ facts["attachment_counts"].append(remove.count())+ facts["pointer_events"].append(+ page.evaluate("getComputedStyle(document.body).pointerEvents")+ )+ if attempt == 0:+ remove.click()+ expect(remove).to_have_count(0)+ page.screenshot(path = str(out / "library-picker-attached.png"), animations = "disabled")+ page.get_by_test_id("nav-row-library").click(timeout = 5_000)+ heading = page.locator("h1").filter(has_text = re.compile(r"^Library$"))+ expect(heading).to_be_visible()+ facts["sidebar_click_succeeded"] = True+ page.locator(f'[data-testid="recent-thread"][data-thread-id="{thread}"]').click()+ page.wait_for_url(+ lambda url: urlsplit(url).path == "/chat" and thread in urlsplit(url).query+ )+ expect(text).to_be_visible()+ marker = uuid.uuid4().hex+ page.evaluate("value => { window.__libraryPickerDocument = value; }", marker)+ retained = composer.element_handle()+ plus.click()+ page.get_by_role("menuitem", name = "More", exact = True).click()+ page.get_by_role("menuitem", name = "Attach from Library", exact = True).click()+ expect(dialog).to_be_visible()+ page.go_back(wait_until = "domcontentloaded")+ page.wait_for_url(lambda url: urlsplit(url).path == "/library")+ expect(heading).to_be_visible()+ expect(dialog).to_be_hidden()+ facts["same_document"] = page.evaluate(+ "value => window.__libraryPickerDocument === value", marker+ )+ facts["composer_retained"] = page.evaluate("node => node.isConnected", retained)+ assert facts["same_document"] and facts["composer_retained"], "Back reloaded the app"+ facts["dialog_hidden_after_back"] = True+ facts["draft_preserved"] = True+ facts["passed"] = True+ finally:+ page.screenshot(path = str(out / "library-picker-final.png"), animations = "disabled")+ (out / "library-picker-facts.json").write_text(+ json.dumps(facts, indent = 2), encoding = "utf-8"+ )+ context.close()+ browser.close()+ print("Library picker browser checks passed.")+++if __name__ == "__main__":+ main()diff --git a/studio/frontend/src/components/assistant-ui/library-attachment-picker.tsx b/studio/frontend/src/components/assistant-ui/library-attachment-picker.tsxnew file mode 100644index 00000000000..781da160073--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/library-attachment-picker.tsx@@ -0,0 +1,209 @@+// 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 { useAui } from "@assistant-ui/react";+import {+ useCallback,+ useContext,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ Command,+ CommandEmpty,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Spinner } from "@/components/ui/spinner";+import { getAuthSessionEpoch } from "@/features/auth";+import {+ createLibraryComposerAttachment,+ fileKind,+ getLibrary,+ libraryItemFile,+ LibraryAttachmentTargetContext,+ LibraryFileTooLarge,+ type LibraryItem,+} from "@/features/library";+import { MAX_AUDIO_SIZE } from "@/lib/audio-utils";+import { MAX_VIDEO_SIZE } from "@/lib/video-utils";+import { useT } from "@/i18n";++function attachmentLimit(item: LibraryItem): number {+ const kind = fileKind(item);+ if (kind === "audio") return MAX_AUDIO_SIZE;+ if (kind === "video") return MAX_VIDEO_SIZE;+ return kind === "image" ||+ kind === "code" ||+ kind === "web" ||+ item.textOnly ||+ item.contentType.startsWith("text/")+ ? 20 * 1024 * 1024+ : 50 * 1024 * 1024;+}++export function LibraryAttachmentPicker({ onClose }: { onClose: () => void }) {+ const t = useT();+ const aui = useAui();+ const target = useContext(LibraryAttachmentTargetContext);+ const currentTarget = useRef(target);+ useLayoutEffect(() => {+ currentTarget.current = target;+ }, [target]);+ const [origin] = useState(() => ({ target, session: getAuthSessionEpoch() }));+ const mounted = useRef(true);+ const [items, setItems] = useState<LibraryItem[]>([]);+ const [loading, setLoading] = useState(true);+ const [query, setQuery] = useState("");+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const valid = useCallback(+ () =>+ mounted.current &&+ currentTarget.current === origin.target &&+ getAuthSessionEpoch() === origin.session,+ [origin],+ );++ useEffect(() => {+ mounted.current = true;+ let cancelled = false;+ void getLibrary()+ .then((library) => {+ if (!cancelled && getAuthSessionEpoch() === origin.session)+ setItems(library.items.filter((item) => !item.model));+ })+ .catch((cause: unknown) => {+ if (!cancelled)+ setError(cause instanceof Error ? cause.message : String(cause));+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ mounted.current = false;+ };+ }, [origin.session]);++ useEffect(() => {+ if (target === null || target !== origin.target) onClose();+ }, [target, origin.target, onClose]);++ const attach = useRef<((item: LibraryItem) => Promise<boolean>) | null>(null);+ useEffect(() => {+ attach.current = createLibraryComposerAttachment<LibraryItem>({+ getTarget: () => currentTarget.current,+ getSession: getAuthSessionEpoch,+ isEditing: () => valid() && aui.composer().getState().isEditing,+ read: (item) => libraryItemFile(item, attachmentLimit(item)),+ add: (file) => aui.composer().addAttachment(file),+ });+ }, [aui, valid]);++ const results = useMemo(() => {+ const search = query.trim().toLocaleLowerCase();+ return items+ .filter((item) =>+ `${item.name} ${item.fileName ?? ""}`+ .toLocaleLowerCase()+ .includes(search),+ )+ .sort((a, b) => b.updatedAt - a.updatedAt)+ .slice(0, 50);+ }, [items, query]);++ const select = async (item: LibraryItem) => {+ if (pending || !valid()) return;+ setPending(true);+ setError(null);+ try {+ if (item.sizeBytes !== null && item.sizeBytes > attachmentLimit(item))+ throw new LibraryFileTooLarge(item.name);+ if ((await attach.current?.(item)) && valid()) onClose();+ } catch (cause) {+ if (valid())+ setError(+ cause instanceof LibraryFileTooLarge+ ? t("library.toast.tooLargeOne", { name: item.name })+ : cause instanceof Error+ ? cause.message+ : String(cause),+ );+ } finally {+ if (mounted.current) setPending(false);+ }+ };++ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DialogContent className="gap-4 sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Attach from Library</DialogTitle>+ <DialogDescription>+ Choose a saved file to attach to this message.+ </DialogDescription>+ </DialogHeader>+ <Command shouldFilter={false}>+ <CommandInput+ placeholder="Search Library files..."+ value={query}+ onValueChange={setQuery}+ disabled={pending}+ />+ <CommandList aria-label="Library files">+ {loading || pending ? (+ <Spinner+ className="mx-auto my-4 size-5"+ label={pending ? "Attaching file" : "Loading Library"}+ />+ ) : null}+ {!loading && !pending ? (+ <CommandEmpty>No files found.</CommandEmpty>+ ) : null}+ {results.map((item) => (+ <CommandItem+ key={item.id}+ value={item.id}+ disabled={pending}+ onSelect={() => {+ void select(item);+ }}+ >+ <span className="min-w-0 flex-1 truncate">{item.name}</span>+ <span className="shrink-0 text-xs text-muted-foreground">+ {t(+ item.source === "generated"+ ? "library.toolbar.generated"+ : "library.toolbar.uploaded",+ )}+ </span>+ </CommandItem>+ ))}+ </CommandList>+ </Command>+ {error ? (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ ) : null}+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 759fb08b9cc..f596d1ba2e0 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -6777,6 +6777,12 @@ function usePickComposerAttachment(): () => void {}, [aui, audioAttachmentsEnabled]);}+const LazyLibraryAttachmentPicker = lazy(() =>+ import("@/components/assistant-ui/library-attachment-picker").then((module) => ({+ default: module.LibraryAttachmentPicker,+ })),+);+const ComposerToolsMenu: FC<{side?: "top" | "bottom";researchAvailable: boolean;@@ -6872,6 +6878,8 @@ const ComposerToolsMenu: FC<{const [newProjectOpen, setNewProjectOpen] = useState(false);const [skillsOn, setSkillsOn] = useSkillsSwitch();const [promptStorageOpen, setPromptStorageOpen] = useState(false);+ const [libraryPickerOpen, setLibraryPickerOpen] = useState(false);+ const libraryPickerRequested = useRef(false);const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);const aui = useAui();const composerCanAddAttachments = useAuiState(@@ -7196,6 +7204,11 @@ const ComposerToolsMenu: FC<{return (<>+ {libraryPickerOpen ? (+ <Suspense fallback={null}>+ <LazyLibraryAttachmentPicker onClose={() => setLibraryPickerOpen(false)} />+ </Suspense>+ ) : null}<PromptStorageDialogopen={promptStorageOpen}onOpenChange={setPromptStorageOpen}@@ -7223,7 +7236,13 @@ const ComposerToolsMenu: FC<{avoidCollisions={true}className="unsloth-plus-menu w-[calc(244px*var(--ui-space-scale,1))]"// Don't refocus the + on close; restored focus showed a stray ring.- onCloseAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ if (libraryPickerRequested.current) {+ libraryPickerRequested.current = false;+ if (chatActive) setLibraryPickerOpen(true);+ }+ }}><DropdownMenuItemdisabled={!composerCanAddAttachments}@@ -7318,6 +7337,14 @@ const ComposerToolsMenu: FC<{More</DropdownMenuSubTrigger><DropdownMenuSubContent className="unsloth-plus-menu w-[calc(248px*var(--ui-space-scale,1))]">+ <DropdownMenuItem+ disabled={!composerCanAddAttachments}+ onSelect={() => { libraryPickerRequested.current = true; }}+ >+ <HugeiconsIcon icon={Attachment01Icon} strokeWidth={2} />+ Attach from Library+ </DropdownMenuItem>+ <DropdownMenuSeparator />{overflowPlusItems.map((id) => (<Fragment key={id}>{plusMenuNodes[id]}</Fragment>))}diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 165e0f5fa02..2fbf4de39e4 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -25,6 +25,7 @@ import {useModelReasoningEffortStore,} from "@/features/model-picker";import { ProjectComposer, Thread } from "@/components/assistant-ui/thread";+import { LibraryAttachmentTargetContext } from "@/features/library";import { usePlatformStore } from "@/config/env";import { CopyableErrorChip } from "@/components/ui/copyable-error-chip";import {@@ -4858,6 +4859,7 @@ export function ChatPage({aborting generation (#8908). Any key here brings the bug back. Compare renders as asibling so it hides this rather than unmounting it, since ComparePane builds its ownproviders and nesting throws. */}+ <LibraryAttachmentTargetContext.Provider value={active ? shownChatKey : null}>{baseView ? (<divclassName={@@ -4933,6 +4935,7 @@ export function ChatPage({/>) : null}+ </LibraryAttachmentTargetContext.Provider>{showBrowserOverlay ? <BrowserOverlay /> : null}</div>diff --git a/studio/frontend/src/features/library/composer-attachment-target.ts b/studio/frontend/src/features/library/composer-attachment-target.tsnew file mode 100644index 00000000000..d76d24e98ca--- /dev/null+++ b/studio/frontend/src/features/library/composer-attachment-target.ts@@ -0,0 +1,8 @@+// 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 { createContext } from "react";++export const LibraryAttachmentTargetContext = createContext<string | null>(+ null,+);diff --git a/studio/frontend/src/features/library/composer-attachment.ts b/studio/frontend/src/features/library/composer-attachment.tsnew file mode 100644index 00000000000..e6954b3dfa1--- /dev/null+++ b/studio/frontend/src/features/library/composer-attachment.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export function createLibraryComposerAttachment<Item>({+ getTarget,+ getSession,+ read,+ add,+ isEditing,+}: {+ getTarget: () => string | null;+ getSession: () => number;+ read: (item: Item) => Promise<File>;+ add: (file: File) => Promise<unknown>;+ isEditing: () => boolean;+}): (item: Item) => Promise<boolean> {+ let pending = false;+ return async (item) => {+ const target = getTarget();+ const session = getSession();+ if (pending || target === null || !isEditing()) return false;+ pending = true;+ try {+ const file = await read(item);+ if (getTarget() !== target || getSession() !== session || !isEditing()) {+ return false;+ }+ await add(file);+ return true;+ } finally {+ pending = false;+ }+ };+}diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.tsindex 04c0243d5b7..787e60e003c 100644--- a/studio/frontend/src/features/library/index.ts+++ b/studio/frontend/src/features/library/index.ts@@ -2,6 +2,8 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export { useLibraryChatHandoffStore } from "./chat-handoff-store";+export { createLibraryComposerAttachment } from "./composer-attachment";+export { LibraryAttachmentTargetContext } from "./composer-attachment-target";export { LIBRARY_CHATS_PREFS_STORAGE_KEY } from "./chats/prefs-store";export { useLibraryFavorite, useLibraryFavorites, useLibraryFavoritesStore } from "./favorites-store";export { ConfirmDeleteDialog } from "./components/library-dialogs";@@ -28,6 +30,9 @@ export {type LibraryLocation,addLibraryItemToProject,errorMessage,+ getLibrary,+ libraryItemFile,+ LibraryFileTooLarge,getLibraryLocations,moveLibraryLocation,revealLibraryLocation,diff --git a/studio/frontend/tests/library-composer-attachment.test.ts b/studio/frontend/tests/library-composer-attachment.test.tsnew file mode 100644index 00000000000..d1a7c2034ab--- /dev/null+++ b/studio/frontend/tests/library-composer-attachment.test.ts@@ -0,0 +1,176 @@+// 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 { createLibraryComposerAttachment } from "../src/features/library/composer-attachment.ts";+import type { LibraryItem } from "../src/features/library/api.ts";+import * as fileNames from "../src/features/library/file-name.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++const item: LibraryItem = {+ id: "upload:report",+ name: "report.txt",+ source: "uploaded",+ contentType: "text/plain",+ sizeBytes: 15,+ createdAt: 1,+ updatedAt: 1,+ fileUrl: "/api/library/uploads/report/file",+ threadId: null,+ threadTitle: null,+ textOnly: false,+ favorite: false,+ folderId: null,+ openedAt: null,+ model: null,+};++const file = () => new File(["Revenue: €42\n"], "report.txt", { type: "text/plain" });++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}++function composer(read: (entry: LibraryItem) => Promise<File> = async () => file()) {+ const state = { target: "chat:existing" as string | null, session: 1, editing: true };+ const attached: { target: string | null; file: File }[] = [];+ const attach = createLibraryComposerAttachment({+ getTarget: () => state.target,+ getSession: () => state.session,+ isEditing: () => state.editing,+ read,+ add: async (selected) => { attached.push({ target: state.target, file: selected }); },+ });+ return { state, attached, attach };+}++test("a saved file keeps its bytes and attaches to the ongoing conversation", async () => {+ const requested: string[] = [];+ const api = loadWithStubs<typeof import("../src/features/library/api.ts")>(+ new URL("../src/features/library/api.ts", import.meta.url), {+ "@/features/auth": {+ authFetch: async (url: string) => {+ requested.push(url);+ return new Response("Revenue: €42\n");+ },+ },+ "@/i18n": {},+ "@/lib/api-base": {},+ "@/lib/format-fastapi-error": {},+ "./file-name": fileNames,+ "./note-text": {},+ },+ );+ const { state, attached, attach } = composer((entry) => api.libraryItemFile(entry, 20));+ assert.equal(await attach(item), true);+ assert.deepEqual(requested, ["/api/library/uploads/report/file"]);+ assert.equal(state.target, "chat:existing");+ assert.equal(attached.length, 1);+ assert.equal(attached[0].target, "chat:existing");+ assert.equal(attached[0].file.name, "report.txt");+ assert.equal(attached[0].file.type, "text/plain");+ assert.equal(await attached[0].file.text(), "Revenue: €42\n");+});++test("the existing Library read limit refuses a grown file before it reaches the composer", async () => {+ const api = loadWithStubs<typeof import("../src/features/library/api.ts")>(+ new URL("../src/features/library/api.ts", import.meta.url), {+ "@/features/auth": { authFetch: async () => new Response("x".repeat(21)) },+ "@/i18n": { translate: (key: string) => key },+ "@/lib/api-base": {},+ "@/lib/format-fastapi-error": {},+ "./file-name": fileNames,+ "./note-text": {},+ },+ );+ const { attached, attach } = composer((entry) => api.libraryItemFile(entry, 20));+ await assert.rejects(attach(item), api.LibraryFileTooLarge);+ assert.deepEqual(attached, []);+});++test("a chat switch while the Library file loads does not attach it to the next chat", async () => {+ const pending = deferred<File>();+ const { state, attached, attach } = composer(() => pending.promise);+ const attaching = attach(item);+ state.target = "chat:next";+ pending.resolve(file());+ assert.equal(await attaching, false);+ assert.deepEqual(attached, []);+});++test("a sign-out while a Library file loads does not pass it to the next account", async () => {+ const pending = deferred<File>();+ const { state, attached, attach } = composer(() => pending.promise);+ const attaching = attach(item);+ state.session += 1;+ pending.resolve(file());+ assert.equal(await attaching, false);+ assert.deepEqual(attached, []);+});++test("sending the draft while a Library file loads does not append it to a locked composer", async () => {+ const pending = deferred<File>();+ const { state, attached, attach } = composer(() => pending.promise);+ const attaching = attach(item);+ state.editing = false;+ pending.resolve(file());+ assert.equal(await attaching, false);+ assert.deepEqual(attached, []);+});++test("double-clicking a Library entry starts one read and adds one attachment", async () => {+ const pending = deferred<File>();+ let reads = 0;+ const { attached, attach } = composer(() => {+ reads += 1;+ return pending.promise;+ });+ const first = attach(item);+ const second = attach(item);+ pending.resolve(file());+ assert.deepEqual(await Promise.all([first, second]), [true, false]);+ assert.equal(reads, 1);+ assert.equal(attached.length, 1);+});++test("a failed read can be retried without losing the existing conversation", async () => {+ let reads = 0;+ const { state, attached, attach } = composer(async () => {+ if (++reads === 1) throw new Error("File no longer available");+ return file();+ });+ await assert.rejects(attach(item), /File no longer available/);+ assert.equal(await attach(item), true);+ assert.equal(state.target, "chat:existing");+ assert.equal(attached.length, 1);+});++test("the existing attachment adapter can refuse a file and allow a later retry", async () => {+ let supported = false;+ let calls = 0;+ const attach = createLibraryComposerAttachment({+ getTarget: () => "chat:existing",+ getSession: () => 1,+ isEditing: () => true,+ read: async () => file(),+ add: async () => {+ calls += 1;+ if (!supported) throw new Error("Load a model first");+ },+ });+ await assert.rejects(attach(item), /Load a model first/);+ supported = true;+ assert.equal(await attach(item), true);+ assert.equal(calls, 2);+});++test("a file removed from the composer may be selected again in the same chat", async () => {+ const { attached, attach } = composer();+ assert.equal(await attach(item), true);+ attached.splice(0);+ assert.equal(await attach(item), true);+ assert.equal(attached.length, 1);+});diff --git a/studio/frontend/tests/library-composer-picker.test.ts b/studio/frontend/tests/library-composer-picker.test.tsnew file mode 100644index 00000000000..48af76b3802--- /dev/null+++ b/studio/frontend/tests/library-composer-picker.test.ts@@ -0,0 +1,163 @@+// 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 { createLibraryComposerAttachment } from "../src/features/library/composer-attachment.ts";+import { loadWithStubs, stubJsxRuntime, type StubElement } from "./helpers/module-stubs.ts";++type Slot = {+ value?: unknown;+ deps?: unknown[];+ cleanup?: (() => void) | void;+};++const sameDeps = (a?: unknown[], b?: unknown[]) =>+ Boolean(a && b && a.length === b.length && a.every((value, i) => Object.is(value, b[i])));+const turn = () => new Promise<void>((resolve) => setImmediate(resolve));+const file = () => new File(["saved report"], "report.txt", { type: "text/plain" });++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}++function pickerHarness({+ read = async () => file(),+ add = async () => {},+}: {+ read?: () => Promise<File>;+ add?: (file: File) => Promise<void>;+} = {}) {+ type Instance = { slots: Slot[]; target: string | null; closes: number; onClose: () => void };+ let current: Instance;+ let cursor = 0;+ let effects: (() => void)[] = [];+ const slot = () => current.slots[cursor++] ??= {};+ const memo = (make: () => unknown, deps?: unknown[]) => {+ const entry = slot();+ if (!("value" in entry) || !sameDeps(entry.deps, deps)) {+ entry.value = make();+ entry.deps = deps;+ }+ return entry.value;+ };+ const effect = (run: () => (() => void) | void, deps?: unknown[]) => {+ const entry = slot();+ if (!sameDeps(entry.deps, deps)) {+ entry.deps = deps;+ effects.push(() => { entry.cleanup?.(); entry.cleanup = run(); });+ }+ };+ const react = {+ useContext: () => current.target,+ useState: (initial: unknown) => {+ const entry = slot();+ if (!("value" in entry)) entry.value = typeof initial === "function" ? initial() : initial;+ return [entry.value, (value: unknown) => {+ entry.value = typeof value === "function" ? value(entry.value) : value;+ }];+ },+ useRef: (initial: unknown) => memo(() => ({ current: initial }), []),+ useMemo: memo,+ useCallback: (callback: unknown, deps: unknown[]) => memo(() => callback, deps),+ useEffect: effect,+ useLayoutEffect: effect,+ };+ const aui = { composer: () => ({ getState: () => ({ isEditing: true }), addAttachment: add }) };+ const { LibraryAttachmentPicker } = loadWithStubs<{+ LibraryAttachmentPicker: (props: { onClose: () => void }) => StubElement;+ }>(new URL("../src/components/assistant-ui/library-attachment-picker.tsx", import.meta.url), {+ react,+ "react/jsx-runtime": stubJsxRuntime(),+ "@assistant-ui/react": { useAui: () => aui },+ "@/components/ui/command": { CommandItem: "CommandItem" },+ "@/components/ui/dialog": {},+ "@/components/ui/spinner": {},+ "@/features/auth": { getAuthSessionEpoch: () => 1 },+ "@/features/library": {+ createLibraryComposerAttachment,+ getLibrary: async () => ({ items: [{ id: "upload:report", name: "report.txt", model: null,+ sizeBytes: 12, contentType: "text/plain", source: "uploaded", updatedAt: 1 }] }),+ libraryItemFile: read,+ fileKind: () => "document",+ LibraryFileTooLarge: class extends Error {},+ },+ "@/lib/audio-utils": {},+ "@/lib/video-utils": {},+ "@/i18n": { useT: () => (key: string) => key },+ });+ return {+ mount(): Instance {+ const instance: Instance = { slots: [], target: "single:existing", closes: 0,+ onClose: () => { instance.closes += 1; } };+ return instance;+ },+ render(instance: Instance) {+ current = instance;+ cursor = 0;+ effects = [];+ const tree = LibraryAttachmentPicker({ onClose: instance.onClose });+ for (const run of effects) run();+ return tree;+ },+ unmount(instance: Instance) {+ for (const entry of instance.slots) entry.cleanup?.();+ },+ };+}++function selectedRow(tree: StubElement): StubElement {+ const visit = (value: unknown): StubElement | undefined => {+ if (Array.isArray(value)) return value.map(visit).find(Boolean);+ if (value === null || typeof value !== "object") return;+ const node = value as StubElement;+ return node.type === "CommandItem" ? node : visit(node.props?.children);+ };+ const row = visit(tree);+ assert.ok(row, "the loaded Library file must be selectable");+ return row;+}++test("leaving Chat while the picker reads a file cancels attachment and closes the old picker", async () => {+ const read = deferred<File>();+ const added: File[] = [];+ const host = pickerHarness({ read: () => read.promise, add: async (value) => { added.push(value); } });+ const picker = host.mount();+ host.render(picker);+ await turn();+ (selectedRow(host.render(picker)).props.onSelect as () => void)();+ picker.target = null;+ host.render(picker);+ read.resolve(file());+ await turn();+ assert.deepEqual(added, []);+ assert.equal(picker.closes, 1);+ host.unmount(picker);+});++test("an old adapter finishing after the picker reopens does not close the replacement", async () => {+ const added = deferred<void>();+ let starts = 0;+ let open = true;+ const host = pickerHarness({ add: async () => { starts += 1; await added.promise; } });+ const old = host.mount();+ old.onClose = () => { old.closes += 1; open = false; };+ host.render(old);+ await turn();+ (selectedRow(host.render(old)).props.onSelect as () => void)();+ await turn();+ assert.equal(starts, 1, "the actual attachment adapter must have started");+ host.unmount(old);+ const replacement = host.mount();+ host.render(replacement);+ await turn();+ selectedRow(host.render(replacement));+ added.resolve();+ await turn();+ assert.equal(old.closes, 0);+ assert.equal(replacement.closes, 0);+ assert.equal(open, true);+ host.unmount(replacement);+});