Skip to content

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

Studio: save a chat or reply to project sources (#8588)

Nilay731ea4cd734b
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 1f79bf533b0..e83eb82d086 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -65,6 +65,7 @@ import {
Archive03Icon,
ArrowRight02Icon,
BadgeInfoIcon,
+ BookOpen01Icon,
BubbleChatIcon,
ChefHatIcon,
CloudIcon,
@@ -292,6 +293,16 @@ async function exportConversationByFormat(
}
}
+async function saveChatToProjectSources(
+ item: SidebarItem,
+ projectId: string,
+): Promise<void> {
+ const { saveChatItemAsProjectSource } = await import(
+ "@/features/chat/prompt-storage/prompt-storage-dialog"
+ );
+ await saveChatItemAsProjectSource(item, projectId);
+}
+
function runStatusDotClass(status: TrainingRunSummary["status"]): string {
switch (status) {
@@ -1985,6 +1996,32 @@ export function AppSidebar() {
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Save to project sources</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">
+ {projects.length === 0 && (
+ <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>
+ )}
+ {projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ onSelect={async () => {
+ try {
+ await saveChatToProjectSources(item, project.id);
+ } catch {
+ toast.error("Failed to save to project sources.");
+ }
+ }}
+ >
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">{project.name}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => void handleArchiveThread(item)}>
<HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index ce71f94a3fe..d6ee8d3c9a7 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -110,6 +110,8 @@ import {
providerModelSupportsStudioTools,
} from "@/features/chat/external-providers";
import { toolStatusKind } from "@/features/chat/utils/tool-status";
+import { replySourceMarkdown } from "@/features/chat/utils/reply-source-markdown";
+import { toolResultModelText } from "@/features/chat/api/chat-adapter";
import {
CONTINUATION_RUN_CONFIG_KEY,
incompleteLabel,
@@ -125,6 +127,7 @@ import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-me
import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";
+import { saveMarkdownAsProjectSource } from "@/features/rag";
import {
PLUS_MENU_ORDER,
CONVERSATION_MARKDOWN_LABEL,
@@ -169,7 +172,10 @@ import {
writeComposerDraft,
} from "@/features/chat";
import { deleteThreadMessage } from "@/features/chat/utils/delete-thread-message";
-import { updateStoredChatThread } from "@/features/chat/utils/chat-history-storage";
+import {
+ getStoredChatThread,
+ updateStoredChatThread,
+} from "@/features/chat/utils/chat-history-storage";
import {
dictationSendBlocked,
shouldSubmitDictation,
@@ -207,6 +213,7 @@ import { flushResourcesSync } from "@assistant-ui/tap";
import {
AttachmentIcon,
Bookmark02Icon,
+ BookOpen01Icon,
CodeIcon,
Copy01Icon,
Delete02Icon,
@@ -6197,9 +6204,11 @@ async function exportMessageMarkdown(content: string): Promise<void> {
}
}
const AssistantActionBar: FC = () => {
+ const aui = useAui();
const { forkMessage, forkDisabled } = useForkMessageAction();
const researchRunId = useResearchMessageRunId();
const researchActive = useThreadResearchActive();
+ const activeProjectId = useChatRuntimeStore((s) => s.activeProjectId);
const [detailsOpen, setDetailsOpen] = useState(false);
const ttsEnabled = useVoiceSettingsStore((s) => s.ttsEnabled);
// hideWhenRunning is thread-level, so a new run would hide this bar and its
@@ -6281,6 +6290,55 @@ const AssistantActionBar: FC = () => {
Export as markdown
</ActionBarMorePrimitive.Item>
</ActionBarPrimitive.ExportMarkdown>
+ {activeProjectId && (
+ <ActionBarMorePrimitive.Item
+ onSelect={() => {
+ // Not getCopyText: it joins text parts alone, so a reply's
+ // reasoning, tool calls and citations would be dropped and a
+ // tool-only reply would read as empty. Same conversion the
+ // whole-chat save runs.
+ const text = replySourceMarkdown(
+ aui.message().getState().content,
+ toolResultModelText,
+ );
+ if (!text.trim()) {
+ toast.info("No content to save.");
+ return;
+ }
+ const state = aui.threadListItem().getState();
+ // The list item's title belongs to the whole chat, so mark the
+ // reply apart or saving both lists two identical names.
+ const title = state.title ? `${state.title} - reply` : "reply";
+ // activeProjectId can lag a thread switch while the stored
+ // thread loads; resolve the destination from this thread.
+ const remoteId =
+ state.remoteId ||
+ useChatRuntimeStore.getState().activeThreadId;
+ void (async () => {
+ const thread = remoteId
+ ? await getStoredChatThread(remoteId).catch(() => null)
+ : null;
+ if (!thread?.projectId) {
+ toast.info("This chat isn't in a project.");
+ return;
+ }
+ await saveMarkdownAsProjectSource(
+ thread.projectId,
+ text,
+ title,
+ );
+ })();
+ }}
+ className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-[12px] px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
+ >
+ <HugeiconsIcon
+ icon={BookOpen01Icon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
+ Save to project sources
+ </ActionBarMorePrimitive.Item>
+ )}
<ActionBarMorePrimitive.Item
onSelect={() => setDetailsOpen(true)}
className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-[12px] px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 17df1d192c0..18bd9af89a7 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -86,6 +86,7 @@ import {
} from "./utils/conversation-markdown";
import {
Archive03Icon,
+ BookOpen01Icon,
BubbleChatTemporaryIcon,
Delete02Icon,
Download01Icon,
@@ -1075,6 +1076,16 @@ async function exportProjectChatItem(
for (const id of ids) await exportProjectConversation(id, format);
}
+async function saveProjectChatItemAsSource(
+ item: SidebarItem,
+ projectId: string,
+): Promise<void> {
+ const { saveChatItemAsProjectSource } = await import(
+ "./prompt-storage/prompt-storage-dialog"
+ );
+ await saveChatItemAsProjectSource(item, projectId);
+}
+
function extractMessageText(content: MessageRecord["content"]): string {
if (typeof content === "string") {
return content;
@@ -1315,6 +1326,17 @@ function ProjectLanding({
[],
);
+ const handleSaveAsSource = useCallback(
+ async (item: SidebarItem) => {
+ try {
+ await saveProjectChatItemAsSource(item, projectId);
+ } catch {
+ toast.error("Failed to save to project sources.");
+ }
+ },
+ [projectId],
+ );
+
useEffect(() => {
if (!activeThreadId) {
// Leaving a created chat for a new one: rotate the nonce so the runtime
@@ -1693,6 +1715,16 @@ function ProjectLanding({
)}
</DropdownMenuSubContent>
</DropdownMenuSub>
+ <DropdownMenuItem
+ onSelect={() => void handleSaveAsSource(item)}
+ >
+ <HugeiconsIcon
+ icon={BookOpen01Icon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
+ <span>Save to project sources</span>
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => void handleArchive(item)}
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index bdd70e4c1ac..49f222f9e07 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -63,9 +63,12 @@ import { createConversationMarkdownExporter } from "../utils/conversation-markdo
import { parseCsv } from "../utils/csv-parse";
import { unwrapPastedTextContent } from "../utils/pasted-text.ts";
import {
+ buildConversationMarkdown,
contentBlocksToMarkdownBlocks,
renderConversationBlocks,
} from "../utils/conversation-markdown";
+import { planChatItemSources } from "../utils/project-source-plan";
+import { saveMarkdownAsProjectSource } from "@/features/rag";
function newId(): string {
return crypto.randomUUID().replace(/-/g, "").slice(0, 12);
@@ -230,10 +233,15 @@ function orderByParentChain<T extends _Msg>(
return result;
}
-async function loadConversationMessages(threadId: string) {
+async function loadConversationMessages(
+ threadId: string,
+ // Every other caller here is an export; the project-sources save is not, and
+ // reporting an export to someone who never asked for one is confusing.
+ emptyMessage = "No messages in this conversation to export.",
+) {
const raw = await listStoredChatMessages(threadId);
if (raw.length === 0) {
- toast.info("No messages in this conversation to export.");
+ toast.info(emptyMessage);
return null;
}
// No parentId = legacy flat thread (already DB createdAt-sorted); walking the
@@ -449,6 +457,62 @@ export const exportConversationMarkdown = createConversationMarkdownExporter({
notifyNoContent: () => toast.info("No exportable content."),
});
+// "skipped" is an empty conversation, which has already said so and must not
+// stop the rest of a pair; "failed" has toasted a reason, so stop there rather
+// than stack a second one.
+type SaveSourceOutcome = "saved" | "skipped" | "failed";
+
+async function saveConversationAsProjectSource(
+ threadId: string,
+ projectId: string,
+ title: string,
+): Promise<SaveSourceOutcome> {
+ const messages = await loadConversationMessages(
+ threadId,
+ "No messages in this conversation to save.",
+ );
+ if (!messages) return "skipped";
+ const markdown = buildConversationMarkdown(
+ messages.map((msg) => ({
+ role: String(msg.role ?? ""),
+ content: messageToMarkdown(msg),
+ })),
+ );
+ if (!markdown) {
+ toast.info("No content to save.");
+ return "skipped";
+ }
+ const saved = await saveMarkdownAsProjectSource(projectId, markdown, title, {
+ quiet: true,
+ });
+ return saved ? "saved" : "failed";
+}
+
+export async function saveChatItemAsProjectSource(
+ item: { id: string; title: string; type: string },
+ projectId: string,
+): Promise<void> {
+ const plans = planChatItemSources(
+ item,
+ item.type === "single" ? [] : await listStoredChatThreads({ pairId: item.id }),
+ );
+ let saved = 0;
+ for (const plan of plans) {
+ const outcome = await saveConversationAsProjectSource(
+ plan.id,
+ projectId,
+ plan.title,
+ );
+ if (outcome === "failed") break;
+ if (outcome === "saved") saved += 1;
+ }
+ // One toast per click, not one per thread in the pair.
+ if (saved === 1) toast.success("Saved to project sources.");
+ else if (saved > 1) {
+ toast.success(`Saved ${saved} chats to project sources.`);
+ }
+}
+
export type ConvExportFormat = "jsonl-raw" | "csv" | "sharegpt";
const EXPORT_FORMAT_LABELS: Record<ConvExportFormat, string> = {
diff --git a/studio/frontend/src/features/chat/utils/project-source-plan.ts b/studio/frontend/src/features/chat/utils/project-source-plan.ts
new file mode 100644
index 00000000000..69369be069b
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/project-source-plan.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** One conversation to save, and the title its source is listed under. */
+export interface ProjectSourcePlan {
+ readonly id: string;
+ readonly title: string;
+}
+
+/** The threads behind a sidebar row, as far as naming their sources needs. */
+export interface ProjectSourceThread {
+ readonly id: string;
+ readonly modelId?: string;
+ readonly modelType?: string;
+}
+
+/** "unsloth/Qwen3-8B-GGUF:Q4_K_M" reads as "Qwen3-8B-GGUF" in a filename. */
+function modelLabel(thread: ProjectSourceThread): string | undefined {
+ const label = thread.modelId?.split("/").pop()?.split(":")[0]?.trim();
+ return label || undefined;
+}
+
+/**
+ * Which half of a compare this is. listStoredChatThreads sorts by updatedAt, so
+ * arrival order is whichever half answered last: naming by index alone would
+ * swap the two names between saves of one pair. modelType carries the pane, so
+ * only a thread missing it falls back to position. The LoRA compare gets the
+ * words the compare header uses, since "base" beats "1" in a filename.
+ */
+function paneLabel(thread: ProjectSourceThread, index: number): string {
+ if (thread.modelType === "base") return "base";
+ if (thread.modelType === "lora") return "fine-tuned";
+ if (thread.modelType === "model1") return "1";
+ if (thread.modelType === "model2") return "2";
+ return String(index + 1);
+}
+
+/**
+ * What a "Save to project sources" click uploads. A compare pair is two models
+ * answering the same prompt and both halves carry the row's single title, so
+ * name each after its model: the sources panel lists a document by filename and
+ * nothing else would tell the two apart.
+ */
+export function planChatItemSources(
+ item: { id: string; title: string; type: string },
+ threads: readonly ProjectSourceThread[],
+): ProjectSourcePlan[] {
+ if (item.type === "single") return [{ id: item.id, title: item.title }];
+ if (threads.length <= 1) {
+ return threads.map((thread) => ({ id: thread.id, title: item.title }));
+ }
+ const named = threads.map((thread, index) => ({
+ thread,
+ label: modelLabel(thread) ?? paneLabel(thread, index),
+ side: paneLabel(thread, index),
+ }));
+ const uses = new Map<string, number>();
+ for (const { label } of named) uses.set(label, (uses.get(label) ?? 0) + 1);
+ return named.map(({ thread, label, side }) => {
+ // Only a colliding half carries a side, so two different models keep the
+ // plain "<title> - <model>" name.
+ const suffix = (uses.get(label) ?? 0) > 1 ? ` - ${side}` : "";
+ return { id: thread.id, title: `${item.title} - ${label}${suffix}` };
+ });
+}
diff --git a/studio/frontend/src/features/chat/utils/reply-source-markdown.ts b/studio/frontend/src/features/chat/utils/reply-source-markdown.ts
new file mode 100644
index 00000000000..03d7e4c5407
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/reply-source-markdown.ts
@@ -0,0 +1,23 @@
+// 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 {
+ contentBlocksToMarkdownBlocks,
+ renderConversationBlocks,
+} from "./conversation-markdown";
+
+/**
+ * One assistant reply as the markdown its saved source holds. The reply's own
+ * reasoning, tool calls and citations are part of what a "save this reply"
+ * click asks to keep, and getCopyText() concatenates text parts alone: they
+ * would be dropped, and a reply that is only a tool call would read as empty.
+ * Same conversion the whole-chat save runs.
+ */
+export function replySourceMarkdown(
+ content: unknown,
+ normalizeToolResult?: (result: unknown, toolName?: string) => unknown,
+): string {
+ return renderConversationBlocks(
+ contentBlocksToMarkdownBlocks(content, normalizeToolResult),
+ );
+}
diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.ts
index cba02c9c019..349c691cc2c 100644
--- a/studio/frontend/src/features/rag/api/rag-api.ts
+++ b/studio/frontend/src/features/rag/api/rag-api.ts
@@ -219,10 +219,44 @@ export async function projectHasSources(projectId: string): Promise<boolean> {
}
}
+export const PROJECT_SOURCES_UPDATED_EVENT = "unsloth-project-sources-updated";
+
export function invalidateProjectSources(projectId: string): void {
projectSourcesCache.delete(projectId);
}
+/** Invalidate, and tell a mounted sources list its documents changed. Kept apart
+ * from invalidateProjectSources because callers invalidate the probe *before*
+ * their own mutation too, and refetching at that point would resurrect a row the
+ * panel has already dropped optimistically. */
+export function announceProjectSourcesUpdated(projectId: string): void {
+ projectSourcesCache.delete(projectId);
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(
+ new CustomEvent(PROJECT_SOURCES_UPDATED_EVENT, { detail: { projectId } }),
+ );
+}
+
+/** Run `onUpdated` whenever this project's sources change somewhere else in the
+ * app. Returns the unsubscribe, so a component can hand it straight back from an
+ * effect. Lives here rather than inline in the panel so the filtering and the
+ * teardown are testable without a DOM. */
+export function subscribeProjectSourcesUpdated(
+ projectId: string,
+ onUpdated: () => void,
+): () => void {
+ if (typeof window === "undefined") return () => undefined;
+ const listener = (event: Event) => {
+ const detail = (event as CustomEvent<{ projectId?: string }>).detail;
+ // Another project's save must not refetch this one's list.
+ if (detail?.projectId === projectId) onUpdated();
+ };
+ window.addEventListener(PROJECT_SOURCES_UPDATED_EVENT, listener);
+ return () => {
+ window.removeEventListener(PROJECT_SOURCES_UPDATED_EVENT, listener);
+ };
+}
+
export async function listLinkedFolders(
scope?: LinkedFolderScope,
): Promise<LinkedFolder[]> {
diff --git a/studio/frontend/src/features/rag/api/save-markdown-source.ts b/studio/frontend/src/features/rag/api/save-markdown-source.ts
new file mode 100644
index 00000000000..e9381c3afa9
--- /dev/null
+++ b/studio/frontend/src/features/rag/api/save-markdown-source.ts
@@ -0,0 +1,136 @@
+// 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 { toast } from "@/lib/toast";
+import { type IndexJob, terminalJobStatus } from "../types/rag";
+import {
+ announceProjectSourcesUpdated,
+ getJob,
+ invalidateProjectSources,
+ uploadProjectDocument,
+} from "./rag-api";
+
+// Windows keeps these device names reserved in every directory, with or without
+// an extension: "NUL.txt and NUL.tar.gz are both equivalent to NUL". The
+// ISO-8859-1 superscripts count as digits in COM#/LPT#.
+const RESERVED_DEVICE_NAME =
+ /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])$/i;
+// Filesystems cap a path component in bytes, not characters, so 80 CJK or emoji
+// code points would overrun the usual 255. Leave room for ".md" too.
+const MAX_STEM_BYTES = 180;
+
+/** Trim to a byte budget on a code point boundary, so a cut never leaves the
+ * lone half of a surrogate pair behind. */
+function clampToBytes(text: string, maxBytes: number): string {
+ const encoder = new TextEncoder();
+ if (encoder.encode(text).length <= maxBytes) return text;
+ let used = 0;
+ let out = "";
+ for (const char of text) {
+ const size = encoder.encode(char).length;
+ if (used + size > maxBytes) break;
+ used += size;
+ out += char;
+ }
+ return out;
+}
+
+/** A chat title as the filename its source is listed under. The backend stores
+ * the upload under a uuid and re-sanitises this for its own metadata, so this is
+ * about what the user reads in the sources panel, not about path safety. */
+export function projectSourceFileName(title: string): string {
+ const stem = clampToBytes(
+ Array.from(title, (char) => {
+ const code = char.codePointAt(0) ?? 0;
+ // Control characters are not filename characters on any host.
+ if (code < 0x20 || code === 0x7f) return " ";
+ // Array.from yields whole code points, so a surrogate here is an unpaired
+ // one the title arrived with; it has no encoding to send.
+ if (code >= 0xd800 && code <= 0xdfff) return "";
+ return "\\/:*?\"<>|".includes(char) ? "_" : char;
+ })
+ .join("")
+ .replace(/\s+/g, " ")
+ .trim(),
+ MAX_STEM_BYTES,
+ )
+ // Windows drops a trailing period or space, so never send one.
+ .replace(/[\s.]+$/, "");
+ // The backend collapses everything outside [A-Za-z0-9._-] to "_", so a title
+ // with no ASCII word character at all would be listed as "_.md". A generic
+ // name at least reads as one.
+ if (!/[A-Za-z0-9]/.test(stem)) return "chat.md";
+ // A device name stays reserved through any extension, and Windows reads it as
+ // the part before the *first* dot, so break the name there.
+ const dot = stem.indexOf(".");
+ const head = dot === -1 ? stem : stem.slice(0, dot);
+ return RESERVED_DEVICE_NAME.test(head)
+ ? `${head}_${stem.slice(head.length)}.md`
+ : `${stem}.md`;
+}
+
+// A save has no chip in the sources panel to carry a "failed" state, so poll the
+// ingest far enough to warn when the document will never become searchable. The
+// panel does the same over SSE for the uploads it owns.
+const INGEST_POLL_MS = 2_000;
+const INGEST_POLL_ATTEMPTS = 150;
+
+async function watchIngestion(
+ projectId: string,
+ jobId: string,
+ filename: string,
+): Promise<void> {
+ for (let attempt = 0; attempt < INGEST_POLL_ATTEMPTS; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, INGEST_POLL_MS));
+ let job: IndexJob;
+ try {
+ job = await getJob(jobId);
+ } catch {
+ // The job is unreachable; the panel's own list is the fallback.
+ return;
+ }
+ const terminal = terminalJobStatus(job.status);
+ if (!terminal) continue;
+ if (terminal === "failed") {
+ // The panel hides failed documents, so without this the source just never
+ // appears after a success toast.
+ toast.error(`Couldn't index ${filename}`, {
+ description: job.error ?? "Indexing failed",
+ });
+ }
+ announceProjectSourcesUpdated(projectId);
+ return;
+ }
+}
+
+/** Upload one markdown document to a project's sources. Resolves true when the
+ * upload was accepted, so a caller saving several can report the count once;
+ * failures toast here, because only this layer knows why. */
+export async function saveMarkdownAsProjectSource(
+ projectId: string,
+ markdown: string,
+ title: string,
+ options: { quiet?: boolean } = {},
+): Promise<boolean> {
+ const filename = projectSourceFileName(title);
+ const file = new File([markdown], filename, { type: "text/markdown" });
+ // Invalidate the sources probe before the upload as well as after it (the
+ // announce below): a chat sent mid-upload must not cache "no sources" for the
+ // probe's TTL.
+ invalidateProjectSources(projectId);
+ try {
+ const result = await uploadProjectDocument(projectId, file);
+ if (!options.quiet) toast.success("Saved to project sources.");
+ void watchIngestion(projectId, result.jobId, result.filename || filename);
+ return true;
+ } catch (error) {
+ toast.error("Failed to save to project sources.", {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ return false;
+ } finally {
+ // Announce only after the upload: a refetch fired before it would just
+ // re-list the rows the panel already has.
+ announceProjectSourcesUpdated(projectId);
+ }
+}
diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
index e5b16f0d2e5..563e64cdb37 100644
--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx
+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
@@ -4,8 +4,12 @@
import { Button } from "@/components/ui/button";
import { FolderAddIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useCallback, useRef } from "react";
-import { invalidateProjectSources, listProjectDocuments } from "../api/rag-api";
+import { useCallback, useEffect, useRef } from "react";
+import {
+ invalidateProjectSources,
+ listProjectDocuments,
+ subscribeProjectSourcesUpdated,
+} from "../api/rag-api";
import { RAG_UPLOAD_ACCEPT, isLinkedFolderManaged } from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
import { LinkedFoldersManager } from "./linked-folders-manager";
@@ -47,6 +51,18 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
void refresh({ quiet: true });
}, [projectId, refresh]);
+ // External mutators (sidebar/thread saves, deletes elsewhere) announce when
+ // they are done; refresh the mounted list so a source saved from a chat shows
+ // up here without a remount. The list only polls while a row it already knows
+ // is indexing, so nothing else would ever fetch it.
+ useEffect(
+ () =>
+ subscribeProjectSourcesUpdated(projectId, () => {
+ void refresh({ quiet: true });
+ }),
+ [projectId, refresh],
+ );
+
const empty = documents.length === 0;
return (
diff --git a/studio/frontend/src/features/rag/index.ts b/studio/frontend/src/features/rag/index.ts
index 24b0c9ac607..e44bd988ebf 100644
--- a/studio/frontend/src/features/rag/index.ts
+++ b/studio/frontend/src/features/rag/index.ts
@@ -12,6 +12,7 @@ export {
listAllDocuments,
listKnowledgeBases,
} from "./api/rag-api";
+export { saveMarkdownAsProjectSource } from "./api/save-markdown-source";
export { useRagAvailabilityStore } from "./api/rag-availability";
export { isLinkedFolderManaged } from "./types/rag";
export type { KnowledgeBase, RagDocument, UploadedDocument } from "./types/rag";
diff --git a/studio/frontend/tests/helpers/store-stubs/auth.ts b/studio/frontend/tests/helpers/store-stubs/auth.ts
index d3d832f1a4b..c9dc028703f 100644
--- a/studio/frontend/tests/helpers/store-stubs/auth.ts
+++ b/studio/frontend/tests/helpers/store-stubs/auth.ts
@@ -1,7 +1,21 @@
// 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 type AuthFetchHandler = (
+ input: string,
+ init?: RequestInit,
+) => Response | Promise<Response>;
+
+let handler: AuthFetchHandler | null = null;
+
+/** Answer authFetch from `next` instead of failing. Pass null to restore the
+ * default, so one test opting in cannot loosen the rest. */
+export function setAuthFetchHandler(next: AuthFetchHandler | null): void {
+ handler = next;
+}
+
/** Fail any unexpected network access. */
-export function authFetch(): Promise<Response> {
- throw new Error("authFetch: no network in tests");
+export function authFetch(input: string, init?: RequestInit): Promise<Response> {
+ if (!handler) throw new Error("authFetch: no network in tests");
+ return Promise.resolve(handler(input, init));
}
diff --git a/studio/frontend/tests/helpers/store-stubs/toast.ts b/studio/frontend/tests/helpers/store-stubs/toast.ts
index 65565eb6a08..3434f40b8a4 100644
--- a/studio/frontend/tests/helpers/store-stubs/toast.ts
+++ b/studio/frontend/tests/helpers/store-stubs/toast.ts
@@ -1,13 +1,36 @@
// 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 interface RecordedToast {
+ kind: "info" | "error" | "warning" | "success" | "loading";
+ message: string;
+ description?: string;
+}
+
+/** Every toast raised since the last clear, for the tests that assert a flow
+ * reports itself exactly once. */
+export const recordedToasts: RecordedToast[] = [];
+
+function record(kind: RecordedToast["kind"]) {
+ return (message?: unknown, options?: { description?: unknown }) => {
+ recordedToasts.push({
+ kind,
+ message: String(message ?? ""),
+ description:
+ typeof options?.description === "string"
+ ? options.description
+ : undefined,
+ });
+ };
+}
+
/** Swallow notifications; the real module pulls in a TSX component. */
export const toast = {
- info: () => undefined,
- error: () => undefined,
- warning: () => undefined,
- success: () => undefined,
- loading: () => undefined,
+ info: record("info"),
+ error: record("error"),
+ warning: record("warning"),
+ success: record("success"),
+ loading: record("loading"),
dismiss: () => undefined,
};
diff --git a/studio/frontend/tests/project-source-filename.test.ts b/studio/frontend/tests/project-source-filename.test.ts
new file mode 100644
index 00000000000..f43aa59de69
--- /dev/null
+++ b/studio/frontend/tests/project-source-filename.test.ts
@@ -0,0 +1,118 @@
+// 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 { installLocalStorageFake, registerStoreStubResolver } from "./helpers/kit.ts";
+
+// save-markdown-source reaches lib/toast and the auth barrel through rag-api,
+// both .tsx node's type stripping cannot load.
+installLocalStorageFake();
+registerStoreStubResolver();
+
+const { projectSourceFileName } = await import(
+ "../src/features/rag/api/save-markdown-source.ts"
+);
+
+test("keeps an ordinary chat title readable", () => {
+ assert.equal(projectSourceFileName("Fix my regex"), "Fix my regex.md");
+ assert.equal(projectSourceFileName("v1.2 notes"), "v1.2 notes.md");
+ assert.equal(projectSourceFileName(".hidden"), ".hidden.md");
+});
+
+test("replaces every character Windows reserves in a name", () => {
+ assert.equal(
+ projectSourceFileName('a\\b/c:d*e?f"g<h>i|j'),
+ "a_b_c_d_e_f_g_h_i_j.md",
+ );
+ assert.equal(projectSourceFileName("50/50 split"), "50_50 split.md");
+});
+
+test("drops control characters instead of sending them in a filename", () => {
+ for (let code = 0; code <= 0x1f; code++) {
+ const name = projectSourceFileName(`a${String.fromCharCode(code)}b`);
+ assert.equal(name, "a b.md", `U+${code.toString(16)} survived as ${name}`);
+ }
+ assert.equal(projectSourceFileName("a\u007fb"), "a b.md");
+});
+
+test("breaks every Windows device name, extension or not", () => {
+ const devices = [
+ "CON",
+ "PRN",
+ "AUX",
+ "NUL",
+ ...Array.from({ length: 9 }, (_, i) => `COM${i + 1}`),
+ ...Array.from({ length: 9 }, (_, i) => `LPT${i + 1}`),
+ "COM¹",
+ "COM²",
+ "COM³",
+ "LPT¹",
+ "LPT²",
+ "LPT³",
+ ];
+ for (const device of devices) {
+ for (const title of [device, device.toLowerCase(), `${device}.txt`]) {
+ const name = projectSourceFileName(title);
+ const head = name.slice(0, name.indexOf("."));
+ assert.equal(
+ devices.some((d) => d.toLowerCase() === head.toLowerCase()),
+ false,
+ `${title} still resolves to the ${device} device as ${name}`,
+ );
+ }
+ }
+});
+
+test("a name that only looks like a device is left alone", () => {
+ assert.equal(projectSourceFileName("CONSOLE"), "CONSOLE.md");
+ assert.equal(projectSourceFileName("COM10"), "COM10.md");
+ assert.equal(projectSourceFileName("COM"), "COM.md");
+});
+
+test("never ends the name in a period or a space", () => {
+ assert.equal(projectSourceFileName("trailing dot."), "trailing dot.md");
+ assert.equal(projectSourceFileName("trailing dots..."), "trailing dots.md");
+ assert.equal(projectSourceFileName("trailing space "), "trailing space.md");
+ assert.equal(projectSourceFileName("mixed . . "), "mixed.md");
+});
+
+test("falls back for a title that leaves nothing usable", () => {
+ for (const title of ["", " ", "\t\n", "...", "..", ".", "///", "***"]) {
+ assert.equal(projectSourceFileName(title), "chat.md", `for ${title}`);
+ }
+});
+
+test("falls back where the backend would list the source as _.md", () => {
+ // The backend collapses anything outside [A-Za-z0-9._-] to "_", so a title
+ // with no ASCII word character would otherwise arrive as "_.md".
+ assert.equal(projectSourceFileName("你好世界"), "chat.md");
+ assert.equal(projectSourceFileName("разговор"), "chat.md");
+ assert.equal(projectSourceFileName("\u{1f600}\u{1f680}"), "chat.md");
+ // One ASCII character is enough to keep the title.
+ assert.equal(projectSourceFileName("Qwen 你好"), "Qwen 你好.md");
+});
+
+/** Any surrogate left over once the well-formed pairs are removed is a half. */
+function loneSurrogates(text: string): number {
+ return (
+ text.replace(/[\ud800-\udbff][\udc00-\udfff]/g, "").match(/[\ud800-\udfff]/g)
+ ?? []
+ ).length;
+}
+
+test("truncates on a code point boundary, within a byte budget", () => {
+ const emoji = projectSourceFileName("\u{1f600}a".repeat(200));
+ const bytes = new TextEncoder().encode(emoji).length;
+ assert.ok(bytes <= 183, `${bytes} bytes`);
+ assert.equal(loneSurrogates(emoji), 0);
+ const cjk = projectSourceFileName(`${"好".repeat(300)}x`);
+ assert.ok(new TextEncoder().encode(cjk).length <= 183);
+ const ascii = projectSourceFileName("a".repeat(300));
+ assert.equal(ascii, `${"a".repeat(180)}.md`);
+});
+
+test("a lone surrogate in the title never reaches the filename", () => {
+ assert.equal(projectSourceFileName("chat \ud83d end"), "chat end.md");
+ assert.equal(loneSurrogates(projectSourceFileName("\udfff a \ud800")), 0);
+});
diff --git a/studio/frontend/tests/project-source-plan.test.ts b/studio/frontend/tests/project-source-plan.test.ts
new file mode 100644
index 00000000000..88b0ba203d4
--- /dev/null
+++ b/studio/frontend/tests/project-source-plan.test.ts
@@ -0,0 +1,119 @@
+// 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 { planChatItemSources } from "../src/features/chat/utils/project-source-plan.ts";
+
+test("a single chat is saved once, under its own title", () => {
+ assert.deepEqual(
+ planChatItemSources({ id: "t1", title: "Fix my regex", type: "single" }, []),
+ [{ id: "t1", title: "Fix my regex" }],
+ );
+});
+
+test("each half of a pair is named after the model that answered", () => {
+ assert.deepEqual(
+ planChatItemSources({ id: "p1", title: "Fix my regex", type: "pair" }, [
+ { id: "t1", modelId: "unsloth/Qwen3-8B-GGUF:Q4_K_M" },
+ { id: "t2", modelId: "openai/gpt-5" },
+ ]),
+ [
+ { id: "t1", title: "Fix my regex - Qwen3-8B-GGUF" },
+ { id: "t2", title: "Fix my regex - gpt-5" },
+ ],
+ );
+});
+
+test("an unnamed model falls back to its position, so the two never collide", () => {
+ const plans = planChatItemSources(
+ { id: "p1", title: "Fix my regex", type: "pair" },
+ [{ id: "t1" }, { id: "t2", modelId: " " }],
+ );
+ assert.deepEqual(
+ plans.map((plan) => plan.title),
+ ["Fix my regex - 1", "Fix my regex - 2"],
+ );
+ assert.equal(new Set(plans.map((plan) => plan.title)).size, 2);
+});
+
+test("a LoRA compare names the adapter halves apart, not twice the same", () => {
+ // The base/lora compare toggles the adapter on one loaded checkpoint, so both
+ // threads record the same modelId; the model name alone cannot tell them apart.
+ const plans = planChatItemSources(
+ { id: "p1", title: "Fix my regex", type: "pair" },
+ [
+ { id: "t1", modelId: "unsloth/Qwen3-8B", modelType: "base" },
+ { id: "t2", modelId: "unsloth/Qwen3-8B", modelType: "lora" },
+ ],
+ );
+ assert.deepEqual(plans, [
+ { id: "t1", title: "Fix my regex - Qwen3-8B - base" },
+ { id: "t2", title: "Fix my regex - Qwen3-8B - fine-tuned" },
+ ]);
+});
+
+test("two panes on the same checkpoint fall back to their position", () => {
+ // Same repo, different quant: the variant is not part of modelId, and the
+ // colon suffix is stripped anyway, so both labels read "Qwen3-8B-GGUF".
+ const plans = planChatItemSources(
+ { id: "p1", title: "Fix my regex", type: "pair" },
+ [
+ { id: "t1", modelId: "unsloth/Qwen3-8B-GGUF:Q4_K_M", modelType: "model1" },
+ { id: "t2", modelId: "unsloth/Qwen3-8B-GGUF:Q8_0", modelType: "model2" },
+ ],
+ );
+ assert.deepEqual(
+ plans.map((plan) => plan.title),
+ ["Fix my regex - Qwen3-8B-GGUF - 1", "Fix my regex - Qwen3-8B-GGUF - 2"],
+ );
+ assert.equal(new Set(plans.map((plan) => plan.title)).size, 2);
+});
+
+test("a pane keeps its number whichever half answered last", () => {
+ // listStoredChatThreads sorts by updatedAt, so the pane that finished last
+ // arrives first. Numbering by arrival would label model2's source "- 1" and
+ // swap the two names between saves of the same pair.
+ const panes = [
+ { id: "t1", modelId: "unsloth/Qwen3-8B-GGUF:Q4_K_M", modelType: "model1" },
+ { id: "t2", modelId: "unsloth/Qwen3-8B-GGUF:Q8_0", modelType: "model2" },
+ ];
+ const item = { id: "p1", title: "Fix my regex", type: "pair" };
+ const byId = (plans: { id: string; title: string }[]) =>
+ Object.fromEntries(plans.map((plan) => [plan.id, plan.title]));
+ assert.deepEqual(byId(planChatItemSources(item, [...panes].reverse())), {
+ t1: "Fix my regex - Qwen3-8B-GGUF - 1",
+ t2: "Fix my regex - Qwen3-8B-GGUF - 2",
+ });
+ assert.deepEqual(
+ byId(planChatItemSources(item, panes)),
+ byId(planChatItemSources(item, [...panes].reverse())),
+ );
+});
+
+test("a LoRA pair keeps its naming when the model name is what collides", () => {
+ const halves = [
+ { id: "t1", modelType: "base" },
+ { id: "t2", modelType: "lora" },
+ ];
+ const item = { id: "p1", title: "Fix my regex", type: "pair" };
+ // No modelId at all: the label itself falls back to the pane, which must not
+ // move with arrival order either.
+ assert.deepEqual(planChatItemSources(item, [...halves].reverse()), [
+ { id: "t2", title: "Fix my regex - fine-tuned" },
+ { id: "t1", title: "Fix my regex - base" },
+ ]);
+});
+
+test("a pair with one surviving half keeps the plain title", () => {
+ assert.deepEqual(
+ planChatItemSources({ id: "p1", title: "Fix my regex", type: "pair" }, [
+ { id: "t1", modelId: "unsloth/Qwen3-8B" },
+ ]),
+ [{ id: "t1", title: "Fix my regex" }],
+ );
+ assert.deepEqual(
+ planChatItemSources({ id: "p1", title: "Fix my regex", type: "pair" }, []),
+ [],
+ );
+});
diff --git a/studio/frontend/tests/project-source-reply-destination.test.ts b/studio/frontend/tests/project-source-reply-destination.test.ts
new file mode 100644
index 00000000000..c9057370e79
--- /dev/null
+++ b/studio/frontend/tests/project-source-reply-destination.test.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// "Save to project sources" on a reply used to upload into useProjectStore's
+// activeProjectId. That id is the project the *sidebar* is showing, and it lags
+// a thread switch: opening a chat with no project query parameter leaves the
+// previous project selected, so the item stayed enabled and the reply went into
+// a project the chat has nothing to do with. One user's project then holds
+// another's content. The destination has to come from the thread being read.
+//
+// thread.tsx is 6k lines of TSX that node cannot load, so this reads the source,
+// the way rag-availability-marker.test.ts does for the same file.
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+const src = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+);
+
+/** The onSelect body of the "Save to project sources" action bar item. */
+function saveHandler(): string {
+ const marker = src.indexOf("Save to project sources");
+ assert.ok(marker > 0, "the reply action is gone or was renamed");
+ const start = src.lastIndexOf("<ActionBarMorePrimitive.Item", marker);
+ assert.ok(start > 0 && start < marker, "could not find the item's opening tag");
+ return src.slice(start, marker);
+}
+
+test("the reply is saved to its own thread's project, not the selected one", () => {
+ const handler = saveHandler();
+ assert.match(
+ handler,
+ /await getStoredChatThread\(remoteId\)/,
+ "the destination is not read from the stored thread",
+ );
+ assert.match(
+ handler,
+ /saveMarkdownAsProjectSource\(\n\s*thread\.projectId,/,
+ "the upload does not address the thread's own project",
+ );
+ assert.ok(
+ !/saveMarkdownAsProjectSource\(\s*activeProjectId/.test(handler),
+ "the reply is still uploaded into whatever project the sidebar has selected",
+ );
+});
+
+test("a thread with no project is refused rather than sent somewhere", () => {
+ assert.match(
+ saveHandler(),
+ /if \(!thread\?\.projectId\) \{\n\s*toast\.info\("This chat isn't in a project\."\);\n\s*return;\n\s*\}/,
+ "a chat that is not in a project falls through to a save with no destination",
+ );
+});
+
+test("the thread id is resolved before the menu can close", () => {
+ const handler = saveHandler();
+ const idRead = handler.indexOf("aui.threadListItem().getState()");
+ const firstAwait = handler.indexOf("await");
+ assert.ok(idRead > 0, "the thread list item is no longer read at all");
+ assert.ok(
+ firstAwait === -1 || idRead < firstAwait,
+ "the message and thread context is read after an await, by which point the " +
+ "menu has closed and the assistant-ui context can be gone",
+ );
+ assert.match(
+ handler,
+ /const remoteId =\n\s*state\.remoteId \|\|\n\s*useChatRuntimeStore\.getState\(\)\.activeThreadId;/,
+ "a thread whose list item has no remoteId yet has no destination to resolve",
+ );
+});
+
+// The action is still hidden outside a project, so the reply menu does not grow
+// an item that can only refuse itself.
+test("the item is only rendered while a project is selected", () => {
+ const marker = src.indexOf("Save to project sources");
+ // From the item's own opening tag, so the window cannot miss the guard by
+ // being outgrown by the handler.
+ const open = src.lastIndexOf("<ActionBarMorePrimitive.Item", marker);
+ const before = src.slice(Math.max(0, open - 200), open);
+ assert.match(
+ before,
+ /\{activeProjectId && \(/,
+ "the reply action is offered outside a project",
+ );
+});
diff --git a/studio/frontend/tests/project-source-reply-markdown.test.ts b/studio/frontend/tests/project-source-reply-markdown.test.ts
new file mode 100644
index 00000000000..4a3e59bc24d
--- /dev/null
+++ b/studio/frontend/tests/project-source-reply-markdown.test.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// "Save to project sources" on one reply used to upload getCopyText(), which is
+// the text parts of the message joined and nothing else. A reply that searched,
+// ran a tool or reasoned would be saved with that work missing, and a reply that
+// is only a tool call has no text part at all, so it saved nothing.
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { register } from "node:module";
+import test from "node:test";
+
+// The module under test imports a sibling without its extension, the way vite
+// resolves it.
+register("./bundler-resolver.mjs", import.meta.url);
+const { replySourceMarkdown } = await import(
+ "../src/features/chat/utils/reply-source-markdown.ts"
+);
+
+/** An assistant reply as assistant-ui holds it: parts, not a string. */
+const reply = [
+ { type: "reasoning", text: "the docs pin it to 3.1" },
+ {
+ type: "tool-call",
+ toolCallId: "call_1",
+ toolName: "web_search",
+ argsText: '{"query":"pin version"}',
+ args: { query: "pin version" },
+ result: { answer: "3.1" },
+ },
+ { type: "text", text: "Pin it to 3.1." },
+ {
+ type: "source",
+ sourceType: "url",
+ id: "s1",
+ url: "https://example.com/changelog",
+ title: "Changelog",
+ },
+];
+
+test("a saved reply keeps the work behind it, not just its prose", () => {
+ const markdown = replySourceMarkdown(reply);
+ assert.match(markdown, /Pin it to 3\.1\./);
+ assert.match(markdown, /web_search/, "the tool call is missing");
+ assert.match(markdown, /pin version/, "the tool arguments are missing");
+ assert.match(markdown, /3\.1/, "the tool result is missing");
+ assert.match(markdown, /the docs pin it to 3\.1/, "the reasoning is missing");
+ assert.match(markdown, /example\.com\/changelog/, "the citation is missing");
+});
+
+test("a reply that is only a tool call still has something to save", () => {
+ const markdown = replySourceMarkdown([
+ {
+ type: "tool-call",
+ toolCallId: "call_2",
+ toolName: "generate_image",
+ argsText: '{"prompt":"a red bus"}',
+ args: { prompt: "a red bus" },
+ result: { url: "sandbox:/bus.png" },
+ },
+ ]);
+ assert.ok(
+ markdown.trim().length > 0,
+ "a tool-only reply is still reported as having no content to save",
+ );
+ assert.match(markdown, /generate_image/);
+});
+
+test("a tool result is normalised the way the whole-chat save normalises it", () => {
+ const markdown = replySourceMarkdown(
+ [
+ {
+ type: "tool-call",
+ toolCallId: "call_3",
+ toolName: "read_file",
+ argsText: "{}",
+ args: {},
+ result: { raw: "unreadable" },
+ },
+ ],
+ () => "the model saw this",
+ );
+ assert.match(markdown, /the model saw this/);
+});
+
+test("the reply action saves through this conversion", async () => {
+ // thread.tsx is 6k lines of TSX that node cannot load, so this reads the
+ // source, the way project-source-reply-destination.test.ts does.
+ const src = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ const marker = src.indexOf("Save to project sources");
+ assert.ok(marker > 0, "the reply action is gone or was renamed");
+ const handler = src.slice(
+ src.lastIndexOf("<ActionBarMorePrimitive.Item", marker),
+ marker,
+ );
+ assert.match(
+ handler,
+ /replySourceMarkdown\(\n\s*aui\.message\(\)\.getState\(\)\.content,/,
+ "the reply is uploaded without rendering its non-text parts",
+ );
+ assert.ok(
+ !/aui\.message\(\)\.getCopyText\(\)/.test(handler),
+ "the reply is still saved as text parts alone",
+ );
+});
diff --git a/studio/frontend/tests/project-source-save.test.ts b/studio/frontend/tests/project-source-save.test.ts
new file mode 100644
index 00000000000..e8d4ee25a7c
--- /dev/null
+++ b/studio/frontend/tests/project-source-save.test.ts
@@ -0,0 +1,244 @@
+// 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";
+import {
+ installLocalStorageFake,
+ registerStoreStubResolver,
+} from "./helpers/kit.ts";
+import { setAuthFetchHandler } from "./helpers/store-stubs/auth.ts";
+import { recordedToasts } from "./helpers/store-stubs/toast.ts";
+
+const { storage } = installLocalStorageFake();
+// A real EventTarget in place of the inert window the fake installs: the sources
+// panel only learns about a save through a window event.
+const events = new EventTarget();
+Object.assign(globalThis, {
+ window: Object.assign(events, {
+ localStorage: storage,
+ location: { protocol: "http:" },
+ }),
+});
+registerStoreStubResolver();
+
+const {
+ PROJECT_SOURCES_UPDATED_EVENT,
+ announceProjectSourcesUpdated,
+ invalidateProjectSources,
+ subscribeProjectSourcesUpdated,
+} = await import("../src/features/rag/api/rag-api.ts");
+const { saveMarkdownAsProjectSource } = await import(
+ "../src/features/rag/api/save-markdown-source.ts"
+);
+
+function collectUpdates(): string[] {
+ const seen: string[] = [];
+ events.addEventListener(PROJECT_SOURCES_UPDATED_EVENT, (event) => {
+ seen.push(
+ String((event as CustomEvent<{ projectId?: string }>).detail?.projectId),
+ );
+ });
+ return seen;
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+test.beforeEach(() => {
+ recordedToasts.length = 0;
+ setAuthFetchHandler(null);
+});
+
+test("invalidating the probe does not refetch anyone's document list", () => {
+ // The sources panel invalidates *before* its own delete, having already
+ // dropped the row; a refetch there would put the row straight back.
+ const seen = collectUpdates();
+ invalidateProjectSources("p1");
+ assert.deepEqual(seen, []);
+ announceProjectSourcesUpdated("p1");
+ assert.deepEqual(seen, ["p1"]);
+});
+
+test("uploads the chat under its sanitised name and reports it once", async () => {
+ const seen = collectUpdates();
+ const uploaded: File[] = [];
+ setAuthFetchHandler((input, init) => {
+ assert.equal(input, "/api/rag/projects/p%20one/documents");
+ uploaded.push((init?.body as FormData).get("file") as File);
+ return json({ documentId: "d1", jobId: "j1", filename: "Chat.md" });
+ });
+ const ok = await saveMarkdownAsProjectSource("p one", "# Chat\n", "Chat:1");
+ assert.equal(ok, true);
+ assert.equal(uploaded.length, 1);
+ assert.equal(uploaded[0].name, "Chat_1.md");
+ assert.equal(uploaded[0].type, "text/markdown");
+ assert.equal(await uploaded[0].text(), "# Chat\n");
+ assert.deepEqual(
+ recordedToasts.map((t) => [t.kind, t.message]),
+ [["success", "Saved to project sources."]],
+ );
+ // Announced after the upload, so the panel refetches a list that has it.
+ assert.deepEqual(seen, ["p one"]);
+});
+
+test("a quiet save stays silent so a pair can report the count itself", async () => {
+ setAuthFetchHandler((input) =>
+ input.includes("/jobs/")
+ ? json({ id: "j2", documentId: "d2", status: "completed" })
+ : json({ documentId: "d2", jobId: "j2", filename: "Chat.md" }),
+ );
+ assert.equal(
+ await saveMarkdownAsProjectSource("p2", "# Chat\n", "Chat", {
+ quiet: true,
+ }),
+ true,
+ );
+ assert.deepEqual(recordedToasts, []);
+});
+
+test("a rejected upload resolves false and says why", async () => {
+ const seen = collectUpdates();
+ setAuthFetchHandler(() => json({ detail: "Project not found" }, 404));
+ assert.equal(
+ await saveMarkdownAsProjectSource("gone", "# Chat\n", "Chat"),
+ false,
+ );
+ assert.deepEqual(
+ recordedToasts.map((t) => [t.kind, t.message, t.description]),
+ [["error", "Failed to save to project sources.", "Project not found"]],
+ );
+ // The probe is still invalidated, so the next chat re-reads the truth.
+ assert.deepEqual(seen, ["gone"]);
+});
+
+test("a quiet save still reports its own failure", async () => {
+ setAuthFetchHandler(() => json({ detail: "RAG is unavailable" }, 503));
+ assert.equal(
+ await saveMarkdownAsProjectSource("p3", "# Chat\n", "Chat", {
+ quiet: true,
+ }),
+ false,
+ );
+ assert.equal(recordedToasts.length, 1);
+ assert.equal(recordedToasts[0].kind, "error");
+});
+
+test("an ingest that fails after the upload is not left silent", async () => {
+ const seen = collectUpdates();
+ setAuthFetchHandler((input) => {
+ if (input.includes("/jobs/")) {
+ return json({
+ id: "j4",
+ documentId: "d4",
+ status: "failed",
+ error: "Could not parse the document",
+ });
+ }
+ return json({ documentId: "d4", jobId: "j4", filename: "Chat.md" });
+ });
+ await saveMarkdownAsProjectSource("p4", "# Chat\n", "Chat");
+ // The panel hides failed documents, so the success toast would otherwise be
+ // the only thing the user ever sees about a source that never arrives.
+ const failure = await waitFor(() =>
+ recordedToasts.find((t) => t.message === "Couldn't index Chat.md"),
+ );
+ assert.equal(failure?.kind, "error");
+ assert.equal(failure?.description, "Could not parse the document");
+ // And the panel is told again, so a chip left "pending" resolves.
+ assert.equal(seen.filter((id) => id === "p4").length, 2);
+});
+
+async function waitFor<T>(read: () => T | undefined): Promise<T | undefined> {
+ for (let attempt = 0; attempt < 100; attempt++) {
+ const value = read();
+ if (value !== undefined) return value;
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ return undefined;
+}
+
+// The panel is a .tsx component node cannot load, so the subscription it mounts
+// lives in rag-api and is exercised here directly. These assert the refresh
+// itself runs, not merely that an event was dispatched.
+
+test("a mounted sources list refetches when a chat is saved into its project", async () => {
+ // Model the panel: subscribe, and let the callback re-run the same lister
+ // useRagDocuments.refresh calls. Before the fix, nothing here ever ran again,
+ // because the list only polls while a row it already knows is indexing, and an
+ // empty panel knows none.
+ const listed: string[][] = [];
+ let rows: string[] = [];
+ const unsubscribe = subscribeProjectSourcesUpdated("p5", () => {
+ listed.push([...rows]);
+ });
+ setAuthFetchHandler((input) => {
+ if (input.includes("/jobs/")) {
+ return json({ id: "j5", documentId: "d5", status: "completed" });
+ }
+ // The upload is what puts the row on the server.
+ rows = ["Chat.md"];
+ return json({ documentId: "d5", jobId: "j5", filename: "Chat.md" });
+ });
+ await saveMarkdownAsProjectSource("p5", "# Chat\n", "Chat");
+ assert.deepEqual(
+ listed,
+ [["Chat.md"]],
+ "the list was never refetched, so the saved source stays absent until remount",
+ );
+ unsubscribe();
+});
+
+test("another project's save leaves this list alone", () => {
+ let refreshed = 0;
+ const unsubscribe = subscribeProjectSourcesUpdated("mine", () => {
+ refreshed += 1;
+ });
+ announceProjectSourcesUpdated("theirs");
+ assert.equal(refreshed, 0, "every open panel refetches on any project's save");
+ announceProjectSourcesUpdated("mine");
+ assert.equal(refreshed, 1);
+ unsubscribe();
+});
+
+test("unsubscribing stops the refetch, so an unmounted panel cannot set state", () => {
+ let refreshed = 0;
+ const unsubscribe = subscribeProjectSourcesUpdated("p6", () => {
+ refreshed += 1;
+ });
+ unsubscribe();
+ announceProjectSourcesUpdated("p6");
+ assert.equal(refreshed, 0);
+});
+
+test("the panel subscribes, and does not resurrect a row it just deleted", async () => {
+ const src = await readFile(
+ new URL(
+ "../src/features/rag/components/project-sources-panel.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ src,
+ /subscribeProjectSourcesUpdated\(projectId, \(\) => \{\n\s*void refresh\(\{ quiet: true \}\);\n\s*\}\),/,
+ "the mounted list no longer refreshes when a source is saved elsewhere",
+ );
+ assert.ok(
+ !src.includes("PROJECT_SOURCES_UPDATED_EVENT"),
+ "the panel listens for the raw event again, bypassing the tested subscription",
+ );
+ // handleRemove drops the row optimistically and *then* invalidates, so an
+ // invalidate that also refetched would re-list the row before the DELETE went
+ // out, and the panel has no request sequencing to drop the stale answer.
+ assert.match(
+ src,
+ /invalidateProjectSources\(projectId\);\n\s*await remove\(documentId\);/,
+ "the delete path no longer invalidates before its own mutation",
+ );
+});