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: Chat with files search row lists its documents, which open in the attachment viewer (#13681)
Michael Hanf075667d0103
diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex 0ef0cce7dac..4b02b100fbf 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -1101,48 +1101,6 @@ def _verify_document_token(document_id: str, token: str) -> AccountContext | Nonreturn None if account is None or account.is_owner else account[email protected]("/documents/{document_id}/preview-target")-def preview_target(- document_id: str,- chunk_id: str | None = Query(default = None),- subject: str = Depends(get_current_subject),-) -> dict:- """Resolve a citation to filename, page, and highlight regions."""- _require_rag()- conn = _rag_connection()- try:- doc = store.get_visible_document(conn, document_id)- if doc is None:- raise HTTPException(status_code = 404, detail = "Document not found")- _require_document_owner(conn, doc)- ext = os.path.splitext(doc["filename"])[1].lower()- out = {- "documentId": document_id,- "filename": doc["filename"],- "mediaKind": "pdf" if ext == ".pdf" else "text",- "targetPage": None,- "pdfRegions": [],- "text": None,- }- if chunk_id:- row = conn.execute(- "SELECT text, page_number, pdf_regions_json FROM chunks "- "WHERE id=? AND document_id=?",- (chunk_id, document_id),- ).fetchone()- if row is not None:- out["text"] = row["text"]- out["targetPage"] = row["page_number"]- if row["pdf_regions_json"]:- try:- out["pdfRegions"] = json.loads(row["pdf_regions_json"])- except Exception:- out["pdfRegions"] = []- return out- finally:- conn.close()--@router.get("/documents/{document_id}/file-url")def document_file_url(document_id: str,diff --git a/studio/backend/tests/multi_account/factories_rag.py b/studio/backend/tests/multi_account/factories_rag.pyindex ba990572448..94482e43949 100644--- a/studio/backend/tests/multi_account/factories_rag.py+++ b/studio/backend/tests/multi_account/factories_rag.py@@ -232,9 +232,6 @@ FACTORIES = {"routes.rag:GET:/documents/{document_id}/file-url": Factory("rag-document", fragment = "file-signed"),- "routes.rag:GET:/documents/{document_id}/preview-target": Factory(- "rag-document", fragment = FILENAME- ),"routes.rag:GET:/jobs/{job_id}": Factory("rag-job", fragment = DOCUMENT_ID),"routes.rag:GET:/jobs/{job_id}/events": Factory("rag-job",diff --git a/studio/backend/tests/test_rag_linked_folders.py b/studio/backend/tests/test_rag_linked_folders.pyindex efd51c310de..c2405b79136 100644--- a/studio/backend/tests/test_rag_linked_folders.py+++ b/studio/backend/tests/test_rag_linked_folders.py@@ -2226,9 +2226,6 @@ def test_kb_deletion_retries_retired_scope_cleanup_after_failure(subject = "test",)assert getattr(exc_info.value, "status_code", None) == 404- with pytest.raises(Exception) as exc_info:- rag_routes.preview_target(document["id"], subject = "test")- assert getattr(exc_info.value, "status_code", None) == 404with _connection() as conn:assert (conn.execute(diff --git a/studio/backend/tests/test_rag_preview.py b/studio/backend/tests/test_rag_preview.pyindex 348907486f8..523a4ba54e3 100644--- a/studio/backend/tests/test_rag_preview.py+++ b/studio/backend/tests/test_rag_preview.py@@ -83,7 +83,7 @@ def test_chunks_carry_pdf_regions(rag_home, stub_embeddings):assert 0.0 <= region[key] <= 1.0-def test_preview_routes_and_signed_file(rag_home, stub_embeddings):+def test_signed_file_routes(rag_home, stub_embeddings):from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -110,11 +110,6 @@ def test_preview_routes_and_signed_file(rag_home, stub_embeddings):},).json()["results"]assert res- chunk_id = res[0]["chunkId"]-- pt = c.get(f"/api/rag/documents/{doc_id}/preview-target", params = {"chunk_id": chunk_id}).json()- assert pt["mediaKind"] == "pdf"- assert pt["text"]url = c.get(f"/api/rag/documents/{doc_id}/file-url").json()["url"]full = c.get(url)diff --git a/studio/backend/tests/test_rag_unavailable_quiet.py b/studio/backend/tests/test_rag_unavailable_quiet.pyindex 207d4b64fed..9c428992b1c 100644--- a/studio/backend/tests/test_rag_unavailable_quiet.py+++ b/studio/backend/tests/test_rag_unavailable_quiet.py@@ -167,10 +167,6 @@ def test_list_knowledge_bases_degrades_to_empty(rag_home, reset_unavailable_warnlambda r: r.job_status("job1", subject = "tester"),id = "job-status",),- pytest.param(- lambda r: r.preview_target("doc1", subject = "tester"),- id = "preview-target",- ),pytest.param(lambda r: r.document_file_url("doc1", subject = "tester"),id = "file-url",diff --git a/studio/frontend/src/components/assistant-ui/citation-utils.ts b/studio/frontend/src/components/assistant-ui/citation-utils.tsindex 58000c038f9..cd76fca97ce 100644--- a/studio/frontend/src/components/assistant-ui/citation-utils.ts+++ b/studio/frontend/src/components/assistant-ui/citation-utils.ts@@ -61,14 +61,20 @@ export function parseCitations(result: unknown): Citation[] {try {const parsed = JSON.parse(trimmed);if (Array.isArray(parsed)) rows = parsed;- else if (parsed && Array.isArray((parsed as { results?: unknown }).results)) {+ else if (+ parsed &&+ Array.isArray((parsed as { results?: unknown }).results)+ ) {rows = (parsed as { results: unknown[] }).results;}} catch {rows = null;}}- } else if (result && Array.isArray((result as { results?: unknown }).results)) {+ } else if (+ result &&+ Array.isArray((result as { results?: unknown }).results)+ ) {rows = (result as { results: unknown[] }).results;}if (!rows) return [];@@ -103,3 +109,75 @@ export function parseCitations(result: unknown): Citation[] {});return citations;}++/** One citation per document, its best-scoring passage, in first-seen order. */+export function topCitationPerDocument(+ citations: readonly Citation[],+): Citation[] {+ const byDoc = new Map<string, Citation>();+ for (const c of citations) {+ const key = c.documentId ?? c.filename;+ const prev = byDoc.get(key);+ if (+ !prev ||+ (c.score ?? Number.NEGATIVE_INFINITY) >+ (prev.score ?? Number.NEGATIVE_INFINITY)+ ) {+ byDoc.set(key, c);+ }+ }+ return Array.from(byDoc.values());+}++/** The key a citation's document goes by: its id, else its filename. */+export function documentKey(citation: Citation): string {+ return citation.documentId ?? citation.filename;+}++/** Each document's cited pages, ascending and deduplicated, keyed by documentKey. */+export function citedPagesPerDocument(+ citations: readonly Citation[],+): Map<string, number[]> {+ const pages = new Map<string, Set<number>>();+ for (const c of citations) {+ const key = documentKey(c);+ const set = pages.get(key) ?? new Set<number>();+ if (c.page != null) {+ set.add(c.page);+ }+ pages.set(key, set);+ }+ return new Map(+ Array.from(pages, ([key, set]) => [key, [...set].sort((a, b) => a - b)]),+ );+}++/** "p.3", "p.1–5" or "pp.1–3, 7": runs of consecutive pages collapse into ranges. */+export function pageLabel(pages: readonly number[]): string {+ const runs: string[] = [];+ for (let i = 0; i < pages.length; i++) {+ let end = i;+ while (+ end + 1 < pages.length &&+ pages[end + 1] === Number(pages[end]) + 1+ ) {+ end++;+ }+ runs.push(end === i ? `${pages[i]}` : `${pages[i]}–${pages[end]}`);+ i = end;+ }+ return `${runs.length > 1 ? "pp." : "p."}${runs.join(", ")}`;+}++/** A badge's label: the filename, then the pages it stands for, else the citation's own page. */+export function citationLabel(+ citation: Citation,+ pages?: readonly number[],+): string {+ if (pages && pages.length > 0) {+ return `${citation.filename} · ${pageLabel(pages)}`;+ }+ return citation.page != null+ ? `${citation.filename} · p.${citation.page}`+ : citation.filename;+}diff --git a/studio/frontend/src/components/assistant-ui/rag-sources.tsx b/studio/frontend/src/components/assistant-ui/rag-sources.tsxindex 5e5dfde1f48..6e666847ccc 100644--- a/studio/frontend/src/components/assistant-ui/rag-sources.tsx+++ b/studio/frontend/src/components/assistant-ui/rag-sources.tsx@@ -3,30 +3,16 @@"use client";-import { useMessage } from "@assistant-ui/react";import type { FC } from "react";-import { type Citation, parseCitations } from "./citation-utils";+import { type Citation, topCitationPerDocument } from "./citation-utils";import { CitationBadge } from "./tool-ui-knowledge-base";export const DocumentSourcesGroup: FC<{sources: Citation[];label?: string;}> = ({ sources: all, label = "Document Sources" }) => {- // Map keeps first-seen order while retaining each document's top score.- const byDoc = new Map<string, Citation>();- for (const c of all) {- const key = c.documentId ?? c.filename;- const prev = byDoc.get(key);- if (- !prev ||- (c.score ?? Number.NEGATIVE_INFINITY) >- (prev.score ?? Number.NEGATIVE_INFINITY)- ) {- byDoc.set(key, c);- }- }- const sources = Array.from(byDoc.values());+ const sources = topCitationPerDocument(all);if (sources.length === 0) {return null;}@@ -44,18 +30,3 @@ export const DocumentSourcesGroup: FC<{</div>);};--export const RagSourcesGroup: FC = () => {- const message = useMessage();-- const sources: Citation[] = [];- for (const part of message.content ?? []) {- if (- part.type === "tool-call" &&- part.toolName === "search_knowledge_base"- ) {- sources.push(...parseCitations(part.result));- }- }- return <DocumentSourcesGroup sources={sources} />;-};diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex e12ff9df5ab..74c282f8070 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -62,7 +62,6 @@ import { attachWheelHoverSuppression } from "@/components/assistant-ui/thread-whimport { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";import { observeThreadWidthSteps } from "@/components/assistant-ui/thread-width-steps";import { Reasoning, ReasoningGroup } from "@/components/assistant-ui/reasoning";-import { RagSourcesGroup } from "@/components/assistant-ui/rag-sources";import { researchReplyOwners } from "@/components/assistant-ui/research-reply-owners";import { Sources, SourcesGroup } from "@/components/assistant-ui/sources";import {@@ -353,7 +352,6 @@ import {import { useRagAvailabilityStore } from "@/features/rag/api/rag-availability";import { ThreadDocumentsBar } from "@/features/rag/components/thread-documents-bar";import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";-import { DocumentPreviewMount } from "@/features/rag/components/document-preview-mount";import { useUserProfileStore } from "@/features/profile/stores/user-profile-store";import { usePublishedFrame } from "@/features/settings/hooks/use-published-frame";import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";@@ -2408,8 +2406,6 @@ export const Thread: FC<{)}</IntentAwareScrollProvider></ThreadPrimitive.Root>- {/* Document preview, opened by citation badges. */}- <DocumentPreviewMount /><RewindDialogMount /></PageDragContext.Provider></GeneratedImageOverlayProvider>@@ -2779,7 +2775,6 @@ export const ProjectComposer: FC<{disableQueue/>{/* Its file cards open previews; the thread's mount is not on this page. */}- <DocumentPreviewMount /></GeneratedImageOverlayProvider>);};@@ -8330,7 +8325,6 @@ const AssistantMessage: FC = () => {*/}<MessagePrimitive.Parts components={ASSISTANT_PART_COMPONENTS} /><SourcesGroup />- <RagSourcesGroup /><MessageHtmlArtifacts /><ContinueMessageBar /></>diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsxindex b4cb9c5cbe4..6fc3b16f457 100644--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx@@ -183,6 +183,7 @@ function ToolFallbackTrigger({mcpTool,status,icon: ToolIcon,+ singleLine = false,className,...props}: ComponentProps<typeof CollapsibleTrigger> & {@@ -194,7 +195,10 @@ function ToolFallbackTrigger({mcpTool?: string;status?: ToolCallMessagePartStatus;icon?: ElementType;+ /** Keep the label to one line when open, for a label that repeats an argument the content shows in full. */+ singleLine?: boolean;}) {+ const wrapWhenOpen = !singleLine;const statusType = status?.type ?? "complete";const isRunning = isToolCallRunning(status);const isCancelled = isToolCallCancelled(status);@@ -242,7 +246,8 @@ function ToolFallbackTrigger({<spanclassName={cn("block truncate leading-normal",- "group-data-[state=open]/trigger:overflow-visible group-data-[state=open]/trigger:whitespace-normal group-data-[state=open]/trigger:break-words",+ wrapWhenOpen &&+ "group-data-[state=open]/trigger:overflow-visible group-data-[state=open]/trigger:whitespace-normal group-data-[state=open]/trigger:break-words",)}>{label}:{" "}@@ -254,6 +259,7 @@ function ToolFallbackTrigger({data-slot="tool-fallback-trigger-shimmer"className={cn("aui-tool-fallback-trigger-shimmer shimmer pointer-events-none absolute inset-0 block truncate leading-normal motion-reduce:animate-none",+ wrapWhenOpen &&"group-data-[state=open]/trigger:overflow-visible group-data-[state=open]/trigger:whitespace-normal group-data-[state=open]/trigger:break-words",)}>diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsxindex 28a8024e195..23c31ed6091 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx@@ -8,13 +8,15 @@ import {useAuiState,} from "@assistant-ui/react";import { partsHaveNonEmptyText } from "@/components/assistant-ui/message-derived";-import { LibraryBigIcon } from "lucide-react";+import { LibrariesIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";import { Spinner } from "@/components/ui/spinner";import { useToolAwaitingApproval } from "@/features/chat";+import { RagDocumentTrigger } from "@/features/rag/components/rag-document-trigger";import { FileGlyph } from "@/lib/file-icon";import { stringifyToolResult } from "@/lib/strip-ansi";-import { memo, useMemo } from "react";+import { type ComponentProps, memo, useMemo, useState } from "react";import { Badge } from "./badge";import {isToolCallRunning,@@ -27,34 +29,30 @@ import {ToolFallbackTrigger,} from "./tool-fallback";import { useToolActivityOpen } from "./use-tool-activity-open";-import { useDocumentPreviewStore } from "@/features/rag/components/preview-store";-import { type Citation, parseCitations } from "./citation-utils";+import {+ type Citation,+ parseCitations,+ citationLabel,+ citedPagesPerDocument,+ documentKey,+ topCitationPerDocument,+} from "./citation-utils";import { ScrollPane } from "./scroll-pane";export function CitationBadge({citation,index,+ pages,}: {citation: Citation;index: number;+ /** Every page cited from this document, when the badge stands for all of them. */+ pages?: readonly number[];}) {- const openPreview = useDocumentPreviewStore((s) => s.openPreview);- const clickable = Boolean(citation.documentId);- const label =- citation.page != null- ? `${citation.filename} · p.${citation.page}`- : citation.filename;-- const open = () => {- if (!citation.documentId) return;- openPreview({- documentId: citation.documentId,- chunkId: citation.chunkId,- filename: citation.filename,- page: citation.page,- });- };+ const label = citationLabel(citation, pages);+ const { documentId, filename } = citation;+ const clickable = Boolean(documentId);const badge = (<Badge@@ -68,19 +66,34 @@ export function CitationBadge({><span className="tabular-nums text-muted-foreground">{index + 1}</span><FileGlyph className="size-3 shrink-0" />- <span className="truncate">{label}</span>+ <span className="truncate" title={label}>+ {label}+ </span></Badge>);- return clickable ? (- <button type="button" onClick={open} className="inline-block">- {badge}- </button>- ) : (- <span className="inline-block">{badge}</span>+ if (!documentId) {+ return <span className="inline-block">{badge}</span>;+ }+ return (+ <RagDocumentTrigger documentId={documentId} filename={filename}>+ <button type="button" className="inline-block rounded-full">+ {badge}+ </button>+ </RagDocumentTrigger>);}+// The app's Library icon, as in the sidebar.+const LibraryGlyph = (+ props: Omit<ComponentProps<typeof HugeiconsIcon>, "icon">,+) => <HugeiconsIcon icon={LibrariesIcon} strokeWidth={1.75} {...props} />;++// Longer queries get a scroll box rather than a line of text.+const QUERY_INLINE_MAX = 80;+// The model picks top_k with no ceiling, so a huge search could cite very many documents.+const DOCUMENTS_SHOWN = 20;+const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({args,result,@@ -92,11 +105,18 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({const resultText = result == null ? "" : stringifyToolResult(result);const citations = useMemo(() => parseCitations(result), [result]);- // Citations render in RagSourcesGroup; this block keeps a one-line summary.- const docCount = useMemo(- () => new Set(citations.map((c) => c.documentId ?? c.filename)).size,+ // The documents behind the passages, listed in the expanded card.+ const documents = useMemo(+ () => topCitationPerDocument(citations),[citations],);+ const docCount = documents.length;+ const pagesByDocument = useMemo(+ () => citedPagesPerDocument(citations),+ [citations],+ );+ const [showAll, setShowAll] = useState(false);+ const shown = showAll ? documents : documents.slice(0, DOCUMENTS_SHOWN);const hasText = useAuiState(({ message }) =>partsHaveNonEmptyText(message.content),@@ -115,7 +135,8 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({<ToolFallbackTriggertoolName={knowledgeBaseToolName({ isRunning, query })}status={status}- icon={LibraryBigIcon}+ icon={LibraryGlyph}+ singleLine={true}/><ToolFallbackContent>{isRunning ? (@@ -129,21 +150,63 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({)}</span></div>- ) : citations.length > 0 ? (- <div className="text-sm text-muted-foreground">- Retrieved {citations.length} passage- {citations.length === 1 ? "" : "s"} from {docCount} document- {docCount === 1 ? "" : "s"}. See Document Sources below.- </div>- ) : resultText ? (- <ScrollPane- className="rounded bg-muted/50 p-2"- scrollerClassName="max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs"- >- {resultText}- </ScrollPane>) : (- <div className="text-sm text-muted-foreground">No matching passages.</div>+ // Outcome first, then the full query: the one-line header may clip it in every outcome.+ <div className="flex flex-col gap-2 text-sm text-muted-foreground">+ {citations.length > 0 ? (+ <>+ <div>+ Retrieved {citations.length} passage+ {citations.length === 1 ? "" : "s"} from {docCount} document+ {docCount === 1 ? "" : "s"}.+ </div>+ <div className="flex flex-wrap gap-1.5">+ {shown.map((citation, i) => (+ <CitationBadge+ key={citation.id}+ citation={citation}+ index={i}+ pages={pagesByDocument.get(documentKey(citation))}+ />+ ))}+ </div>+ {shown.length < documents.length ? (+ <button+ type="button"+ onClick={() => setShowAll(true)}+ className="self-start text-xs underline-offset-2 hover:text-foreground hover:underline"+ >+ Show {documents.length - shown.length} more+ </button>+ ) : null}+ </>+ ) : resultText ? (+ <ScrollPane+ className="rounded bg-muted/50 p-2"+ scrollerClassName="max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs"+ >+ {resultText}+ </ScrollPane>+ ) : (+ <div>No matching passages.</div>+ )}+ {query.length > QUERY_INLINE_MAX ? (+ <ScrollPane+ data-slot="knowledge-base-query"+ className="rounded bg-muted/50 p-2"+ scrollerClassName="max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs"+ >+ {query}+ </ScrollPane>+ ) : query ? (+ <div+ data-slot="knowledge-base-query"+ className="break-words text-xs"+ >+ Query: “{query}”+ </div>+ ) : null}+ </div>)}</ToolFallbackContent></ToolFallbackRoot>diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.tsindex 2d37fa72e95..9af9e4282bc 100644--- a/studio/frontend/src/features/rag/api/rag-api.ts+++ b/studio/frontend/src/features/rag/api/rag-api.ts@@ -15,7 +15,6 @@ import type {KnowledgeBase,LinkedFolder,LinkedFolderScope,- PreviewTarget,RagDocument,UploadedDocument,} from "../types/rag";@@ -823,16 +822,6 @@ export function streamFolderSyncJobEvents();}-export function getPreviewTarget(- documentId: string,- chunkId?: string,-): Promise<PreviewTarget> {- const qs = chunkId ? `?chunk_id=${encodeURIComponent(chunkId)}` : "";- return ragRequest(- `/documents/${encodeURIComponent(documentId)}/preview-target${qs}`,- );-}-// Signed URL (no bearer) so pdf.js can issue Range requests. Absolute because consumers bypass// authFetch, and a relative path under Tauri resolves against the webview origin.export async function getDocumentFileUrl(documentId: string): Promise<string> {diff --git a/studio/frontend/src/features/rag/components/document-preview-mount.tsx b/studio/frontend/src/features/rag/components/document-preview-mount.tsxdeleted file mode 100644index 400ee5db000..00000000000--- a/studio/frontend/src/features/rag/components/document-preview-mount.tsx+++ /dev/null@@ -1,32 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--"use client";--import { Suspense, lazy, useEffect, useState } from "react";--import { useDocumentPreviewStore } from "./preview-store";--// pdf.js / react-pdf are heavy (~0.5 MB gzip): defer until the first citation-// click, then keep mounted for open/close anims.-const DocumentPreviewSheet = lazy(() =>- import("./document-preview-sheet").then((m) => ({- default: m.DocumentPreviewSheet,- })),-);--export function DocumentPreviewMount() {- const open = useDocumentPreviewStore((s) => s.open);- const [mounted, setMounted] = useState(false);-- useEffect(() => {- if (open) setMounted(true);- }, [open]);-- if (!mounted) return null;- return (- <Suspense fallback={null}>- <DocumentPreviewSheet />- </Suspense>- );-}diff --git a/studio/frontend/src/features/rag/components/document-preview-sheet.tsx b/studio/frontend/src/features/rag/components/document-preview-sheet.tsxdeleted file mode 100644index 5f95692ae6b..00000000000--- a/studio/frontend/src/features/rag/components/document-preview-sheet.tsx+++ /dev/null@@ -1,496 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--"use client";--import {- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from "react";-import { Document, Page, pdfjs } from "react-pdf";-import {- ChevronLeftIcon,- ChevronRightIcon,- ZoomInIcon,- ZoomOutIcon,-} from "lucide-react";-import { Spinner } from "@/components/ui/spinner";-import { usePdfWorker } from "@/components/file-viewer/use-pdf-worker";--import {- Sheet,- SheetCloseButton,- SheetContent,- SheetHeader,- SheetTitle,-} from "@/components/ui/sheet";-import { Button } from "@/components/ui/button";-import { cn } from "@/lib/utils";-import { FileGlyph } from "@/lib/file-icon";-import { getDocumentFileUrl, getPreviewTarget } from "../api/rag-api";-import type { PdfRegion, PreviewTarget } from "../types/rag";-import { useDocumentPreviewStore } from "./preview-store";--// Serve the pdf.js worker from the app origin.-pdfjs.GlobalWorkerOptions.workerSrc = new URL(- "pdfjs-dist/build/pdf.worker.min.mjs",- import.meta.url,-).toString();--// Highlight rects; coords are 0..1 of the page box.-function RegionOverlay({ regions }: { regions: PdfRegion[] }) {- if (regions.length === 0) return null;- return (- <>- {regions.map((r, i) => (- <div- key={i}- className="pointer-events-none absolute rounded-sm bg-amber-300/35 ring-1 ring-amber-500/70 mix-blend-multiply"- style={{- left: `${r.x * 100}%`,- top: `${r.y * 100}%`,- width: `${r.width * 100}%`,- height: `${r.height * 100}%`,- }}- />- ))}- </>- );-}--// Zoom multiplies fit-to-panel width: 1 = fit.-const ZOOM_MIN = 0.5;-const ZOOM_MAX = 3;-const ZOOM_STEP = 0.25;--const clampZoom = (z: number) =>- Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, Number(z.toFixed(2))));--function PdfPreview({- fileUrl,- initialPage,- regions,-}: {- fileUrl: string;- initialPage: number;- regions: PdfRegion[];-}) {- const containerRef = useRef<HTMLDivElement | null>(null);- const [width, setWidth] = useState(0);- const [numPages, setNumPages] = useState(0);- const [page, setPage] = useState(initialPage);- const [scale, setScale] = useState(1);- const [error, setError] = useState<string | null>(null);- const [grabbing, setGrabbing] = useState(false);- const [scrollable, setScrollable] = useState(false);- const pdfWorker = usePdfWorker(error === null);- const options = useMemo(- () => (pdfWorker ? { worker: pdfWorker.worker } : null),- [pdfWorker],- );- const panRef = useRef<{- x: number;- y: number;- left: number;- top: number;- } | null>(null);-- // Reset page/zoom when a new citation reuses this viewer.- useEffect(() => setPage(initialPage), [initialPage, fileUrl]);-- useEffect(() => setScale(1), [fileUrl]);-- useLayoutEffect(() => {- const el = containerRef.current;- if (!el) return;- const measure = () => setWidth(el.clientWidth);- measure();- const ro = new ResizeObserver(measure);- ro.observe(el);- return () => ro.disconnect();- }, []);-- // Non-passive wheel listener so preventDefault can stop the panel scrolling.- useEffect(() => {- const el = containerRef.current;- if (!el) return;- const onWheel = (e: WheelEvent) => {- e.preventDefault();- setScale((s) => clampZoom(s - Math.sign(e.deltaY) * ZOOM_STEP));- };- el.addEventListener("wheel", onWheel, { passive: false });- return () => el.removeEventListener("wheel", onWheel);- }, []);-- const onLoad = useCallback(- (doc: { numPages: number; destroy(): Promise<void> }) => {- const n = doc.numPages;- pdfWorker?.loaded.add(doc);- setNumPages(n);- setPage((p) => Math.min(Math.max(p, 1), n));- },- [pdfWorker],- );-- const zoomBy = useCallback(- (delta: number) => setScale((s) => clampZoom(s + delta)),- [],- );-- // Whether the page overflows the panel (so panning matters).- const recheckScrollable = useCallback(() => {- const el = containerRef.current;- if (!el) return;- setScrollable(- el.scrollWidth > el.clientWidth + 1 ||- el.scrollHeight > el.clientHeight + 1,- );- }, []);-- useEffect(() => {- recheckScrollable();- }, [recheckScrollable, width, scale, page, numPages]);-- // Grab-to-pan; listen on window so the drag tracks past the panel edge.- useEffect(() => {- if (!grabbing) return;- const onMove = (e: MouseEvent) => {- const el = containerRef.current;- const start = panRef.current;- if (!el || !start) return;- el.scrollLeft = start.left - (e.clientX - start.x);- el.scrollTop = start.top - (e.clientY - start.y);- };- const onUp = () => {- setGrabbing(false);- panRef.current = null;- };- window.addEventListener("mousemove", onMove);- window.addEventListener("mouseup", onUp);- return () => {- window.removeEventListener("mousemove", onMove);- window.removeEventListener("mouseup", onUp);- };- }, [grabbing]);-- const onPanStart = useCallback(- (e: React.MouseEvent) => {- const el = containerRef.current;- if (!el || e.button !== 0 || !scrollable) return;- panRef.current = {- x: e.clientX,- y: e.clientY,- left: el.scrollLeft,- top: el.scrollTop,- };- setGrabbing(true);- e.preventDefault(); // stop canvas image-drag / selection- },- [scrollable],- );-- const pageRegions = regions.filter(- (r) => r.pageNumber === page || r.pageIndex === page - 1,- );-- if (error) {- return (- <div className="p-6 text-sm text-muted-foreground">- Could not render this PDF ({error}).- </div>- );- }-- return (- <div className="flex h-full flex-col">- <div- ref={containerRef}- onMouseDown={onPanStart}- className={cn(- "flex-1 overflow-auto bg-muted/30 px-4 py-3",- grabbing- ? "cursor-grabbing select-none"- : scrollable- ? "cursor-grab"- : "",- )}- >- {options && (- <Document- file={fileUrl}- options={options}- onLoadSuccess={onLoad}- onLoadError={(e) => setError(e.message)}- loading={- <div className="flex items-center gap-2 p-6 text-sm text-muted-foreground">- <Spinner className="size-3.5" /> Loading PDF…- </div>- }- >- {width > 0 && (- // min-w-fit lets the zoomed row grow past the panel so the page stays- // centered and reachable on both sides.- <div className="flex min-w-fit justify-center">- <div className="relative w-fit shadow-sm">- <Page- pageNumber={page}- width={(width - 8) * scale}- renderTextLayer={false}- renderAnnotationLayer={false}- onRenderSuccess={recheckScrollable}- />- <RegionOverlay regions={pageRegions} />- </div>- </div>- )}- </Document>- )}- </div>- <div className="grid grid-cols-[1fr_auto_1fr] items-center border-t px-3 py-2 text-xs">- <div className="flex items-center gap-0.5 justify-self-start">- <Button- variant="ghost"- size="icon"- className="size-7"- disabled={scale <= ZOOM_MIN}- onClick={() => zoomBy(-ZOOM_STEP)}- aria-label="Zoom out"- >- <ZoomOutIcon className="size-4" />- </Button>- <button- type="button"- onClick={() => setScale(1)}- className="w-11 text-center tabular-nums text-muted-foreground hover:text-foreground"- aria-label="Reset zoom"- >- {Math.round(scale * 100)}%- </button>- <Button- variant="ghost"- size="icon"- className="size-7"- disabled={scale >= ZOOM_MAX}- onClick={() => zoomBy(ZOOM_STEP)}- aria-label="Zoom in"- >- <ZoomInIcon className="size-4" />- </Button>- </div>- {numPages > 1 ? (- <div className="flex items-center gap-3 justify-self-center">- <Button- variant="ghost"- size="icon"- className="size-7"- disabled={page <= 1}- onClick={() => setPage((p) => Math.max(1, p - 1))}- aria-label="Previous page"- >- <ChevronLeftIcon className="size-4" />- </Button>- <span className="tabular-nums text-muted-foreground">- Page {page} / {numPages}- </span>- <Button- variant="ghost"- size="icon"- className="size-7"- disabled={page >= numPages}- onClick={() => setPage((p) => Math.min(numPages, p + 1))}- aria-label="Next page"- >- <ChevronRightIcon className="size-4" />- </Button>- </div>- ) : (- <span />- )}- <span aria-hidden />- </div>- </div>- );-}--// Resizable preview width (px). Default matches the prior fixed 44rem; drag the-// left edge to widen. Persisted so it survives reopen.-const PREVIEW_WIDTH_KEY = "unsloth-rag-preview-width";-const MIN_PREVIEW_WIDTH = 384;-const DEFAULT_PREVIEW_WIDTH = 704;--const maxPreviewWidth = () =>- typeof window === "undefined"- ? DEFAULT_PREVIEW_WIDTH- : Math.round(window.innerWidth * 0.95);--const clampPreviewWidth = (w: number) =>- Math.min(maxPreviewWidth(), Math.max(MIN_PREVIEW_WIDTH, Math.round(w)));--function readStoredPreviewWidth(): number {- if (typeof window === "undefined") return DEFAULT_PREVIEW_WIDTH;- const raw = Number(window.localStorage.getItem(PREVIEW_WIDTH_KEY));- return Number.isFinite(raw) && raw > 0- ? clampPreviewWidth(raw)- : DEFAULT_PREVIEW_WIDTH;-}--function persistPreviewWidth(w: number) {- try {- window.localStorage.setItem(PREVIEW_WIDTH_KEY, String(Math.round(w)));- } catch {- // ignore storage errors (private mode, quota, etc.)- }-}--export function DocumentPreviewSheet() {- const { open, documentId, chunkId, filename, page, closePreview } =- useDocumentPreviewStore();- const [target, setTarget] = useState<PreviewTarget | null>(null);- const [fileUrl, setFileUrl] = useState<string | null>(null);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<string | null>(null);-- // Left-edge drag resizing of the panel.- const [previewWidth, setPreviewWidth] = useState<number>(- readStoredPreviewWidth,- );- const [resizing, setResizing] = useState(false);- const resizeRef = useRef<{ startX: number; startWidth: number } | null>(null);- const widthRef = useRef(previewWidth);- widthRef.current = previewWidth;-- const onResizeStart = useCallback((e: React.MouseEvent) => {- e.preventDefault();- resizeRef.current = { startX: e.clientX, startWidth: widthRef.current };- setResizing(true);- }, []);-- useEffect(() => {- if (!resizing) return;- const onMove = (e: MouseEvent) => {- const start = resizeRef.current;- if (!start) return;- // Right-anchored panel: dragging left (smaller clientX) widens it.- setPreviewWidth(- clampPreviewWidth(start.startWidth + (start.startX - e.clientX)),- );- };- const onUp = () => {- setResizing(false);- resizeRef.current = null;- persistPreviewWidth(widthRef.current);- };- window.addEventListener("mousemove", onMove);- window.addEventListener("mouseup", onUp);- return () => {- window.removeEventListener("mousemove", onMove);- window.removeEventListener("mouseup", onUp);- };- }, [resizing]);-- useEffect(() => {- if (!open || !documentId) return;- let cancelled = false;- setLoading(true);- setError(null);- setTarget(null);- setFileUrl(null);- (async () => {- try {- const t = await getPreviewTarget(documentId, chunkId ?? undefined);- if (cancelled) return;- setTarget(t);- if (t.mediaKind === "pdf") {- const url = await getDocumentFileUrl(documentId);- if (!cancelled) setFileUrl(url);- }- } catch (e) {- if (!cancelled) setError(e instanceof Error ? e.message : String(e));- } finally {- if (!cancelled) setLoading(false);- }- })();- return () => {- cancelled = true;- };- }, [open, documentId, chunkId]);-- const headerName = target?.filename ?? filename ?? "Document";- const headerPage = target?.targetPage ?? page ?? null;-- return (- <Sheet open={open} onOpenChange={(o) => !o && closePreview()}>- <SheetContent- side="right"- style={{ width: previewWidth, maxWidth: "95vw" }}- className={cn(- "flex w-full flex-col gap-0 p-0",- resizing && "select-none",- )}- showCloseButton={false}- >- {/* Drag the left edge to widen the preview; double-click to reset. */}- <div- role="separator"- aria-orientation="vertical"- aria-label="Resize document preview"- onMouseDown={onResizeStart}- onDoubleClick={() => {- setPreviewWidth(DEFAULT_PREVIEW_WIDTH);- persistPreviewWidth(DEFAULT_PREVIEW_WIDTH);- }}- className={cn(- "absolute inset-y-0 left-0 z-20 w-2 cursor-col-resize transition-colors hover:bg-primary/25",- resizing && "bg-primary/40",- )}- />- <SheetHeader className="gap-1 border-b p-4">- <div className="relative">- <SheetTitle className="flex items-center gap-2 pr-10 text-sm">- <FileGlyph className="size-4 shrink-0" />- <span className="min-w-0 truncate">{headerName}</span>- {headerPage != null && (- <span className="shrink-0 text-muted-foreground">- · page {headerPage}- </span>- )}- </SheetTitle>- <SheetCloseButton className="absolute top-1/2 right-0 -translate-y-1/2" />- </div>- </SheetHeader>-- <div className="min-h-0 flex-1">- {loading ? (- <div className="flex items-center gap-2 p-6 text-sm text-muted-foreground">- <Spinner className="size-3.5" /> Resolving source…- </div>- ) : error ? (- <div className="p-6 text-sm text-muted-foreground">- Could not open this document ({error}).- </div>- ) : target && target.mediaKind === "pdf" && fileUrl ? (- <PdfPreview- fileUrl={fileUrl}- initialPage={target.targetPage ?? 1}- regions={target.pdfRegions ?? []}- />- ) : target?.text ? (- <div className="h-full overflow-auto p-5">- <p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-foreground/90">- {target.text}- </p>- </div>- ) : (- <div className="p-6 text-sm text-muted-foreground">- No preview available for this source.- </div>- )}- </div>- </SheetContent>- </Sheet>- );-}diff --git a/studio/frontend/src/features/rag/components/preview-store.ts b/studio/frontend/src/features/rag/components/preview-store.tsdeleted file mode 100644index e583c5a391c..00000000000--- a/studio/frontend/src/features/rag/components/preview-store.ts+++ /dev/null@@ -1,39 +0,0 @@-// 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 { create } from "zustand";--// Global store for the shared preview Sheet, so any citation drives the one viewer-// without prop-drilling.-interface DocumentPreviewState {- open: boolean;- documentId: string | null;- /** Chunk to highlight; null opens at page 1. */- chunkId: string | null;- filename: string | null;- page: number | null;- openPreview: (args: {- documentId: string;- chunkId?: string | null;- filename?: string | null;- page?: number | null;- }) => void;- closePreview: () => void;-}--export const useDocumentPreviewStore = create<DocumentPreviewState>((set) => ({- open: false,- documentId: null,- chunkId: null,- filename: null,- page: null,- openPreview: ({ documentId, chunkId, filename, page }) =>- set({- open: true,- documentId,- chunkId: chunkId ?? null,- filename: filename ?? null,- page: page ?? null,- }),- closePreview: () => set({ open: false }),-}));diff --git a/studio/frontend/src/features/rag/components/project-source-chip.tsx b/studio/frontend/src/features/rag/components/project-source-chip.tsxindex e986cf17945..1e1999d25d4 100644--- a/studio/frontend/src/features/rag/components/project-source-chip.tsx+++ b/studio/frontend/src/features/rag/components/project-source-chip.tsx@@ -1,16 +1,11 @@// 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 { LocalFileDialog } from "@/components/assistant-ui/attachment-document-dialog";-import { MAX_DOCUMENT_PREVIEW_BYTES } from "@/components/file-viewer";-import { attachmentFileKind } from "@/features/chat";import { DocumentStatusChip } from "./document-status-chip";-import { useDocumentPreviewStore } from "./preview-store";-import { asViewerFile, fetchSourceFile, isViewableSource } from "./source-file";+import { RagDocumentTrigger } from "./rag-document-trigger";import type { TrackedDocument } from "./use-rag-documents";-/** A Sources tab chip whose name opens the file, the same viewers as the chat with files cards:- * PDFs in the source preview, other pages, markdown and text in the attachment viewer. */+/** A Sources tab chip whose name opens the file, as the chat with files cards do. */export function ProjectSourceChip({doc,onRemove,@@ -20,19 +15,7 @@ export function ProjectSourceChip({onRemove?: () => void;onRetry?: () => void;}) {- const openPreview = useDocumentPreviewStore((s) => s.openPreview);const ready = doc.status === "completed" && !doc.id.startsWith("pending_");- const isPdf = attachmentFileKind(doc.filename, undefined) === "pdf";- const viewable = !isPdf && isViewableSource(doc.filename);- const name = doc.filename.split("/").pop() ?? doc.filename;- // Read on open; the dialog keeps the latest one in a ref, so a new identity per render is fine.- const load = async (): Promise<Blob> => {- const file = await fetchSourceFile(doc, MAX_DOCUMENT_PREVIEW_BYTES);- if (!file) {- throw new Error(`Couldn't preview ${doc.filename}`);- }- return asViewerFile(file);- };return (<DocumentStatusChipfilename={doc.filename}@@ -42,17 +25,12 @@ export function ProjectSourceChip({error={doc.error}onRemove={onRemove}onRetry={onRetry}- onOpen={- ready && isPdf- ? () => openPreview({ documentId: doc.id, filename: doc.filename })- : undefined- }openTrigger={- ready && viewable+ ready? (trigger) => (- <LocalFileDialog name={name} load={load}>+ <RagDocumentTrigger documentId={doc.id} filename={doc.filename}>{trigger}- </LocalFileDialog>+ </RagDocumentTrigger>): undefined}diff --git a/studio/frontend/src/features/rag/components/rag-document-trigger.tsx b/studio/frontend/src/features/rag/components/rag-document-trigger.tsxnew file mode 100644index 00000000000..46259040e72--- /dev/null+++ b/studio/frontend/src/features/rag/components/rag-document-trigger.tsx@@ -0,0 +1,64 @@+// 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 { LocalFileDialog } from "@/components/assistant-ui/attachment-document-dialog";+import { MAX_DOCUMENT_PREVIEW_BYTES } from "@/components/file-viewer";+import { canShowFile } from "@/features/browser/file-kind";+import { useBrowserPanelAvailable } from "@/features/browser/panel-availability";+import { useBrowserPrefsStore } from "@/features/browser/prefs-store";+import { type ReactElement, cloneElement } from "react";+import {+ offerRagDocumentOutside,+ openRagDocumentExternally,+ openRagDocumentInBrowser,+} from "../lib/open-document";+import { asViewerFile, fetchSourceFile, isViewableSource } from "./source-file";++/**+ * Opens an indexed document from `children` (a button): in Studio's browser when it can show the+ * format and files open there. Otherwise viewable files use the attachment viewer, the rest a new tab.+ */+export function RagDocumentTrigger({+ documentId,+ filename,+ children,+}: {+ documentId: string;+ filename: string;+ children: ReactElement;+}) {+ const panel = useBrowserPanelAvailable();+ const filesInBrowser = useBrowserPrefsStore((s) => s.openFilesInBrowser);+ // A non-empty type, so only the name decides: canShowFile accepts any file with no type.+ const browser =+ panel &&+ filesInBrowser &&+ canShowFile(filename, "application/octet-stream");+ if (browser) {+ return cloneElement(children as ReactElement<{ onClick?: () => void }>, {+ onClick: () => openRagDocumentInBrowser(documentId, filename),+ });+ }+ if (isViewableSource(filename)) {+ const load = async (): Promise<Blob> => {+ const file = await fetchSourceFile(+ { id: documentId, filename },+ MAX_DOCUMENT_PREVIEW_BYTES,+ );+ if (!file) {+ // Past the viewer's limit (uploads go up to 200 MB): still let it open outside Studio.+ offerRagDocumentOutside(documentId, filename);+ throw new Error(`Couldn't preview ${filename}`);+ }+ return asViewerFile(file);+ };+ return (+ <LocalFileDialog name={filename.split("/").pop() ?? filename} load={load}>+ {children}+ </LocalFileDialog>+ );+ }+ return cloneElement(children as ReactElement<{ onClick?: () => void }>, {+ onClick: () => openRagDocumentExternally(documentId, filename),+ });+}diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsxindex ba280da0223..a027e037f6a 100644--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx@@ -31,8 +31,6 @@ import {AttachmentCardPreview,attachmentPreview,} from "@/components/assistant-ui/attachment-card-preview";-import { LocalFileDialog } from "@/components/assistant-ui/attachment-document-dialog";-import { MAX_DOCUMENT_PREVIEW_BYTES } from "@/components/file-viewer";import { Spinner } from "@/components/ui/spinner";import {Tooltip,@@ -95,7 +93,6 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import { STAGE_LABELS } from "./document-status-chip";-import { useDocumentPreviewStore } from "./preview-store";import {type KnowledgeBaseFocus,KnowledgeBaseDialog,@@ -105,7 +102,8 @@ import {SUPPORTED_SOURCES_HINT,isSupportedSourceName,} from "./source-drop-policy";-import { asViewerFile, fetchSourceFile, isViewableSource } from "./source-file";+import { RagDocumentTrigger } from "./rag-document-trigger";+import { fetchSourceFile } from "./source-file";import { EXPIRY_GRACE_MS } from "./staged-source";import {type RagUploadItem,@@ -419,7 +417,6 @@ function DocumentCard({onRemove?: () => void;onRetry?: () => void;}) {- const openPreview = useDocumentPreviewStore((s) => s.openPreview);const kind = attachmentFileKind(doc.filename, undefined);const processing = isProcessing(doc);const failed = doc.status === "failed";@@ -447,22 +444,8 @@ function DocumentCard({const ready = doc.status === "completed" && !pending;const [slot, setSlot] = useState<HTMLDivElement | null>(null);const thumbnail = useDocumentThumbnail(doc, ready, slot);- // PDFs open the source preview, which can jump to a page. Without a chunk it has no text for- // anything else, so other files open in the attachment viewer, read on click.- const isPdf = kind === "pdf";- const viewable = !isPdf && isViewableSource(doc.filename);- const thumbnailFile = thumbnail?.kind === "file" ? thumbnail.file : null;- const loadSource = useCallback(async (): Promise<Blob> => {- // The thumbnail's copy when there is one; past its cap, up to the viewer's own limit, the- // same one the Library holds to. Past that the viewer says it can't preview.- const file =- thumbnailFile ?? (await fetchSourceFile(doc, MAX_DOCUMENT_PREVIEW_BYTES));- if (!file) throw new Error(`Couldn't preview ${doc.filename}`);- return asViewerFile(file);- // The id names the stored file; the rest of the row changes with progress frames.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [doc.id, thumbnailFile]);- const canOpen = ready && (isPdf || viewable);+ // Every indexed file opens: RagDocumentTrigger picks the browser, the viewer or a new tab.+ const canOpen = ready;const preview =thumbnail?.kind === "image" ? (<img@@ -485,11 +468,6 @@ function DocumentCard({<buttontype="button"disabled={!canOpen}- onClick={- isPdf- ? () => openPreview({ documentId: doc.id, filename: doc.filename })- : undefined- }title={doc.error ??(shared@@ -529,10 +507,10 @@ function DocumentCard({CARD_SLOT,)}>- {viewable && ready ? (- <LocalFileDialog name={doc.filename.split("/").pop() ?? doc.filename} load={loadSource}>+ {ready ? (+ <RagDocumentTrigger documentId={doc.id} filename={doc.filename}>{card}- </LocalFileDialog>+ </RagDocumentTrigger>) : (card)}diff --git a/studio/frontend/src/features/rag/lib/open-document.ts b/studio/frontend/src/features/rag/lib/open-document.tsnew file mode 100644index 00000000000..ed9602ef6b9--- /dev/null+++ b/studio/frontend/src/features/rag/lib/open-document.ts@@ -0,0 +1,93 @@+// 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 { MAX_DOCUMENT_PREVIEW_BYTES } from "@/components/file-viewer";+import { openFileInBrowser } from "@/features/browser";+import { isTauri } from "@/lib/api-base";+import { toast } from "@/lib/toast";+import { getDocumentFileUrl } from "../api/rag-api";++/**+ * Opens an indexed document's file outside Studio: the OS opener on Desktop (its webview has no+ * window.open), else a new tab opened inside the click, since popup blockers refuse one opened+ * after the URL request.+ */+export function openRagDocumentExternally(+ documentId: string,+ filename: string,+): void {+ const failed = () => toast.error(`Could not open ${filename}`);+ if (isTauri) {+ getDocumentFileUrl(documentId)+ .then(async (url) => {+ const { openUrl } = await import("@tauri-apps/plugin-opener");+ await openUrl(url);+ })+ .catch(failed);+ return;+ }+ const tab = window.open("about:blank", "_blank");+ if (!tab) {+ toast.error(`Your browser blocked the new tab for ${filename}`, {+ description: "Allow popups for Studio and try again.",+ });+ return;+ }+ tab.opener = null;+ getDocumentFileUrl(documentId)+ .then((url) => tab.location.replace(url))+ .catch(() => {+ tab.close();+ failed();+ });+}++/** For a file Studio can't preview: a toast whose action opens it outside Studio. */+export function offerRagDocumentOutside(+ documentId: string,+ filename: string,+): void {+ toast.message(`${filename} is too large to preview in Studio`, {+ action: {+ label: "Open",+ onClick: () => openRagDocumentExternally(documentId, filename),+ },+ });+}++/** Opens an indexed document's file in Studio's browser; past the preview limit, offers it outside. */+export function openRagDocumentInBrowser(+ documentId: string,+ filename: string,+): void {+ getDocumentFileUrl(documentId)+ // Signed URL: no bearer, so no credentials either.+ .then((url) => fetch(url, { credentials: "omit" }))+ .then((response) => {+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }+ // The file view refuses these anyway: don't buffer up to the upload limit to say so.+ if (+ Number(response.headers.get("content-length")) >+ MAX_DOCUMENT_PREVIEW_BYTES+ ) {+ void response.body?.cancel();+ return null;+ }+ return response.blob();+ })+ .then((blob) => {+ if (blob === null || blob.size > MAX_DOCUMENT_PREVIEW_BYTES) {+ offerRagDocumentOutside(documentId, filename);+ return;+ }+ openFileInBrowser({+ blob,+ name: filename,+ contentType: blob.type,+ key: `rag:${documentId}`,+ });+ })+ .catch(() => toast.error(`Could not open ${filename}`));+}diff --git a/studio/frontend/src/features/rag/types/rag.ts b/studio/frontend/src/features/rag/types/rag.tsindex 8836313332d..78dd3e6e3df 100644--- a/studio/frontend/src/features/rag/types/rag.ts+++ b/studio/frontend/src/features/rag/types/rag.ts@@ -190,24 +190,6 @@ export function retainActiveFolderJobs(}/** Coords 0..1, top-left origin. */-export interface PdfRegion {- pageIndex: number;- pageNumber: number;- x: number;- y: number;- width: number;- height: number;-}--export interface PreviewTarget {- documentId: string;- filename: string;- mediaKind: "pdf" | "text";- targetPage?: number | null;- pdfRegions: PdfRegion[];- text?: string | null;-}-export const RAG_UPLOAD_ACCEPT = ".pdf,.txt,.md,.markdown,.docx,.html,.htm";/** Mirrors backend `DOCUMENT_UPLOAD_EXTS`. */diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsindex f644c75f427..3e0311859bf 100644--- a/studio/frontend/tests/attachment-preview-text.test.ts+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -2206,8 +2206,8 @@ test("a UTF-16 text source opened from the files panel previews as its text", asassert.match(dialog, /blob instanceof File\s*\?\s*await readAttachmentText\(blob, source\.name, blob\.type\)/);const sourceFile = await readFile(new URL("../src/features/rag/components/source-file.ts", import.meta.url), "utf8");assert.match(sourceFile, /new File\(\[file\], file\.name, \{ type: "text\/plain" \}\)/);- const bar = await readFile(new URL("../src/features/rag/components/thread-documents-bar.tsx", import.meta.url), "utf8");- assert.match(bar, /return asViewerFile\(file\);/);+ const trigger = await readFile(new URL("../src/features/rag/components/rag-document-trigger.tsx", import.meta.url), "utf8");+ assert.match(trigger, /return asViewerFile\(file\);/);});async function readRtf(rtf: string | Uint8Array<ArrayBuffer>): Promise<string> {diff --git a/studio/frontend/tests/citation-pages.test.ts b/studio/frontend/tests/citation-pages.test.tsnew file mode 100644index 00000000000..df9bd895cf1--- /dev/null+++ b/studio/frontend/tests/citation-pages.test.ts@@ -0,0 +1,38 @@+// 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 {+ type Citation,+ citedPagesPerDocument,+ pageLabel,+} from "../src/components/assistant-ui/citation-utils.ts";++test("cited pages collapse into ranges", () => {+ assert.equal(pageLabel([3]), "p.3");+ assert.equal(pageLabel([1, 2, 3, 4, 5]), "p.1–5");+ assert.equal(pageLabel([1, 2, 3, 7]), "pp.1–3, 7");+ assert.equal(pageLabel([2, 4, 6]), "pp.2, 4, 6");+});++test("each document's pages are deduplicated and sorted", () => {+ const cite = (documentId: string | null, filename: string, page: number | null): Citation => ({+ id: `${documentId}-${page}`,+ filename,+ page,+ text: "",+ documentId,+ });+ const pages = citedPagesPerDocument([+ cite("a", "a.pdf", 5),+ cite("a", "a.pdf", 1),+ cite("a", "a.pdf", 5),+ cite("b", "b.md", null),+ cite(null, "c.txt", 2),+ ]);+ assert.deepEqual(pages.get("a"), [1, 5]);+ assert.deepEqual(pages.get("b"), []);+ assert.deepEqual(pages.get("c.txt"), [2]);+});diff --git a/studio/frontend/tests/pdf-worker-failure-lifecycle.test.ts b/studio/frontend/tests/pdf-worker-failure-lifecycle.test.tsdeleted file mode 100644index 3ceb02d3cf6..00000000000--- a/studio/frontend/tests/pdf-worker-failure-lifecycle.test.ts+++ /dev/null@@ -1,19 +0,0 @@-// 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 { readFile } from "node:fs/promises";-import test from "node:test";--test("RAG PDF previews release their worker after a load error", async () => {- const source = await readFile(- new URL(- "../src/features/rag/components/document-preview-sheet.tsx",- import.meta.url,- ),- "utf8",- );-- assert.match(source, /usePdfWorker\(error === null\)/);- assert.match(source, /onLoadError=\{\(e\) => setError\(e\.message\)\}/);-});diff --git a/studio/frontend/tests/project-source-chip-open.test.ts b/studio/frontend/tests/project-source-chip-open.test.tsindex cedfad58086..ca4cb7255d6 100644--- a/studio/frontend/tests/project-source-chip-open.test.ts+++ b/studio/frontend/tests/project-source-chip-open.test.ts@@ -31,28 +31,14 @@ const chip = loadWithStubs<typeof ChipModule>(},);-const opened: Record<string, unknown>[] = [];-const LocalFileDialog = () => null;+const RagDocumentTrigger = () => null;const { ProjectSourceChip } = loadWithStubs<typeof SourceChipModule>(new URL("../src/features/rag/components/project-source-chip.tsx", import.meta.url),{"react/jsx-runtime": stubJsxRuntime(),- "@/components/assistant-ui/attachment-document-dialog": { LocalFileDialog },- "@/components/file-viewer": { MAX_DOCUMENT_PREVIEW_BYTES: 1 },- "@/features/chat": {- attachmentFileKind: (name: string) => (name.endsWith(".pdf") ? "pdf" : "file"),- },"./document-status-chip": chip,- "./preview-store": {- useDocumentPreviewStore: (select: (s: Record<string, unknown>) => unknown) =>- select({ openPreview: (args: Record<string, unknown>) => opened.push(args) }),- },- "./source-file": {- asViewerFile: (file: File) => file,- fetchSourceFile: async () => null,- isViewableSource: (name: string) => /\.(md|txt|docx)$/.test(name),- },+ "./rag-document-trigger": { RagDocumentTrigger },},);@@ -64,34 +50,26 @@ function chipProps(doc: Record<string, unknown>): Record<string, unknown> {return element.props;}-test("an indexed PDF source opens the source preview", () => {- opened.length = 0;- const props = chipProps({ id: "doc-1", filename: "handbook.pdf", status: "completed" });- assert.equal(props.openTrigger, undefined);- assert.equal(typeof props.onOpen, "function");- (props.onOpen as () => void)();- assert.deepEqual(opened, [{ documentId: "doc-1", filename: "handbook.pdf" }]);-});--test("an indexed text, markdown or Office source opens in the attachment viewer", () => {- for (const filename of ["notes.md", "notes.txt", "Docs/report.docx"]) {+// Every indexed source opens through the shared trigger, which picks where it shows.+test("an indexed source of any format opens through the document trigger", () => {+ for (const filename of ["handbook.pdf", "notes.md", "Docs/report.docx", "archive.epub"]) {const props = chipProps({ id: "doc-2", filename, status: "completed" });assert.equal(props.onOpen, undefined);const trigger = React.createElement("button");const wrapped = (props.openTrigger as (t: React.ReactElement) => StubElement)(trigger);- assert.equal(wrapped.type, LocalFileDialog);- assert.equal(wrapped.props.name, filename.split("/").pop());+ assert.equal(wrapped.type, RagDocumentTrigger);+ assert.equal(wrapped.props.documentId, "doc-2");+ assert.equal(wrapped.props.filename, filename);assert.equal(wrapped.props.children, trigger);}});-test("sources still indexing, failed, optimistic or unviewable stay inert", () => {+test("sources still indexing, failed or optimistic stay inert", () => {for (const doc of [{ id: "doc-3", filename: "handbook.pdf", status: "running" },{ id: "doc-3", filename: "notes.md", status: "pending" },{ id: "doc-3", filename: "notes.md", status: "failed" },{ id: "pending_1", filename: "notes.md", status: "completed" },- { id: "doc-3", filename: "archive.epub", status: "completed" },]) {const props = chipProps(doc);assert.equal(props.onOpen, undefined, JSON.stringify(doc));diff --git a/studio/frontend/tests/project-sources-model-without-tools.test.ts b/studio/frontend/tests/project-sources-model-without-tools.test.tsindex 0128d7489fc..13b8200a520 100644--- a/studio/frontend/tests/project-sources-model-without-tools.test.ts+++ b/studio/frontend/tests/project-sources-model-without-tools.test.ts@@ -88,9 +88,6 @@ const { ThreadDocumentsBar } = loadWithStubs<typeof BarModule>(TooltipTrigger: Passthrough,},"@/components/ui/spinner": { Spinner: Nothing },- "./preview-store": {- useDocumentPreviewStore: selectorStore({ openPreview: () => undefined }),- },"@/lib/chevron-icons": {},"@assistant-ui/react": {useAui: () => ({}),@@ -147,6 +144,7 @@ const { ThreadDocumentsBar } = loadWithStubs<typeof BarModule>("@/components/ui/alert-dialog": new Proxy({}, { get: () => Passthrough }),"./document-status-chip": { STAGE_LABELS: {} },"./knowledge-base-dialog": { KnowledgeBaseDialog: Nothing },+ "./rag-document-trigger": { RagDocumentTrigger: Passthrough },"./source-file": loadWithStubs(new URL("../src/features/rag/components/source-file.ts", import.meta.url),{@@ -255,9 +253,8 @@ test("a linked folder's files collapse into one folder card", () => {}});-// The source preview has text only for PDFs when opened without a chunk; other files open in the-// attachment viewer, whatever their size, and a type it cannot draw is not offered at all.-test("non-PDF cards open only when the attachment viewer can show them", () => {+// Every indexed card opens: the browser, the attachment viewer or a new tab.+test("indexed cards of any format open", () => {extraProjectDocs = [{ id: "doc-2", filename: "notes.docx", status: "completed" },{ id: "doc-3", filename: "book.epub", status: "completed" },@@ -267,10 +264,10 @@ test("non-PDF cards open only when the attachment viewer can show them", () => {{ checkpoint: "unsloth/Qwen3-4B-GGUF", supportsTools: true },true,);- assert.match(html, /aria-label="Preview handbook\.pdf/);- assert.match(html, /aria-label="Preview notes\.docx/);- assert.doesNotMatch(html, /aria-label="Preview book\.epub/);- assert.match(html, /<button[^>]*disabled=""[^>]*aria-label="book\.epub/);+ for (const name of ["handbook\\.pdf", "notes\\.docx", "book\\.epub"]) {+ assert.match(html, new RegExp(`aria-label="Preview ${name}`));+ }+ assert.doesNotMatch(html, /<button[^>]*disabled=""[^>]*aria-label="book\.epub/);} finally {extraProjectDocs = [];}diff --git a/studio/frontend/tests/rag-document-trigger.test.ts b/studio/frontend/tests/rag-document-trigger.test.tsnew file mode 100644index 00000000000..be7f2302947--- /dev/null+++ b/studio/frontend/tests/rag-document-trigger.test.ts@@ -0,0 +1,92 @@+// 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 * as React from "react";++import type * as TriggerModule from "../src/features/rag/components/rag-document-trigger.tsx";+import { type StubElement, loadWithStubs, stubJsxRuntime } from "./helpers/module-stubs.ts";++const LocalFileDialog = () => null;+const env = { panel: true, filesInBrowser: true };+const opened: string[] = [];++const { RagDocumentTrigger } = loadWithStubs<typeof TriggerModule>(+ new URL("../src/features/rag/components/rag-document-trigger.tsx", import.meta.url),+ {+ react: React,+ "react/jsx-runtime": stubJsxRuntime(),+ "@/components/assistant-ui/attachment-document-dialog": { LocalFileDialog },+ "@/components/file-viewer": { MAX_DOCUMENT_PREVIEW_BYTES: 1 },+ // What the browser's FileView renders by name: documents, text and HTML, not EPUB or RTF.+ "@/features/browser/file-kind": {+ canShowFile: (name: string) => /\.(pdf|docx|md|txt|html)$/.test(name),+ },+ "@/features/browser/panel-availability": { useBrowserPanelAvailable: () => env.panel },+ "@/features/browser/prefs-store": {+ useBrowserPrefsStore: (select: (s: { openFilesInBrowser: boolean }) => unknown) =>+ select({ openFilesInBrowser: env.filesInBrowser }),+ },+ "../lib/open-document": {+ openRagDocumentInBrowser: (_id: string, name: string) => opened.push(`browser:${name}`),+ openRagDocumentExternally: (_id: string, name: string) => opened.push(`tab:${name}`),+ offerRagDocumentOutside: (_id: string, name: string) => opened.push(`offer:${name}`),+ },+ "./source-file": {+ asViewerFile: (file: File) => file,+ fetchSourceFile: async () => null,+ isViewableSource: (name: string) => /\.(pdf|docx|md|txt|rtf)$/.test(name),+ },+ },+);++function route(filename: string): "browser" | "viewer" | "tab" {+ const child = React.createElement("button");+ const element = RagDocumentTrigger({+ documentId: "doc-1",+ filename,+ children: child,+ }) as unknown as StubElement;+ if (element.type === LocalFileDialog) return "viewer";+ opened.length = 0;+ (element.props.onClick as () => void)();+ return opened[0]?.startsWith("browser:") ? "browser" : "tab";+}++test("formats the browser can show open there", () => {+ Object.assign(env, { panel: true, filesInBrowser: true });+ for (const name of ["handbook.pdf", "notes.md", "page.html"]) {+ assert.equal(route(name), "browser", name);+ }+});++test("formats the browser can't show skip it, as they do without the panel", () => {+ Object.assign(env, { panel: true, filesInBrowser: true });+ assert.equal(route("letter.rtf"), "viewer");+ assert.equal(route("book.epub"), "tab");+});++test("without the panel or with files set to open elsewhere, the viewer or a new tab", () => {+ for (const state of [+ { panel: false, filesInBrowser: true },+ { panel: true, filesInBrowser: false },+ ]) {+ Object.assign(env, state);+ assert.equal(route("handbook.pdf"), "viewer", JSON.stringify(state));+ assert.equal(route("page.html"), "tab", JSON.stringify(state));+ }+});++test("a file too large for the attachment viewer is offered outside Studio", async () => {+ Object.assign(env, { panel: false, filesInBrowser: true });+ const element = RagDocumentTrigger({+ documentId: "doc-1",+ filename: "scan.pdf",+ children: React.createElement("button"),+ }) as unknown as StubElement;+ assert.equal(element.type, LocalFileDialog);+ opened.length = 0;+ await assert.rejects((element.props.load as () => Promise<Blob>)());+ assert.deepEqual(opened, ["offer:scan.pdf"]);+});diff --git a/studio/frontend/tests/rag-open-document.test.ts b/studio/frontend/tests/rag-open-document.test.tsnew file mode 100644index 00000000000..4ab67e7ff78--- /dev/null+++ b/studio/frontend/tests/rag-open-document.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 type * as OpenModule from "../src/features/rag/lib/open-document.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++const LIMIT = 100;+const toasts: string[] = [];+const opened: { name: string; size: number }[] = [];++const { openRagDocumentInBrowser, openRagDocumentExternally } = loadWithStubs<typeof OpenModule>(+ new URL("../src/features/rag/lib/open-document.ts", import.meta.url),+ {+ "@/components/file-viewer": { MAX_DOCUMENT_PREVIEW_BYTES: LIMIT },+ "@/features/browser": {+ openFileInBrowser: ({ name, blob }: { name: string; blob: Blob }) =>+ opened.push({ name, size: blob.size }),+ },+ "@/lib/api-base": { isTauri: false },+ "@/lib/toast": {+ toast: {+ error: (title: string) => toasts.push(`error:${title}`),+ message: (title: string) => toasts.push(`message:${title}`),+ },+ },+ "../api/rag-api": { getDocumentFileUrl: async () => "http://studio.test/file" },+ },+);++const settle = () => new Promise((resolve) => setTimeout(resolve, 10));++function serve(size: number, contentLength = String(size)) {+ let cancelled = false;+ globalThis.fetch = (async () => ({+ ok: true,+ headers: new Headers(contentLength ? { "content-length": contentLength } : {}),+ body: { cancel: async () => void (cancelled = true) },+ blob: async () => new Blob([new Uint8Array(size)]),+ })) as unknown as typeof fetch;+ return () => cancelled;+}++test("a file within the preview limit opens in the browser", async () => {+ toasts.length = 0;+ opened.length = 0;+ serve(LIMIT);+ openRagDocumentInBrowser("doc-1", "handbook.pdf");+ await settle();+ assert.deepEqual(opened, [{ name: "handbook.pdf", size: LIMIT }]);+ assert.deepEqual(toasts, []);+});++test("past the limit the body is never buffered and the file is offered outside Studio", async () => {+ toasts.length = 0;+ opened.length = 0;+ const cancelled = serve(LIMIT + 1);+ openRagDocumentInBrowser("doc-1", "scan.pdf");+ await settle();+ assert.equal(cancelled(), true);+ assert.deepEqual(opened, []);+ assert.deepEqual(toasts, ["message:scan.pdf is too large to preview in Studio"]);+ // No Content-Length: the size is still checked once read.+ toasts.length = 0;+ serve(LIMIT + 1, "");+ openRagDocumentInBrowser("doc-1", "scan.pdf");+ await settle();+ assert.deepEqual(opened, []);+ assert.equal(toasts.length, 1);+});++test("a blocked new tab says so instead of doing nothing", () => {+ toasts.length = 0;+ (globalThis as { window?: unknown }).window = { open: () => null };+ try {+ openRagDocumentExternally("doc-1", "book.epub");+ } finally {+ (globalThis as { window?: unknown }).window = undefined;+ }+ assert.deepEqual(toasts, ["error:Your browser blocked the new tab for book.epub"]);+});diff --git a/studio/frontend/tests/rag-thread-initialization.test.ts b/studio/frontend/tests/rag-thread-initialization.test.tsindex c3c6bbe1cde..24d80bf7eac 100644--- a/studio/frontend/tests/rag-thread-initialization.test.ts+++ b/studio/frontend/tests/rag-thread-initialization.test.ts@@ -157,10 +157,10 @@ function harness("@/components/assistant-ui/attachment": {},"@/components/assistant-ui/attachment-card-preview": {},"@/components/assistant-ui/attachment-document-dialog": {},+ "./rag-document-trigger": {},"@/components/file-viewer": {},"@/components/ui/tooltip": {},"@/components/ui/spinner": {},- "./preview-store": { useDocumentPreviewStore: () => undefined },"@/lib/chevron-icons": {},"@assistant-ui/react": {useAui: () => ({ threadListItem: () => item }),diff --git a/studio/frontend/tests/tool-fallback-label.test.ts b/studio/frontend/tests/tool-fallback-label.test.tsindex b1c4fa396ef..ed4ca869813 100644--- a/studio/frontend/tests/tool-fallback-label.test.ts+++ b/studio/frontend/tests/tool-fallback-label.test.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";+import { readFileSync } from "node:fs";import test from "node:test";import {@@ -87,3 +88,71 @@ test("the query reaches the header, whichever tense it is in", () => {);}});++// A document search can carry a whole page as its query; wrapping it into the open header pushed the+// icon and chevron to the middle of a tall block and the retrieval summary below it.+test("the document search header stays one line, with the summary first and the long query below", () => {+ const kb = readFileSync(+ new URL(+ "../src/components/assistant-ui/tool-ui-knowledge-base.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(kb, /singleLine=\{true\}/);+ assert.match(kb, /icon=\{LibraryGlyph\}/);+ assert.match(kb, /icon=\{LibrariesIcon\}/);+ const summary = kb.indexOf("Retrieved {citations.length} passage");+ const fullQuery = kb.indexOf('data-slot="knowledge-base-query"');+ assert.ok(+ summary >= 0 && fullQuery >= 0,+ "both the summary and the full query render",+ );+ assert.ok(summary < fullQuery);+ // The query renders after every outcome (hits, raw result, no hits), not only with citations.+ assert.ok(kb.indexOf("No matching passages.") < fullQuery);+ const fallback = readFileSync(+ new URL(+ "../src/components/assistant-ui/tool-fallback.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(fallback, /const wrapWhenOpen = !singleLine;/);+});++// A search lists each document once in its expanded card, with the pages it cited, not every+// passage; documents open in Studio's browser; no separate Document Sources strip or PDF sheet.+test("a document search lists each document once in the card, with its cited pages", () => {+ const read = (path: string) =>+ readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");+ const kb = read("components/assistant-ui/tool-ui-knowledge-base.tsx");+ assert.match(+ kb,+ /shown\.map\(\(citation, i\) => \(\s*<CitationBadge[\s\S]*?pages=\{pagesByDocument\.get\(/,+ );+ assert.ok(!kb.includes("{citation.text}"), "passage snippets are not shown");+ // A model-chosen top_k has no ceiling: the rest wait behind "Show N more".+ assert.match(kb, /documents\.slice\(0, DOCUMENTS_SHOWN\)/);+ assert.match(kb, /Show \{documents\.length - shown\.length\} more/);+ assert.match(kb, /<RagDocumentTrigger/);+ const trigger = read("features/rag/components/rag-document-trigger.tsx");+ // Browser first; without its panel (mobile) the attachment viewer, else a new tab.+ assert.match(+ trigger,+ /if \(browser\)[\s\S]*?openRagDocumentInBrowser[\s\S]*?if \(isViewableSource\(filename\)\)[\s\S]*?<LocalFileDialog[\s\S]*?openRagDocumentExternally\(documentId, filename\)/,+ );+ assert.ok(!kb.includes("See Document Sources below"));+ const thread = read("components/assistant-ui/thread.tsx");+ assert.ok(!thread.includes("RagSourcesGroup"));+ assert.ok(!thread.includes("DocumentPreviewMount"));+ for (const path of [+ "features/rag/components/project-source-chip.tsx",+ "features/rag/components/thread-documents-bar.tsx",+ ]) {+ assert.ok(+ !read(path).includes("isPdf"),+ `${path} sends PDFs to the attachment viewer too`,+ );+ }+});diff --git a/tests/studio/test_chat_response_details_ui_contract.py b/tests/studio/test_chat_response_details_ui_contract.pyindex a2e84b09e5d..079489422e3 100644--- a/tests/studio/test_chat_response_details_ui_contract.py+++ b/tests/studio/test_chat_response_details_ui_contract.py@@ -16,9 +16,6 @@ MESSAGE_MENU_TIME_TSX = REPO / "studio/frontend/src/components/assistant-ui/messDETAILS_TSX = (REPO / "studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx")-DOCUMENT_PREVIEW_TSX = (- REPO / "studio/frontend/src/features/rag/components/document-preview-sheet.tsx"-)SHEET_TSX = REPO / "studio/frontend/src/components/ui/sheet.tsx"REASONING_TSX = REPO / "studio/frontend/src/components/assistant-ui/reasoning.tsx"ADAPTER_TS = REPO / "studio/frontend/src/features/chat/api/chat-adapter.ts"@@ -436,9 +433,6 @@ def test_sheet_headers_center_the_shared_close_button_on_the_title():assert_sheet_close_button_tracks_title_center(DETAILS_TSX.read_text(encoding = "utf-8"),)- assert_sheet_close_button_tracks_title_center(- DOCUMENT_PREVIEW_TSX.read_text(encoding = "utf-8"),- )sheet_src = SHEET_TSX.read_text(encoding = "utf-8")close_button = sheet_src[diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex 2a8886e25b5..153efaef4e8 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -33,7 +33,6 @@ TITLEBAR = FRONTEND / "components/tauri/window-titlebar.tsx"SHEET = FRONTEND / "components/ui/sheet.tsx"RESEARCH_ACTIVITY_PANEL = FRONTEND / "features/chat/components/research-activity-panel.tsx"RESPONSE_DETAILS_SHEET = FRONTEND / "components/assistant-ui/message-response-details-sheet.tsx"-DOCUMENT_PREVIEW_SHEET = FRONTEND / "features/rag/components/document-preview-sheet.tsx"INTERFACE_SCALE_RUNTIME = FRONTEND / "features/settings/lib/interface-scale-runtime.ts"NATIVE_DIALOGS = REPO / "studio/src-tauri/src/native_file_dialogs.rs"NATIVE_CLIPBOARD = REPO / "studio/src-tauri/src/native_clipboard.rs"@@ -899,7 +898,6 @@ def test_fixed_sheets_start_below_the_custom_titlebar():for portalled in (RESEARCH_ACTIVITY_PANEL,RESPONSE_DETAILS_SHEET,- DOCUMENT_PREVIEW_SHEET,):assert "studio-custom-titlebar-height" not in _ui_source(portalled)