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 recovery following a run this tab is already streaming (#9854)

Daniel Hand99cee713974
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 2295941f274..d50edff75bf 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -234,9 +234,11 @@ import {
resumesExactly,
} from "../utils/continuation";
import {
+ claimLiveGenerationRun,
generationChunkCountsTowardTiming,
generationChunkHasSubstantiveDelta,
generationIsSettled,
+ releaseLiveGenerationRun,
} from "../utils/chat-generation-recovery";
import {
generateAudio,
@@ -6108,6 +6110,12 @@ export function createOpenAIStreamAdapter(
generationDecision = "legacy";
} else {
generationDecision = "durable";
+ // Before admission, not after. The run id is ours (`cancelId` is passed as
+ // `runId`), and the run becomes visible through /active as soon as the POST
+ // lands, so a visibility, pageshow, online or history-load trigger during
+ // this await could otherwise start a recovery that the later claim would
+ // not stop: the scheduler only tests ownership at startup.
+ claimLiveGenerationRun(cancelId);
try {
generationRun = await createChatGenerationRunUntilAbort(
{
@@ -6131,6 +6139,9 @@ export function createOpenAIStreamAdapter(
if (generationDecision === "durable") return;
} else {
generationRunId = generationRun.id;
+ // Normally the same id we claimed above; claimed again in case the server
+ // ever echoes a different one. Both are released in the finally below.
+ claimLiveGenerationRun(generationRunId);
generationStatus = generationRun.status;
if (generationStopRequested) {
void cancelChatGenerationRun(generationRun.id).catch(
@@ -7594,6 +7605,10 @@ export function createOpenAIStreamAdapter(
}
throw err;
} finally {
+ // Unconditional, and both ids: the pre-admission claim uses `cancelId`, and a run
+ // left claimed after its stream died is one this tab would never recover.
+ releaseLiveGenerationRun(cancelId);
+ if (generationRunId) releaseLiveGenerationRun(generationRunId);
runSignal.removeEventListener("abort", onAbortCancel);
abortSignal.removeEventListener("abort", forwardAbort);
// Resolve once: the clears below drop the owner the lookup keys on.
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 977b7e2d1af..dac9153d007 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -94,6 +94,7 @@ import {
generationChunkCountsTowardTiming,
generationChunkHasSubstantiveDelta,
generationNeedsRecovery,
+ isLiveGenerationRun,
generationRawContent,
loadGenerationOverlaySnapshot,
recoveredContentToImport,
@@ -743,6 +744,11 @@ function scheduleGenerationRecovery(
const metadata = (storedMessage.metadata ?? {}) as Record<string, unknown>;
const runId = metadata.generationRunId;
if (typeof runId !== "string" || !generationNeedsRecovery(metadata)) return;
+ // This tab is streaming the run itself. Following it from storage as well gives the reply
+ // two writers, and the follower is always behind, so it imports a lagging prefix over the
+ // live text. It also costs a PUT and a full re-parse per chunk against the same backend the
+ // model is saturating.
+ if (isLiveGenerationRun(runId)) return;
const existingRecovery = generationRecoveries.get(runId);
if (existingRecovery) {
existingRecovery.views.add(aui);
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 86a31c22361..101763dcecc 100644
--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
@@ -390,3 +390,44 @@ export function subscribeGenerationRecoveryTriggers(
documentTarget.removeEventListener("visibilitychange", onVisible);
};
}
+
+/**
+ * Runs this tab is streaming itself, so a recovery never follows one of them.
+ *
+ * A durable run otherwise gets TWO readers in the tab that started it. The adapter streams
+ * it, and `scheduleGenerationRecovery` also replays it from storage, because its only gate
+ * is `generationNeedsRecovery(metadata)` and `history.load()` force-writes
+ * `generationSettled: false` onto any message matching an active run. Nothing asks whether
+ * this tab is already the producer.
+ *
+ * That second reader is expensive, not merely redundant. It publishes on EVERY chunk event,
+ * and each publish re-parses the whole reply and awaits a PUT of the entire message, so a
+ * reply of N chunks costs N round trips and N full parses whose payload grows with the
+ * reply: quadratic in the length of the answer, on the main thread, against the same backend
+ * the model is saturating.
+ *
+ * Module state, deliberately. A reload is exactly the case where this tab has STOPPED being
+ * the producer and a recovery should run, and a reload clears this by construction. Nothing
+ * needs to expire it.
+ */
+const liveGenerationRuns = new Set<string>();
+
+/** Claim a run as streamed by this tab. Pair with `releaseLiveGenerationRun` in a finally. */
+export function claimLiveGenerationRun(runId: string): void {
+ liveGenerationRuns.add(runId);
+}
+
+/**
+ * Release a run this tab was streaming.
+ *
+ * Must be unconditional, in a finally: a run left claimed after its stream died is a run this
+ * tab will never recover, which is the failure this registry could introduce if it leaked.
+ */
+export function releaseLiveGenerationRun(runId: string): void {
+ liveGenerationRuns.delete(runId);
+}
+
+/** Whether this tab is the one streaming `runId`. */
+export function isLiveGenerationRun(runId: string): boolean {
+ return liveGenerationRuns.has(runId);
+}
diff --git a/studio/frontend/tests/generation-recovery-own-run.test.ts b/studio/frontend/tests/generation-recovery-own-run.test.ts
new file mode 100644
index 00000000000..8914d629658
--- /dev/null
+++ b/studio/frontend/tests/generation-recovery-own-run.test.ts
@@ -0,0 +1,116 @@
+// 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 run gets TWO readers in the tab that started it: the adapter streaming it, and
+// `scheduleGenerationRecovery` replaying the same run from storage. Its only gate is
+// `generationNeedsRecovery(metadata)`, and `history.load()` force-writes
+// `generationSettled: false` onto any message matching an active run, so nothing ever asks
+// whether this tab is already the producer.
+//
+// The visible cost is the reasoning pane flicker: the follower is always behind, so it imports
+// a lagging prefix over the live reply. The unseen cost is larger. The follower publishes on
+// EVERY chunk event and each publish re-parses the whole reply and awaits a PUT of the entire
+// message, so a reply of N chunks costs N round trips whose payload grows with the reply.
+//
+// These pin the ownership registry that stops it, and the leak that would be its own failure
+// mode: a run left claimed is a run this tab can never recover.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const {
+ claimLiveGenerationRun,
+ isLiveGenerationRun,
+ releaseLiveGenerationRun,
+} = await import("../src/features/chat/utils/chat-generation-recovery.ts");
+
+const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");
+
+test("a claimed run is reported as this tab's, and a released one is not", () => {
+ assert.equal(isLiveGenerationRun("run-a"), false);
+ claimLiveGenerationRun("run-a");
+ assert.equal(isLiveGenerationRun("run-a"), true);
+ releaseLiveGenerationRun("run-a");
+ assert.equal(
+ isLiveGenerationRun("run-a"),
+ false,
+ "a released run must be recoverable again, or a dead stream strands it forever",
+ );
+});
+
+test("releasing a run that was never claimed is not an error", () => {
+ // The adapter releases in a finally that also runs on paths where no durable run was ever
+ // created, so this has to be a no-op rather than a throw.
+ releaseLiveGenerationRun("never-claimed");
+ assert.equal(isLiveGenerationRun("never-claimed"), false);
+});
+
+test("runs are tracked independently", () => {
+ claimLiveGenerationRun("run-b");
+ claimLiveGenerationRun("run-c");
+ releaseLiveGenerationRun("run-b");
+ assert.equal(isLiveGenerationRun("run-b"), false);
+ assert.equal(isLiveGenerationRun("run-c"), true, "releasing one run must not free another");
+ releaseLiveGenerationRun("run-c");
+});
+
+test("the recovery scheduler refuses a run this tab is streaming", () => {
+ // Source-pinned: scheduleGenerationRecovery is not reachable from a test (it needs a live
+ // aui view and the store), so the guard is asserted where it sits. It must come BEFORE the
+ // scheduler registers itself as running, or the early return is unreachable.
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ const guard = provider.indexOf("if (isLiveGenerationRun(runId)) return;");
+ const register = provider.indexOf("runtime.registerThreadServerCancel(threadId, serverCancel)");
+
+ assert.ok(guard > 0, "the ownership guard is gone; the follower will race the adapter again");
+ assert.ok(register > 0);
+ assert.ok(guard < register, "the guard must precede the scheduler taking ownership");
+});
+
+test("the adapter claims the run BEFORE admission, not after the response", () => {
+ // The create POST is awaited, and the run is visible through /active as soon as it lands.
+ // A claim that waits for the response leaves that whole round trip open: a visibility,
+ // pageshow, online or history-load trigger can start a recovery inside it, and the later
+ // claim does not stop one already running, because the scheduler only tests ownership at
+ // startup. The run id is the client's own (`cancelId` is passed as `runId`), so there is no
+ // reason to wait for the server to hand it back.
+ const adapter = read("../src/features/chat/api/chat-adapter.ts");
+ const claim = adapter.indexOf("claimLiveGenerationRun(cancelId)");
+ const admission = adapter.indexOf("generationRun = await createChatGenerationRunUntilAbort(");
+
+ assert.ok(claim > 0, "nothing claims the run before admission");
+ assert.ok(admission > 0);
+ assert.ok(
+ claim < admission,
+ "the claim must precede the create POST, or the round trip is an open window",
+ );
+ // And the pre-admission id has to be released too, or a failed admission strands it.
+ assert.ok(
+ adapter.includes("releaseLiveGenerationRun(cancelId)"),
+ "the pre-admission claim is never released; a failed admission would strand the run",
+ );
+});
+
+test("the adapter claims the run and releases it in a finally", () => {
+ const adapter = read("../src/features/chat/api/chat-adapter.ts");
+
+ assert.ok(
+ adapter.includes("claimLiveGenerationRun(generationRunId)"),
+ "nothing claims the run, so the guard above can never fire",
+ );
+ // The release has to be inside a finally. Without that, an aborted or failed stream leaves
+ // the run claimed and this tab stops being able to recover it at all, which is worse than
+ // the defect being fixed.
+ const release = adapter.indexOf("releaseLiveGenerationRun(generationRunId)");
+ assert.ok(release > 0);
+ const before = adapter.slice(0, release);
+ assert.ok(
+ before.lastIndexOf("} finally {") > before.lastIndexOf("} catch ("),
+ "the release must sit in a finally, not on the success path",
+ );
+});