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 cancelled prompt from stranding two user turns in chat history (#9489)
Nilay500eebc6eaa7
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 706f949fc9b..2ba65500943 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -1394,6 +1394,105 @@ function toOpenAIMessages(];}+/** Payload the turn carries in its own parts, so that a turn holding real history is kept+ * even when the replay serialiser emits nothing for it.+ *+ * Tool calls are deliberately absent. A call the serialiser can carry leaves `tool_calls` on+ * the wire and is caught by the shape check below; a call it cannot carry (a local call+ * Stopped before its result arrived, which OpenAI forbids replaying without a responding+ * `role="tool"` message) reaches the provider as nothing. Counting the second as payload keeps+ * a turn the backend then drops (`_drop_empty_assistant_sentinels`), so+ * `_coalesce_consecutive_user_turns` merges the two user turns, resending the cancelled+ * prompt and inviting the tool request again. */+function assistantTurnCarriesPayload(message: RunMessage): boolean {+ for (const part of message.content ?? []) {+ // sanitizeAssistantReplayText only substitutes, never empties, so the raw part is+ // equivalent here and keeps the scan off that regex.+ if (part.type === "text" && part.text.trim().length > 0) return true;+ }+ if (collectImageParts(message).length > 0) return true;+ return "attachments" in message && (message.attachments?.length ?? 0) > 0;+}++/** Whitespace is not content: `_build_external_messages` (studio/backend/routes/inference.py)+ * drops any assistant turn whose string content trims away, so counting it here would keep a+ * pair the backend then splits apart again. */+function hasReplayContent(content: OpenAIMessageContent | null): boolean {+ if (typeof content === "string") return content.trim().length > 0;+ return Boolean(content);+}++/** `status` is session state only (a reloaded thread comes back stamped complete), so the+ * persisted marker is read alongside it. */+function assistantTurnEndedEarly(message: RunMessage): boolean {+ return (+ message.status?.type === "incomplete" ||+ readIncompleteInfo((message as { metadata?: unknown }).metadata) !== null+ );+}++/** A Stop that landed before the turn produced anything: it serialises to a lone empty+ * assistant message, which every backend drops, stranding two user turns in a row. */+function isAbandonedAssistantTurn(+ message: RunMessage,+ includeReasoningContent: boolean,+): boolean {+ if (message.role !== "assistant") return false;+ if (assistantTurnCarriesPayload(message)) return false;+ // A turn that finished on reasoning alone is a reply; on an external request it serialises+ // empty only because reasoning is stripped there, which must not read as abandoned.+ if (+ !assistantTurnEndedEarly(message) &&+ (message.content ?? []).some((part) => part.type === "reasoning")+ ) {+ return false;+ }+ const [only, ...rest] = toOpenAIMessages(message, includeReasoningContent);+ return (+ rest.length === 0 &&+ only?.role === "assistant" &&+ !hasReplayContent(only.content) &&+ !only.tool_calls &&+ !only.reasoning_content+ );+}++/** Drop refused and abandoned assistant turns along with the user prompt that triggered+ * them: a refusal re-triggers the classifier, an abandoned turn breaks role alternation. */+function pruneOutboundHistory(+ messages: RunMessages,+ includeReasoningContent: boolean,+): RunMessage[] {+ const history = [...messages];+ const abandoned = history.map((message) =>+ isAbandonedAssistantTurn(message, includeReasoningContent),+ );+ // A prompt is only stranded when something survives after it, so a thread whose last turn+ // was abandoned keeps its trailing prompt: that is the history the next send needs.+ let lastSurviving = -1;+ for (let index = history.length - 1; index >= 0; index -= 1) {+ if (!abandoned[index] && !isAnthropicRefusalMessage(history[index])) {+ lastSurviving = index;+ break;+ }+ }++ const surviving: RunMessage[] = [];+ for (let index = 0; index < history.length; index += 1) {+ const message = history[index];+ const refused = isAnthropicRefusalMessage(message);+ if (refused || abandoned[index]) {+ if (refused || index < lastSurviving) {+ const last = surviving.at(-1);+ if (last && last.role === "user") surviving.pop();+ }+ continue;+ }+ surviving.push(message);+ }+ return surviving;+}+function extractImageBase64(input: string): string | undefined {if (!input) {return undefined;@@ -1569,17 +1668,7 @@ export async function buildOutboundMessagesForTokenCount(messages: RunMessages,threadId: string | undefined,): Promise<OpenAIChatMessage[]> {- const survivingMessages: RunMessage[] = [];- for (const message of messages) {- if (isAnthropicRefusalMessage(message)) {- const last = survivingMessages.at(-1);- if (last && last.role === "user") survivingMessages.pop();- continue;- }- survivingMessages.push(message);- }-- const outboundMessages = survivingMessages+ const outboundMessages = pruneOutboundHistory(messages, true).flatMap((message) => toOpenAIMessages(message, true)).filter((message): message is NonNullable<typeof message> =>Boolean(message),@@ -4418,19 +4507,10 @@ export function createOpenAIStreamAdapter(throw new Error("Image generation edit unavailable.");}- // Drop refused assistant turns + their triggering user prompt;- // otherwise context re-triggers the classifier.- const survivingMessages: RunMessage[] = [];- for (const message of messages) {- if (isAnthropicRefusalMessage(message)) {- const last = survivingMessages.at(-1);- if (last && last.role === "user") {- survivingMessages.pop();- }- continue;- }- survivingMessages.push(message);- }+ const survivingMessages = pruneOutboundHistory(+ messages,+ !isExternalRequest,+ );// toOpenAIMessages emits assistant tool_calls + role="tool"// follow-ups; the backend Gemini translator rebuilds thediff --git a/studio/frontend/tests/cancelled-turn-history-prune.test.ts b/studio/frontend/tests/cancelled-turn-history-prune.test.tsnew file mode 100644index 00000000000..2034f5d731e--- /dev/null+++ b/studio/frontend/tests/cancelled-turn-history-prune.test.ts@@ -0,0 +1,76 @@+// 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";++const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+);++test("a Stop with no output is recognised by what it puts on the wire", () => {+ assert.match(adapter, /function isAbandonedAssistantTurn\(/);+ assert.match(+ adapter,+ /!hasReplayContent\(only\.content\) &&\s*!only\.tool_calls &&\s*!only\.reasoning_content/,+ );+});++test("whitespace is not content, the way the backend already reads it", () => {+ assert.match(adapter, /function hasReplayContent\(/);+ assert.match(+ adapter,+ /if \(typeof content === "string"\) return content\.trim\(\)\.length > 0;/,+ );+ assert.match(+ adapter,+ /part\.type === "text" && part\.text\.trim\(\)\.length > 0/,+ );+});++test("a turn that carries payload of its own is never abandoned", () => {+ assert.match(adapter, /function assistantTurnCarriesPayload\(/);+ assert.match(+ adapter,+ /if \(assistantTurnCarriesPayload\(message\)\) return false;/,+ );+});++test("a tool call is left to the wire shape, not counted as payload up front", () => {+ const start = adapter.indexOf("function assistantTurnCarriesPayload(");+ const end = adapter.indexOf("function hasReplayContent(");+ assert.ok(start > 0 && end > start);+ // A call the replay can carry already leaves tool_calls on the wire; one it cannot carry+ // reaches the provider as nothing; short-circuiting here would keep the empty turn the+ // backend drops, stranding the pair this prune exists to repair.+ assert.doesNotMatch(adapter.slice(start, end), /part\.type === "tool-call"/);+});++test("a turn that finished on reasoning alone keeps its prompt", () => {+ assert.match(adapter, /function assistantTurnEndedEarly\(/);+ assert.match(adapter, /!assistantTurnEndedEarly\(message\) &&/);+});++test("an abandoned turn is pruned with the user prompt that triggered it", () => {+ assert.match(+ adapter,+ /if \(last && last\.role === "user"\) surviving\.pop\(\)/,+ );+});++test("a trailing abandoned turn keeps the prompt it followed", () => {+ assert.match(adapter, /if \(refused \|\| index < lastSurviving\) \{/);+});++test("the send and token-count paths prune through the same helper", () => {+ assert.match(+ adapter,+ /const outboundMessages = pruneOutboundHistory\(messages, true\)/,+ );+ assert.match(+ adapter,+ /const survivingMessages = pruneOutboundHistory\(\s*messages,\s*!isExternalRequest,\s*\);/,+ );+});diff --git a/tests/studio/test_cancelled_turn_history_prune.py b/tests/studio/test_cancelled_turn_history_prune.pynew file mode 100644index 00000000000..b53f4fe0123--- /dev/null+++ b/tests/studio/test_cancelled_turn_history_prune.py@@ -0,0 +1,457 @@+# 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 Stop before the turn produced anything must not strand two user turns (#9484).++The abandoned turn serialises to a lone empty assistant message, every backend drops it, and+strict templates (Ministral, Gemma) then refuse the two user turns that are left touching.+``pruneOutboundHistory`` drops that turn together with the prompt that triggered it, the way+refusals are already dropped.++The prune, ``toOpenAIMessages`` and ``serializeAssistantReplayMessages`` are sliced verbatim out+of the studio sources and run under ``node`` (see ``_node_harness``), so what is asserted is the+wire shape rather than the spelling of the source. ``cancelled-turn-history-prune.test.ts`` pins+the wiring; this pins what it does, and the refusal-only prune the fix replaces is run beside it+so the case states the defect rather than only the repair.+"""++from __future__ import annotations++import textwrap++from _node_harness import (+ WORKDIR,+ read,+ require_node,+ run_harness,+ slice_between,+ source_path,+)++ADAPTER = source_path("studio/frontend/src/features/chat/api/chat-adapter.ts")+CODEX = source_path("studio/frontend/src/features/chat/codex-reasoning.ts")+CONTINUATION = source_path("studio/frontend/src/features/chat/utils/continuation.ts")++TEMP = WORKDIR / "temp" / "cancelled_turn_history_prune"++SOURCES = (ADAPTER, CODEX, CONTINUATION)++# Fixtures the sliced code reads through. Only the tool-call helpers are stand-ins, and they stay+# real enough to prove a turn carrying a call is NOT abandoned: ``canReplayToolCallWithoutRoleTool``+# is driven off the fixture rather than pinned, so the resultless call the replay has to drop+# stays reachable here instead of being stubbed out of existence.+HARNESS = """+// @ts-nocheck+function readCodexReasoning(_metadata: any): any {+ return undefined;+}++function codexReasoningForToolCalls(_ledger: any, _ids: any): any {+ return undefined;+}++function getToolReplayProvenance(part: any): any {+ return part?.provenance;+}++function shouldFlushCompletedLocalToolPair(_part: any): boolean {+ return false;+}++function canReplayToolCallWithoutRoleTool(part: any): boolean {+ return part?.canReplay === true;+}++function serializeAssistantToolCallPart(part: any): any {+ return part?.toolCallId+ ? {+ id: part.toolCallId,+ type: "function",+ function: { name: part.toolName ?? "", arguments: part.args ?? "{}" },+ }+ : null;+}++function serializeToolResultPart(part: any): any {+ return part?.result === undefined+ ? null+ : { role: "tool", content: String(part.result), tool_call_id: part.toolCallId };+}++// ---- PRELUDE ENDS: verbatim studio source follows ----+"""+++def _adapter_slice(start: str, end: str) -> str:+ return slice_between(read(ADAPTER), start, end)+++def _send_path_slice() -> str:+ """The send path's own outbound build, wrapped so the test runs it instead of reading it.++ Sliced out of ``createOpenAIStreamAdapter``. Wiring assertions on the source text pass just+ as happily against a send path that went back to ``messages.flatMap(...)``; this one only+ passes while the payload is actually built from pruned history.+ """+ body = slice_between(+ read(ADAPTER),+ "const survivingMessages = pruneOutboundHistory(",+ "if (selectedImageEditReference) {",+ )+ return (+ "export function buildSendPathOutbound(messages: any, isExternalRequest: boolean) {\n"+ + body+ + " return outboundMessages;\n}\n"+ )+++def _harness_source() -> str:+ return (+ HARNESS+ + _adapter_slice("function collectTextParts(", "function normalizeOpenAIReasoningItem(")+ + _adapter_slice(+ "// Refusal flag stamped on assistant metadata",+ "type SerializedMessage = {",+ )+ + _adapter_slice(+ "function sanitizeAssistantReplayText(",+ "function serializeAssistantReplayMessages(",+ )+ + _adapter_slice(+ "function serializeAssistantReplayMessages(",+ "function extractImageBase64(",+ )+ + slice_between(+ read(CODEX),+ "export function codexLocalToolRoundId(",+ "export function addCodexReasoning(",+ )+ + slice_between(+ read(CONTINUATION),+ "/** Why a turn ended before the model was done. */",+ "const INCOMPLETE_LABELS",+ )+ + """+// The refusal-only prune this fix replaces, kept so each case can show what the wire looked+// like before rather than only that it is right now.+export function pruneRefusalsOnly(messages: any[]): any[] {+ const surviving: any[] = [];+ for (const message of messages) {+ if (isAnthropicRefusalMessage(message)) {+ const last = surviving.at(-1);+ if (last && last.role === "user") surviving.pop();+ continue;+ }+ surviving.push(message);+ }+ return surviving;+}++/** Roles on the wire, after the backend drops the empty assistant turns it always drops. */+export function wireRoles(messages: any[], includeReasoningContent: boolean): string[] {+ return messages+ .flatMap((message: any) => toOpenAIMessages(message, includeReasoningContent))+ .filter((message: any) => !(message.role === "assistant" && !message.content+ && !message.tool_calls && !message.reasoning_content))+ .map((message: any) => message.role);+}++export { pruneOutboundHistory, toOpenAIMessages };+"""+ + _send_path_slice()+ )+++def _run(script: str) -> dict:+ require_node(SOURCES)+ return run_harness(TEMP, _harness_source(), script)+++USER = '{ role: "user", content: [{ type: "text", text: "TEXT" }] }'+CANCELLED = (+ '{ role: "assistant", content: [], status: { type: "incomplete" },'+ ' metadata: { custom: { incomplete: { reason: "cancelled" } } } }'+)+++def _script(history: str, include_reasoning: str = "true") -> str:+ return textwrap.dedent(+ f"""+ // @ts-nocheck+ import {{ pruneOutboundHistory, pruneRefusalsOnly, toOpenAIMessages, wireRoles }}+ from "./harness.ts";+ const history = {history};+ const kept = pruneOutboundHistory(history, {include_reasoning});+ console.log(JSON.stringify({{+ kept: kept.map((m) => m.role),+ keptText: kept.flatMap((m) => (m.content ?? []).filter((p) => p.type === "text")+ .map((p) => p.text)),+ wire: wireRoles(kept, {include_reasoning}),+ wireBefore: wireRoles(pruneRefusalsOnly(history), {include_reasoning}),+ }}));+ """+ )+++def _user(text: str) -> str:+ return USER.replace("TEXT", text)+++def test_the_defect_is_two_user_turns_touching_on_the_wire():+ """What #9484 reported: the empty turn goes, and the prompts it separated end up adjacent."""+ out = _run(_script(f"[{_user('first')}, {CANCELLED}, {_user('second')}]"))+ assert out["wireBefore"] == ["user", "user"], (+ "the refusal-only prune must still reproduce the stranded pair, or this case has "+ "stopped measuring the bug it was written for"+ )+++def test_a_stop_before_any_output_takes_its_prompt_with_it():+ out = _run(_script(f"[{_user('first')}, {CANCELLED}, {_user('second')}]"))+ assert out["kept"] == ["user"]+ assert out["keptText"] == ["second"]+ assert out["wire"] == ["user"]+++def test_a_reply_that_produced_text_is_kept_with_its_prompt():+ """The prune reads the wire shape, so anything the model actually said protects the pair."""+ answered = '{ role: "assistant", content: [{ type: "text", text: "an answer" }] }'+ out = _run(_script(f"[{_user('first')}, {answered}, {_user('second')}]"))+ assert out["kept"] == ["user", "assistant", "user"]+ assert out["wire"] == ["user", "assistant", "user"]+++def test_a_stop_during_reasoning_is_abandoned_on_both_serialisations():+ """An incomplete turn never replays its reasoning, so the local and external builds agree.++ They pass different ``includeReasoningContent``: the recount always sends true, the request+ sends ``!isExternalRequest``. A turn cut mid-think must prune either way or the two paths+ would price and send different histories.+ """+ thinking = (+ '{ role: "assistant", content: [{ type: "reasoning", text: "let me think" }],'+ ' status: { type: "incomplete" } }'+ )+ for include_reasoning in ("true", "false"):+ out = _run(_script(f"[{_user('first')}, {thinking}, {_user('second')}]", include_reasoning))+ assert out["kept"] == ["user"], f"includeReasoningContent={include_reasoning}"+ assert out["keptText"] == ["second"]+++def test_a_turn_that_called_a_tool_is_not_abandoned():+ """tool_calls are payload even with no text; dropping the pair would orphan the call."""+ called = (+ '{ role: "assistant", content: [{ type: "tool-call", toolCallId: "call_1",'+ ' toolName: "web_search", args: "{}", result: "ok" }],'+ ' status: { type: "incomplete" } }'+ )+ out = _run(_script(f"[{_user('first')}, {called}, {_user('second')}]"))+ assert out["kept"] == ["user", "assistant", "user"]+ assert out["wire"] == ["user", "assistant", "tool", "user"]+++def test_refusals_are_still_pruned_with_their_prompt():+ """The behaviour the prune already had; the abandoned-turn rule shares its loop now."""+ refused = (+ '{ role: "assistant", content: [{ type: "text", text: "I cannot help with that." }],'+ " metadata: { custom: { anthropicRefusal: true } } }"+ )+ out = _run(_script(f"[{_user('first')}, {refused}, {_user('second')}]"))+ assert out["kept"] == ["user"]+ assert out["keptText"] == ["second"]+++def test_back_to_back_stops_collapse_to_the_live_prompt():+ """Stop twice and both abandoned pairs go, rather than one prune uncovering the next."""+ history = f"[{_user('first')}, {CANCELLED}, {_user('second')}, {CANCELLED}, {_user('third')}]"+ out = _run(_script(history))+ assert out["kept"] == ["user"]+ assert out["keptText"] == ["third"]+ assert out["wireBefore"] == ["user", "user", "user"]+++def test_a_reply_that_finished_on_reasoning_alone_keeps_its_prompt():+ """A complete reasoning-only turn is a reply, not a Stop.++ External requests serialise with ``includeReasoningContent = false``, which strips the+ reasoning and leaves an empty assistant message. Reading only the wire shape called that+ abandoned and deleted the prompt that produced it, so the question the user actually asked+ left the context on hosted providers but survived on local ones.+ """+ answered = '{ role: "assistant", content: [{ type: "reasoning", text: "thought" }] }'+ for include_reasoning in ("true", "false"):+ out = _run(_script(f"[{_user('first')}, {answered}, {_user('second')}]", include_reasoning))+ assert out["kept"] == [+ "user",+ "assistant",+ "user",+ ], f"includeReasoningContent={include_reasoning}"+ assert out["keptText"] == ["first", "second"]+++def test_a_reply_that_finished_with_no_text_at_all_is_still_abandoned():+ """The turn holds nothing either serialisation could carry, so it prunes like a Stop."""+ silent = '{ role: "assistant", content: [{ type: "text", text: "" }] }'+ out = _run(_script(f"[{_user('first')}, {silent}, {_user('second')}]"))+ assert out["kept"] == ["user"]+++def test_a_tool_call_the_replay_cannot_carry_prunes_with_its_prompt():+ """A resultless local call is dropped by the serialiser, so the turn carries nothing.++ OpenAI rejects an assistant ``tool_calls`` turn whose ids have no responding ``role="tool"``+ message, so the serialiser cannot rescue this by emitting the call -- it skips it, and the+ turn reaches the provider as the same lone empty assistant message a Stop with no output+ produces. Treating the call as payload only moved the defect one hop: the backend drops the+ empty assistant (``_drop_empty_assistant_sentinels``) and then merges the two user turns+ that are left touching (``_coalesce_consecutive_user_turns``), which resends the cancelled+ prompt glued to the next one and invites the tool request the user Stopped.+ """+ stopped = (+ ', status: { type: "incomplete" },'+ ' metadata: { custom: { incomplete: { reason: "cancelled" } } } }'+ )+ for marker in (stopped, " }"):+ unreplayable = (+ '{ role: "assistant", content: [{ type: "tool-call", toolCallId: "call_1",'+ ' toolName: "delete_file", args: "{}" }]' + marker+ )+ out = _run(_script(f"[{_user('first')}, {unreplayable}, {_user('second')}]"))+ assert out["kept"] == ["user"], marker+ assert out["keptText"] == ["second"]+ assert out["wire"] == ["user"]+ assert out["wireBefore"] == ["user", "user"], (+ "the refusal-only prune must still strand the pair here, or this case has stopped "+ "measuring the defect it was written for"+ )+++def test_a_resultless_call_that_replays_without_role_tool_keeps_its_prompt():+ """Resultless is not the test; unreplayable is.++ Provider-native builtin cards replay through ``extra_content``/native parts and never+ produce a ``role="tool"`` message, so ``canReplayToolCallWithoutRoleTool`` lets the+ serialiser emit the call with no result. That call does reach the provider, so the prompt+ that asked for it is history and pruning the pair would delete it.+ """+ builtin = (+ '{ role: "assistant", content: [{ type: "tool-call", toolCallId: "call_1",'+ ' toolName: "web_search", args: "{}", canReplay: true }],'+ ' status: { type: "incomplete" } }'+ )+ out = _run(_script(f"[{_user('first')}, {builtin}, {_user('second')}]"))+ assert out["kept"] == ["user", "assistant", "user"]+ assert out["keptText"] == ["first", "second"]+ assert out["wire"] == ["user", "assistant", "user"]+++def test_a_trailing_abandoned_turn_keeps_the_prompt_it_followed():+ """Nothing follows it, so there is no stranded pair to repair and nothing to drop.++ The token-count path rebuilds outbound history for the live thread, which after a Stop+ ends on the abandoned turn. Popping there emptied the whole history and priced the thread+ at zero.+ """+ for include_reasoning in ("true", "false"):+ out = _run(_script(f"[{_user('first')}, {CANCELLED}]", include_reasoning))+ assert out["kept"] == ["user"], f"includeReasoningContent={include_reasoning}"+ assert out["keptText"] == ["first"]+++def test_a_thread_that_is_only_a_stop_keeps_its_system_prompt_and_prompt():+ history = (+ '[{ role: "system", content: [{ type: "text", text: "sys" }] }, '+ f"{_user('first')}, {CANCELLED}]"+ )+ out = _run(_script(history))+ assert out["kept"] == ["system", "user"]+ assert out["keptText"] == ["sys", "first"]+++def test_the_count_and_send_paths_prune_the_same_history():+ """The recount always passes true and the request passes ``!isExternalRequest``.++ Any shape whose verdict depends on that flag prices one history and sends another, so the+ context bar and the payload disagree.+ """+ shapes = {+ "cancelled": CANCELLED,+ "text": '{ role: "assistant", content: [{ type: "text", text: "an answer" }] }',+ "reasoning_complete": '{ role: "assistant", content: [{ type: "reasoning",'+ ' text: "thought" }] }',+ "reasoning_incomplete": '{ role: "assistant", content: [{ type: "reasoning",'+ ' text: "thought" }], status: { type: "incomplete" } }',+ "tool_unreplayable": '{ role: "assistant", content: [{ type: "tool-call",'+ ' toolCallId: "call_1", toolName: "web_search", args: "{}" }] }',+ "image": '{ role: "assistant", content: [{ type: "image", image: "QUJD" }] }',+ }+ for name, shape in shapes.items():+ history = f"[{_user('first')}, {shape}, {_user('second')}]"+ counted = _run(_script(history, "true"))+ sent = _run(_script(history, "false"))+ assert counted["kept"] == sent["kept"], name+ assert counted["keptText"] == sent["keptText"], name+++def _send_script(history: str, is_external: str) -> str:+ return textwrap.dedent(+ f"""+ // @ts-nocheck+ import {{ buildSendPathOutbound }} from "./harness.ts";+ const outbound = buildSendPathOutbound({history}, {is_external});+ console.log(JSON.stringify({{+ roles: outbound.map((m) => m.role),+ contents: outbound.map((m) => m.content),+ }}));+ """+ )+++def test_the_send_path_builds_its_payload_out_of_pruned_history():+ """Run the send path's own outbound build, not a restatement of it.++ A send path that stopped pruning would still satisfy every wiring assertion on the source+ text, so the abandoned pair is put through the real slice here.+ """+ for is_external in ("false", "true"):+ out = _run(_send_script(f"[{_user('first')}, {CANCELLED}, {_user('second')}]", is_external))+ assert out["roles"] == ["user"], f"isExternalRequest={is_external}"+ assert out["contents"] == ["second"]+++def test_the_send_path_still_carries_an_answered_exchange():+ """The counterpart: pruning must not be the send path quietly dropping history."""+ answered = '{ role: "assistant", content: [{ type: "text", text: "an answer" }] }'+ out = _run(_send_script(f"[{_user('first')}, {answered}, {_user('second')}]", "false"))+ assert out["roles"] == ["user", "assistant", "user"]+ assert out["contents"] == ["first", "an answer", "second"]+++def test_a_stop_that_produced_only_whitespace_takes_its_prompt_with_it():+ """Whitespace is not an answer, and the backend already agrees.++ ``_build_external_messages`` drops any assistant turn whose string content trims away+ (studio/backend/routes/inference.py). Keeping the pair here because " " is truthy in JS+ only moved the defect one hop: the backend removed the assistant alone and put the two user+ turns back on the wire touching.+ """+ for blank in (" ", "\\n\\t"):+ whitespace = (+ '{ role: "assistant", content: [{ type: "text", text: "%s" }],'+ ' status: { type: "incomplete" },'+ ' metadata: { custom: { incomplete: { reason: "cancelled" } } } }' % blank+ )+ out = _run(_script(f"[{_user('first')}, {whitespace}, {_user('second')}]"))+ assert out["kept"] == ["user"], repr(blank)+ assert out["keptText"] == ["second"]+ assert out["wireBefore"] == ["user", "assistant", "user"], (+ "the refusal-only prune kept the whitespace turn, which is the hop the backend "+ "trim then undid"+ )+++def test_whitespace_only_replies_leave_no_pair_for_the_backend_to_split():+ """The same shape without a Stop marker: the backend trims it either way."""+ whitespace = '{ role: "assistant", content: [{ type: "text", text: " " }] }'+ out = _run(_script(f"[{_user('first')}, {whitespace}, {_user('second')}]"))+ assert out["kept"] == ["user"]diff --git a/tests/studio/test_token_count_prompt_parity.py b/tests/studio/test_token_count_prompt_parity.pyindex 4d75ed70752..8a182a31a0b 100644--- a/tests/studio/test_token_count_prompt_parity.py+++ b/tests/studio/test_token_count_prompt_parity.py@@ -46,6 +46,15 @@ def _canvas_constants() -> str:)+def _prune_helpers() -> str:+ """isAbandonedAssistantTurn + pruneOutboundHistory, which the outbound builder calls."""+ return slice_between(+ read(ADAPTER),+ "/** Payload the turn carries in its own parts",+ "function extractImageBase64(",+ )++def _outbound_builder() -> str:return slice_between(read(ADAPTER),@@ -114,6 +123,18 @@ function isAnthropicRefusalMessage(_message: any): boolean {return false;}+function sanitizeAssistantReplayText(text: string): string {+ return text;+}++function readIncompleteInfo(_metadata: any): any {+ return null;+}++function collectImageParts(_message: any): any[] {+ return [];+}+function toOpenAIMessages(message: any): any[] {return [{ role: message.role, content: message.text }];}@@ -157,6 +178,7 @@ def _harness_source() -> str:return (HARNESS+ _canvas_constants()+ + _prune_helpers()+ _outbound_builder()+ _reasoning_builder()+ _extras_builder()