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: strip the trailing template placeholder once, on the finished reply (#9101)
Daniel Han2d8e0a00f79a
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 42a021d816d..ebfb22b65b5 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -4689,6 +4689,12 @@ export function createOpenAIStreamAdapter(// What the cap is measured against: only grows, unlike cumulativeText,// and counts tool-argument deltas, which never reach it.let streamedChars = 0;+ // Whether this run appended reply text of its own. A continuation is+ // SEEDED with the previous run's partial, and that partial is the middle+ // of a reply someone is still writing rather than the end of a finished+ // one, so a run that adds nothing to it must not have its tail trimmed.+ // Read by the trailing-fragment strip after the stream.+ let producedReplyText = false;const continuationPartial = continuation?.partial ?? "";// Local backends (and a self-hosted vLLM / llama-server, which get the flags)// resume at the exact token boundary, so their output is already the rest of the@@ -6344,7 +6350,7 @@ export function createOpenAIStreamAdapter(if (!delta && !reasoning) {continue;}- // So the strip below can be told from a chunk that added nothing.+ // So a chunk that added nothing can be told from one that did.const textLenBeforeChunk = cumulativeText.length;if (waitingFirstChunk) {waitingFirstChunk = false;@@ -6369,24 +6375,11 @@ export function createOpenAIStreamAdapter(appendCumulative(delta);}streamedChars += reasoning.length + delta.length;- // Strip a trailing ${...} template-literal fragment from- // external streams (mistral magistral occasionally emits one).- // The watch answers from the deltas whether a fragment could be- // sitting at the end, so the scan itself, which has to touch the- // buffer and therefore flatten the whole reply, runs only on an- // arrival that ends in one. It never says no when the scan would- // cut, so nothing that used to be stripped survives.- if (isExternalRequest && placeholderWatch.isCandidate()) {- const stripped =- stripTrailingTemplatePlaceholder(cumulativeText);- if (stripped.length !== cumulativeText.length) {- cumulativeText = stripped;- // A suffix went away, so both trackers have to be told; the- // parse notices by itself, from the length.- thinkTags.retract(cumulativeText);- placeholderWatch.retract(cumulativeText);- }- }+ producedReplyText = true;+ // The trailing ${...} strip used to run here, once per arrival.+ // It now runs once, on the finished reply, below the loop. See+ // the comment there. Nothing on this path reads the buffer any+ // more, so no arrival can flatten it.const textEndsInsideThink = thinkTags.endsInsideThink();const assistantContent = liveAssistantContent();@@ -6466,6 +6459,46 @@ export function createOpenAIStreamAdapter(throw streamError;}}+ // Strip a trailing ${...} template-literal fragment from external+ // streams (mistral magistral occasionally emits one at the end of an+ // otherwise complete answer).+ //+ // Once, on the finished reply. "Ends with ${...}" is a property of the+ // completed answer, and running the strip on every arrival tested it+ // against every prefix of that answer instead: the one arrival whose+ // buffer happened to end at `...${name}` was cut, and reassigning the+ // result made the cut permanent, so "return `Hi, ${name}!`" arrived as+ // "return `Hi,!`". Any reply containing a template literal lost text.+ // See #9098.+ //+ // Only where the stream ran to completion. An abort leaves more text+ // still to come, so its tail is a prefix again and stripping it would+ // be the same bug; that path keeps the buffer whole and this runs on+ // the resumed reply instead. `producedReplyText` is the same case one+ // step in: a continuation that finishes without a text or reasoning+ // delta, having emitted only a tool call, leaves the buffer holding+ // nothing but the seeded partial, and a partial is a prefix too.+ //+ // The watch still gates the scan, and now saves the whole reply from+ // being flattened rather than one arrival's worth: a reply that does+ // not end in a brace is rejected without the buffer being read at all.+ // Before the <think> close below, so a fragment at the end of an+ // unterminated reasoning block is still the end of the reply when it+ // is tested.+ if (+ isExternalRequest &&+ producedReplyText &&+ placeholderWatch.isCandidate()+ ) {+ const stripped = stripTrailingTemplatePlaceholder(cumulativeText);+ if (stripped.length !== cumulativeText.length) {+ cumulativeText = stripped;+ // A suffix went away, so both trackers have to be told; the parse+ // notices by itself, from the length.+ thinkTags.retract(cumulativeText);+ placeholderWatch.retract(cumulativeText);+ }+ }// If the stream ended while we were still inside a// delta.reasoning_content block (Kimi / DeepSeek path), close// the open <think> tag so the reasoning panel parses cleanly.diff --git a/studio/frontend/tests/chat-adapter-scan-cost.test.ts b/studio/frontend/tests/chat-adapter-scan-cost.test.tsindex c24c1d8d153..aa899447c10 100644--- a/studio/frontend/tests/chat-adapter-scan-cost.test.ts+++ b/studio/frontend/tests/chat-adapter-scan-cost.test.ts@@ -435,6 +435,22 @@ test("the reply only grows through the one call that keeps the trackers in step"}});+/** Anchors and shapes this file matches against the adapter source. */+const SSE_LOOP_START = "for await (const chunk of stream) {";+const SSE_LOOP_END = "} catch (streamError) {";+const STRIP_CALL_SITE = "stripTrailingTemplatePlaceholder(cumulativeText)";+const STRIP_CALL_SITES = /stripTrailingTemplatePlaceholder\(cumulativeText\)/g;+const STRIP_GATE_HEAD =+ /if \(\s*isExternalRequest &&\s*producedReplyText &&\s*placeholderWatch\.isCandidate\(\)\s*\) \{/;+const STRIP_GATE =+ /if \(\s*isExternalRequest &&\s*producedReplyText &&\s*placeholderWatch\.isCandidate\(\)\s*\) \{\s*const stripped =\s*$/;+const STRIP_ANYWHERE = /stripTrailingTemplatePlaceholder\(/;+const FLAG_WRITES = /producedReplyText = true;/g;+const CUT_GUARD = /if \(stripped\.length !== cumulativeText\.length\) \{/;+const CUT_KEPT = /cumulativeText = stripped;/;+const FLAG_NEXT_TO_APPEND =+ /streamedChars \+= reasoning\.length \+ delta\.length;\s*producedReplyText = true;/;+/** The adapter between two anchors, without its comments. */function regionOf(from: string, to: string, maxChars = 60_000): string {const start = ADAPTER.indexOf(from);@@ -466,32 +482,15 @@ test("the arrival loop touches the reply only in ways that cannot flatten it", ("} catch (streamError) {",);- // The strip is the one step allowed to flatten, so it and the repairs that- // follow a cut are checked as a block and then taken out of the scan below.- const stripStart = loop.indexOf(- "if (isExternalRequest && placeholderWatch.isCandidate()) {",- );- assert.notEqual(- stripStart,- -1,- "the strip is no longer gated by the watch, so it flattens on every arrival",+ // Since #9098 the strip runs once on the finished reply rather than once per+ // arrival, so nothing on this path is allowed to flatten at all and there is+ // no carve-out. The strip block and its two tracker repairs are checked+ // below the loop instead, in "the trailing strip runs on the finished reply".+ assert.doesNotMatch(+ loop,+ STRIP_ANYWHERE,+ "the strip is back inside the loop, where it both flattens the reply and sees prefixes of it rather than the reply",);- const stripEnd = loop.indexOf("\n }", stripStart);- assert.notEqual(stripEnd, -1, "the strip block's end is gone");- const stripBlock = loop.slice(stripStart, stripEnd);- // Both trackers have to be repaired when a cut happens, and only then: a cut- // has already flattened the buffer, so reading it again there is free.- for (const repair of [- "thinkTags.retract(cumulativeText)",- "placeholderWatch.retract(cumulativeText)",- ]) {- assert.equal(- stripBlock.includes(repair),- true,- `${repair} is not inside the strip block, so it runs on arrivals that never cut`,- );- }- const outsideStrip = loop.slice(0, stripStart) + loop.slice(stripEnd);const allowed = [// `length` is stored on the cons string, so it never forces a copy.@@ -499,7 +498,7 @@ test("the arrival loop touches the reply only in ways that cannot flatten it", (];const mentions: string[] = [];- for (const line of outsideStrip.split("\n")) {+ for (const line of loop.split("\n")) {if (!line.includes("cumulativeText")) {continue;}@@ -514,17 +513,17 @@ test("the arrival loop touches the reply only in ways that cannot flatten it", (`these lines touch the accumulated reply on every arrival, which copies the whole reply each time:\n ${mentions.join("\n ")}`,);- // And the loop still does the work, so the list above cannot pass by the- // buffer having left the loop entirely.+ // And the loop still handles the reply, so the empty list above cannot pass+ // by the buffer having left the loop entirely.assert.equal(- stripBlock.includes("stripTrailingTemplatePlaceholder(cumulativeText)"),+ loop.includes("cumulativeText.length"),true,- "the strip is gone from the loop; this test is no longer guarding anything",+ "the loop no longer reads the reply's length; this test needs rewriting",);assert.equal(- outsideStrip.includes("cumulativeText.length"),+ loop.includes("appendCumulative(delta)"),true,- "the loop no longer reads the reply's length; this test needs rewriting",+ "the loop no longer appends the delta; this test needs rewriting",);});@@ -558,21 +557,104 @@ test("nothing on the arrival path is handed the accumulated reply", () => {}// The strip is the one step that has to touch the buffer when it fires, so- // it fires only when the watch says a fragment could be there.+ // it still fires only when the watch says a fragment could be there. Since+ // #9098 that is once per reply rather than once per arrival, which is why+ // the ordering below is the watch and then the strip, both outside the loop.assert.match(source,- /if \(isExternalRequest && placeholderWatch\.isCandidate\(\)\) \{/,+ STRIP_GATE_HEAD,"the strip is running unconditionally again",);const candidate = source.indexOf("placeholderWatch.isCandidate()");const strip = source.indexOf("stripTrailingTemplatePlaceholder(cumulativeText)",);- const ask = source.indexOf("thinkTags.endsInsideThink()");- assert.equal(candidate !== -1 && strip !== -1 && ask !== -1, true);+ assert.equal(candidate !== -1 && strip !== -1, true);+ assert.equal(+ candidate < strip,+ true,+ "the buffer must not be touched before the watch has been asked",+ );+});++test("the trailing strip runs on the finished reply, not on every arrival", () => {+ // #9098. The pattern is anchored at the end, so running it once per arrival+ // tested "ends with ${...}" against every PREFIX of the reply. The one+ // arrival whose buffer ended at `...${name}` was cut, and reassigning the+ // result made the cut permanent: "return `Hi, ${name}!`" arrived as+ // "return `Hi,!`". Nothing about the pattern can fix that, only where it runs.+ const source = withoutComments(ADAPTER);++ const calls = source.match(STRIP_CALL_SITES) ?? [];+ assert.equal(+ calls.length,+ 1,+ "one call site: the finished reply is stripped once, and a second site would be a second chance to cut a prefix",+ );+ const strip = source.indexOf(STRIP_CALL_SITE);++ // After the loop and before the reply is turned into content, so the finished+ // text is what gets stripped and what gets saved.+ const loopEnd = source.indexOf(SSE_LOOP_END);+ assert.notEqual(loopEnd, -1);assert.equal(- candidate < strip && strip < ask,+ loopEnd < strip,true,- "the buffer must be asked about only after the strip has settled it",+ "the strip must sit after the SSE loop, not inside it",+ );+ const finalBuild = source.indexOf(+ "buildAssistantContent(mergeContinuation(cumulativeText))",+ strip,+ );+ assert.equal(+ finalBuild > strip,+ true,+ "the finished reply is built before the strip runs, so the strip cannot reach what is saved",+ );++ // Still external-only, and still only where this run wrote reply text of its+ // own. Local GGUF replies never leaked the fragment and must not start losing+ // template literals to a strip that stopped being gated; a continuation that+ // adds nothing holds the previous run's PARTIAL, which is a prefix, so+ // trimming its tail would be #9098 one step in.+ assert.match(+ source.slice(Math.max(0, strip - 220), strip),+ STRIP_GATE,+ "the strip is no longer gated on an external request that produced text",+ );++ // The flag has to be set where the reply grows, not somewhere a skipped+ // arrival can miss, and nowhere else.+ const flagWrites = source.match(FLAG_WRITES) ?? [];+ assert.equal(flagWrites.length, 1, "one place sets producedReplyText");+ assert.match(+ regionOf(SSE_LOOP_START, SSE_LOOP_END),+ FLAG_NEXT_TO_APPEND,+ "producedReplyText must be set next to the append, inside the loop",+ );++ // A cut still tells both trackers, and still only when it cuts.+ const stripBlock = source.slice(strip, source.indexOf("\n }", strip));+ for (const repair of [+ "thinkTags.retract(cumulativeText)",+ "placeholderWatch.retract(cumulativeText)",+ ]) {+ assert.equal(+ stripBlock.includes(repair),+ true,+ `${repair} is not inside the strip block`,+ );+ }+ assert.match(+ stripBlock,+ CUT_GUARD,+ "the trackers are repaired when nothing was cut",+ );+ // And the cut is kept. Dropping this line leaves a strip that computes the+ // right answer and throws it away, which every other assertion here passes.+ assert.match(+ stripBlock,+ CUT_KEPT,+ "the strip's result is not assigned back, so nothing is actually removed",);});diff --git a/studio/frontend/tests/trailing-placeholder-prefix-safety.test.ts b/studio/frontend/tests/trailing-placeholder-prefix-safety.test.tsnew file mode 100644index 00000000000..f3fc582ed27--- /dev/null+++ b/studio/frontend/tests/trailing-placeholder-prefix-safety.test.ts@@ -0,0 +1,403 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++import { stripTrailingTemplatePlaceholder } from "../src/features/chat/utils/trailing-template-placeholder.ts";++/**+ * #9098. The trailing `${...}` strip is a statement about a FINISHED reply: a+ * provider occasionally leaves a fragment on the end of an otherwise complete+ * answer. Run once per SSE arrival it was tested against every PREFIX of that+ * answer instead, and any prefix that happened to end at a complete `${...}`+ * was cut. The adapter assigns the result back, so the cut was permanent and+ * the rest of the reply streamed in on top of the hole:+ *+ * in return `Hi, ${name}!` 21 chars+ * out return `Hi,!` 13 chars+ *+ * The two modes below are the before and the after. Both call the same shipped+ * function; only WHEN it is called differs, which is the whole change. The+ * function itself is not touched, so its own suite+ * (`trailing-template-placeholder.test.ts`) still describes what it removes.+ */++/** Old: strip after every arrival, assigning the result back. */+function replayPerArrival(chunks: readonly string[]): string {+ let buffer = "";+ for (const chunk of chunks) {+ buffer += chunk;+ buffer = stripTrailingTemplatePlaceholder(buffer);+ }+ return buffer;+}++/** New: accumulate, then strip the finished reply once. */+function replayAtEnd(chunks: readonly string[]): string {+ let buffer = "";+ for (const chunk of chunks) {+ buffer += chunk;+ }+ return stripTrailingTemplatePlaceholder(buffer);+}++/** Split `text` into `size`-character arrivals. */+function chunked(text: string, size: number): string[] {+ const out: string[] = [];+ for (let at = 0; at < text.length; at += size) {+ out.push(text.slice(at, at + size));+ }+ return out;+}++type Case = {+ name: string;+ /** The reply as the provider sends it, split into arrivals. */+ chunks: string[];+ /** What the user must end up with. */+ expect: string;+ /**+ * Whether the per-arrival placement lost text on this input. `true` marks a+ * case that discriminates the fix from the bug by itself; `false` marks one+ * that was already correct and must stay correct.+ */+ lostBefore: boolean;+};++const FULL = "return `Hi, ${name}!`";++const CASES: Case[] = [+ {+ // The issue, verbatim, one character per arrival: the worst case, because+ // every prefix of the reply is a buffer the strip gets to see.+ name: "the reported reproduction, one character per arrival",+ chunks: [...FULL],+ expect: FULL,+ lostBefore: true,+ },+ {+ // The case the strip exists for. Mistral magistral leaks a fragment onto+ // the end of a complete answer; deleting the strip outright brings that+ // back, so it is pinned here rather than assumed.+ name: "a fragment genuinely at the end of a finished reply is still removed",+ chunks: ["The answer ", "is 42.", " ${answer}"],+ expect: "The answer is 42.",+ lostBefore: false,+ },+ {+ name: "nested placeholders",+ chunks: [..."`${a${b}}`"],+ expect: "`${a${b}}`",+ lostBefore: true,+ },+ {+ name: "several placeholders in one reply",+ chunks: [..."const s = `${x} and ${y}`;"],+ expect: "const s = `${x} and ${y}`;",+ lostBefore: true,+ },+ {+ // Two arrivals, split so the closing brace lands on the second. The strip+ // cannot match the first, which is exactly why the bug was believed+ // impossible: it fires on the arrival that COMPLETES the fragment.+ name: "a placeholder split across two arrivals",+ // The boundary lands right after the closing brace, which is the arrival+ // the strip fires on. Move it one character later and this reply survives+ // the old placement untouched: the bug is a property of where the chunks+ // fell, not of the reply.+ chunks: ["greet(`Hi, ${na", "me}", "!`)"],+ expect: "greet(`Hi, ${name}!`)",+ lostBefore: true,+ },+ {+ name: "an unterminated ${ is never touched",+ chunks: [..."the shell wants ${HOME"],+ expect: "the shell wants ${HOME",+ lostBefore: false,+ },+ {+ name: "a placeholder inside a fenced code block",+ // Arrivals cut so one of them ends at the closing brace, as a real+ // token boundary can. Chunked any other way this reply comes through+ // whole, which is why the bug looks intermittent from the outside.+ chunks: ["```js\n", "const s = ", "`v=${v}", "`;\n", "```"],+ expect: "```js\nconst s = `v=${v}`;\n```",+ lostBefore: true,+ },+ {+ // #9088 landed CRLF handling on this path. `\r` is whitespace to the+ // pattern, so a CRLF reply gives the strip more places to fire, not fewer.+ name: "CRLF line endings",+ chunks: ["line one\r\n", "const t = `${q}", "`;\r\n", "line three"],+ expect: "line one\r\nconst t = `${q}`;\r\nline three",+ lostBefore: true,+ },+ {+ // Both at once: a real template literal in the body AND a leaked fragment+ // on the end. The fix has to keep one and remove the other.+ name: "a template literal in the body and a leaked fragment on the end",+ chunks: chunked("use `${name}` here. ${answer}", 2),+ expect: "use `${name}` here.",+ lostBefore: true,+ },+];++test("every case survives the stream intact", () => {+ for (const item of CASES) {+ assert.equal(+ replayAtEnd(item.chunks),+ item.expect,+ `${item.name}: the finished reply is wrong`,+ );+ }+});++test("the cases that discriminate really did lose text before", () => {+ // Without this the suite could go green against a corpus that never+ // exercised the bug, which is the failure mode a passing test hides best.+ for (const item of CASES) {+ const before = replayPerArrival(item.chunks);+ assert.equal(+ before !== item.expect,+ item.lostBefore,+ `${item.name}: expected lostBefore=${item.lostBefore}, but the ` ++ `per-arrival placement produced ${JSON.stringify(before)}`,+ );+ }+ assert.equal(+ CASES.filter((item) => item.lostBefore).length,+ 7,+ "the corpus must keep discriminating; a case that stops losing text " ++ "before the fix stops testing the fix",+ );+});++test("the reported reproduction, character for character", () => {+ assert.equal(replayPerArrival([...FULL]), "return `Hi,!`");+ assert.equal(replayPerArrival([...FULL]).length, 13);+ assert.equal(replayAtEnd([...FULL]), FULL);+ assert.equal(replayAtEnd([...FULL]).length, 21);+});++test("the finished reply does not depend on how the stream was split", () => {+ // The property behind the fix, stated directly. An SSE stream chunks+ // arbitrarily, so a placement whose answer depends on where the chunk+ // boundaries fell is wrong however good it looks on one recording.+ for (const item of CASES) {+ const whole = item.chunks.join("");+ for (const size of [1, 2, 3, 5, 7, 13, 1_000]) {+ assert.equal(+ replayAtEnd(chunked(whole, size)),+ stripTrailingTemplatePlaceholder(whole),+ `${item.name}: split into ${size}-character arrivals`,+ );+ }+ }+});++test("chunk-independence is a claim the old placement fails", () => {+ // The mirror of the test above: if the per-arrival placement also satisfied+ // it, the test would be measuring nothing.+ const disagreements = CASES.filter((item) => {+ const whole = item.chunks.join("");+ return [1, 2, 3, 5, 7, 13].some(+ (size) =>+ replayPerArrival(chunked(whole, size)) !==+ stripTrailingTemplatePlaceholder(whole),+ );+ });+ assert.equal(+ disagreements.length,+ 7,+ "the per-arrival placement is supposed to be chunking-dependent; if it " ++ "is not, this corpus no longer separates the two placements",+ );+});++test("the finished reply is always a prefix of what the model sent", () => {+ // The strip only ever takes a suffix off, so a correct placement can shorten+ // the reply and can never rewrite the middle of it. This is the sharpest+ // statement of the bug available: the old placement BREAKS it, because a cut+ // made mid-stream sits in the middle of the finished reply.+ for (const item of CASES) {+ const whole = item.chunks.join("");+ const atEnd = replayAtEnd(item.chunks);+ assert.equal(+ whole.startsWith(atEnd),+ true,+ `${item.name}: the result ${JSON.stringify(atEnd)} is not a prefix of what the model sent`,+ );+ }+});++test("the old placement spliced the middle out, which is why text vanished", () => {+ const whole = FULL;+ const before = replayPerArrival([...whole]);+ assert.equal(before, "return `Hi,!`");+ assert.equal(+ whole.startsWith(before),+ false,+ "if the old result were merely a shortened reply this would be a trimming " ++ "bug; it is not a prefix, so characters were removed from the middle",+ );+});++test("randomised replies keep the two placements apart", () => {+ // Fixed seed, so a failure is reproducible from the message alone.+ let seed = 0x9098;+ const next = () => {+ seed = (seed * 1_103_515_245 + 12_345) & 0x7fffffff;+ return seed / 0x7fffffff;+ };+ const alphabet = ["a", " ", "`", "$", "{", "}", "\n", "\r", "!", "${"];++ let lost = 0;+ let spliced = 0;+ for (let trial = 0; trial < 4_000; trial += 1) {+ let reply = "";+ const length = 3 + Math.floor(next() * 25);+ for (let at = 0; at < length; at += 1) {+ reply += alphabet[Math.floor(next() * alphabet.length)];+ }+ const size = 1 + Math.floor(next() * 4);+ const atEnd = replayAtEnd(chunked(reply, size));+ const perArrival = replayPerArrival(chunked(reply, size));++ // The fix's guarantee: one answer, the one the whole reply deserves.+ assert.equal(+ atEnd,+ stripTrailingTemplatePlaceholder(reply),+ `atEnd disagreed on ${JSON.stringify(reply)} at size ${size}`,+ );+ // And what it returns is always a prefix of the reply. The old placement+ // is not: on 4,000 random replies it produced a non-prefix often enough to+ // be counted below, which is text removed from the middle.+ assert.equal(+ reply.startsWith(atEnd),+ true,+ `atEnd returned a non-prefix on ${JSON.stringify(reply)}`,+ );+ if (!reply.startsWith(perArrival)) {+ spliced += 1;+ }+ if (atEnd !== perArrival) {+ lost += 1;+ }+ }+ assert.equal(+ lost > 200,+ true,+ `only ${lost} of 4,000 random replies separated the two placements; this test is no longer measuring the difference it was written for`,+ );+ assert.equal(+ spliced > 50,+ true,+ `only ${spliced} of 4,000 random replies came back from the old placement as a non-prefix; that is the data loss this fix is about`,+ );+});++// ---------------------------------------------------------- the shipped placement ---++const ADAPTER = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+);++/**+ * Which of the two modes above the adapter is actually running.+ *+ * Read out of the source rather than assumed, so the corpus is exercised+ * through the placement that ships. Without this the cases would go on passing+ * against `replayAtEnd` no matter what the adapter did, which is the exact+ * shape of a test that measures nothing.+ */+function shippedReplay(): {+ replay: (chunks: readonly string[]) => string;+ loopStart: number;+ loopEnd: number;+ sites: number[];+} {+ const loopStart = ADAPTER.indexOf("for await (const chunk of stream) {");+ const loopEnd = ADAPTER.indexOf("} catch (streamError) {", loopStart);+ const sites: number[] = [];+ let at = ADAPTER.indexOf("stripTrailingTemplatePlaceholder(cumulativeText)");+ while (at !== -1) {+ sites.push(at);+ at = ADAPTER.indexOf(+ "stripTrailingTemplatePlaceholder(cumulativeText)",+ at + 1,+ );+ }+ const inLoop =+ sites.length === 1 && sites[0] > loopStart && sites[0] < loopEnd;+ return {+ replay: inLoop ? replayPerArrival : replayAtEnd,+ loopStart,+ loopEnd,+ sites,+ };+}++test("the corpus is run through the placement the adapter actually ships", () => {+ const { replay, loopStart, loopEnd, sites } = shippedReplay();+ assert.ok(+ loopStart !== -1 && loopEnd !== -1,+ "the SSE loop anchors are gone; this test needs rewriting",+ );+ assert.equal(+ sites.length,+ 1,+ `expected one strip call site in the adapter, found ${sites.length}`,+ );+ for (const item of CASES) {+ assert.equal(+ replay(item.chunks),+ item.expect,+ `${item.name}: the finished reply is wrong under the shipped placement`,+ );+ }+});++// ------------------------------------------------------------- continuation ---++/**+ * A whole run, the way the adapter does it: the buffer starts at whatever a+ * Continue was seeded with, and the strip is skipped entirely unless this run+ * appended reply text of its own.+ */+function replayRun(seed: string, chunks: readonly string[]): string {+ let buffer = seed;+ let produced = false;+ for (const chunk of chunks) {+ buffer += chunk;+ produced = true;+ }+ return produced ? stripTrailingTemplatePlaceholder(buffer) : buffer;+}++const SEEDED_PARTIAL = "greet(`Hi, ${name}";++test("a continuation that adds nothing leaves the seeded partial alone", () => {+ // A Continue run is seeded with the previous run's partial. If it finishes+ // without a text or reasoning delta, having emitted only a tool call, the+ // buffer holds nothing but that partial. The partial is the middle of a reply+ // someone is still writing, so trimming its tail is #9098 one step in: the+ // user presses Continue again and the text is already gone.+ assert.equal(replayRun(SEEDED_PARTIAL, []), SEEDED_PARTIAL);+ // And the strip would have cut it, so the gate is what saves it rather than+ // the input happening not to match.+ assert.equal(stripTrailingTemplatePlaceholder(SEEDED_PARTIAL), "greet(`Hi,");+});++test("a continuation that does add text is finished normally", () => {+ // The gate must not turn into "continuations are never trimmed". A Continue+ // that writes the rest of the answer produces a finished reply like any+ // other, artefact and all.+ assert.equal(replayRun(SEEDED_PARTIAL, ["!", "`)"]), "greet(`Hi, ${name}!`)");+ assert.equal(+ replayRun("The answer is 42.", [" ${", "answer}"]),+ "The answer is 42.",+ );+});