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
fix(chat): import branch threads parents-before-children on refresh (#13113)
CelesteHeartsongbc3c978c6aaa
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex bcde1959d0a..8f47ace1256 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -191,6 +191,8 @@ import { savedBranchHead } from "./utils/branch-head";import {createParentResolver,orderBySelectedBranch,+ orderParentsFirst,+ resolveSavedBranchHead,} from "./utils/message-order";import { estimateContextUsage } from "./utils/estimate-chat-tokens";import {@@ -1813,18 +1815,9 @@ export async function ensureThreadRecord({function parentsFirst(items: readonly ExportedMessageRepositoryItem[],): ExportedMessageRepositoryItem[] {- const byId = new Map(items.map((item) => [item.message.id, item]));- const seen = new Set<string>();- const ordered: ExportedMessageRepositoryItem[] = [];- const visit = (item: ExportedMessageRepositoryItem) => {- if (seen.has(item.message.id)) return;- seen.add(item.message.id);- const parent = item.parentId ? byId.get(item.parentId) : undefined;- if (parent) visit(parent);- ordered.push(item);- };- items.forEach(visit);- return ordered;+ return orderParentsFirst(+ items.map((item) => ({ item, id: item.message.id, parentId: item.parentId })),+ ).map(({ item }) => item);}/** Save a temporary chat to history: its row, then every message on every branch in one batch,@@ -2672,7 +2665,12 @@ function useStudioRuntimeAdapters(}// select the persisted branch for import and context-usage restoration- const headId = savedBranchHead(remoteId, msgs);+ const savedHeadId = savedBranchHead(remoteId, msgs);+ // follow the newest stored row to a leaf before parent-first ordering moves the tail.+ const headId = resolveSavedBranchHead(+ msgs,+ savedHeadId ?? msgs.at(-1)?.id,+ );const branch = orderBySelectedBranch(msgs, headId);// restore usage from the selected branch's last assistant message when the model matches@@ -2720,13 +2718,18 @@ function useStudioRuntimeAdapters(// rebuild branches when parentIds exist; infer sequential parents for mixed legacy threadsconst hasParentIds = msgs.some((m) => m.parentId != null);if (hasParentIds) {+ // resolve legacy parents in storage order before sorting parents ahead of children.const resolveParent = createParentResolver();+ const ordered = orderParentsFirst(+ msgs.map((m) => ({ record: m, id: m.id, parentId: resolveParent(m) })),+ );return completeLoad({+ // savedBranchHead selects a leaf so import retains its descendants.headId,- messages: msgs.map((m) => ({- parentId: resolveParent(m),- message: toThreadMessage(m),+ messages: ordered.map(({ record, parentId }) => ({+ parentId,+ message: toThreadMessage(record),})),},remoteId,diff --git a/studio/frontend/src/features/chat/utils/message-order.ts b/studio/frontend/src/features/chat/utils/message-order.tsindex d90ea904443..c88632e8eca 100644--- a/studio/frontend/src/features/chat/utils/message-order.ts+++ b/studio/frontend/src/features/chat/utils/message-order.ts@@ -29,6 +29,40 @@ export function createParentResolver(): (};}+// assistant-ui import requires parents first, even when edited timestamps place replies earlier.+export function orderParentsFirst<+ T extends {+ id: string;+ parentId?: string | null;+ },+>(messages: readonly T[]): T[] {+ const byId = new Map(messages.map((message) => [message.id, message]));+ const seen = new Set<string>();+ const ordered: T[] = [];+ for (const message of messages) {+ if (seen.has(message.id)) continue;+ const stack: { message: T; emit: boolean }[] = [{ message, emit: false }];+ while (stack.length > 0) {+ const current = stack.pop();+ if (!current) break;+ if (current.emit) {+ ordered.push(current.message);+ continue;+ }+ if (seen.has(current.message.id)) continue;+ seen.add(current.message.id);+ stack.push({ message: current.message, emit: true });+ const parent = current.message.parentId+ ? byId.get(current.message.parentId)+ : undefined;+ if (parent && !seen.has(parent.id)) {+ stack.push({ message: parent, emit: false });+ }+ }+ }+ return ordered;+}+export function compareStoredMessages(a: ParentLinkedMessage,b: ParentLinkedMessage,diff --git a/studio/frontend/tests/refresh-branch-import-order.test.ts b/studio/frontend/tests/refresh-branch-import-order.test.tsnew file mode 100644index 00000000000..11472d773b1--- /dev/null+++ b/studio/frontend/tests/refresh-branch-import-order.test.ts@@ -0,0 +1,144 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import type { ThreadMessage } from "@assistant-ui/core";+import { MessageRepository } from "@assistant-ui/core/internal"; // intentional internal API+import {+ compareStoredMessages,+ createParentResolver,+ orderParentsFirst,+ resolveSavedBranchHead,+} from "../src/features/chat/utils/message-order.ts";++type Row = {+ id: string;+ parentId: string | null;+ createdAt: number;+ role: string;+};++// edited user messages can be stored after replies, so createdAt alone orders replies first.+const ANOMALOUS = [+ { id: "R", parentId: null, createdAt: 1, role: "user" },+ { id: "A1", parentId: "R", createdAt: 2, role: "assistant" },+ { id: "E1", parentId: "A1", createdAt: 10, role: "user" },+ { id: "R1", parentId: "E1", createdAt: 9, role: "assistant" },+ { id: "E2", parentId: "A1", createdAt: 20, role: "user" },+ { id: "R2", parentId: "E2", createdAt: 19, role: "assistant" },+];++// use the production comparator to exercise the load path's ordering.+function byCreatedAt(rows: Row[]): Row[] {+ return [...rows].sort(compareStoredMessages);+}++// assistant-ui import fails when a message precedes its parent.+function countMissingParents(ordered: Row[]): number {+ const seen = new Set<string>();+ let missing = 0;+ for (const row of ordered) {+ if (row.parentId !== null && !seen.has(row.parentId)) missing += 1;+ seen.add(row.id);+ }+ return missing;+}++// user and assistant messages require distinct properties, so assert the literal as the union type.+function threadMessage(id: string, role: string): ThreadMessage {+ return {+ id,+ role: role as "user" | "assistant",+ content: [{ type: "text" as const, text: `text-${id}` }],+ createdAt: new Date(0),+ metadata: {+ unstable_state: null,+ unstable_annotations: [],+ unstable_data: [],+ steps: [],+ custom: {},+ },+ ...(role === "user"+ ? { attachments: [] }+ : { status: { type: "complete" as const, reason: "stop" as const } }),+ } as ThreadMessage;+}++test("createdAt order alone misorders a reply before its edited user parent", () => {+ assert.ok(countMissingParents(byCreatedAt(ANOMALOUS)) > 0);+});++test("orderParentsFirst emits every parent before its child", () => {+ const ordered = orderParentsFirst(ANOMALOUS);+ assert.equal(countMissingParents(ordered), 0);+});++test("orderParentsFirst handles a long reversed chain without recursion", () => {+ const rows = Array.from({ length: 10_000 }, (_, index) => ({+ id: String(index),+ parentId: index === 0 ? null : String(index - 1),+ })).reverse();+ const ordered = orderParentsFirst(rows);+ assert.equal(ordered.length, rows.length);+ assert.equal(ordered[0]?.id, "0");+ assert.equal(ordered.at(-1)?.id, "9999");+});++test("the fallback head stays on the newest row's branch after reordering", () => {+ const rows = byCreatedAt([+ { id: "root", parentId: null, createdAt: 0, role: "user" },+ { id: "reply", parentId: "edited", createdAt: 1, role: "assistant" },+ { id: "other", parentId: "root", createdAt: 2, role: "assistant" },+ { id: "edited", parentId: "root", createdAt: 3, role: "user" },+ ]);+ const resolveParent = createParentResolver();+ const ordered = orderParentsFirst(+ rows.map((record) => ({+ record,+ id: record.id,+ parentId: resolveParent(record),+ })),+ );+ assert.equal(ordered.at(-1)?.id, "other");+ assert.equal(resolveSavedBranchHead(rows, rows.at(-1)?.id), "reply");+});++test("the saved-branch head resolves to a leaf, so import keeps every reply", () => {+ // mirror the load path through a real repository import.+ const resolveParent = createParentResolver();+ const ordered = orderParentsFirst(+ byCreatedAt(ANOMALOUS).map((m) => ({+ record: m,+ id: m.id,+ parentId: resolveParent(m),+ })),+ );+ // choose leaf R2 because resetHead drops a non-leaf head's descendants.+ const headId = resolveSavedBranchHead(byCreatedAt(ANOMALOUS), "A1");+ assert.equal(headId, "R2");+ const repo = new MessageRepository();+ repo.import({+ headId,+ messages: ordered.map(({ record, parentId }) => ({+ parentId,+ message: threadMessage(record.id, record.role),+ })),+ });+ const present = new Set(repo.export().messages.map((m) => m.message.id));+ for (const row of ANOMALOUS)+ assert.ok(present.has(row.id), `${row.id} was dropped`);+});++test("a missing parent is treated as a root rather than crashing or looping", () => {+ const rows = [+ { id: "orphan", parentId: "gone", createdAt: 1, role: "user" },+ { id: "child", parentId: "orphan", createdAt: 2, role: "assistant" },+ ];+ // ignore missing-parent edges so present parents stay ordered and the walk terminates.+ assert.deepEqual(+ orderParentsFirst(rows).map((r) => r.id),+ ["orphan", "child"],+ );+});diff --git a/studio/frontend/tests/save-temporary-chat.test.ts b/studio/frontend/tests/save-temporary-chat.test.tsindex 5045be44e90..7a2de59e35b 100644--- a/studio/frontend/tests/save-temporary-chat.test.ts+++ b/studio/frontend/tests/save-temporary-chat.test.ts@@ -1,14 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Saving a temporary chat to history. runtime-provider.tsx cannot load under stubs, so the-// ordering helper is run on its own and the rest is pinned on source.+// runtime-provider.tsx cannot load under stubs, so test its ordering helper directly and pin the rest on source.import assert from "node:assert/strict";import { stripTypeScriptTypes } from "node:module";import test from "node:test";import { readSrc } from "./helpers/kit.ts";+import { orderParentsFirst } from "../src/features/chat/utils/message-order.ts";const provider = readSrc("features/chat/runtime-provider.tsx");const storage = readSrc("features/chat/utils/chat-history-storage.ts");@@ -16,9 +16,11 @@ const button = readSrc("features/chat/components/temporary-chat-save.tsx");const page = readSrc("features/chat/chat-page.tsx");type Item = { parentId: string | null; message: { id: string } };+// parentsFirst delegates to dependency-free orderParentsFirst so the isolated scope can use it directly.const parentsFirst = new Function(+ "orderParentsFirst",`${stripTypeScriptTypes(provider.slice(provider.indexOf("function parentsFirst("), provider.indexOf("/** Save a temporary chat to history")))}\nreturn parentsFirst;`,-)() as (items: Item[]) => Item[];+)(orderParentsFirst) as (items: Item[]) => Item[];const item = (id: string, parentId: string | null = null): Item => ({ parentId, message: { id } });const ids = (items: Item[]) => items.map((i) => i.message.id);@@ -30,7 +32,7 @@ function persistBody(): string {}test("every message is saved after its parent, on every branch", () => {- // Two replies to u1 (a regenerate), and a child listed before its parent.+ // the input covers a regenerated reply and a child listed before its parent.const ordered = ids(parentsFirst([item("a2", "u2"), item("u1"), item("a1", "u1"), item("u2", "a1"), item("b1", "u1")]),);