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: keep both branches when a chat's first message is edited (#10163)
Nilay381b9fccb741
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.pyindex c4873586d9f..8f5c32bc2f9 100644--- a/studio/backend/core/rag/conversation_archive.py+++ b/studio/backend/core/rag/conversation_archive.py@@ -825,8 +825,9 @@ def _active_chain(Walked newest leaf back to root, the same shape the frontend's `orderBySelectedBranch`uses to decide what the model is actually shown. `parent_id` is missing on rows writtenbefore that column, so the previous row stands in for it, which is exactly a flat list- when nothing branches. ``fallback=False`` lets callers decline when the request cannot- seed a chain instead of silently reading the newest stored sibling. ``require_unique``+ when nothing branches. Unlike the frontend, this default path never roots a null after+ a recorded parent. ``fallback=False`` lets callers decline when the request cannot seed+ a chain instead of silently reading the newest stored sibling. ``require_unique``likewise declines when indistinguishable leaves tie for the best branch match and trimsthe winner after the last stored row the request actually matched."""diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 38ba0f97024..cb4e4531be9 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -4508,7 +4508,11 @@ export function createOpenAIStreamAdapter(await saveStoredChatMessage({id: userMessage.id,threadId: resolvedThreadId,- parentId: storedUserMessage?.parentId ?? userMessageParentId,+ // A stored null is an edited root; `??` would reparent it.+ parentId:+ storedUserMessage && storedUserMessage.parentId !== undefined+ ? storedUserMessage.parentId+ : userMessageParentId,role: "user",content: userMessage.content,...(userMessage.attachments?.lengthdiff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 35e586cd984..1b474a9d71b 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -122,6 +122,7 @@ import {onChatAttachmentDeleted,} from "./utils/chat-attachment-events";import { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";+import { createParentResolver } from "./utils/message-order";import {awaitStoredChatThreadWrites,deleteStoredChatThreads,@@ -2013,17 +2014,13 @@ function useStudioRuntimeAdapters(// preserve the chain. Fall back to fromArray for fully legacy threads.const hasParentIds = msgs.some((m) => m.parentId != null);if (hasParentIds) {- let previousId: string | null = null;+ const resolveParent = createParentResolver();return completeLoad({- messages: msgs.map((m) => {- const parentId = m.parentId != null ? m.parentId : previousId;- previousId = m.id;- return {- parentId,- message: toThreadMessage(m),- };- }),+ messages: msgs.map((m) => ({+ parentId: resolveParent(m),+ message: toThreadMessage(m),+ })),},remoteId,);diff --git a/studio/frontend/src/features/chat/utils/message-order.ts b/studio/frontend/src/features/chat/utils/message-order.tsindex 7f25c83b37b..46a3dc5f805 100644--- a/studio/frontend/src/features/chat/utils/message-order.ts+++ b/studio/frontend/src/features/chat/utils/message-order.ts@@ -10,6 +10,25 @@ export type ParentLinkedMessage = {const ROLE_ORDER: Record<string, number> = { system: 0, user: 1, assistant: 2 };+// Rows in storage order. A null is a root only after a recorded parent; earlier it chains.+export function createParentResolver(): (+ message: ParentLinkedMessage,+) => string | null {+ let previousId: string | null = null;+ let sawRecordedParent = false;+ return (message) => {+ const inferred =+ message.parentId === undefined ||+ (message.parentId === null && !sawRecordedParent);+ const parentId = inferred ? previousId : message.parentId;+ if (message.parentId != null) {+ sawRecordedParent = true;+ }+ previousId = message.id;+ return parentId ?? null;+ };+}+export function orderBySelectedBranch<T extends ParentLinkedMessage>(messages: T[],): T[] {@@ -28,11 +47,10 @@ export function orderBySelectedBranch<T extends ParentLinkedMessage>(const byId = new Map<string, T>();const parentOf = new Map<string, string | null>();- let previousId: string | null = null;+ const resolveParent = createParentResolver();for (const message of sorted) {byId.set(message.id, message);- parentOf.set(message.id, message.parentId ?? previousId);- previousId = message.id;+ parentOf.set(message.id, resolveParent(message));}const chain: T[] = [];diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.tsindex c1e301f626b..4f14a4596e7 100644--- a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts@@ -15,6 +15,7 @@ import { isExternalModelId } from "../external-providers";import { useChatRuntimeStore } from "../stores/chat-runtime-store";import type { MessageRecord } from "../types";import { listStoredChatMessages } from "./chat-history-storage";+import { orderBySelectedBranch } from "./message-order";// Per thread, not per module: in compare mode a hidden pane's history load would otherwise// invalidate the visible thread's count, blanking the bar.@@ -80,45 +81,6 @@ function storedMessageToRunMessage(record: MessageRecord): ThreadMessage {};}-// Same order the history adapter sorts stored records in before importing them.-const ROLE_ORDER: Record<string, number> = { system: 0, user: 1, assistant: 2 };--/**- * The displayed branch, rebuilt as the history adapter does: sort by (createdAt, role, id), parent- * legacy records to the previous one, then walk the last record's ancestor chain. Greedy- * newest-child descent would pick another branch and drop pre-parentId history.- */-function orderBySelectedBranch<T extends MessageRecord>(messages: T[]): T[] {- const sorted = messages.slice().sort((a, b) => {- if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;- const aOrder = ROLE_ORDER[a.role] ?? 99;- const bOrder = ROLE_ORDER[b.role] ?? 99;- if (aOrder !== bOrder) return aOrder - bOrder;- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;- });-- const byId = new Map<string, T>();- const parentOf = new Map<string, string | null>();- let previousId: string | null = null;- for (const m of sorted) {- byId.set(m.id, m);- parentOf.set(m.id, m.parentId ?? previousId);- previousId = m.id;- }-- const chain: T[] = [];- const seen = new Set<string>();- let cur: string | null = sorted.at(-1)?.id ?? null;- while (cur != null && !seen.has(cur)) {- seen.add(cur);- const record = byId.get(cur);- if (!record) break;- chain.push(record);- cur = parentOf.get(cur) ?? null;- }- return chain.reverse();-}-/** Rolling 32-bit hash. Only has to change when the input does, not resist an adversary. */function foldHash(text: string, seed: number): number {let hash = seed;diff --git a/studio/frontend/tests/current-date-context-usage.test.ts b/studio/frontend/tests/current-date-context-usage.test.tsindex e1f6e93c679..f61f108c184 100644--- a/studio/frontend/tests/current-date-context-usage.test.ts+++ b/studio/frontend/tests/current-date-context-usage.test.ts@@ -4,6 +4,7 @@import assert from "node:assert/strict";import test from "node:test";+import * as messageOrder from "../src/features/chat/utils/message-order.ts";import { loadWithStubs } from "./helpers/module-stubs.ts";type RefreshModule = {@@ -36,6 +37,7 @@ test("a prompt setting change clears local usage even during a run", async () =>"../stores/chat-runtime-store": {useChatRuntimeStore: { getState: () => state },},+ "./message-order": messageOrder,"./chat-history-storage": {},},);@@ -71,6 +73,7 @@ test("a prompt setting change leaves external usage intact", async () => {"../stores/chat-runtime-store": {useChatRuntimeStore: { getState: () => state },},+ "./message-order": messageOrder,"./chat-history-storage": {},},);diff --git a/studio/frontend/tests/edited-first-message-branches.test.ts b/studio/frontend/tests/edited-first-message-branches.test.tsnew file mode 100644index 00000000000..09d001fe908--- /dev/null+++ b/studio/frontend/tests/edited-first-message-branches.test.ts@@ -0,0 +1,235 @@+// 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 {+ createParentResolver,+ orderBySelectedBranch,+} from "../src/features/chat/utils/message-order.ts";++type Shape = { id: string; parentId?: string | null };++function resolveAll(rows: Shape[]): (string | null)[] {+ const resolveParent = createParentResolver();+ return rows.map((row) => resolveParent(row));+}++const EDITED_ROOT = [+ { id: "a", parentId: null, createdAt: 1, role: "user" },+ { id: "reply-a", parentId: "a", createdAt: 2, role: "assistant" },+ { id: "b", parentId: null, createdAt: 3, role: "user" },+ { id: "reply-b", parentId: "b", createdAt: 4, role: "assistant" },+];++test("a stored null is a root once the thread has recorded a real parent", () => {+ assert.deepEqual(+ resolveAll([+ { id: "a", parentId: null },+ { id: "reply-a", parentId: "a" },+ { id: "b", parentId: null },+ ]),+ [null, "a", null],+ );+});++test("a record from before the field existed still chains to its predecessor", () => {+ assert.deepEqual(resolveAll([{ id: "a" }, { id: "b" }]), [null, "a"]);+});++test("an undefined parentId is treated as absent, not as a root", () => {+ assert.deepEqual(+ resolveAll([{ id: "a" }, { id: "b", parentId: undefined }]),+ [null, "a"],+ );+});++test("a leading run of stored nulls is legacy, so storage order stands in", () => {+ // Server rows always carry the key; with no recorded parent yet, these nulls chain.+ assert.deepEqual(+ resolveAll([+ { id: "old-1", parentId: null },+ { id: "old-2", parentId: null },+ { id: "new", parentId: "old-2" },+ { id: "root", parentId: null },+ ]),+ [null, "old-1", "old-2", null],+ );+});++test("editing the first message leaves two branches, not one conversation", () => {+ assert.deepEqual(+ orderBySelectedBranch(EDITED_ROOT).map(({ id }) => id),+ ["b", "reply-b"],+ );+});++test("a legacy thread with no parentIds at all still loads in order", () => {+ const legacy = [+ { id: "u1", createdAt: 1, role: "user" },+ { id: "a1", createdAt: 2, role: "assistant" },+ { id: "u2", createdAt: 3, role: "user" },+ { id: "a2", createdAt: 4, role: "assistant" },+ ];++ assert.deepEqual(+ orderBySelectedBranch(legacy).map(({ id }) => id),+ ["u1", "a1", "u2", "a2"],+ );+});++test("a mixed thread keeps its legacy chain instead of dropping it", () => {+ const mixed = [+ { id: "old-1", createdAt: 1, role: "user" },+ { id: "old-2", createdAt: 2, role: "assistant" },+ { id: "new-1", parentId: "old-2", createdAt: 3, role: "user" },+ { id: "new-2", parentId: "new-1", createdAt: 4, role: "assistant" },+ ];++ assert.deepEqual(+ orderBySelectedBranch(mixed).map(({ id }) => id),+ ["old-1", "old-2", "new-1", "new-2"],+ );+});++test("a server-backed legacy thread survives its first parent-linked turn", () => {+ // Rooting these explicit legacy nulls dropped every turn before the first linked one.+ const serverBacked = [+ { id: "old-u1", parentId: null, createdAt: 1, role: "user" },+ { id: "old-a1", parentId: null, createdAt: 2, role: "assistant" },+ { id: "old-u2", parentId: null, createdAt: 3, role: "user" },+ { id: "old-a2", parentId: null, createdAt: 4, role: "assistant" },+ { id: "new-u3", parentId: "old-a2", createdAt: 5, role: "user" },+ { id: "new-a3", parentId: "new-u3", createdAt: 6, role: "assistant" },+ ];++ assert.deepEqual(+ orderBySelectedBranch(serverBacked).map(({ id }) => id),+ ["old-u1", "old-a1", "old-u2", "old-a2", "new-u3", "new-a3"],+ );+});++test("editing the first message of a server-backed thread keeps both branches", () => {+ const edited = [+ { id: "u1", parentId: null, createdAt: 1, role: "user" },+ { id: "a1", parentId: "u1", createdAt: 2, role: "assistant" },+ { id: "u1-edited", parentId: null, createdAt: 3, role: "user" },+ { id: "a1-edited", parentId: "u1-edited", createdAt: 4, role: "assistant" },+ ];++ assert.deepEqual(+ orderBySelectedBranch(edited).map(({ id }) => id),+ ["u1-edited", "a1-edited"],+ );+});++test("retrying a reply mid-thread still selects the newest branch", () => {+ const retried = [+ { id: "u1", parentId: null, createdAt: 1, role: "user" },+ { id: "a1-old", parentId: "u1", createdAt: 2, role: "assistant" },+ { id: "a1-new", parentId: "u1", createdAt: 3, role: "assistant" },+ { id: "u2", parentId: "a1-new", createdAt: 4, role: "user" },+ { id: "a2", parentId: "u2", createdAt: 5, role: "assistant" },+ ];++ assert.deepEqual(+ orderBySelectedBranch(retried).map(({ id }) => id),+ ["u1", "a1-new", "u2", "a2"],+ );+});++type Row = {+ id: string;+ parentId?: string | null;+ createdAt?: number;+ role?: string;+};++function rng(seed: number) {+ let s = seed;+ return () => {+ s = (s * 1103515245 + 12345) % 2147483648;+ return s / 2147483648;+ };+}++function generate(r: () => number): Row[] {+ const n = 2 + Math.floor(r() * 10);+ const rows: Row[] = [];+ for (let i = 0; i < n; i++) {+ const roll = r();+ let parentId: string | null | undefined;+ if (i === 0) {+ parentId = null;+ } else if (roll < 0.15) {+ parentId = null; // a second root+ } else if (roll < 0.3) {+ parentId = undefined; // pre-parentId record+ } else if (roll < 0.4) {+ parentId = `ghost-${i}`; // dangling reference+ } else {+ parentId = rows[Math.floor(r() * rows.length)].id;+ }+ const row: Row = {+ id: `m${i}`,+ createdAt: i,+ role: i % 2 ? "assistant" : "user",+ };+ if (parentId !== undefined) {+ row.parentId = parentId;+ }+ rows.push(row);+ }+ return rows;+}++// The previous rule, `parentId ?? previous`, kept verbatim as the reference.+function orderByPreviousRule(rows: Row[]): string[] {+ const sorted = [...rows].sort(+ (a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0),+ );+ const parentOf = new Map<string, string | null>();+ let prev: string | null = null;+ for (const m of sorted) {+ parentOf.set(m.id, m.parentId ?? prev);+ prev = m.id;+ }+ const chain: string[] = [];+ const seen = new Set<string>();+ let cur: string | null = sorted.at(-1)?.id ?? null;+ while (cur != null && !seen.has(cur)) {+ seen.add(cur);+ if (!sorted.some((x) => x.id === cur)) {+ break;+ }+ chain.push(cur);+ cur = parentOf.get(cur) ?? null;+ }+ return chain.reverse();+}++test("threads with no explicit null parent are completely unaffected", () => {+ // Only a stored null changes meaning; everything else must order as before.+ const r = rng(7);+ for (let c = 0; c < 300; c++) {+ const rows = generate(r).filter((m) => m.parentId !== null);+ assert.deepEqual(+ orderBySelectedBranch(rows).map((m) => m.id),+ orderByPreviousRule(rows),+ );+ }+});++test("the resolver is total over the three shapes", () => {+ assert.deepEqual(+ resolveAll([+ { id: "p", parentId: null },+ { id: "link", parentId: "p" },+ { id: "root", parentId: null },+ { id: "absent" },+ { id: "dangling", parentId: "gone" },+ ]),+ [null, "p", null, "root", "gone"],+ );+});diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.pyindex 76e306f07d7..d7a0c03fe14 100644--- a/tests/studio/test_deep_research_frontend_contract.py+++ b/tests/studio/test_deep_research_frontend_contract.py@@ -146,7 +146,11 @@ def test_research_presave_keeps_the_follow_up_parent() -> None:assert "const userMessageIndex = messages.indexOf(userMessage);" in presaveassert "const userMessageParentId =" in presaveassert "userMessageIndex > 0 ? messages[userMessageIndex - 1]!.id : null" in presave- assert "parentId: storedUserMessage?.parentId ?? userMessageParentId" in presave+ # A stored null is an edited root; `??` would reparent it under the predecessor.+ assert "storedUserMessage && storedUserMessage.parentId !== undefined" in presave+ assert "? storedUserMessage.parentId" in presave+ assert ": userMessageParentId," in presave+ assert "parentId: storedUserMessage?.parentId ?? userMessageParentId" not in presaveassert "parentId: storedUserMessage?.parentId ?? null" not in presavediff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.pyindex d729bf3b65d..544e865f426 100644--- a/tests/studio/test_new_chat_context_recount.py+++ b/tests/studio/test_new_chat_context_recount.py@@ -35,10 +35,11 @@ REFRESH = source_path("studio/frontend/src/features/chat/utils/refresh-context-uPROVIDER = source_path("studio/frontend/src/features/chat/runtime-provider.tsx")STORE = source_path("studio/frontend/src/features/chat/stores/chat-runtime-store.ts")RUNTIME = source_path("studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts")+MESSAGE_ORDER = source_path("studio/frontend/src/features/chat/utils/message-order.ts")TEMP = WORKDIR / "temp" / "new_chat_context_recount"-SOURCES = (REFRESH, PROVIDER, STORE, RUNTIME)+SOURCES = (REFRESH, PROVIDER, STORE, RUNTIME, MESSAGE_ORDER)# Every name the emulator can supply to a sliced dependency array.BOUND_NAMES = {@@ -58,10 +59,30 @@ BOUND_NAMES = {def _refresh_module_body() -> str:- """Everything in refresh-context-usage.ts after its import block, verbatim."""+ """Everything in refresh-context-usage.ts after its import block, verbatim.++ The marker is one import, not the last one: anything sorting after+ "./chat-history-storage" follows it. Those lines are dropped rather than replayed,+ because the harness supplies those modules itself and an `import` inside harness.ts+ would resolve against the temp directory, where they do not exist.+ """text = read(REFRESH)marker = 'from "./chat-history-storage";'- return text[text.index(marker) + len(marker) :]+ rest = text[text.index(marker) + len(marker) :]+ lines = rest.split("\n")+ while lines and (not lines[0].strip() or lines[0].startswith("import ")):+ lines.pop(0)+ return "\n" + "\n".join(lines)+++def _message_order_body() -> str:+ """message-order.ts verbatim: it takes no imports of its own.++ refresh-context-usage.ts used to carry its own copy of `orderBySelectedBranch`, so+ the replayed body defined it. Now that it imports the shared one, the harness has to+ supply it or the recount prices the wrong branch.+ """+ return read(MESSAGE_ORDER)def _component_effects(start: str, end: str) -> list[tuple[list[str], str]]:@@ -565,7 +586,7 @@ def _harness_source() -> str:)resident = HARNESS_RESIDENT.replace("__FAST_PATH__", _resident_fast_path())history = HARNESS_HISTORY.replace("__RESTORE__", _history_usage_restore())- return prelude + _refresh_module_body() + render + resident + history+ return prelude + _message_order_body() + _refresh_module_body() + render + resident + historydef _run(script: str) -> dict: