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: use the reply on screen when turning chats into training data (#12584)

Nilay1db4f7046a58
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 212553b5cad..a896c0b35fa 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
@@ -247,15 +247,21 @@ async function loadConversationMessages(
// No parentId = legacy flat thread (already DB createdAt-sorted); walking the chain would invert order.
const hasParentIds = raw.some((m) => (m as { parentId?: unknown }).parentId != null);
if (!hasParentIds) return raw;
- // Newest saved turn of the branch on screen: a reply still generating is not stored yet, and falling back to the newest leaf would export the reply it replaces.
- const storedIds = new Set(raw.map((m) => m.id));
- // An empty list is no opinion, not an empty branch: switching chats sets remoteId before the history load refills the view.
- const headId = liveBranch?.length
- ? ([...liveBranch].reverse().find((id) => storedIds.has(id)) ?? null)
- : undefined;
+ const headId = liveBranchHeadId(liveBranch, raw);
return orderByParentChain(raw, { includeSiblings, headId }) as typeof raw;
}
+// Newest saved turn of the branch on screen: a reply still generating is not stored yet, and falling back to the newest leaf would export the reply it replaces.
+function liveBranchHeadId(
+ liveBranch: string[] | null,
+ raw: Array<{ id: string }>,
+): string | null | undefined {
+ // An empty list is no opinion, not an empty branch: switching chats sets remoteId before the history load refills the view.
+ if (!liveBranch?.length) return undefined;
+ const storedIds = new Set(raw.map((m) => m.id));
+ return [...liveBranch].reverse().find((id) => storedIds.has(id)) ?? null;
+}
+
function exportTs(): string {
return new Date().toISOString().slice(0, 19).replace(/:/g, "-");
}
@@ -956,13 +962,17 @@ export async function buildFineTuneJsonl(
let conversations = 0;
let skipped = 0;
for (const id of ids) {
+ const liveBranch = liveThreadBranch(id);
const raw = await listStoredChatMessages(id);
const hasParentIds = raw.some(
(m) => (m as { parentId?: unknown }).parentId != null,
);
// Chain only: retries/regenerations leave sibling branches, and mixing alternate replies into one conversation corrupts the training targets.
const ordered = hasParentIds
- ? (orderByParentChain(raw, { includeSiblings: false }) as typeof raw)
+ ? (orderByParentChain(raw, {
+ includeSiblings: false,
+ headId: liveBranchHeadId(liveBranch, raw),
+ }) as typeof raw)
: raw;
const turns = messagesToFineTuneTurns(ordered);
const converted = turns ? turnsToFineTuneLines(turns, format) : [];
diff --git a/studio/frontend/src/features/chat/utils/live-thread-head.ts b/studio/frontend/src/features/chat/utils/live-thread-head.ts
index 21171ec899a..d81a79a5a98 100644
--- a/studio/frontend/src/features/chat/utils/live-thread-head.ts
+++ b/studio/frontend/src/features/chat/utils/live-thread-head.ts
@@ -2,7 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
type LiveThreadView = {
- threadListItem: () => { getState: () => { remoteId?: string | null } };
+ threads: () => { getState: () => { mainThreadId?: string } };
+ threadListItem: () => {
+ getState: () => { id?: string; remoteId?: string | null };
+ };
thread: () => {
getState: () => { messages: ReadonlyArray<{ id: string }> };
};
@@ -21,7 +24,10 @@ export function registerLiveThreadView(view: LiveThreadView): () => void {
export function liveThreadBranch(threadId: string): string[] | null {
for (const view of views) {
try {
- if (view.threadListItem().getState().remoteId !== threadId) continue;
+ const item = view.threadListItem().getState();
+ if (item.remoteId !== threadId) continue;
+ // A chat opened earlier keeps its runtime alive, but its thread() reads the chat on screen.
+ if (item.id !== view.threads().getState().mainThreadId) continue;
return view.thread().getState().messages.map((message) => message.id);
} catch {
// A view torn down mid-switch has no thread to read.
diff --git a/studio/frontend/tests/finetune-export-branches.test.ts b/studio/frontend/tests/finetune-export-branches.test.ts
new file mode 100644
index 00000000000..668fb01fe13
--- /dev/null
+++ b/studio/frontend/tests/finetune-export-branches.test.ts
@@ -0,0 +1,164 @@
+// 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 vm from "node:vm";
+import ts from "typescript";
+
+import * as liveThreadHead from "../src/features/chat/utils/live-thread-head.ts";
+import { orderByParentChain } from "../src/features/chat/utils/message-order.ts";
+import { unwrapPastedTextContent } from "../src/features/chat/utils/pasted-text.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+type StoredMessage = {
+ id: string;
+ parentId: string | null;
+ createdAt: number;
+ role: string;
+ content: string;
+};
+
+type FineTuneExport = {
+ lines: string[];
+ conversations: number;
+ skipped: number;
+};
+
+const SOURCE = readSrc(
+ "features/chat/prompt-storage/prompt-storage-dialog.tsx",
+);
+
+function sliceSource(startMarker: string, endMarker: string): string {
+ const start = SOURCE.indexOf(startMarker);
+ const end = SOURCE.indexOf(endMarker, start);
+ assert.notEqual(start, -1, `${startMarker} must exist`);
+ assert.notEqual(end, -1, `${endMarker} must exist`);
+ return SOURCE.slice(start, end);
+}
+
+function storedMessages(
+ rows: [id: string, parentId: string | null, role: string, content: string][],
+): StoredMessage[] {
+ return rows.map(([id, parentId, role, content], index) => ({
+ id,
+ parentId,
+ createdAt: index + 1,
+ role,
+ content,
+ }));
+}
+
+function loadBuilder(chats: Record<string, StoredMessage[]>) {
+ const javascript = ts.transpileModule(
+ [
+ sliceSource(
+ "async function loadConversationMessages(",
+ "function exportTs(",
+ ),
+ sliceSource(
+ "// One JSONL line per conversation",
+ "/** Download the fine-tuning JSONL",
+ ),
+ "globalThis.__build = buildFineTuneJsonl;",
+ ].join("\n"),
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ },
+ ).outputText;
+ const context = {
+ exports: {},
+ toast: { info: () => {} },
+ listStoredChatThreads: async () =>
+ Object.keys(chats).map((id) => ({ id })),
+ listStoredChatMessages: async (id: string) => chats[id],
+ ...liveThreadHead,
+ orderByParentChain,
+ unwrapPastedTextContent,
+ } as Record<string, unknown>;
+ vm.runInNewContext(javascript, context);
+ return context.__build as (format: string) => Promise<FineTuneExport>;
+}
+
+async function fineTuneMessages(
+ chats: Record<string, StoredMessage[]>,
+ liveBranch: string[] | null = null,
+ openedEarlier: string[] = [],
+) {
+ const build = loadBuilder(chats);
+ const unregisters = liveBranch
+ ? [...openedEarlier, "open"].map((remoteId) =>
+ liveThreadHead.registerLiveThreadView({
+ threads: () => ({ getState: () => ({ mainThreadId: "open" }) }),
+ threadListItem: () => ({ getState: () => ({ id: remoteId, remoteId }) }),
+ thread: () => ({
+ getState: () => ({ messages: liveBranch.map((id) => ({ id })) }),
+ }),
+ }),
+ )
+ : [];
+ try {
+ const { lines } = await build("openai");
+ return [...lines].map((line) => JSON.parse(line).messages);
+ } finally {
+ for (const unregister of unregisters) unregister();
+ }
+}
+
+const regenerated = (prefix = "") =>
+ storedMessages([
+ [`${prefix}u1`, null, "user", "Name one fruit."],
+ [`${prefix}a1`, `${prefix}u1`, "assistant", "Apples."],
+ [`${prefix}a1-retry`, `${prefix}u1`, "assistant", "Pears."],
+ ]);
+
+test("chat fine-tune data uses the reply picked in the branch picker", async () => {
+ assert.deepEqual(
+ await fineTuneMessages(
+ { open: regenerated(), other: regenerated() },
+ ["u1", "a1"],
+ ),
+ [
+ [
+ { role: "user", content: "Name one fruit." },
+ { role: "assistant", content: "Apples." },
+ ],
+ [
+ { role: "user", content: "Name one fruit." },
+ { role: "assistant", content: "Pears." },
+ ],
+ ],
+ );
+});
+
+test("chat fine-tune data uses the newest reply when no chat is open", async () => {
+ assert.deepEqual(await fineTuneMessages({ open: regenerated() }), [
+ [
+ { role: "user", content: "Name one fruit." },
+ { role: "assistant", content: "Pears." },
+ ],
+ ]);
+});
+
+test("chat fine-tune data keeps chats opened earlier on their newest reply", async () => {
+ assert.deepEqual(
+ await fineTuneMessages(
+ { open: regenerated(), other: regenerated("other-") },
+ ["u1", "a1"],
+ ["other"],
+ ),
+ [
+ [
+ { role: "user", content: "Name one fruit." },
+ { role: "assistant", content: "Apples." },
+ ],
+ [
+ { role: "user", content: "Name one fruit." },
+ { role: "assistant", content: "Pears." },
+ ],
+ ],
+ );
+});
diff --git a/studio/frontend/tests/markdown-export-branches.test.ts b/studio/frontend/tests/markdown-export-branches.test.ts
index 9bae7dad2ee..bcbc5d6bc16 100644
--- a/studio/frontend/tests/markdown-export-branches.test.ts
+++ b/studio/frontend/tests/markdown-export-branches.test.ts
@@ -147,7 +147,10 @@ async function markdownOutputs(
const exporters = loadExporters(stored, downloads, sources);
const unregister = liveBranch
? liveThreadHead.registerLiveThreadView({
- threadListItem: () => ({ getState: () => ({ remoteId: "thread" }) }),
+ threads: () => ({ getState: () => ({ mainThreadId: "thread" }) }),
+ threadListItem: () => ({
+ getState: () => ({ id: "thread", remoteId: "thread" }),
+ }),
thread: () => ({
getState: () => ({ messages: liveBranch.map((id) => ({ id })) }),
}),
diff --git a/studio/frontend/tests/sharegpt-export-branches.test.ts b/studio/frontend/tests/sharegpt-export-branches.test.ts
index 737f94d969f..1464ec4f238 100644
--- a/studio/frontend/tests/sharegpt-export-branches.test.ts
+++ b/studio/frontend/tests/sharegpt-export-branches.test.ts
@@ -104,7 +104,8 @@ async function withLiveBranch<T>(
): Promise<T> {
if (!ids) return run();
const unregister = liveThreadHead.registerLiveThreadView({
- threadListItem: () => ({ getState: () => ({ remoteId: "thread" }) }),
+ threads: () => ({ getState: () => ({ mainThreadId: "thread" }) }),
+ threadListItem: () => ({ getState: () => ({ id: "thread", remoteId: "thread" }) }),
thread: () => ({
getState: () => ({ messages: ids.map((id) => ({ id })) }),
}),
@@ -210,7 +211,8 @@ test("ShareGPT keeps the picked branch when the chat is switched during the expo
let unregister = () => {};
const exporters = loadExporters(regenerated, downloads, () => unregister());
unregister = liveThreadHead.registerLiveThreadView({
- threadListItem: () => ({ getState: () => ({ remoteId: "thread" }) }),
+ threads: () => ({ getState: () => ({ mainThreadId: "thread" }) }),
+ threadListItem: () => ({ getState: () => ({ id: "thread", remoteId: "thread" }) }),
thread: () => ({
getState: () => ({ messages: [{ id: "u1" }, { id: "a1" }] }),
}),
diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.ts
index 83f3746d12e..8b93e3065dc 100644
--- a/studio/frontend/tests/sidebar-row-actions.test.ts
+++ b/studio/frontend/tests/sidebar-row-actions.test.ts
@@ -24,7 +24,8 @@ test("row forks retain the visible branch across settings settlement", async ()
for (const open of [true, false]) {
let visible = open;
const unregister = liveThreadHead.registerLiveThreadView({
- threadListItem: () => ({ getState: () => ({ remoteId: visible ? "source" : "other" }) }),
+ threads: () => ({ getState: () => ({ mainThreadId: "main" }) }),
+ threadListItem: () => ({ getState: () => ({ id: "main", remoteId: visible ? "source" : "other" }) }),
thread: () => ({ getState: () => ({ messages: [{ id: "root" }, { id: "older-reply" }] }) }),
});
const calls: string[] = [];