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.

Studio: report a Claude reply cut off by the context window as truncated (#10557)

Nilaydc1b0be27182
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 66794addad4..a41dcaef33a 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -2535,6 +2535,7 @@ class ExternalProviderClient:
"stop_sequence": "stop",
"tool_use": "tool_calls",
"refusal": "content_filter",
+ "model_context_window_exceeded": "length",
"pause_turn": None,
}
@@ -3196,6 +3197,15 @@ class ExternalProviderClient:
# message_stop but we skip emitting a
# finish_reason="stop" chunk that would truncate
# the rendered message in the UI.
+ # The `stop` default below reports an unmapped reason as a
+ # finished answer, hiding a truncating one added upstream.
+ if stop_reason not in _finish_reason_map:
+ logger.warning(
+ "Unmapped Anthropic stop_reason %r (model=%s); "
+ "reporting the turn as finished",
+ stop_reason,
+ model,
+ )
mapped = _finish_reason_map.get(stop_reason, "stop")
# Streaming refusal: emit a visible notice plus an
# out-of-band _toolEvent so the frontend can prune
@@ -3217,6 +3227,12 @@ class ExternalProviderClient:
"again._"
)
yield _emit_tool_event({"type": "anthropic_refusal"})
+ if stop_reason == "model_context_window_exceeded":
+ logger.warning(
+ "Anthropic context window exhausted (model=%s)",
+ model,
+ )
+ yield _emit_tool_event({"type": "context_window_exceeded"})
if mapped is not None:
chunk = {
"id": completion_id,
diff --git a/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py b/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
index 28b741ad29c..2ac100554e6 100644
--- a/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
+++ b/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
@@ -6,12 +6,16 @@
fast_mode=True on Opus 4.6/4.7 attaches the ``fast-mode-2026-02-01`` beta
header and sets ``speed: "fast"``; unsupported models drop both. Streaming
``stop_reason: "refusal"`` surfaces a user notice before the
-``content_filter`` finish chunk.
+``content_filter`` finish chunk, and ``model_context_window_exceeded`` finishes
+as ``length`` with an out-of-band event; a reason missing from the map keeps the
+``stop`` default but is logged.
https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
+https://platform.claude.com/docs/en/api/handling-stop-reasons
"""
import asyncio
import json
+from types import SimpleNamespace
import httpx
@@ -174,3 +178,106 @@ def test_refusal_emits_tool_event_for_chat_adapter_drop(monkeypatch):
# Visible refusal text must not embed a sentinel that could spoof a
# context reset if echoed by another assistant message.
assert "studio:anthropic-refusal" not in body, body
+
+
+def _stop_reason_sse(reason: str) -> bytes:
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"id":"m1","content":[],"model":"claude-sonnet-4-5","role":"assistant",'
+ b'"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}\n\n'
+ b'event: content_block_start\ndata: {"type":"content_block_start",'
+ b'"index":0,"content_block":{"type":"text","text":""}}\n\n'
+ b'event: content_block_delta\ndata: {"type":"content_block_delta",'
+ b'"index":0,"delta":{"type":"text_delta","text":"Half an ans"}}\n\n'
+ b'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta",'
+ b'"delta":{"stop_reason":"' + reason.encode() + b'"}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+
+
+def _stop_reason_lines(monkeypatch, reason: str) -> list[str]:
+ _, lines = _capture(
+ monkeypatch,
+ sse = _stop_reason_sse(reason),
+ model = "claude-sonnet-4-5",
+ )
+ return lines
+
+
+def _finish_reasons(lines: list[str]) -> list[str]:
+ seen: list[str] = []
+ for line in lines:
+ if not line.startswith("data: ") or line == "data: [DONE]":
+ continue
+ for choice in json.loads(line[len("data: ") :]).get("choices") or []:
+ if choice.get("finish_reason"):
+ seen.append(choice["finish_reason"])
+ return seen
+
+
+def _record_stream_logs(monkeypatch) -> list[tuple[str, str]]:
+ # Not caplog: this is a structlog bound logger, which never reaches the
+ # stdlib handlers caplog installs.
+ records: list[tuple[str, str]] = []
+
+ def _record(level):
+ return lambda fmt, *args, **kwargs: records.append((level, str(fmt) % args))
+
+ monkeypatch.setattr(
+ ep_mod,
+ "logger",
+ SimpleNamespace(
+ debug = _record("debug"),
+ info = _record("info"),
+ warning = _record("warning"),
+ error = _record("error"),
+ exception = _record("exception"),
+ ),
+ )
+ return records
+
+
+def test_context_window_exceeded_finishes_as_length(monkeypatch):
+ lines = _stop_reason_lines(monkeypatch, "model_context_window_exceeded")
+ assert _finish_reasons(lines) == ["length"], lines
+ assert "Half an ans" in "\n".join(lines), lines
+
+
+def test_context_window_exceeded_emits_tool_event(monkeypatch):
+ # `length` alone arms the automatic continuation, which would replay the
+ # partial into the window that just overflowed.
+ body = "\n".join(_stop_reason_lines(monkeypatch, "model_context_window_exceeded"))
+ assert '"_toolEvent": {"type": "context_window_exceeded"}' in body, body
+
+
+def test_max_tokens_still_finishes_as_length_without_the_event(monkeypatch):
+ body = "\n".join(_stop_reason_lines(monkeypatch, "max_tokens"))
+ assert '"finish_reason": "length"' in body, body
+ assert "context_window_exceeded" not in body, body
+
+
+def test_end_turn_is_still_a_completed_answer(monkeypatch):
+ body = "\n".join(_stop_reason_lines(monkeypatch, "end_turn"))
+ assert '"finish_reason": "stop"' in body, body
+ assert "context_window_exceeded" not in body, body
+
+
+def test_an_unmapped_stop_reason_is_logged(monkeypatch):
+ # The `stop` default hid the context-window reason until it was mapped.
+ records = _record_stream_logs(monkeypatch)
+ body = "\n".join(_stop_reason_lines(monkeypatch, "model_ran_out_of_ideas"))
+ assert '"finish_reason": "stop"' in body, body
+ assert [
+ message
+ for level, message in records
+ if level == "warning" and "model_ran_out_of_ideas" in message
+ ], records
+
+
+def test_a_mapped_stop_reason_is_not_logged(monkeypatch):
+ records = _record_stream_logs(monkeypatch)
+ _stop_reason_lines(monkeypatch, "end_turn")
+ assert not [
+ message for level, message in records if level == "warning" and "stop_reason" in message
+ ], records
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 8d83a384c6c..1b1c1383b98 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -139,7 +139,9 @@ import { toolResultModelText } from "@/features/chat/api/chat-adapter";
import {
CONTINUATION_RUN_CONFIG_KEY,
incompleteLabel,
+ incompleteRemedy,
isContinuableContent,
+ isProviderReportedReason,
modeAllowsContinuation,
readIncompleteInfo,
readTextThoughtSignature,
@@ -6993,11 +6995,15 @@ const ContinueMessageBarForLastMessage: FC = () => {
return Boolean(activeModel?.isAudio && !activeModel.hasAudioInput);
});
// Cancelled comes through status (the adapter yields nothing after an abort); the
- // other two are stamped on metadata so they survive a reload.
+ // other two are stamped on metadata so they survive a reload. A provider-reported reason
+ // is on the metadata either way, and outranks a cancelled status.
const stamped = readIncompleteInfo(metadata);
const cancelled =
status?.type === "incomplete" && status?.reason === "cancelled";
- const reason = cancelled ? ("cancelled" as const) : stamped?.reason;
+ const reason =
+ cancelled && !isProviderReportedReason(stamped?.reason)
+ ? ("cancelled" as const)
+ : stamped?.reason;
// Every gate the bar itself answers to. Resuming without asking has to clear the same
// ones, or it would resume a turn the bar would have refused to offer.
@@ -7014,6 +7020,9 @@ const ContinueMessageBarForLastMessage: FC = () => {
}) &&
Boolean(partial.trim());
+ // A cut with a remedy is one resuming cannot undo, so the way out replaces the button.
+ const remedy = reason ? incompleteRemedy(reason) : null;
+
// The parent is what every round of one logical turn shares; the message id changes
// each round, because a continuation runs as a sibling.
const parentId = useAuiState(({ thread, message }) => {
@@ -7169,7 +7178,8 @@ const ContinueMessageBarForLastMessage: FC = () => {
// A turn cut mid-thought has no text to resume from, so Retry stays the way out.
// `reason` is repeated rather than left to `resumable`, which is a boolean and so
// narrows nothing: the label below needs it proven non-undefined.
- if (!resumable || !reason) {
+ // The remedy is owed even when nothing can be resumed: a tool-calling turn never can be.
+ if (!reason || (!remedy && !resumable)) {
return null;
}
if (autoContinuing) {
@@ -7204,18 +7214,20 @@ const ContinueMessageBarForLastMessage: FC = () => {
return (
<div className="aui-continue-bar mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-md border border-border/70 bg-muted/50 p-2.5 text-sm">
<span className="min-w-0 flex-1 text-muted-foreground">
- {incompleteLabel(reason)}.
+ {incompleteLabel(reason)}.{remedy ? ` ${remedy}.` : ""}
</span>
- <Button
- type="button"
- size="sm"
- variant="secondary"
- className="h-7 shrink-0 gap-1.5 text-xs"
- onClick={handleContinue}
- >
- <FastForwardIcon strokeWidth={1.75} className="size-3.5" />
- Continue
- </Button>
+ {remedy ? null : (
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ className="h-7 shrink-0 gap-1.5 text-xs"
+ onClick={handleContinue}
+ >
+ <FastForwardIcon strokeWidth={1.75} className="size-3.5" />
+ Continue
+ </Button>
+ )}
</div>
);
};
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index abec4673519..630b81e5f8d 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -257,6 +257,7 @@ import {
createContinuationMerger,
type IncompleteReason,
readIncompleteInfo,
+ resolveIncompleteReason,
readContinuationRequest,
rejectsAssistantPrefill,
resumesExactly,
@@ -5188,13 +5189,17 @@ export function createOpenAIStreamAdapter(
const liveAssistantContent = () =>
buildAssistantContent(mergeContinuation(cumulativeText));
+ // Declared above the live metadata that reads it, or it is in its temporal dead zone.
+ let contextWindowExceeded = false;
// Provisional reason on every streamed yield: an abort skips the terminal yields and a reload
- // rebuilds messages as "complete".
+ // rebuilds messages as "complete". Stop is only the guess; a reported window outranks it.
const liveCustom = () => ({
...reasoningDurationTracker.metadata(),
openaiCodexReasoning: codexReasoningLedger,
contextTruncation,
- incomplete: { reason: "cancelled" as const },
+ incomplete: {
+ reason: resolveIncompleteReason("cancelled" as const, contextWindowExceeded),
+ },
...generationCustom(),
});
// Why this turn stopped early. Drives the Continue affordance.
@@ -6532,6 +6537,25 @@ export function createOpenAIStreamAdapter(
anthropicRefusalSeen = true;
continue;
}
+ if (toolEvent.type === "context_window_exceeded") {
+ contextWindowExceeded = true;
+ // assistant-ui saves the last STREAMED yield and drops everything after an
+ // abort, and the finish chunk that follows carries no delta, so nothing
+ // between here and `[DONE]` need yield. Unconditional because redacted
+ // thinking renders as no text: this publishes why the turn ended, not a body.
+ yield {
+ content: liveAssistantContent(),
+ metadata: {
+ timing: buildTiming(
+ streamStartTime,
+ totalChunks,
+ firstTokenTime,
+ ),
+ custom: liveCustom(),
+ },
+ };
+ continue;
+ }
if (toolEvent.type === "tool_output") {
// Incremental stdout from a running tool: append to the live store so the card renders it.
// The final result arrives via tool_end.
@@ -7769,6 +7793,10 @@ export function createOpenAIStreamAdapter(
);
reasoningDurationTracker.finishGroup();
+ const finalIncompleteReason = resolveIncompleteReason(
+ incompleteReason,
+ contextWindowExceeded,
+ );
yield {
content: [
...buildAssistantContent(mergeContinuation(cumulativeText, { final: true })),
@@ -7783,8 +7811,8 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
contextTruncation,
- incomplete: incompleteReason
- ? { reason: incompleteReason }
+ incomplete: finalIncompleteReason
+ ? { reason: finalIncompleteReason }
: undefined,
// Persisted refusal flag driving the two-pass prune.
anthropicRefusal: anthropicRefusalSeen || undefined,
@@ -7916,15 +7944,18 @@ export function createOpenAIStreamAdapter(
custom: {
...reasoningDurationTracker.metadata(),
contextTruncation,
- // This partial is unfinished too, so it also offers Continue.
+ // Unfinished too, so it also offers Continue -- unless the provider already
+ // said why the model stopped.
incomplete: {
- reason:
+ reason: resolveIncompleteReason(
err instanceof GenerationLengthError
- ? "length"
+ ? ("length" as const)
: err instanceof ChatGenerationTerminalError &&
err.generationStatus === "cancelled"
- ? "cancelled"
- : "interrupted",
+ ? ("cancelled" as const)
+ : ("interrupted" as const),
+ contextWindowExceeded,
+ ),
},
timing: partialTiming,
...generationCustom(),
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index 87dd2ecfff0..dba970f3ec0 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -5,8 +5,13 @@
* is re-sent with the partial as the final assistant turn plus `continue_final_message`, so
* the prompt ends mid-sentence and the new text is appended to the partial. */
-/** Why a turn ended before the model was done. */
-export type IncompleteReason = "length" | "cancelled" | "interrupted";
+/** Why a turn ended before the model was done. `context_window` is a `length` cut the same
+ * request can never fit into, hence its own reason. */
+export type IncompleteReason =
+ | "length"
+ | "cancelled"
+ | "interrupted"
+ | "context_window";
/** Metadata stamped on an assistant message that stopped early. */
export type IncompleteInfo = {
@@ -17,6 +22,7 @@ const INCOMPLETE_REASONS: readonly IncompleteReason[] = [
"length",
"cancelled",
"interrupted",
+ "context_window",
];
/** Below this a shared boundary is likely coincidence, and trimming would eat output. */
@@ -28,6 +34,24 @@ const MAX_OVERLAP = 400;
/** How much of the partial's opening a restart has to reproduce to be called a restart. */
const RESTART_PROBE = 48;
+/** The stop reason for a turn. The provider reports a filled window on the event ending its
+ * turn, so the model had already stopped: that outranks every inferred reason, missing ones
+ * included. */
+export function resolveIncompleteReason<T extends IncompleteReason | null>(
+ reason: T,
+ contextWindowExceeded: boolean,
+): T | "context_window" {
+ return contextWindowExceeded ? "context_window" : reason;
+}
+
+/** Whether the provider reported this reason rather than the client inferring it; the provider
+ * wins where they disagree. */
+export function isProviderReportedReason(
+ reason: IncompleteReason | null | undefined,
+): boolean {
+ return reason === "context_window";
+}
+
/** Read the incomplete marker off an assistant message's metadata. */
export function readIncompleteInfo(metadata: unknown): IncompleteInfo | null {
const custom = (metadata as { custom?: Record<string, unknown> } | undefined)
@@ -53,6 +77,7 @@ const STATUS_REASON: Record<
cancelled: "cancelled",
length: "length",
interrupted: "error",
+ context_window: "length",
};
/** Restore assistant-ui's status without losing the product-specific stop reason. */
@@ -70,6 +95,7 @@ const INCOMPLETE_LABELS: Record<IncompleteReason, string> = {
length: "Response hit the Max Tokens limit",
cancelled: "Response stopped",
interrupted: "Response interrupted",
+ context_window: "Response filled the model's context window",
};
/** The user-facing explanation of why a turn stopped. */
@@ -77,6 +103,17 @@ export function incompleteLabel(reason: IncompleteReason): string {
return INCOMPLETE_LABELS[reason];
}
+/** A hosted window is fixed and the partial has nothing left to replay into, so the only
+ * levers are a shorter conversation or a new one. */
+const INCOMPLETE_REMEDIES: Partial<Record<IncompleteReason, string>> = {
+ context_window: "Start a new chat, or shorten this one, to keep going",
+};
+
+/** What to do about a turn that stopped early, or `null` when resuming is the answer. */
+export function incompleteRemedy(reason: IncompleteReason): string | null {
+ return INCOMPLETE_REMEDIES[reason] ?? null;
+}
+
/** Drop text the continuation repeated from the end of the partial: local models continue
* token-exactly, but a provider that ignores assistant prefill can restate the last few
* words. Only a suffix the continuation opens with is removed. */
@@ -284,8 +321,9 @@ export function readContinuationRequest(
/** Resuming a Max Tokens cut WITHOUT asking: hitting the cap is not a decision the user made.
* Every other reason is left alone, since `cancelled` would restart what the user just
- * stopped and `interrupted` can hide a broken link. Bounded, because a model that will not
- * stop would loop forever and each round drives compaction harder. */
+ * stopped, `interrupted` can hide a broken link, and `context_window` has no room left to
+ * resume into. Bounded, because a model that will not stop would loop forever and each round
+ * drives compaction harder. */
export const AUTO_CONTINUE_LIMIT = 3;
/** Rounds already spent per logical turn, keyed by the parent the continuation hangs off: a
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index 6052d78525e..d27847651b9 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -23,13 +23,17 @@ const {
createAutoContinueTab,
budgetImpliesTruncation,
incompleteLabel,
+ incompleteRemedy,
isContinuableContent,
+ isProviderReportedReason,
isRestart,
joinContinuation,
modeAllowsContinuation,
readContinuationRequest,
readIncompleteInfo,
readTextThoughtSignature,
+ resolveIncompleteReason,
+ restoredAssistantStatus,
claimAutoContinue,
recordAutoContinue,
rejectsAssistantPrefill,
@@ -182,6 +186,172 @@ test("every stop reason has a label", () => {
assert.equal(incompleteLabel("length"), "Response hit the Max Tokens limit");
assert.equal(incompleteLabel("cancelled"), "Response stopped");
assert.equal(incompleteLabel("interrupted"), "Response interrupted");
+ assert.equal(
+ incompleteLabel("context_window"),
+ "Response filled the model's context window",
+ );
+});
+
+test("the provider's own reason outranks every reason the client infers", () => {
+ // The event ends Anthropic's turn, so the model has already stopped. A null reason
+ // matters most: it reads as a completed answer.
+ assert.equal(resolveIncompleteReason("length", true), "context_window");
+ assert.equal(resolveIncompleteReason(null, true), "context_window");
+ assert.equal(resolveIncompleteReason("cancelled", true), "context_window");
+ assert.equal(resolveIncompleteReason("interrupted", true), "context_window");
+ assert.equal(resolveIncompleteReason("length", false), "length");
+ assert.equal(resolveIncompleteReason("cancelled", false), "cancelled");
+ assert.equal(resolveIncompleteReason("interrupted", false), "interrupted");
+ assert.equal(resolveIncompleteReason(null, false), null);
+});
+
+test("a provider-reported reason is the one a cancelled status cannot overrule", () => {
+ assert.equal(isProviderReportedReason("context_window"), true);
+ assert.equal(isProviderReportedReason("length"), false);
+ assert.equal(isProviderReportedReason("cancelled"), false);
+ assert.equal(isProviderReportedReason("interrupted"), false);
+ assert.equal(isProviderReportedReason(null), false);
+ assert.equal(isProviderReportedReason(undefined), false);
+});
+
+test("a window-exhausted turn is stamped apart from a Max Tokens cut", () => {
+ resetAutoContinue();
+ // `length` either way; only the out-of-band signal separates budget from window.
+ assert.equal(resolveIncompleteReason("length", false), "length");
+ const reason = resolveIncompleteReason("length", true);
+ assert.equal(reason, "context_window");
+ assert.deepEqual(readIncompleteInfo({ custom: { incomplete: { reason } } }), {
+ reason: "context_window",
+ });
+ assert.deepEqual(restoredAssistantStatus({ custom: { incomplete: { reason } } }), {
+ type: "incomplete",
+ reason: "length",
+ });
+});
+
+test("a window-exhausted turn is never resumed automatically", () => {
+ resetAutoContinue();
+ // The `fits` guard cannot catch this: that metadata is only emitted by local models.
+ assert.equal(
+ shouldAutoContinue(resolveIncompleteReason("length", true), "parent-1"),
+ false,
+ );
+ assert.equal(
+ shouldAutoContinueMessage(
+ "m1",
+ resolveIncompleteReason("length", true),
+ "parent-1",
+ ),
+ false,
+ );
+ assert.equal(autoContinueCount("parent-1"), 0);
+});
+
+test("the adapter latches the backend window-exhaustion event", () => {
+ // The mapping lives in the streaming loop, which cannot be imported here.
+ const adapter = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ adapter,
+ /toolEvent\.type === "context_window_exceeded"[\s\S]{0,120}contextWindowExceeded = true/,
+ "the backend event is no longer latched",
+ );
+ assert.match(
+ adapter,
+ /resolveIncompleteReason\(\s*incompleteReason,\s*contextWindowExceeded,\s*\)/,
+ "the latched signal no longer reaches the stamped reason",
+ );
+ assert.match(
+ adapter,
+ /incomplete: finalIncompleteReason\s*\?\s*\{ reason: finalIncompleteReason \}/,
+ "the resolved reason no longer reaches the persisted metadata",
+ );
+ assert.match(
+ adapter,
+ /reason: resolveIncompleteReason\([\s\S]{0,400}contextWindowExceeded,\s*\)/,
+ "the error path decides a reason without asking what the provider reported",
+ );
+ assert.match(
+ adapter,
+ /incomplete: \{\s*reason: resolveIncompleteReason\("cancelled" as const, contextWindowExceeded\),\s*\}/,
+ "an abort saves a bare cancelled again, losing what the provider reported",
+ );
+ // The finish chunk carries no delta, so nothing between here and `[DONE]` need yield.
+ const handler = adapter.slice(
+ adapter.indexOf('toolEvent.type === "context_window_exceeded"'),
+ adapter.indexOf('toolEvent.type === "tool_output"'),
+ );
+ assert.ok(handler.length > 0, "the handler moved; this assertion reads nothing");
+ assert.match(
+ handler,
+ /yield \{[\s\S]*custom: liveCustom\(\),/,
+ "the latched signal is no longer published when it arrives",
+ );
+ // Redacted thinking renders as no text, so a length check would drop the reason.
+ assert.doesNotMatch(
+ handler,
+ /\.length > 0/,
+ "publishing the reason depends on renderable content again",
+ );
+});
+
+test("only the cut no continuation can undo carries a way out", () => {
+ assert.equal(incompleteRemedy("length"), null);
+ assert.equal(incompleteRemedy("cancelled"), null);
+ assert.equal(incompleteRemedy("interrupted"), null);
+ // A hosted window is fixed, so not the "Context Length" lever local models point at.
+ assert.equal(
+ incompleteRemedy("context_window"),
+ "Start a new chat, or shorten this one, to keep going",
+ );
+});
+
+test("a tool-using turn that fills the window is the case the bar must not miss", () => {
+ // A continuation runs as a sibling, without the call or its result, so a tool-calling
+ // turn is never continuable -- and a big tool result is a likely way to fill the window.
+ const content = [
+ { type: "tool-call", toolName: "web_search", toolCallId: "t1", args: {} },
+ { type: "text", text: "Based on those results, the three main causes are, first, the" },
+ ];
+ assert.equal(isContinuableContent(content), false);
+ const reason = resolveIncompleteReason("length", true);
+ assert.equal(reason, "context_window");
+ assert.notEqual(incompleteRemedy(reason!), null);
+});
+
+test("the bar offers the way out in place of a Continue that cannot help", () => {
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ thread,
+ /const remedy = reason \? incompleteRemedy\(reason\) : null/,
+ "the bar no longer asks whether resuming can help",
+ );
+ assert.match(
+ thread,
+ /if \(!reason \|\| \(!remedy && !resumable\)\) \{\n\s*return null;/,
+ "the way out is gated on the turn being resumable again",
+ );
+ // Reading the cancelled status first shows "Response stopped" and offers Continue.
+ assert.match(
+ thread,
+ /cancelled && !isProviderReportedReason\(stamped\?\.reason\)/,
+ "a cancelled status overrules the provider's own reason again",
+ );
+ assert.match(
+ thread,
+ /\{incompleteLabel\(reason\)\}\.\{remedy \? ` \$\{remedy\}\.` : ""\}/,
+ "the way out is no longer rendered beside the reason",
+ );
+ assert.match(
+ thread,
+ /\{remedy \? null : \([\s\S]{0,400}Continue\n\s*<\/Button>/,
+ "Continue is offered again for a cut it cannot help",
+ );
});
test("a continuation request is read only when it carries text", () => {