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.

Stop a generation recovery rewinding the reply it is following (#9853)

Daniel Hand5996dd1be2c
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index b1dc511e800..977b7e2d1af 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -94,7 +94,9 @@ import {
generationChunkCountsTowardTiming,
generationChunkHasSubstantiveDelta,
generationNeedsRecovery,
+ generationRawContent,
loadGenerationOverlaySnapshot,
+ recoveredContentToImport,
recoveredReasoningSummaryMetadata,
recoveredGenerationFinalMetadata,
generationRecoveryMetadata,
@@ -733,33 +735,6 @@ type GenerationRecovery = {
const generationRecoveries = new Map<string, GenerationRecovery>();
-function generationRawContent(content: MessageRecord["content"]): {
- raw: string;
- reasoningOpen: boolean;
-} {
- if (typeof content === "string") {
- return { raw: content, reasoningOpen: false };
- }
- if (!Array.isArray(content)) return { raw: "", reasoningOpen: false };
- let raw = "";
- let reasoningOpen = false;
- for (const part of content) {
- if (!part || typeof part !== "object") continue;
- const record = part as { type?: string; text?: unknown };
- const text = typeof record.text === "string" ? record.text : "";
- if (record.type === "reasoning") {
- if (reasoningOpen) raw += text;
- else raw += `<think>${text}`;
- reasoningOpen = true;
- } else if (record.type === "text") {
- if (reasoningOpen) raw += "</think>";
- raw += text;
- reasoningOpen = false;
- }
- }
- return { raw, reasoningOpen };
-}
-
function scheduleGenerationRecovery(
threadId: string,
storedMessage: MessageRecord,
@@ -871,7 +846,14 @@ function scheduleGenerationRecovery(
...item,
message: {
...item.message,
- content,
+ // The status and the metadata are always this publish's:
+ // they are what the recovery is following the run FOR. The
+ // body is not, because a run this tab is also streaming is
+ // replayed hundreds of characters behind the live reply.
+ content: recoveredContentToImport(
+ item.message.content,
+ content,
+ ),
status: generationNeedsRecovery(nextMetadata)
? { type: "running" as const }
: restoredAssistantStatus({ custom: nextMetadata }),
diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
index 537f6115d76..86a31c22361 100644
--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
@@ -205,6 +205,70 @@ export function recoveredGenerationFinalMetadata(options: {
return next;
}
+/**
+ * The reply as one string, with reasoning back inside `<think>` tags.
+ *
+ * The recovery follows a run by replaying its chunk events, so it keeps the
+ * reply as the text those chunks carried rather than as parts. This is the
+ * inverse of `parseAssistantContent`, and it is what lets a body that arrived
+ * as parts be compared against one that arrived as deltas.
+ */
+export function generationRawContent(content: unknown): {
+ raw: string;
+ reasoningOpen: boolean;
+} {
+ if (typeof content === "string") {
+ return { raw: content, reasoningOpen: false };
+ }
+ if (!Array.isArray(content)) return { raw: "", reasoningOpen: false };
+ let raw = "";
+ let reasoningOpen = false;
+ for (const part of content) {
+ if (!part || typeof part !== "object") continue;
+ const record = part as { type?: string; text?: unknown };
+ const text = typeof record.text === "string" ? record.text : "";
+ if (record.type === "reasoning") {
+ if (reasoningOpen) raw += text;
+ else raw += `<think>${text}`;
+ reasoningOpen = true;
+ } else if (record.type === "text") {
+ if (reasoningOpen) raw += "</think>";
+ raw += text;
+ reasoningOpen = false;
+ }
+ }
+ return { raw, reasoningOpen };
+}
+
+/**
+ * Which body a recovery publish should put in front of the reader.
+ *
+ * A recovery replays the run's events from the cursor the last save recorded,
+ * one publish per event, each publish paying a write to storage before the
+ * next event is read. When the run being replayed is the one this tab is also
+ * streaming, that walk is orders of magnitude behind the live stream, so its
+ * body is a PREFIX of what the reader is already looking at. Importing it
+ * rewinds the reply to its opening lines until the adapter's next yield
+ * restores it, which is the reasoning pane collapsing and recovering about
+ * twice a second.
+ *
+ * Prefix, not length: a body that genuinely disagrees with the view is the
+ * server's and still wins, because storage is authoritative for everything a
+ * recovery exists to repair. Only a body that carries nothing the view is not
+ * already showing is refused.
+ */
+export function recoveredContentToImport<TContent>(
+ viewContent: TContent,
+ recoveredContent: TContent,
+): TContent {
+ const view = generationRawContent(viewContent).raw;
+ const recovered = generationRawContent(recoveredContent).raw;
+ if (recovered.length < view.length && view.startsWith(recovered)) {
+ return viewContent;
+ }
+ return recoveredContent;
+}
+
export function generationNeedsRecovery(
metadata: Record<string, unknown>,
): boolean {
diff --git a/studio/frontend/tests/generation-recovery-import-call-site.test.ts b/studio/frontend/tests/generation-recovery-import-call-site.test.ts
new file mode 100644
index 00000000000..464819debe7
--- /dev/null
+++ b/studio/frontend/tests/generation-recovery-import-call-site.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
+
+// generation-recovery-monotonic.test.ts holds the rule. This holds the wiring,
+// because the rule is enforced at exactly one place: the object a recovery
+// publish hands to `view.thread().import`. Deleting the call there restores the
+// rewind while leaving every behavioural test green, so the call site is pinned
+// rather than trusted.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+const SOURCE = fileURLToPath(
+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),
+);
+
+const parsed = ts.createSourceFile(
+ "runtime-provider.tsx",
+ readFileSync(SOURCE, "utf8"),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+);
+
+const findRecoveryFunction = (): ts.FunctionDeclaration | null => {
+ let found: ts.FunctionDeclaration | null = null;
+ const walk = (node: ts.Node): void => {
+ if (
+ ts.isFunctionDeclaration(node) &&
+ node.name?.text === "scheduleGenerationRecovery"
+ ) {
+ found = node;
+ return;
+ }
+ ts.forEachChild(node, walk);
+ };
+ walk(parsed);
+ return found;
+};
+
+const propertyName = (property: ts.ObjectLiteralElementLike): string => {
+ const name = property.name;
+ return name !== undefined && ts.isIdentifier(name) ? name.text : "";
+};
+
+/**
+ * The object literals the publish builds for the thread import: the ones that
+ * set both a `content` and a `status`, which is the message body swap.
+ */
+const publishedMessageObjects = (
+ root: ts.Node,
+): ts.ObjectLiteralExpression[] => {
+ const objects: ts.ObjectLiteralExpression[] = [];
+ const walk = (node: ts.Node): void => {
+ if (ts.isObjectLiteralExpression(node)) {
+ const names = node.properties.map(propertyName);
+ if (names.includes("content") && names.includes("status")) {
+ objects.push(node);
+ }
+ }
+ ts.forEachChild(node, walk);
+ };
+ walk(root);
+ return objects;
+};
+
+test("the recovery publish swaps the body through the monotonicity guard", () => {
+ const recovery = findRecoveryFunction();
+ assert.ok(recovery, "scheduleGenerationRecovery was not found");
+ const objects = publishedMessageObjects(recovery);
+ assert.equal(
+ objects.length,
+ 1,
+ "expected exactly one published message body in the recovery",
+ );
+
+ const content = objects[0].properties.find(
+ (property) =>
+ ts.isPropertyAssignment(property) &&
+ ts.isIdentifier(property.name) &&
+ property.name.text === "content",
+ );
+ assert.ok(
+ content && ts.isPropertyAssignment(content),
+ "the published body must assign `content` rather than pass it through",
+ );
+
+ const initializer = content.initializer;
+ assert.ok(
+ ts.isCallExpression(initializer) &&
+ ts.isIdentifier(initializer.expression) &&
+ initializer.expression.text === "recoveredContentToImport",
+ "`content` must come from recoveredContentToImport, or the recovery can rewind the reply again",
+ );
+ assert.equal(
+ initializer.arguments.length,
+ 2,
+ "recoveredContentToImport takes the view's body first, then the recovered one",
+ );
+ assert.equal(
+ initializer.arguments[0].getText(parsed),
+ "item.message.content",
+ "the view's own body must be the first argument",
+ );
+});
diff --git a/studio/frontend/tests/generation-recovery-monotonic.test.ts b/studio/frontend/tests/generation-recovery-monotonic.test.ts
new file mode 100644
index 00000000000..bfb0ff6777f
--- /dev/null
+++ b/studio/frontend/tests/generation-recovery-monotonic.test.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A durable generation run has two readers while the tab that started it is
+// still streaming: the adapter, which publishes the whole reply about once per
+// animation frame, and the recovery follower, which replays the run's stored
+// events and pays a write to storage before it reads the next one. The follower
+// is therefore hundreds of characters behind, and its publish used to be
+// imported into the thread unconditionally, so the reasoning pane rewound to
+// its opening lines for the frame or two before the next adapter yield.
+//
+// The trace below is the one from the report: "Create a detailed SVG image of a
+// cute kitten", reasoning only, no tool calls, no continuation.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { generationRawContent, recoveredContentToImport } = await import(
+ "../src/features/chat/utils/chat-generation-recovery.ts"
+);
+const { parseAssistantContent } = await import(
+ "../src/features/chat/utils/parse-assistant-content.ts"
+);
+
+const PARAGRAPHS = [
+ "The user wants a detailed SVG image of a cute kitten. I should create a rich, crafted SVG, not a trivial circle-cat. Let me design a sitting kitten with fur texture, big eyes, whiskers, tabby markings, gradients, shading, maybe a soft background scene.",
+ "Let me think about composition: a seated kitten facing viewer, three-quarter view. Big glossy eyes, pink nose, whiskers, inner ear pink, small front paws, tail curled around the body, and a soft ground shadow beneath it.",
+ "Canvas: viewBox 0 0 800 800. Body: an egg shape centred around (400, 520), width about 300, height about 300. Head: a circle at (400, 300) with radius 150, slightly flattened at the top.",
+ "Ears: triangles with rounded tips at roughly (280, 190) and (520, 190). Inner ear in a warmer pink, inset about 18 units and shorter, so the fur edge reads.",
+ "Eyes: two ellipses at (340, 300) and (460, 300), rx 42 ry 48. Iris in green with a radial gradient, pupil a vertical slit, two white highlights.",
+];
+const TRACE = PARAGRAPHS.join("\n\n");
+
+/** What the adapter yields once `chars` of the trace have arrived. */
+const liveContent = (chars: number) =>
+ parseAssistantContent(`<think>${TRACE.slice(0, chars)}`);
+
+/**
+ * What a recovery publish carries once its replay has reached `chars`. It
+ * closes the block it is inside, exactly as `publish` does before it parses.
+ */
+const recoveredContent = (chars: number) =>
+ parseAssistantContent(`<think>${TRACE.slice(0, chars)}</think>`);
+
+const reasoningLength = (content: unknown): number => {
+ if (!Array.isArray(content)) {
+ return 0;
+ }
+ let total = 0;
+ for (const part of content) {
+ if (part && typeof part === "object" && part.type === "reasoning") {
+ total += String(part.text ?? "").length;
+ }
+ }
+ return total;
+};
+
+test("a recovery publish behind the live reply leaves the view alone", () => {
+ // The frame the report caught: the reader is eleven paragraphs in, the
+ // follower has replayed 323 characters.
+ const view = liveContent(2400);
+ const recovered = recoveredContent(323);
+ assert.equal(recoveredContentToImport(view, recovered), view);
+});
+
+test("reasoning never goes backwards across an interleaved run", () => {
+ // One recovery publish per twenty-eight adapter yields, which is the ratio a
+ // ~500 ms storage round trip has against a per-frame publish. The follower
+ // advances one replayed chunk each time, as the recording's episodes do.
+ let shown: unknown = [];
+ const lengths: number[] = [];
+ let replayed = 0;
+ let yields = 0;
+ for (let live = 40; live <= TRACE.length; live += 40) {
+ shown = liveContent(live);
+ lengths.push(reasoningLength(shown));
+ yields += 1;
+ if (yields % 4 === 0) {
+ replayed += 6;
+ shown = recoveredContentToImport(shown, recoveredContent(replayed));
+ lengths.push(reasoningLength(shown));
+ }
+ }
+ assert.ok(replayed > 0, "the run must actually publish a recovery body");
+ assert.ok(
+ replayed < TRACE.length,
+ "the follower must stay behind, or there is nothing to test",
+ );
+ for (let i = 1; i < lengths.length; i += 1) {
+ assert.ok(
+ lengths[i] >= lengths[i - 1],
+ `reasoning shrank from ${lengths[i - 1]} to ${lengths[i]} at step ${i}`,
+ );
+ }
+});
+
+test("a recovery ahead of the view still wins", () => {
+ // The case the follower exists for: a reload left the thread holding the last
+ // saved prefix and the run kept going on the server.
+ const view = liveContent(200);
+ const recovered = recoveredContent(2400);
+ assert.equal(recoveredContentToImport(view, recovered), recovered);
+});
+
+test("an empty view takes the recovered body", () => {
+ const recovered = recoveredContent(900);
+ assert.equal(recoveredContentToImport([], recovered), recovered);
+});
+
+test("a recovered body that disagrees with the view still wins", () => {
+ // Not a prefix, so storage is repairing something rather than lagging. Shorter
+ // than the view and still imported.
+ const view = liveContent(2400);
+ const recovered = parseAssistantContent(
+ "<think>The server recorded a different reply for this run.</think>",
+ );
+ assert.equal(recoveredContentToImport(view, recovered), recovered);
+});
+
+test("an equal body is still imported, so metadata-only publishes land", () => {
+ const view = liveContent(900);
+ const recovered = liveContent(900);
+ assert.equal(recoveredContentToImport(view, recovered), recovered);
+});
+
+test("the comparison reads tool calls as neither text nor reasoning", () => {
+ // A view carrying a tool-call part must not read as longer than the same
+ // reply without one, or a live view would be preferred for the wrong reason.
+ const withTool = [
+ { type: "reasoning", text: TRACE.slice(0, 100) },
+ { type: "tool-call", toolCallId: "call_0", toolName: "search", args: {} },
+ ];
+ assert.equal(
+ generationRawContent(withTool).raw,
+ `<think>${TRACE.slice(0, 100)}`,
+ );
+});