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: fork chats from the row menu (#11564)
Michael Han2036ee0ba1f0
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 61f403afff7..1a06ad6bf82 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -38,6 +38,7 @@ from utils.reasoning_budget import validate_reasoning_budget_messagefrom utils.api_errors import safe_validation_errorsfrom utils.utils import safe_curated_detail, log_and_http_errorfrom storage.studio_db import (+ ChatForkActiveGenerationError,ChatMessageConflictError,ChatMessageProtectedError,ChatThreadDeletedError,@@ -1599,7 +1600,8 @@ def put_settings(payload: dict[str, Any], current_subject: str = Depends(get_curclass ChatForkRequest(BaseModel):- messageId: str+ # an omitted message selects the tip within the fork transaction.+ messageId: Optional[str] = NonenewThreadId: strcreatedAt: int@@ -1633,10 +1635,22 @@ def fork_thread("""import uuid+ from hub.services.models import account_access+ from state import active_generations+source = get_chat_thread(thread_id)if source is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")- if get_chat_message(thread_id, payload.messageId) is None:+ # A generation in flight leaves the tip unsettled: the last message is a prompt with no+ # answer yet, or a reply still being written, and a fork taken now would end there. A+ # client check cannot close this on its own, since another tab can start a generation+ # between its snapshot and this request.+ if thread_id in active_generations.active_thread_ids(account_access.account_scope()):+ raise HTTPException(+ status_code = 409,+ detail = "This chat is still generating. Fork it once it finishes.",+ )+ if payload.messageId is not None and get_chat_message(thread_id, payload.messageId) is None:raise HTTPException(status_code = 404,detail = f"Message {payload.messageId} not found in thread {thread_id}",@@ -1652,12 +1666,14 @@ def fork_thread(created_at = payload.createdAt,id_factory = lambda: str(uuid.uuid4()),)+ except ChatForkActiveGenerationError as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from excexcept ChatThreadDeletedError as exc:raise _deleted_thread_error(payload.newThreadId) from excif forked is None:# The source can be deleted between the reads above and the fork transaction, which the# threadpool lets run concurrently. Report it gone rather than as a server fault.- raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")+ raise HTTPException(status_code = 404, detail = f"Thread {thread_id} or fork message not found")messages = list_chat_messages(payload.newThreadId)# Stub: v1 always starts a fresh container and surfaces the same warning for every provider.warning: Optional[str] = Nonediff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex b83d4fcb0b8..35b125645b6 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -3906,9 +3906,13 @@ def _detach_research_message_json()+class ChatForkActiveGenerationError(RuntimeError):+ """A durable generation prevents copying a settled chat."""++def fork_chat_thread(source_thread_id: str,- branch_message_id: str,+ branch_message_id: Optional[str],new_thread_id: str,new_title: str,created_at: int,@@ -3918,6 +3922,8 @@ def fork_chat_thread(the new thread dict (with messages copied) or None if source missing. Reset both code-execcontainer ids; the per-provider snapshot is handled by the route layer. `id_factory()` producesfresh message uuids, injected for testability."""+ from storage.research_runs_db import ACTIVE_STATUSES as active_research_statuses+conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")@@ -3929,26 +3935,57 @@ def fork_chat_thread(if src is None:conn.rollback()return None- branch_row = conn.execute(- "SELECT * FROM chat_messages WHERE thread_id = ? AND id = ?",- (source_thread_id, branch_message_id),- ).fetchone()+ # admission and copying share the write lock, including the gap before supervisor registration.+ research_status_placeholders = ",".join("?" for _ in active_research_statuses)+ if (+ _active_chat_generation_run_ids(conn, {source_thread_id})+ or conn.execute(+ f"SELECT 1 FROM research_runs WHERE thread_id = ? "+ f"AND status IN ({research_status_placeholders}) LIMIT 1",+ (source_thread_id, *sorted(active_research_statuses)),+ ).fetchone()+ is not None+ ):+ raise ChatForkActiveGenerationError(+ "This chat is still generating. Fork it once it finishes."+ )+ rows = conn.execute(+ """SELECT * FROM chat_messages WHERE thread_id = ?+ ORDER BY created_at,+ CASE role WHEN 'system' THEN 0 WHEN 'user' THEN 1+ WHEN 'assistant' THEN 2 ELSE 99 END,+ id""",+ (source_thread_id,),+ ).fetchall()+ by_id = {row["id"]: row for row in rows}+ branch_row = (+ (rows[-1] if rows else None)+ if branch_message_id is None+ else by_id.get(branch_message_id)+ )if branch_row is None:conn.rollback()return None+ branch_message_id = branch_row["id"]+ # match the runtime's sequential legacy prefix while preserving recorded branches and later roots.+ parents: dict[str, Optional[str]] = {}+ previous_id = None+ saw_recorded_parent = False+ for row in rows:+ parent = row["parent_id"]+ parents[row["id"]] = (+ previous_id if parent is None and not saw_recorded_parent else parent+ )+ if parent is not None:+ saw_recorded_parent = True+ previous_id = row["id"]ancestry: list[sqlite3.Row] = []cursor_row = branch_rowseen: set[str] = set()while cursor_row is not None and cursor_row["id"] not in seen:ancestry.append(cursor_row)seen.add(cursor_row["id"])- parent = cursor_row["parent_id"]- if not parent:- break- cursor_row = conn.execute(- "SELECT * FROM chat_messages WHERE thread_id = ? AND id = ?",- (source_thread_id, parent),- ).fetchone()+ cursor_row = by_id.get(parents[cursor_row["id"]])ancestry.reverse() # root .. branch msgid_map: dict[str, str] = {row["id"]: id_factory() for row in ancestry}src_dict = dict(src)@@ -3983,7 +4020,7 @@ def fork_chat_thread((id_map[row["id"]],new_thread_id,- id_map.get(row["parent_id"]) if row["parent_id"] else None,+ id_map.get(parents[row["id"]]),row["role"],content_json,row["attachments_json"],diff --git a/studio/backend/tests/test_chat_generation_runs.py b/studio/backend/tests/test_chat_generation_runs.pyindex de5e22313ab..55384899ae4 100644--- a/studio/backend/tests/test_chat_generation_runs.py+++ b/studio/backend/tests/test_chat_generation_runs.py@@ -123,6 +123,7 @@ def test_create_is_owner_scoped_idempotent_and_binds_placeholder(chat_home):"serverManaged": True,}_assert_protected({**message, "content": [{"type": "text", "text": "stale overwrite"}]})+synced = studio_db.sync_chat_messages("thread-1", [], prune_missing = True)assert {message["id"] for message in synced} == {"user-1", "assistant-1"}assert runs_db.get_run("run-1", "alice") is not None@@ -140,6 +141,63 @@ def test_create_is_owner_scoped_idempotent_and_binds_placeholder(chat_home):_create(request = _request(max_tokens = 9))[email protected]("admit_before_route", [True, False])+def test_fork_refuses_durable_run_before_supervisor_registration(+ chat_home, monkeypatch, admit_before_route+):+ from fastapi import HTTPException+ from routes import chat_history+ from state import active_generations++ assert "thread-1" not in active_generations.active_thread_ids()+ if admit_before_route:+ _create()+ else:+ original_fork = chat_history.fork_chat_thread++ def admit_then_fork(**kwargs):+ _create()+ return original_fork(**kwargs)++ monkeypatch.setattr(chat_history, "fork_chat_thread", admit_then_fork)++ with pytest.raises(HTTPException) as exc:+ chat_history.fork_thread(+ "thread-1",+ chat_history.ChatForkRequest(newThreadId = "fork-1", createdAt = 10),+ current_subject = "alice",+ )+ assert exc.value.status_code == 409+ assert "still generating" in exc.value.detail+ assert studio_db.get_chat_thread("fork-1") is None+++def test_fork_resolves_tip_after_concurrent_generation_completes(chat_home, monkeypatch):+ from routes import chat_history++ original_fork = chat_history.fork_chat_thread++ def complete_then_fork(**kwargs):+ _create()+ token = runs_db.get_worker_token("run-1")+ assert runs_db.mark_running("run-1", token)+ message = studio_db.get_chat_message("thread-1", "assistant-1")+ message["content"] = [{"type": "text", "text": "Finished reply"}]+ message["metadata"].update({"generationSeq": 1, "generationStatus": "running"})+ studio_db.upsert_chat_message(message)+ runs_db.finish_run("run-1", worker_token = token, status = "completed")+ return original_fork(**kwargs)++ monkeypatch.setattr(chat_history, "fork_chat_thread", complete_then_fork)+ response = chat_history.fork_thread(+ "thread-1",+ chat_history.ChatForkRequest(newThreadId = "fork-1", createdAt = 10),+ current_subject = "alice",+ )+ assert response.thread.forkedFromMessageId == "assistant-1"+ assert response.messages[-1].content == [{"type": "text", "text": "Finished reply"}]++def test_shared_thread_rejects_a_second_subjects_active_generation(chat_home):_create()with pytest.raises(runs_db.ChatGenerationConflictError, match = "active generation"):diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex e18dbee1d69..8ae39197a03 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -730,6 +730,118 @@ def test_fork_thread_404_when_branch_message_missing(monkeypatch):assert exc.value.status_code == 404[email protected]("same_timestamp", [False, True])+def test_fork_thread_resolves_the_tip_when_no_message_is_given(same_timestamp):+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": "src", "title": "T", "modelType": "base", "modelId": "local", "createdAt": 1}+ )+ for message_id, parent_id, role, created_at in (+ ("root", None, "user", 1),+ ("z-user", "root", "user", 2),+ ("a-reply", "z-user", "assistant", 2 if same_timestamp else 3),+ ):+ message = _message(message_id, "src").model_dump()+ message.update({"createdAt": created_at, "parentId": parent_id, "role": role})+ studio_db.upsert_chat_message(message)+ response = chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(newThreadId = "new", createdAt = 4),+ current_subject = "test-user",+ )+ assert response.thread.forkedFromMessageId == "a-reply"+ assert len(response.messages) == 3+ assert any(message.role == "assistant" for message in response.messages)+++def test_fork_thread_404_when_the_thread_has_no_messages():+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": "src", "title": "T", "modelType": "base", "modelId": "local", "createdAt": 1}+ )+ with pytest.raises(HTTPException) as exc:+ chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(newThreadId = "new", createdAt = 1),+ current_subject = "test-user",+ )+ assert exc.value.status_code == 404+ assert studio_db.get_chat_thread("new") is None+++def test_fork_thread_refuses_before_it_resolves_the_tip(monkeypatch):+ """The generation check runs first, or the tip would be read while it is still moving."""+ import threading++ from state import active_generations++ monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})++ def _never(_t):+ raise AssertionError("the tip was read before the generation check")++ monkeypatch.setattr(chat_history, "list_chat_messages", _never)+ with active_generations.ActiveGeneration(threading.Event(), thread_id = "src"):+ with pytest.raises(HTTPException) as exc:+ chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(newThreadId = "new", createdAt = 1),+ current_subject = "test-user",+ )+ assert exc.value.status_code == 409+++def test_fork_thread_409_while_the_chat_is_generating(monkeypatch):+ """A fork taken mid-generation ends at a prompt with no answer, or a half-written reply.++ The client checks too, but another tab can start a generation between its snapshot and+ this request, so the refusal has to live inside the request that forks.+ """+ import threading++ from state import active_generations++ monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})+ with active_generations.ActiveGeneration(threading.Event(), thread_id = "src"):+ with pytest.raises(HTTPException) as exc:+ chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(+ messageId = "m1",+ newThreadId = "new",+ createdAt = 1,+ ),+ current_subject = "test-user",+ )+ assert exc.value.status_code == 409+ assert "still generating" in str(exc.value.detail)+++def test_fork_thread_allows_a_fork_of_another_generating_chat(monkeypatch):+ """Only the chat being forked is refused; a different one generating is no reason to."""+ import threading++ from state import active_generations++ monkeypatch.setattr(chat_history, "get_chat_thread", lambda _id: {"id": _id, "title": "T"})+ monkeypatch.setattr(chat_history, "get_chat_message", lambda _t, _m: None)+ with active_generations.ActiveGeneration(threading.Event(), thread_id = "other"):+ with pytest.raises(HTTPException) as exc:+ chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(+ messageId = "missing",+ newThreadId = "new",+ createdAt = 1,+ ),+ current_subject = "test-user",+ )+ # Past the generation gate, refused later for the missing branch message.+ assert exc.value.status_code == 404++def test_fork_thread_happy_path(monkeypatch):source = {"id": "src",diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex 8a9db2e763f..51d02ee674f 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -845,6 +845,29 @@ def test_fork_chat_thread_copies_ancestry_with_fresh_ids(tmp_path, monkeypatch):assert {m["id"] for m in copied}.isdisjoint({"m1", "m2", "m3"})[email protected]("linked_tip", [False, True])[email protected]("branch_message_id", [None, "m2"])+def test_fork_preserves_legacy_ancestry(tmp_path, monkeypatch, linked_tip, branch_message_id):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread("src"))+ studio_db.sync_chat_messages(+ "src",+ [_msg("m1", None, 1), _msg("m2", None, 2), _msg("m3", "m2" if linked_tip else None, 3)],+ )+ studio_db.fork_chat_thread(+ source_thread_id = "src",+ branch_message_id = branch_message_id,+ new_thread_id = "fork-1",+ new_title = "fork",+ created_at = 4,+ id_factory = iter(("copy-1", "copy-2", "copy-3")).__next__,+ )+ copied = studio_db.list_chat_messages("fork-1")+ expected = ["m1", "m2", "m3"] if branch_message_id is None else ["m1", "m2"]+ assert [row["content"][0]["text"] for row in copied] == expected+ assert [row["parentId"] for row in copied] == [None, *[row["id"] for row in copied[:-1]]]++def test_fork_chat_thread_preserves_project_id(tmp_path, monkeypatch):_reset_studio_db(tmp_path, monkeypatch)studio_db.upsert_chat_project(_project("project-1"))diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.pyindex 300a734a293..09d7b0a26fa 100644--- a/studio/backend/tests/test_research_runs_storage.py+++ b/studio/backend/tests/test_research_runs_storage.py@@ -134,6 +134,32 @@ def _create()[email protected]("status", sorted(research_db.ALL_STATUSES))+def test_row_fork_waits_for_research_to_settle(research_home, status):+ from fastapi import HTTPException+ from routes import chat_history+ from state import active_generations++ _create()+ conn = studio_db.get_connection()+ try:+ conn.execute("UPDATE research_runs SET status=? WHERE id='run-1'", (status,))+ conn.commit()+ finally:+ conn.close()+ assert "thread-1" not in active_generations.active_thread_ids()+ payload = chat_history.ChatForkRequest(newThreadId = "fork-1", createdAt = 20)+ if status in research_db.ACTIVE_STATUSES:+ with pytest.raises(HTTPException) as exc:+ chat_history.fork_thread("thread-1", payload, current_subject = "alice")+ assert exc.value.status_code == 409+ assert studio_db.get_chat_thread("fork-1") is None+ else:+ response = chat_history.fork_thread("thread-1", payload, current_subject = "alice")+ assert response.thread.forkedFromMessageId == "assistant-1"+ assert len(response.messages) == 2++def test_source_persistence_rejects_url_outside_run_allowlist(research_home):config = {"model": "local-model",diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex e41a9f506f9..57b4b6111e4 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -123,7 +123,7 @@ import {} from "@/components/ui/tooltip";import { Tooltip as TooltipPrimitive } from "radix-ui";import { HugeiconsIcon } from "@hugeicons/react";-import { ArrowRightIcon, ChevronDown, ChevronUp, Moon } from "lucide-react";+import { ArrowRightIcon, ChevronDown, ChevronUp, GitBranchIcon, Moon } from "lucide-react";import {Link,useNavigate,@@ -134,11 +134,15 @@ import {archiveChatItem,ChatSearchDialog,clearNewChatDraft,+ canForkChatRow,chatExportOptions,EditProjectDialog,OpenChatFolderUnavailableItem,exportConversationByFormat,+ forkChatRow,+ showForkCreatedToast,getSidebarItemThreadIds,+ useForkInFlight,sandboxSessionIdsHolding,deleteChatProject,deleteChatItem,@@ -1136,6 +1140,8 @@ export function AppSidebar() {const setActiveThreadId = useChatRuntimeStore((s) => s.setActiveThreadId);// The whole map, so each row can show its own spinner.const runningByThreadId = useChatRuntimeStore((s) => s.runningByThreadId);+ // Shared with the thread's own Fork, so neither surface can post a second one.+ const forkInFlight = useForkInFlight((s) => s.forking);// Rows, not raw thread ids: a compare conversation runs two pane threads but is one row.const runningChatCount = useMemo(() => {const running = new Set(@@ -2354,6 +2360,32 @@ export function AppSidebar() {}}+ /** Forks a chat from the row menu and opens the copy, the way the thread's own Fork does. */+ async function forkChatFromRow(item: SidebarItem) {+ // Read, do not trust the render: reopening the menu and picking Fork again before the first+ // request lands would post a second, each with its own new thread id.+ const inFlight = useForkInFlight.getState();+ if (inFlight.forking) return;+ inFlight.setForking(true);+ try {+ const result = await forkChatRow(item);+ setActiveThreadId(result.thread.id);+ navigate({ to: "/chat", search: { thread: result.thread.id } });+ showForkCreatedToast(result.containerSnapshotWarning);+ } catch (error) {+ // A chat still generating is a refusal, not a failure: say so without the alarm.+ if ((error as { unslothForkRefused?: boolean } | null)?.unslothForkRefused) {+ toast.info(error instanceof Error ? error.message : "Cannot fork this chat.");+ } else {+ toast.error("Failed to fork", {+ description: error instanceof Error ? error.message : undefined,+ });+ }+ } finally {+ inFlight.setForking(false);+ }+ }+type RenameTarget =// `inline` is the row's own pill, and a chord has no row under the cursor// and may have none on screen at all, so it opens the dialog instead.@@ -3413,6 +3445,16 @@ export function AppSidebar() {: t("shell.selection.markUnread")}</span></DropdownMenuItem>+ <DropdownMenuItem+ disabled={!canForkChatRow(item) || isGenerating || forkInFlight}+ title="Copy this chat into a new one, from its last message"+ onSelect={() => void forkChatFromRow(item)}+ >+ <GitBranchIcon strokeWidth={1.75} className="size-icon" />+ <span>Fork</span>+ </DropdownMenuItem>+ {/* Rename through Fork act on the row; the rule sets off what reaches outside it. */}+ <DropdownMenuSeparator />{sandboxSessionId ? (isTauri ? (<DropdownMenuItemdiff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex fcfc5af9083..f361c01c2f6 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -180,7 +180,6 @@ import {} from "@/features/settings";import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";import { useT } from "@/i18n";-import { create } from "zustand";import {clampReasoningEffortToLevels,getExternalReasoningCapabilities,@@ -244,6 +243,8 @@ import {usePromptQueueUI,forkCountFor,subscribeForkCounts,+ useForkInFlight,+ showForkCreatedToast,type PlusMenuItemId,usePlusMenuPrefsStore,writeComposerDraft,@@ -7890,22 +7891,6 @@ const ForkCountBadge: FC = () => {);};-/**- * One fork at a time, across every caller of the hook below.- *- * The chord and the button each hold their own instance, so a `useState` flag- * only disables the one that was used: pressing the chord and then clicking- * Fork before the first request lands would post two, each with its own new- * thread id, and race their navigations. A store is what both of them read.- */-const useForkInFlight = create<{- forking: boolean;- setForking: (forking: boolean) => void;-}>((set) => ({- forking: false,- setForking: (forking) => set({ forking }),-}));-const useForkMessageAction = () => {const aui = useAui();const navigate = useNavigate();@@ -7952,13 +7937,7 @@ const useForkMessageAction = () => {search: { thread: result.thread.id },replace: false,});- if (result.containerSnapshotWarning) {- toast.info("Fork created", {- description: result.containerSnapshotWarning,- });- } else {- toast.success("Fork created");- }+ showForkCreatedToast(result.containerSnapshotWarning);} catch (error) {console.error("Failed to fork", error);toast.error("Failed to fork", {diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex e1500ec1a5a..b487228e8ca 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -997,7 +997,9 @@ export interface ForkChatThreadResult {export async function forkChatThread(threadId: string,- args: { messageId: string; newThreadId: string; createdAt: number },+ /** Omit `messageId` to fork at the tip, which the route resolves after its own check that+ * the chat is not generating. */+ args: { messageId?: string; newThreadId: string; createdAt: number },): Promise<ForkChatThreadResult> {const response = await authFetch(`/api/chat/threads/${encodeURIComponent(threadId)}/fork`,diff --git a/studio/frontend/src/features/chat/components/chat-row-menu.ts b/studio/frontend/src/features/chat/components/chat-row-menu.tsindex 34bf2af0c30..d10ca53eda7 100644--- a/studio/frontend/src/features/chat/components/chat-row-menu.ts+++ b/studio/frontend/src/features/chat/components/chat-row-menu.ts@@ -12,6 +12,7 @@ import {CONVERSATION_MARKDOWN_LABEL,} from "../utils/conversation-markdown";import { allRecordedSandboxSessionIds } from "../utils/recorded-sandbox-session";+import { liveThreadBranch } from "../utils/live-thread-head";import type { SidebarItem } from "../hooks/use-chat-sidebar-items";import { listStoredChatMessages } from "../utils/chat-history-storage";@@ -66,6 +67,45 @@ export function getSidebarItemThreadIds(item: SidebarItem): string[] {return item.threadIds?.length ? item.threadIds : [item.id];}+/** A comparison is two threads with no single tip to fork from. */+export function canForkChatRow(item: SidebarItem): boolean {+ return item.type === "single";+}++/**+ * Forks a chat from its last message, which is what the thread's own Fork does from the message+ * it is on. Settings are settled first: the fork copies `settings_json` in its own transaction,+ * so an edit still in the debounce would be left out and the copy would open on the older modes.+ */+export async function forkChatRow(item: SidebarItem) {+ const messageId = liveThreadBranch(item.id)?.at(-1);+ const { forkChatThread } = await import("../api/chat-api");+ const { settleThreadScopedSettingsForCopy } = await import(+ "../stores/chat-runtime-store"+ );+ await settleThreadScopedSettingsForCopy(item.id);+ try {+ // closed chats use the transaction-selected tip; open chats keep the branch visible at invocation.+ return await forkChatThread(item.id, {+ messageId,+ newThreadId: crypto.randomUUID(),+ createdAt: Date.now(),+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : "";+ if (message.includes("still generating")) throw forkRefused();+ throw error;+ }+}++/** Tagged, so the caller says this rather than reporting a failure that did not happen. */+function forkRefused(): Error {+ return Object.assign(+ new Error("This chat is still generating. Fork it once it finishes."),+ { unslothForkRefused: true },+ );+}+/** The sandbox sessions this chat's stored tool results name, if any. */export async function recordedSandboxSessionIds(ids: string[],diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex c33b7e5b643..41f7c71d611 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -265,14 +265,18 @@ export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";export type { ProjectRecord } from "./types";export { EditProjectDialog } from "./components/edit-project-dialog";export {+ canForkChatRow,chatExportOptions,exportConversationByFormat,+ forkChatRow,getSidebarItemThreadIds,recordedSandboxSessionIds,sandboxSessionIdsHolding,type ConversationExportFormat,} from "./components/chat-row-menu";export { OpenChatFolderUnavailableItem } from "./components/open-chat-folder-item";+export { useForkInFlight } from "./utils/fork-in-flight";+export { showForkCreatedToast } from "./utils/fork-toast";export { clearAllChats, countAllChats } from "./utils/clear-all-chats";export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";export { pasteClipboardFiles } from "./utils/clipboard-files";diff --git a/studio/frontend/src/features/chat/utils/fork-in-flight.ts b/studio/frontend/src/features/chat/utils/fork-in-flight.tsnew file mode 100644index 00000000000..1cea064aa0a--- /dev/null+++ b/studio/frontend/src/features/chat/utils/fork-in-flight.ts@@ -0,0 +1,20 @@+// 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";++/**+ * One fork at a time, across every caller.+ *+ * The chord, the message button and the row menu each hold their own instance, so a `useState`+ * flag only disables the one that was used: pressing the chord and then clicking Fork before the+ * first request lands would post two, each with its own new thread id, and race their+ * navigations. A store is what all of them read.+ */+export const useForkInFlight = create<{+ forking: boolean;+ setForking: (forking: boolean) => void;+}>((set) => ({+ forking: false,+ setForking: (forking) => set({ forking }),+}));diff --git a/studio/frontend/src/features/chat/utils/fork-toast.ts b/studio/frontend/src/features/chat/utils/fork-toast.tsnew file mode 100644index 00000000000..f875d9c0ef5--- /dev/null+++ b/studio/frontend/src/features/chat/utils/fork-toast.ts@@ -0,0 +1,12 @@+// 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 "sonner";++export function showForkCreatedToast(containerSnapshotWarning: string | null): void {+ if (containerSnapshotWarning) {+ toast.info("Fork created", { description: containerSnapshotWarning });+ } else {+ toast.success("Fork created");+ }+}diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.tsindex 2b3b3078f21..fa5ba96461f 100644--- a/studio/frontend/tests/keyboard-shortcuts.test.ts+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts@@ -1090,12 +1090,15 @@ test("the fork chord is registered where it mounts, not from an action bar", asy);// Two instances of the action now exist on the last message, the chord's and- // the button's, so the in-flight flag cannot be either one's own state: the- // chord followed by a click would post two forks with two thread ids.+ // the button's, and the sidebar row menu is a third, so the in-flight flag cannot be any one+ // of their own state: the chord followed by a click would post two forks with two thread ids.+ // It lives in its own module so every caller reads the one flag.+ const FORK_STORE = await readSrcAsync("features/chat/utils/fork-in-flight.ts");assert.match(- THREAD,- /const useForkInFlight = create<\{\n\s*forking: boolean;/,+ FORK_STORE,+ /export const useForkInFlight = create<\{\n\s*forking: boolean;/,);+ assert.ok(!THREAD.includes("const useForkInFlight = create<"));assert.match(THREAD, /const pending = useForkInFlight\(\(s\) => s\.forking\);/);assert.match(THREAD,diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.tsindex bb3736c6283..0be56e84186 100644--- a/studio/frontend/tests/sidebar-row-actions.test.ts+++ b/studio/frontend/tests/sidebar-row-actions.test.ts@@ -7,10 +7,57 @@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 { readSrcAsync } from "./helpers/kit.ts";const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");+test("row forks retain the visible branch across settings settlement", async () => {+ const source = await readSrcAsync("features/chat/components/chat-row-menu.ts");+ const javascript = ts.transpileModule(+ source.slice(source.indexOf("export async function forkChatRow("), source.indexOf("/** The sandbox sessions")),+ { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } },+ ).outputText;+ for (const open of [true, false]) {+ let visible = open;+ const unregister = liveThreadHead.registerLiveThreadView({+ threadListItem: () => ({ getState: () => ({ remoteId: visible ? "source" : "other" }) }),+ thread: () => ({ getState: () => ({ messages: [{ id: "root" }, { id: "older-reply" }] }) }),+ });+ const calls: string[] = [];+ const context = {+ exports: {} as { forkChatRow: (item: { id: string }) => Promise<unknown> },+ crypto,+ ...liveThreadHead,+ require: (specifier: string) => {+ if (specifier === "../api/chat-api") return {+ forkChatThread: async (id: string, args: { messageId?: string }) => {+ calls.push("fork");+ assert.equal(id, "source");+ assert.equal(args.messageId, open ? "older-reply" : undefined);+ },+ };+ if (specifier === "../stores/chat-runtime-store") return {+ settleThreadScopedSettingsForCopy: async () => {+ calls.push("settings");+ visible = false;+ },+ };+ throw new Error(`Unexpected module: ${specifier}`);+ },+ };+ try {+ vm.runInNewContext(javascript, context);+ await context.exports.forkChatRow({ id: "source" });+ assert.deepEqual(calls, ["settings", "fork"]);+ } finally {+ unregister();+ }+ }+});+// The pin used to appear on a Recents row only once it was pinned, so the only way to pin one was// through the menu, while the project rows beside it had the one-click affordance all along.test("every chat row offers the pin without opening a menu", () => {@@ -192,3 +239,76 @@ test("the chat-folder hint names what to click instead", async () => {"the hint is no longer stated for both the pointer and the screen reader",);});++// Forking was reachable only from a message in the open thread, so copying a chat meant opening+// it first. The row menu does it from wherever the row is drawn.+test("a chat row forks from its own menu", async () => {+ const ROW_MENU = await readSrcAsync(+ "features/chat/components/chat-row-menu.ts",+ );+ // Below Mark as unread, and before the rule that sets off the rest.+ assert.match(+ APP_SIDEBAR,+ /t\("shell\.selection\.markUnread"\)\}\n\s*<\/span>\n\s*<\/DropdownMenuItem>\n\s*<DropdownMenuItem\n\s*disabled=\{!canForkChatRow\(item\)/,+ );+ assert.match(APP_SIDEBAR, /<span>Fork<\/span>\n\s*<\/DropdownMenuItem>\n\s*\{\/\*[^]*?\*\/\}\n\s*<DropdownMenuSeparator \/>/);+ // A comparison has two threads and no single tip to fork from.+ assert.match(ROW_MENU, /export function canForkChatRow[^]*?return item\.type === "single";/);+ // The fork carries the settings on screen, not the ones the row was last written with.+ assert.match(+ ROW_MENU,+ /await settleThreadScopedSettingsForCopy\(item\.id\);\n\s*try \{/,+ );+ // the visible branch is optional; closed chats use the server-selected tip.+ assert.ok(!ROW_MENU.includes("messages[messages.length - 1]"));+ assert.match(+ ROW_MENU,+ /return await forkChatThread\(item\.id, \{\n\s*messageId,\n\s*newThreadId: crypto\.randomUUID\(\),/,+ );+ assert.match(+ APP_SIDEBAR,+ /setActiveThreadId\(result\.thread\.id\);\n\s*navigate\(\{ to: "\/chat", search: \{ thread: result\.thread\.id \} \}\);/,+ );+});++// A streaming chat has no settled tip: its last stored message is the prompt, or a reply still+// being written, so the fork would end mid-answer. The message-level Fork disables on isRunning+// for the same reason.+test("a row being generated into cannot be forked", async () => {+ const THREAD = await readSrcAsync("components/assistant-ui/thread.tsx");+ assert.match(+ APP_SIDEBAR,+ /disabled=\{!canForkChatRow\(item\) \|\| isGenerating \|\| forkInFlight\}/,+ );+ // One fork at a time, and the row menu shares the guard with the thread's own Fork rather+ // than keeping a second one: two surfaces with a flag each would still post two.+ assert.match(APP_SIDEBAR, /const inFlight = useForkInFlight\.getState\(\);\n\s*if \(inFlight\.forking\) return;\n\s*inFlight\.setForking\(true\);/);+ assert.match(APP_SIDEBAR, /\} finally \{\n\s*inFlight\.setForking\(false\);/);+ assert.match(APP_SIDEBAR, /const forkInFlight = useForkInFlight\(\(s\) => s\.forking\);/);+ // The store moved out of thread.tsx so both callers read the one flag.+ assert.ok(!/const useForkInFlight = create</.test(THREAD));+ assert.match(THREAD, /^\s*useForkInFlight,$/m);+ const STORE = await readSrcAsync("features/chat/utils/fork-in-flight.ts");+ assert.match(STORE, /export const useForkInFlight = create</);+});++// closed chats resolve their tip under the server generation guard.+test("closed-chat forks leave tip selection to the server", async () => {+ const ROW_MENU = await readSrcAsync(+ "features/chat/components/chat-row-menu.ts",+ );+ const ROUTE = await readSrcAsync(+ "../../backend/routes/chat_history.py",+ );+ // selecting the tip does not require a client-side storage snapshot.+ assert.ok(!ROW_MENU.includes("getActiveGenerations"));+ assert.ok(!ROW_MENU.includes("listStoredChatMessages(item.id)"));+ // the transaction resolves the tip after checking durable runs.+ const fork = ROUTE.slice(ROUTE.indexOf("def fork_thread("));+ assert.match(fork, /branch_message_id = payload\.messageId/);+ assert.match(fork, /except ChatForkActiveGenerationError/);+ // Its 409 is a refusal, not a failure.+ assert.match(ROW_MENU, /if \(message\.includes\("still generating"\)\) throw forkRefused\(\);/);+ assert.match(ROW_MENU, /\{ unslothForkRefused: true \}/);+ assert.match(APP_SIDEBAR, /\?\.unslothForkRefused\) \{\n\s*toast\.info\(/);+});