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: stop a reopened chat from saving every replayed event, and let Stop reach it (#12464)
oobaboogac1e5a56fe626
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 41dfc06e2b0..34eac6c25c3 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -90,6 +90,7 @@ import {useChatAudioUpload,useInComparePane,refreshSkillsCatalog,+ stopRecoveredRun,} from "@/features/chat";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import {@@ -7105,6 +7106,9 @@ const ComposerRightControls: FC<{);const isQueueRunning = Boolean(queueEntry);const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);+ const threadRemoteId = useAuiState(+ ({ threadListItem }) => threadListItem.remoteId,+ );// Id and status, not the run: run identity changes on every streamed research delta.const activeResearchRunId = useResearchRunStore((state) =>activeThreadId ? state.latestRunByThreadId[activeThreadId] : undefined,@@ -7162,6 +7166,8 @@ const ComposerRightControls: FC<{return;}if (isQueueRunning) onStopClick?.();+ // A reply replayed after a reload has no adapter run for Cancel to abort.+ stopRecoveredRun(threadRemoteId);};return (<div className="aui-composer-action-wrapper flex shrink-0 items-center gap-1.5">diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex dedbc45cae5..197cd59802b 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -341,6 +341,7 @@ export { pickAndImportChats } from "./utils/import-chats";export { useForkInFlight } from "./utils/fork-in-flight";export { showForkCreatedToast } from "./utils/fork-toast";export { clearAllChats, countAllChats } from "./utils/clear-all-chats";+export { stopRecoveredRun } from "./utils/chat-generation-recovery";export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";export { pasteClipboardFiles } from "./utils/clipboard-files";export {diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex b284a181ca2..0817e5e0f95 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -145,6 +145,10 @@ import {generationChunkCountsTowardTiming,generationChunkHasSubstantiveDelta,generationIsCorroboratedLive,+ generationIsSettled,+ generationReplayMetadata,+ createRecoveryPublishSchedule,+ registerRecoveredRunStop,threadHasDurableGenerationRun,generationNeedsRecovery,requestParsesThinkTags,@@ -230,6 +234,7 @@ import {setActiveBranchReader,} from "./utils/refresh-context-usage";import {+ RUN_CHECKPOINT_INTERVAL_MS,type RunCheckpointScheduler,createRunCheckpointScheduler,} from "./utils/run-checkpoint-scheduler";@@ -1314,6 +1319,7 @@ function scheduleGenerationRecovery(};const runtime = useChatRuntimeStore.getState();runtime.registerThreadServerCancel(threadId, serverCancel);+ const unregisterStop = registerRecoveredRunStop(threadId, serverCancel);runtime.setThreadRunning(threadId, true, {local: true,owner: serverCancel,@@ -1342,21 +1348,23 @@ function scheduleGenerationRecovery(const commit = async (nextMetadata: Record<string, unknown>,running: boolean,+ save = true,) => {currentMetadata = nextMetadata;const content = rebuild();- await saveStoredChatMessage({- id: storedMessage.id,- threadId,- parentId: storedMessage.parentId ?? null,- role: "assistant",- content,- metadata: nextMetadata,- createdAt: storedMessage.createdAt,- }).catch(() => {- // The producer may have committed a newer status between the event and this write. Keep- // following; the terminal publish carries all content.- });+ if (save) {+ await saveStoredChatMessage({+ id: storedMessage.id,+ threadId,+ parentId: storedMessage.parentId ?? null,+ role: "assistant",+ content,+ metadata: nextMetadata,+ createdAt: storedMessage.createdAt,+ }).catch(() => {+ // A newer server status can reject this save; settlement retries with full content.+ });+ }for (const view of views) {if (view.threadListItem().getState().remoteId !== threadId) continue;@@ -1392,6 +1400,7 @@ function scheduleGenerationRecovery(}};+ const schedule = createRecoveryPublishSchedule(RUN_CHECKPOINT_INTERVAL_MS);const publish = async (run: ChatGenerationRun) => {const status = run.status;const runModel = useChatRuntimeStore@@ -1428,8 +1437,18 @@ function scheduleGenerationRecovery(toolCalls: toolNames(rebuild()),});}- await commit(nextMetadata, generationNeedsRecovery(nextMetadata));+ const settled = nextMetadata.generationSettled === true;+ await commit(+ nextMetadata,+ generationNeedsRecovery(nextMetadata),+ schedule.takeSave(settled),+ );};+ const caughtUp = (run: ChatGenerationRun) =>+ schedule.shouldPublish(+ cursor,+ generationIsSettled(run.status, cursor, run.lastEventSeq),+ );try {let lastPublishedStatus = "";@@ -1498,6 +1517,7 @@ function scheduleGenerationRecovery(parseThinkTags: parseThink,};}+ schedule.attach(update.run.lastEventSeq);identityValidated = true;}// Replay from 0 re-delivers already-saved chunks: apply them, but publish nothing.@@ -1539,8 +1559,10 @@ function scheduleGenerationRecovery(currentMetadata,chunk._reasoningDurationMs,);- lastPublishedStatus = update.run.status;- await publish(update.run);+ if (caughtUp(update.run)) {+ lastPublishedStatus = update.run.status;+ await publish(update.run);+ }continue;}if (generationChunkCountsTowardTiming(chunk)) {@@ -1589,10 +1611,14 @@ function scheduleGenerationRecovery(}}const shouldPublish =- (update.event?.type === "chunk" && advanced) ||- update.run.status !== lastPublishedStatus ||- (["cancelled", "completed", "failed"].includes(update.run.status) &&- cursor >= update.run.lastEventSeq);+ caughtUp(update.run) &&+ ((update.event?.type === "chunk" && advanced) ||+ update.run.status !== lastPublishedStatus ||+ generationIsSettled(+ update.run.status,+ cursor,+ update.run.lastEventSeq,+ ));if (shouldPublish) {lastPublishedStatus = update.run.status;await publish(update.run);@@ -1622,6 +1648,14 @@ function scheduleGenerationRecovery(await commit({...currentMetadata,+ // Catch-up can advance content past the last published cursor.+ ...generationReplayMetadata({+ cursor,+ firstChunkAt,+ totalChunks,+ usage: recoveryUsage,+ timings: recoveryTimings,+ }),incomplete: { reason: "interrupted" as const },// The run row may still be non-terminal, so without this marker generationNeedsRecovery stays// true and the next trigger starts another follower. history.load clears it if@@ -1638,6 +1672,7 @@ function scheduleGenerationRecovery(// entries, so a later real approval reads as non-sole and loses its Enter/Escape chords.// Joined first because the arming is no longer awaited at its call site, so without this a// late arm lands after the disarm and leaves the card up on a finished run.+ unregisterStop();if (seededApprovals) await seededApprovals.catch(() => {});toolRecovery.disarmAll();const store = useChatRuntimeStore.getState();diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.tsindex 71dffc6a40a..3f3912d16f6 100644--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts@@ -95,6 +95,36 @@ export function generationIsSettled(return status !== null && TERMINAL.has(status) && cursor >= lastEventSeq;}+/** Publish after catch-up; save at checkpoint intervals and on settlement.+ * Server events remain available to replay any unsaved progress. */+export function createRecoveryPublishSchedule(+ intervalMs: number,+ now: () => number = Date.now,+): {+ /** Set the cursor replay must reach before publishing. */+ attach(lastEventSeq: number): void;+ shouldPublish(cursor: number, settled: boolean): boolean;+ /** Allow a save if due or settled, and record its time. */+ takeSave(settled: boolean): boolean;+} {+ let attachSeq = 0;+ let lastSaveAt = Number.NEGATIVE_INFINITY;+ return {+ attach(lastEventSeq) {+ attachSeq = lastEventSeq;+ },+ shouldPublish(cursor, settled) {+ return settled || cursor >= attachSeq;+ },+ takeSave(settled) {+ const at = now();+ if (!settled && at - lastSaveAt < intervalMs) return false;+ lastSaveAt = at;+ return true;+ },+ };+}+export async function loadGenerationOverlaySnapshot<TMessage, TRun>(threadId: string,listActiveRuns: (id: string) => Promise<TRun[]>,@@ -566,6 +596,32 @@ export function generationNeedsRecovery();}+/** The replay cursor with the state accumulated behind it. The usage chunk arrives before the+ * terminal event, so a cursor saved past it without these resumes after it and loses the token+ * counts and server timings for good. */+export function generationReplayMetadata(state: {+ cursor: number;+ firstChunkAt?: number;+ totalChunks?: number;+ usage?: unknown;+ timings?: unknown;+}): Record<string, unknown> {+ const next: Record<string, unknown> = { generationSeq: state.cursor };+ if (state.firstChunkAt !== undefined) {+ next.generationFirstChunkAt = state.firstChunkAt;+ }+ if (state.totalChunks !== undefined) {+ next.generationChunkCount = state.totalChunks;+ }+ if (state.usage !== undefined) {+ next.generationRecoveryUsage = state.usage;+ }+ if (state.timings !== undefined) {+ next.generationRecoveryTimings = state.timings;+ }+ return next;+}+export function generationRecoveryMetadata(options: {current: Record<string, unknown>;runId: string;@@ -595,8 +651,14 @@ export function generationRecoveryMetadata(options: {const settled = generationIsSettled(status, cursor, lastEventSeq);const next: Record<string, unknown> = {...current,+ ...generationReplayMetadata({+ cursor,+ firstChunkAt,+ totalChunks,+ usage,+ timings,+ }),generationRunId: runId,- generationSeq: cursor,generationStatus: status,generationSettled: settled,serverManaged: true,@@ -615,21 +677,6 @@ export function generationRecoveryMetadata(options: {} else {next.incomplete = { reason: "cancelled" };}- if (firstChunkAt !== undefined) {- next.generationFirstChunkAt = firstChunkAt;- }- if (totalChunks !== undefined) {- next.generationChunkCount = totalChunks;- }- // Carried with the cursor for the same reason as the two above: the usage chunk arrives before- // the terminal event, so a cursor published past it and reloaded would resume after it and- // lose the token counts and server timings for good.- if (usage !== undefined) {- next.generationRecoveryUsage = usage;- }- if (timings !== undefined) {- next.generationRecoveryTimings = timings;- }return next;}@@ -702,6 +749,29 @@ const liveGenerationThreads = new Map<string, string>();* aborted, so the await can outlast the cap. */const provisionalGenerationRuns = new Set<string>();+// Recovered runs need server cancellation because they have no local adapter run.+const recoveredRunStops = new Map<string, () => void>();++/** Register Stop and return cleanup that preserves newer registrations. */+export function registerRecoveredRunStop(+ threadId: string,+ stop: () => void,+): () => void {+ recoveredRunStops.set(threadId, stop);+ return () => {+ if (recoveredRunStops.get(threadId) === stop) {+ recoveredRunStops.delete(threadId);+ }+ };+}++/** Cancel the thread's recovered run; return false if none is registered. */+export function stopRecoveredRun(threadId: string | null | undefined): boolean {+ const stop = threadId ? recoveredRunStops.get(threadId) : undefined;+ stop?.();+ return stop !== undefined;+}+/** Claim a run as streamed by this tab. Pair with `releaseLiveGenerationRun` in a finally. */export function claimLiveGenerationRun(runId: string,diff --git a/studio/frontend/tests/generation-recovery-publish-schedule.test.ts b/studio/frontend/tests/generation-recovery-publish-schedule.test.tsnew file mode 100644index 00000000000..81c6c359fd0--- /dev/null+++ b/studio/frontend/tests/generation-recovery-publish-schedule.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Full scheduler catch-up and settlement are tested in generation-tool-recovery.test.ts.++import assert from "node:assert/strict";+import test from "node:test";++import { readText, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const {+ createRecoveryPublishSchedule,+ generationIsSettled,+ registerRecoveredRunStop,+ stopRecoveredRun,+} = await import("../src/features/chat/utils/chat-generation-recovery.ts");++const INTERVAL_MS = 8_000;++test("a live follow renders every event but saves at checkpoint pace", () => {+ // The live trace: attached with 1,595 events of history, then followed at ~35 events/s for 55 s.+ let clock = 0;+ const schedule = createRecoveryPublishSchedule(INTERVAL_MS, () => clock);+ schedule.attach(1595);+ const events: Array<{+ seq: number;+ status: "running" | "completed";+ lastEventSeq: number;+ at: number;+ }> = [];+ for (let seq = 1; seq <= 1595; seq += 1) {+ events.push({ seq, status: "running", lastEventSeq: 1595, at: 0 });+ }+ for (let seq = 1596; seq <= 3507; seq += 1) {+ const at = Math.round(((seq - 1595) / 1912) * 55_000);+ events.push({ seq, status: "running", lastEventSeq: seq, at });+ }+ events.push({ seq: 3508, status: "completed", lastEventSeq: 3508, at: 55_100 });++ let published = 0;+ const saved: string[] = [];+ for (const event of events) {+ clock = event.at;+ const settled = generationIsSettled(event.status, event.seq, event.lastEventSeq);+ if (!schedule.shouldPublish(event.seq, settled)) continue;+ published += 1;+ if (schedule.takeSave(settled)) saved.push(event.status);+ }++ assert.equal(published, 3508 - 1595 + 1, "history folds, live events all render");+ // One at the live edge, one per elapsed interval, and the settled end.+ assert.ok(saved.length <= Math.ceil(55_100 / INTERVAL_MS) + 2, `saved ${saved.length} times`);+ assert.equal(saved.at(-1), "completed", "the settled end is always saved");+});++test("Stop reaches the run a recovery is replaying, and only while it is", () => {+ const stopped: string[] = [];+ const unregister = registerRecoveredRunStop("thread-a", () => stopped.push("run-1"));+ assert.equal(stopRecoveredRun("thread-b"), false, "another thread's Stop must not cancel it");+ assert.equal(stopRecoveredRun(undefined), false);+ assert.equal(stopRecoveredRun("thread-a"), true);+ assert.deepEqual(stopped, ["run-1"]);++ // Old cleanup must preserve the newer registration.+ const unregisterNewer = registerRecoveredRunStop("thread-a", () => stopped.push("run-2"));+ unregister();+ assert.equal(stopRecoveredRun("thread-a"), true);+ assert.deepEqual(stopped, ["run-1", "run-2"]);+ unregisterNewer();+ assert.equal(stopRecoveredRun("thread-a"), false, "a finished recovery leaves nothing to stop");+});++test("the composer Stop and the recovery are wired to that handle", () => {+ // Inspect wiring directly because this harness cannot mount the composer.+ const provider = readText("../src/features/chat/runtime-provider.tsx");+ const recovery = provider.slice(+ provider.indexOf("function scheduleGenerationRecovery("),+ provider.indexOf("const temporaryThreadCreation"),+ );+ assert.match(recovery, /registerRecoveredRunStop\(threadId, serverCancel\)/);+ assert.match(recovery, /finally \{[\s\S]*?unregisterStop\(\);/);++ const thread = readText("../src/components/assistant-ui/thread.tsx");+ const stop = thread.slice(thread.indexOf(" const stop = () => {"));+ assert.match(stop.slice(0, stop.indexOf("\n };")), /stopRecoveredRun\(threadRemoteId\)/);+});diff --git a/studio/frontend/tests/generation-tool-recovery.test.ts b/studio/frontend/tests/generation-tool-recovery.test.tsindex bc57f13dcfa..7d0f3f6ca1e 100644--- a/studio/frontend/tests/generation-tool-recovery.test.ts+++ b/studio/frontend/tests/generation-tool-recovery.test.ts@@ -20,6 +20,9 @@ const parser = await import(const { createGenerationToolRecovery } = await import("../src/features/chat/utils/generation-tool-recovery.ts");+const { RUN_CHECKPOINT_INTERVAL_MS } = await import(+ "../src/features/chat/utils/run-checkpoint-scheduler.ts"+);const start = (id = "call_0") => ({type: "tool_start",@@ -360,8 +363,11 @@ async function recoverRun(cursor?: number;viewContent?: unknown[];metadata?: Record<string, unknown>;+ /** Stall the follow after the payloads, short of this snapshot lastEventSeq. */+ stallBefore?: number;} = {},) {+ class ChatGenerationStalledError extends Error {}let shown = {messages: [{ message: { id: "msg", content: options.viewContent ?? content } },@@ -389,8 +395,8 @@ async function recoverRun(id: "run",threadId: "thread",assistantMessageId: "msg",- status: "completed",- lastEventSeq: payloads.length,+ status: options.stallBefore ? "running" : "completed",+ lastEventSeq: options.stallBefore ?? payloads.length,requestPayload: { model: "test", session_id: "saved-session" },createdAt: 1,startedAt: 1,@@ -400,6 +406,7 @@ async function recoverRun(...recovery,...parser,createGenerationToolRecovery,+ RUN_CHECKPOINT_INTERVAL_MS,generationRecoveries,useChatRuntimeStore: { getState: () => runtime },cancelChatGenerationRun: async () => {},@@ -425,11 +432,12 @@ async function recoverRun(yield update;yield update;}+ if (options.stallBefore) throw new ChatGenerationStalledError();},restoredAssistantStatus: () => ({ type: "complete", reason: "stop" }),- isTerminalChatGenerationRun: () => true,+ isTerminalChatGenerationRun: () => !options.stallBefore,forgetServerActiveGenerationRun() {},- ChatGenerationStalledError: class extends Error {},+ ChatGenerationStalledError,});vm.runInContext(executable, context);context.scheduleGenerationRecovery(@@ -460,7 +468,9 @@ async function recoverRun(await generationRecoveries.get("run").promise;const final = snapshots.at(-1);assert.ok(final);- assert.equal(final.metadata.generationSettled, true);+ if (!options.stallBefore) {+ assert.equal(final.metadata.generationSettled, true);+ }assert.equal(final.metadata.generationSeq, payloads.length);return {content: final.content,@@ -495,6 +505,42 @@ test("the recovery scheduler persists later tool events between reasoning groups);});+test("reopening a run that finished without the tab saves and renders only its end", async () => {+ // The harness yields every update twice, allowing two settlements; production stops at one.+ const payloads = Array.from({ length: 400 }, (_, index) => ({+ choices: [{ delta: { content: `w${index} ` } }],+ }));+ const text = payloads.map((payload) => payload.choices[0].delta.content).join("");+ const { snapshots, imports } = await recoverRun([], payloads);+ assert.ok(snapshots.length <= 2, `saved ${snapshots.length} times`);+ for (const snapshot of snapshots) {+ assert.equal(snapshot.metadata.generationSettled, true);+ assert.equal(snapshot.content.map((part) => part.text).join(""), text);+ }+ assert.ok(imports.length <= 2, `rendered ${imports.length} times`);+});++test("a follow that stalls during catch-up saves its cursor with the replayed usage", async () => {+ const payloads = [+ { choices: [{ delta: { content: "partial" } }] },+ {+ choices: [],+ usage: { completion_tokens: 7 },+ timings: { predicted_n: 7 },+ },+ ];+ const { snapshots } = await recoverRun([], payloads, { stallBefore: 10 });+ assert.equal(snapshots.length, 1, "nothing is published before catch-up");+ const { metadata, content } = snapshots[0];+ assert.deepEqual(metadata.incomplete, { reason: "interrupted" });+ assert.equal(content.map((part) => part.text).join(""), "partial");+ // A later recovery resumes after seq 2, so the usage chunk must be saved with that cursor.+ assert.deepEqual(metadata.generationRecoveryUsage, { completion_tokens: 7 });+ assert.deepEqual(metadata.generationRecoveryTimings, { predicted_n: 7 });+ assert.equal(metadata.generationChunkCount, 1);+ assert.equal(metadata.generationFirstChunkAt, 1);+});+test("a recovered turn keeps the reasoning cut the backend reported", async () => {// The producer stamps the cut on the saved turn; a settle without it is refused.const { snapshots } = await recoverRun(