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 resumed turn retracting text it already streamed (#9851)

Daniel Han0d30cabb2616
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 5862a5b54d5..2295941f274 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -226,8 +226,8 @@ import type { CachedGgufRepo, CachedModelRepo } from "./chat-api";
import {
budgetImpliesTruncation,
CONTINUE_INSTRUCTION,
+ createContinuationMerger,
type IncompleteReason,
- joinContinuation,
readIncompleteInfo,
readContinuationRequest,
rejectsAssistantPrefill,
@@ -5191,18 +5191,20 @@ export function createOpenAIStreamAdapter(
// is for providers that may ignore the prefill and repeat or restart.
const repairContinuation =
isExternalRequest && !resumesExactly(externalProvider?.providerType);
- const mergeContinuation = (text: string): string =>
- continuationPartial && repairContinuation
- ? joinContinuation(
- continuationPartial,
- text.slice(continuationPartial.length),
- )
- : text;
+ // Streamed publishes get the cumulative text unchanged; the repairs run once, on
+ // the finished turn. Both of them re-decide as the continuation grows, so running
+ // them per arrival published a SHORTER text than the arrival before it, and the
+ // restart branch published only the continuation, dropping the whole partial the
+ // reader was already looking at.
+ const mergeContinuation = createContinuationMerger(
+ continuationPartial,
+ repairContinuation,
+ );
// The parse of everything already streamed, extended by each delta.
- // `mergeContinuation` can rewrite the prefix it is handed, and a rewritten
- // prefix is exactly what an extend-only parse cannot follow, so that one
- // path keeps reparsing the whole reply as before. It is a continuation of
- // an external provider that may repeat itself, not the streaming case.
+ // The final merge can rewrite the prefix it is handed, and a rewritten prefix is
+ // exactly what an extend-only parse cannot follow, so that one path keeps
+ // reparsing the whole reply as before. It is a continuation of an external
+ // provider that may repeat itself, not the streaming case.
const segmentedText = createSegmentedAssistantText({
trustAppends: !(continuationPartial && repairContinuation),
});
@@ -7344,7 +7346,7 @@ export function createOpenAIStreamAdapter(
) {
// Rendered parts, not the raw stream: `cumulativeText` carries <think>.
const answerText = answerTextFromParts(
- buildAssistantContent(mergeContinuation(cumulativeText)),
+ buildAssistantContent(mergeContinuation(cumulativeText, { final: true })),
);
const subjects = missingListSubjects(answerText, toolCallParts);
if (subjects.length > 0) {
@@ -7422,7 +7424,7 @@ export function createOpenAIStreamAdapter(
reasoningDurationTracker.finishGroup();
yield {
content: [
- ...buildAssistantContent(mergeContinuation(cumulativeText)),
+ ...buildAssistantContent(mergeContinuation(cumulativeText, { final: true })),
...sourceParts,
...documentCitationParts,
],
@@ -7555,7 +7557,7 @@ export function createOpenAIStreamAdapter(
}
if (!abortSignal.aborted) {
closeReasoningContent();
- const partialText = mergeContinuation(cumulativeText);
+ const partialText = mergeContinuation(cumulativeText, { final: true });
const partialContent = buildAssistantContent(partialText);
if (partialContent.length > 0) {
const partialTiming = buildTiming(
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index b588bea9193..0cf0c8acd1d 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -141,6 +141,50 @@ export function joinContinuation(
return `${partial}${stripContinuationOverlap(partial, continuation)}`;
}
+/**
+ * The merge a resumed turn applies to its cumulative text, streaming and at the end.
+ *
+ * The bug this fixes is `isRestart` running per arrival. It cannot fire until the continuation
+ * reaches RESTART_PROBE characters, and the moment it does it publishes the continuation ALONE.
+ * Over a 1602-character partial that took the value from 1649 characters to 48 in one arrival,
+ * measured character by character. That is not only a visible collapse: Stop persists the last
+ * STREAMED yield, because assistant-ui drops what a run yields after an abort and the terminal
+ * merge sits behind `!abortSignal.aborted`, so stopping in that window SAVED the 48 characters
+ * and discarded the whole partial the user was reading.
+ *
+ * `streaming` exists for exactly this and production never passed it. It suppresses the restart
+ * check, which needs more text than early chunks carry, and leaves the overlap trim, which only
+ * ever removes text the continuation itself repeated. So a streamed merge keeps the partial and
+ * the new text, always, and a genuine restart is collapsed once at the end where the evidence
+ * for it is complete.
+ *
+ * Two things were tried first and are recorded because both were worse:
+ *
+ * * repairing ONLY at the end. That saves `partial + repeated tail` on Stop, so a Continue
+ * built on it replays the duplicate. It swapped a display bug for a stored one.
+ * * holding the partial until the trim could no longer change (at `min(partial.length,
+ * MAX_OVERLAP)`). Monotonic, but Stop inside that window persisted the STALE PARTIAL and
+ * discarded every newly generated character, which is worse than either.
+ *
+ * The overlap trim can still shift the join by up to MAX_OVERLAP characters as a longer overlap
+ * starts matching, so a publish is not strictly monotonic. That is bounded, rare, confined to
+ * external-provider continuations, and never loses text. It is deliberately not worth holding
+ * generated output back to avoid.
+ */
+export function createContinuationMerger(
+ partial: string,
+ repair: boolean,
+): (cumulative: string, options?: { final?: boolean }) => string {
+ return (cumulative, { final = false } = {}) => {
+ if (!partial || !repair) {
+ return cumulative;
+ }
+ return joinContinuation(partial, cumulative.slice(partial.length), {
+ streaming: !final,
+ });
+ };
+}
+
/**
* Whether a finished MLX turn used its whole budget, i.e. stopped for length.
*
diff --git a/studio/frontend/tests/chat-adapter-scan-cost.test.ts b/studio/frontend/tests/chat-adapter-scan-cost.test.ts
index aa899447c10..312bf3b3665 100644
--- a/studio/frontend/tests/chat-adapter-scan-cost.test.ts
+++ b/studio/frontend/tests/chat-adapter-scan-cost.test.ts
@@ -602,8 +602,14 @@ test("the trailing strip runs on the finished reply, not on every arrival", () =
true,
"the strip must sit after the SSE loop, not inside it",
);
+ // Pinned as a prefix, deliberately. What this test is about is WHERE the final
+ // build sits relative to the strip, not how the merge is spelled, and pinning the
+ // closing parens made it fail the first time an argument was added to
+ // `mergeContinuation` even though the ordering it guards was untouched. A pin that
+ // breaks on unrelated edits gets "fixed" by re-pinning, and one of those days it
+ // gets re-pinned past a real reordering.
const finalBuild = source.indexOf(
- "buildAssistantContent(mergeContinuation(cumulativeText))",
+ "buildAssistantContent(mergeContinuation(cumulativeText",
strip,
);
assert.equal(
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index 5eedd12cf6f..4bc90008edb 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -1924,3 +1924,137 @@ test("the gate's pulse is tagged where it is fired and read where it matters", (
"a deadline here is the arming timeout coming back, which lapses live continuations",
);
});
+
+// The live streaming publish path used to run the restart check on every arrival.
+//
+// `isRestart` cannot fire until the continuation reaches 48 characters, and the moment it
+// does it publishes the continuation ALONE. Over a 1602-character partial that took the
+// published value from 1649 characters to 48 in a single arrival.
+//
+// That is not just a visible collapse. Stop persists the last STREAMED yield, because
+// assistant-ui drops what a run yields after an abort and the terminal merge sits behind
+// `!abortSignal.aborted`. So stopping in that window SAVED the 48 characters and threw away
+// the whole partial the user was reading.
+//
+// `joinContinuation`'s `streaming` option exists precisely to suppress that check, and
+// production never passed it. These pin the property that actually matters here, which is not
+// monotonicity but TEXT PRESERVATION: no streamed publish may drop the partial, and none may
+// withhold what the model has generated.
+
+const { createContinuationMerger } = await import(
+ "../src/features/chat/utils/continuation.ts"
+);
+
+const REASONING =
+ "Okay, so the user is asking about how to structure the migration. " +
+ "Let me think through this carefully step by step before answering. " +
+ "First I need to consider what the existing schema looks like, and " +
+ "whether an online migration is even possible given the constraints. ";
+
+/** Replay a stream one character at a time, collecting what each arrival would publish. */
+function replay(partial: string, tail: string): string[] {
+ const merge = createContinuationMerger(partial, true);
+ const published: string[] = [];
+ let cumulative = partial;
+ published.push(merge(cumulative));
+ for (const character of tail) {
+ cumulative += character;
+ published.push(merge(cumulative));
+ }
+ return published;
+}
+
+test("a restart mid-stream never discards the partial", () => {
+ // The original defect, and the one that loses data: Stop here persisted 48 characters.
+ const partial = REASONING.repeat(6);
+ const published = replay(partial, `${REASONING}and so on. `.repeat(2));
+
+ for (const value of published) {
+ assert.equal(
+ value.startsWith(partial),
+ true,
+ "a streamed publish dropped the partial, so Stop would save only the restart",
+ );
+ }
+});
+
+test("no streamed publish withholds generated text", () => {
+ // The failure mode of holding the partial back until the repair settles: Stop inside that
+ // window saves the stale partial and every new character is lost.
+ const partial = REASONING.repeat(6);
+ const tail = "The second consideration is throughput, which matters here. ";
+ const published = replay(partial, tail);
+ const last = published[published.length - 1];
+
+ assert.equal(last, `${partial}${tail}`, "the new text must be present in the live value");
+ assert.equal(
+ published[10].length > partial.length,
+ true,
+ "text generated early must appear early, not wait for a settle point",
+ );
+});
+
+test("what Stop would save mid-stream carries the overlap repair", () => {
+ // The failure mode of repairing only at the end: the duplicated tail reaches storage.
+ const partial = REASONING.repeat(6);
+ const repeated = partial.slice(-60);
+ const published = replay(partial, `${repeated}and then it continues onward. `);
+ const saved = published[published.length - 1];
+
+ assert.equal(
+ saved.includes(`${repeated}${repeated}`),
+ false,
+ "the repeated tail survived into the value Stop persists",
+ );
+ assert.equal(saved.startsWith(partial), true, "the partial itself must be intact");
+});
+
+test("the join can shift by the overlap, and never by more", () => {
+ // Honest about what is NOT fixed. A longer overlap starting to match rewrites the join, so
+ // the published length can dip. It is bounded by MAX_OVERLAP and never loses text, which is
+ // why it is not worth holding output back to avoid.
+ const partial = REASONING.repeat(6);
+ const published = replay(
+ partial,
+ `${partial.slice(-60)}and then it continues onward from there. `,
+ );
+
+ let worst = 0;
+ for (let i = 1; i < published.length; i += 1) {
+ worst = Math.max(worst, published[i - 1].length - published[i].length);
+ }
+ assert.equal(worst <= 400, true, `the join shifted by ${worst}, beyond MAX_OVERLAP`);
+});
+
+test("the final merge still collapses a genuine restart", () => {
+ const partial = REASONING.repeat(6);
+ const restart = `${REASONING}and so on. `;
+ assert.equal(
+ createContinuationMerger(partial, true)(partial + restart, { final: true }),
+ restart,
+ "a restart is collapsed once the turn is complete and the evidence is in",
+ );
+});
+
+test("a short partial with a whitespace-led restart is not collapsed mid-stream", () => {
+ // `isRestart` calls trimStart(), so a leading newline shifts when it can fire. With the
+ // restart check off while streaming, that timing cannot produce a mid-stream collapse.
+ const partial = "Sure, here is a plan for the migration you asked me about.";
+ const merge = createContinuationMerger(partial, true);
+ const restart = `\n${partial}`;
+
+ assert.equal(
+ merge(`${partial}${restart}`).startsWith(partial),
+ true,
+ "the partial must survive a whitespace-led restart while streaming",
+ );
+});
+
+test("a merger with repair off is the identity, streaming or final", () => {
+ // Local backends resume at the exact token boundary, so nothing may be trimmed.
+ const partial = REASONING.repeat(2);
+ const merge = createContinuationMerger(partial, false);
+ const full = `${partial}${REASONING}`;
+ assert.equal(merge(full), full);
+ assert.equal(merge(full, { final: true }), full);
+});