From c43dd22e490333a5feca8dbd6a9744c1a8184c03 Mon Sep 17 00:00:00 2001 From: Aldo Adirajasa Fathoni Date: Tue, 27 Oct 2026 13:53:48 +0700 Subject: [PATCH 1/5] fix(loop): retry stalled bare-announcement terminal turns (#3905) --- src/degenerate-turn.ts | 20 +++ src/loop/core.ts | 51 +++++- src/plugin.ts | 39 +++-- tests/issue3905-announcement-tail.test.ts | 179 ++++++++++++++++++++++ 4 files changed, 268 insertions(+), 21 deletions(-) create mode 100644 tests/issue3905-announcement-tail.test.ts diff --git a/src/degenerate-turn.ts b/src/degenerate-turn.ts index 2092f58f32..7bb11d922b 100644 --- a/src/degenerate-turn.ts +++ b/src/degenerate-turn.ts @@ -72,6 +72,26 @@ export function endsWithDraftClose(text: string): boolean { return text.length > 0 && DRAFT_CLOSE_TAIL.test(text); } +// #3905: the announcement-tail shape. Unlike #2303 there is no draft tag: the +// ENTIRE visible output of the turn is a one-line promise of the next action +// ("Running verify after formatting:") that ends on a colon or ellipsis, with +// no tool call and a clean stop. The upstream reports a healthy turn, the host +// gets nothing actionable, and the session stalls until the user types +// something. Observed verbatim at 24 output tokens / 32 visible chars behind a +// deepseek-v4.1-flash combo member. +// +// The character cap is the whole precision boundary, not a performance guard: +// a genuine answer that happens to end on a colon is prose, and prose is long. +// 400 chars sits an order of magnitude above the observed stub and well below +// any real answer tail. +const ANNOUNCE_TAIL = /(?::|\u2026|\.\.\.)\s*$/; +const ANNOUNCE_MAX_CHARS = 400; +export function endsWithAnnouncement(text: string): boolean { + const t = text.trimEnd(); + if (t.length === 0 || t.length > ANNOUNCE_MAX_CHARS) return false; + return ANNOUNCE_TAIL.test(t); +} + // #2612: the #2303 draft-tail shape has a legitimate producer β€” the CLIENT's // own summarization request. Claude Code's compaction (/compact, auto-compact, // precomputed compression) instructs the model, in the final user message, to diff --git a/src/loop/core.ts b/src/loop/core.ts index bd93cd0dc0..2bd8e041ab 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -45,7 +45,7 @@ import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoBody } from "../st import { log as loggerLog } from "../logger.js"; import { promptInputTotal, type WireProtocol } from "../util.js"; import { DEGENERATE_RETRY_NUDGE } from "../degenerate-retry.js"; -import { endsWithDraftClose, lastUserSummaryInstruction, requestExpectsProseSummary } from "../degenerate-turn.js"; +import { endsWithAnnouncement, endsWithDraftClose, lastUserSummaryInstruction, requestExpectsProseSummary } from "../degenerate-turn.js"; import { safePrefix, safeSuffix, scrubLoneSurrogatesOnWire } from "../text-safe.js"; export const MAX_LOOP_ROUNDS = 10; @@ -218,6 +218,13 @@ export interface LoopCtx { * rebuilt history. Default (undefined) keeps markers on. Paired * tool-call/tool-result messages are unaffected. */ visibilityMarkers?: boolean; + /** #3906: when `false`, keep the πŸ“¦/❌ ACP receipt in rebuilt history (and in + * the round-N+1 system message the model sees) but stop emitting it into + * the client's content stream. Independent of `visibilityMarkers`: this is + * the cosmetic-only switch for clients that merge the marker into the + * assistant's single text part, which makes the answer render above the + * reasoning that produced it. Default (undefined) keeps streaming. */ + streamMarkers?: boolean; /** #1455: tee loop-originated upstream responses (re-request and every * retry fetch) to raw SSE files β€” the outer request's ACP_DUMP_SSE tee * only covers the FIRST response, so an internal re-request that dies @@ -1089,6 +1096,18 @@ export async function* runCompressLoop( } } + // #2303 / #3905: classify the terminal tail shape. Both shapes are + // non-converged handoffs β€” visible prose with no tool call β€” and share + // the budget, the openai/anthropic framing boundary and the #2612 + // exemption below. + const stalledTail: "draft" | "announce" | null = + assistantText.length === 0 || calls.length > 0 + ? null + : endsWithDraftClose(assistantText) + ? "draft" + : endsWithAnnouncement(assistantText) + ? "announce" + : null; // #2303: a terminal turn that DID deliver visible prose but ends with a // compression-draft closing tag (summary/analysis close forms) and no // tool call β€” the model wrote a handoff/compression draft in prose @@ -1114,7 +1133,7 @@ export async function* runCompressLoop( !ctx.textProtocol && assistantText.length > 0 && calls.length === 0 && - endsWithDraftClose(assistantText) && + (stalledTail === "draft" || stalledTail === "announce") && // #2612: the client's own compaction request instructs the // model to answer with a plain-text summary block and no // tool call β€” that compliant reply is a draft tail by @@ -1124,8 +1143,13 @@ export async function* runCompressLoop( !signal?.aborted ) { degenerateRetried = true; - ctx.log(`[acp-loop] round ${round}: terminal turn ends with a compression-draft closing tag and no tool call; retrying once with continuation nudge (#2303)`); - loggerLog("warn", `[acp-loop] draft-tail auto-retry round ${round} (session ${ctx.session.id})`); + if (stalledTail === "announce") { + ctx.log(`[acp-loop] round ${round}: terminal turn is a bare announcement (ends mid-promise, no tool call); retrying once with continuation nudge (#3905)`); + loggerLog("warn", `[acp-loop] announcement-tail auto-retry round ${round} (session ${ctx.session.id})`); + } else { + ctx.log(`[acp-loop] round ${round}: terminal turn ends with a compression-draft closing tag and no tool call; retrying once with continuation nudge (#2303)`); + loggerLog("warn", `[acp-loop] draft-tail auto-retry round ${round} (session ${ctx.session.id})`); + } const nudge: CoreMessage = { id: `acp_draft_tail_retry_r${round}`, role: "user", @@ -1145,11 +1169,11 @@ export async function* runCompressLoop( continue; } catch (e) { if (e instanceof UpstreamHttpError) { - ctx.log(`[acp-loop] round ${round}: draft-tail retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); passing the turn through`); + ctx.log(`[acp-loop] round ${round}: stalled-tail retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); passing the turn through`); } else { - ctx.log(`[acp-loop] round ${round}: draft-tail retry failed (${e instanceof Error ? e.message : String(e)}); passing the turn through`); + ctx.log(`[acp-loop] round ${round}: stalled-tail retry failed (${e instanceof Error ? e.message : String(e)}); passing the turn through`); } - loggerLog("warn", `[acp-loop] draft-tail auto-retry failed round ${round}: ${e instanceof Error ? e.message : String(e)}`); + loggerLog("warn", `[acp-loop] stalled-tail auto-retry failed round ${round}: ${e instanceof Error ? e.message : String(e)}`); } } break; @@ -1216,7 +1240,18 @@ export async function* runCompressLoop( ctx.log(`[acp-loop] suppressed duplicate ${call.name} status marker (identical failure repeated this request)`); } else { seenMarkers.add(markerKey); - yield adapter.emitMarker(call.name, result.text); + // #3906: streamMarkers=false keeps the receipt in the + // rebuilt history (and in the round-N+1 system message + // below) while keeping it OUT of the client's content + // stream. The marker is an assistant-prose delta emitted + // before the continuation re-request, so on a client that + // keys one text part per assistant message (opencode's + // openai-compatible transform uses a fixed txt-0) it opens + // the text part and the round-2 answer merges into it while + // round-2 reasoning opens a NEW part after it β€” the answer + // renders above the thinking that produced it and the turn + // appears to end mid-thought. + if (ctx.streamMarkers !== false) yield adapter.emitMarker(call.name, result.text); } } } else { diff --git a/src/plugin.ts b/src/plugin.ts index 9a4167fa50..70e5efeefe 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -58,7 +58,7 @@ function tailLooksTerminal(tail: string, protocol: WireProtocol | "responses"): return /event: response\.(?:completed|failed|incomplete)/.test(tail.slice(0, 64)) || /"type"\s*:\s*"response\.(?:completed|failed|incomplete)"/.test(tail); } -import { degenerateTurnWarning, endsWithDraftClose, requestExpectsProseSummary } from "./degenerate-turn.js"; +import { degenerateTurnWarning, endsWithAnnouncement, endsWithDraftClose, requestExpectsProseSummary } from "./degenerate-turn.js"; import { getChangelog, latestChangelog, warmChangelogOnce } from "./web/changelog.js"; import { PANEL_BOX_FOOTER } from "./acp-panel.js"; import { excludeDeadRefRanges } from "./acp-status.js"; @@ -2596,6 +2596,12 @@ export async function pipePluginChatWithStrip( // answer β€” a client compaction asking for a plain-text block // must not be retried (its compliant reply IS a draft tail). const draftTail = visibleTextChars > 0 && !sawToolUse && endsWithDraftClose(proseAcc) && !requestExpectsProseSummary(requestText); + // #3905: the same non-convergence without a draft tag β€” the whole visible + // output is a one-line promise of the next action ("Running verify after + // formatting:"). Without this branch the answerChars gate below would read + // that promise as a delivered answer and refuse the retry. + const announceTail = !draftTail && visibleTextChars > 0 && !sawToolUse && endsWithAnnouncement(proseAcc) && !requestExpectsProseSummary(requestText); + const stalledTail = draftTail || announceTail; // #2756: the gate asks "did the host receive ANSWER text?" β€” prose that // is nothing but whitespace (a bare "\n\n" from a degenerate stop, the // B-accident shape) is not an answer; the empty-turn retry must fire for @@ -2603,9 +2609,9 @@ export async function pipePluginChatWithStrip( // chars are already excluded here), and real text keeps refusing the // retry byte-for-byte, so a delivered answer is never duplicated. const answerChars = answerProse.trim().length; - if (!draftTail && (answerChars > 0 || sawToolUse)) return false; + if (!stalledTail && (answerChars > 0 || sawToolUse)) return false; if (reason === undefined || !CLEAN_TURN_REASONS.has(reason)) { - if (!sawToolUse && !draftTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (finish ${reason ?? "none"} is not a clean stop): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`); + if (!sawToolUse && !stalledTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (finish ${reason ?? "none"} is not a clean stop): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`); return false; } if (res.destroyed || res.writableEnded) return false; @@ -2626,14 +2632,16 @@ export async function pipePluginChatWithStrip( // re-issuing it double-bills an empty completion (#732/#821 keep the // same boundary in the compress loop). A draft-tail turn is NOT bare: // it delivered a full handoff draft, which is precisely the stall signal. - if (!sawThinking && !sawStrippedEcho && releasedMarkupChars === 0 && !draftTail) { + if (!sawThinking && !sawStrippedEcho && releasedMarkupChars === 0 && !stalledTail) { log?.(`[plugin] degenerate terminal turn not retried (bare: no thinking, no stripped echo, no released markup): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`); return false; } degenerateRetried = true; - log?.(draftTail - ? "[plugin] terminal turn ends with a compression-draft closing tag and no tool call; retrying once with a continuation nudge (#2303)" - : "[plugin] degenerate terminal turn (no usable output); retrying once with a continuation nudge (#732/#821)"); + log?.(announceTail + ? "[plugin] terminal turn is a bare announcement (ends mid-promise, no tool call); retrying once with a continuation nudge (#3905)" + : draftTail + ? "[plugin] terminal turn ends with a compression-draft closing tag and no tool call; retrying once with a continuation nudge (#2303)" + : "[plugin] degenerate terminal turn (no usable output); retrying once with a continuation nudge (#732/#821)"); let next: ReadableStream | null = null; try { next = await refetch(); @@ -4002,6 +4010,9 @@ export async function pipePluginResponsesWithStrip( // #2612: except when the request itself demands that shape (client // compaction summary instruction) β€” see the chat-pipe twin. const draftTail = (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithDraftClose(proseAcc) && !requestExpectsProseSummary(requestText); + // #3905: bare-announcement twin β€” see the chat-pipe twin above. + const announceTail = !draftTail && (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithAnnouncement(proseAcc) && !requestExpectsProseSummary(requestText); + const stalledTail = draftTail || announceTail; // #2756: same question as the chat-pipe twin β€” "did the host receive // ANSWER text?". Reasoning inlined into item.content[] (vLLM/ // llama.cpp reasoning_text) and whitespace-only output_text (a bare @@ -4009,9 +4020,9 @@ export async function pipePluginResponsesWithStrip( // bare check below, but whitespace-only answer prose must also retry. // Real answer text still refuses the retry byte-for-byte. const answerChars = answerProse.trim().length; - if (!draftTail && (answerChars > 0 || sawFunctionCall)) return false; + if (!stalledTail && (answerChars > 0 || sawFunctionCall)) return false; if (status !== "completed") { - if (!sawFunctionCall && !draftTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (status ${status ?? "none"} is not completed): visibleTextChars=${visibleTextChars}, heldVisibleChars=${heldVisibleChars} (#2756)`); + if (!sawFunctionCall && !stalledTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (status ${status ?? "none"} is not completed): visibleTextChars=${visibleTextChars}, heldVisibleChars=${heldVisibleChars} (#2756)`); return false; } if (res.destroyed || res.writableEnded) return false; @@ -4020,14 +4031,16 @@ export async function pipePluginResponsesWithStrip( // double-bills an empty completion (#732/#821 keep the same boundary in // the compress loop). A draft-tail turn delivered a full handoff draft: // precisely the stall signal. - if (!sawReasoning && !sawStrippedEcho && !draftTail) { + if (!sawReasoning && !sawStrippedEcho && !stalledTail) { log?.(`[plugin] degenerate terminal turn not retried (bare: no reasoning, no stripped echo): visibleTextChars=${visibleTextChars}, heldVisibleChars=${heldVisibleChars} (#2756)`); return false; } degenerateRetried = true; - log?.(draftTail - ? "[plugin] terminal turn ends with a compression-draft closing tag and no function call; retrying once with a continuation nudge (#2303)" - : "[plugin] degenerate terminal turn (no visible output); retrying once with a continuation nudge (#732/#821)"); + log?.(announceTail + ? "[plugin] terminal turn is a bare announcement (ends mid-promise, no function call); retrying once with a continuation nudge (#3905)" + : draftTail + ? "[plugin] terminal turn ends with a compression-draft closing tag and no function call; retrying once with a continuation nudge (#2303)" + : "[plugin] degenerate terminal turn (no visible output); retrying once with a continuation nudge (#732/#821)"); let next: ReadableStream | null = null; try { next = await refetch(); diff --git a/tests/issue3905-announcement-tail.test.ts b/tests/issue3905-announcement-tail.test.ts new file mode 100644 index 0000000000..f3e93216cf --- /dev/null +++ b/tests/issue3905-announcement-tail.test.ts @@ -0,0 +1,179 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { Config, CoreMessage } from "acp-kernel"; +import { createCore, createInitialState } from "acp-kernel"; +import { pipePluginChatWithStrip, pipePluginResponsesWithStrip } from "../src/plugin.ts"; +import { endsWithAnnouncement, endsWithDraftClose } from "../src/degenerate-turn.ts"; +import type { Session } from "../src/session.ts"; +import { runCompressLoop, createOpenaiAdapter } from "../src/loop/index.ts"; +import { buildCompressSystemPrompt } from "../src/compress-tool.ts"; + +// #2303: a terminal turn whose visible prose ends with a compression-draft +// closing tag ( / ) and no tool call used to read as a +// healthy completed turn β€” the model wrote a handoff/compression draft in prose +// instead of issuing the action it described (149 silent stops / 70 sessions, +// DSH native). All three terminal-verdict lanes must now treat it as non- +// converged and spend their one-shot continuation nudge on it: the plugin chat +// pipe, the plugin responses pipe, and the compress loop. + +// ---------- helper ---------- + +test("endsWithAnnouncement: the production stub, its ellipsis forms, and the prose boundary", () => { + // Verbatim production stub (ses_eb6da0d60ffeYpnNQDoGz000Pc, 2026-10-19 11:21:43Z, + // 24 output tokens / 32 visible chars, finish=stop, no tool call). + assert.equal(endsWithAnnouncement("\nRunning verify after formatting:"), true); + assert.equal(endsWithAnnouncement("Running verify after formatting:"), true); + assert.equal(endsWithAnnouncement("Now I'll check the three suites:"), true); + assert.equal(endsWithAnnouncement("Let me look at that output\u2026"), true, "unicode ellipsis"); + assert.equal(endsWithAnnouncement("Let me look at that output..."), true, "ascii ellipsis"); + assert.equal(endsWithAnnouncement("Running verify after formatting: \r\n"), true, "trailing whitespace"); +}); + +test("endsWithAnnouncement: rejects everything that is not a stub", () => { + assert.equal(endsWithAnnouncement(""), false); + assert.equal(endsWithAnnouncement(" \n\t "), false, "whitespace-only is the empty-turn shape, not this one"); + assert.equal(endsWithAnnouncement("All done."), false, "a normal sentence end is not a promise"); + assert.equal(endsWithAnnouncement("Deleted."), false); + assert.equal(endsWithAnnouncement("The answer is 42:"), true, "documented cost: a very short answer ending on a colon is indistinguishable from a stub"); + // The 400-char cap is the entire recall/precision boundary: a long answer + // that happens to end on a colon is prose. + assert.equal(endsWithAnnouncement("x".repeat(399) + ":"), true, "exactly 400 chars is still inside the cap"); + assert.equal(endsWithAnnouncement("x".repeat(400) + ":"), false, "401 chars is past the cap"); + assert.equal(endsWithAnnouncement("y".repeat(400)), false, "no promise tail at all"); +}); + +test("endsWithAnnouncement: disjoint from endsWithDraftClose", () => { + assert.equal(endsWithAnnouncement("handoff draft\n"), false, "#2303 owns the draft-close shape"); + assert.equal(endsWithDraftClose("Running verify after formatting:"), false, "#3905 owns the announcement shape"); +}); + +// ---------- compress loop (proxy mode) ---------- + +function makeCtx(id: string, protocol: "responses" | "openai" = "openai") { + return { + core: createCore(), + config: { modelContextLimit: 200000 } as Config, + messages: [] as CoreMessage[], + session: { + id, + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, contextTokens: 0 }, + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + } as unknown as Session, + log: () => {}, + protocol, + }; +} + +function openaiSse(frames: Array>): string { + return frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n"; +} + +const ANNOUNCE_STUB = "Running verify after formatting:"; + +const OPENAI_ANNOUNCE = openaiSse([ + { id: "chatcmpl_a1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_a1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] }, + { id: "chatcmpl_a1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, +]); + +const OPENAI_ANSWER_END_COLON = openaiSse([ + { id: "chatcmpl_n1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_n1", choices: [{ index: 0, delta: { content: "Here is the full explanation of the three failing suites:" }, finish_reason: null }] }, + { id: "chatcmpl_n1", choices: [{ index: 0, delta: { content: " 1) aaaa 2) bbbb 3) cccc and the remainder of a genuinely long answer that keeps going well past the cap" }, finish_reason: null }] }, + { id: "chatcmpl_n1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, +]); + +const OPENAI_GOOD = openaiSse([ + { id: "chatcmpl_g1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_g1", choices: [{ index: 0, delta: { content: "continued after nudge" }, finish_reason: null }] }, + { id: "chatcmpl_g1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, +]); + +async function drainOpenai(first: string, retries: string[], id: string): Promise<{ out: string; fetchCalls: number; bodies: string[] }> { + let fetchCalls = 0; + const bodies: string[] = []; + const orig = globalThis.fetch; + globalThis.fetch = (async (_url: unknown, init?: { body?: unknown }) => { + fetchCalls++; + if (init?.body !== undefined) bodies.push(typeof init.body === "string" ? init.body : String(init.body)); + const body = retries[fetchCalls - 1] ?? ""; + return new Response(body, { status: 200 }); + }) as typeof fetch; + const chunks: Buffer[] = []; + try { + const ctx = makeCtx(id, "openai"); + for await (const chunk of runCompressLoop( + new Response(first, { status: 200 }).body!, + ctx, + { model: "deepseek-chat", stream: true }, + { url: "http://mock", headers: {} }, + createOpenaiAdapter({ model: "deepseek-chat", stream: true }), + buildCompressSystemPrompt(), + )) { + chunks.push(chunk); + } + } finally { + globalThis.fetch = orig; + } + return { out: Buffer.concat(chunks).toString("utf8"), fetchCalls, bodies }; +} + +test("#3905 loop: a bare announcement β†’ one invisible retry with the continuation nudge", async () => { + const { out, fetchCalls, bodies } = await drainOpenai(OPENAI_ANNOUNCE, [OPENAI_GOOD], "at-l1"); + assert.equal(fetchCalls, 1, "exactly one announcement-tail auto-retry"); + assert.ok(bodies[0]!.includes("ended without a tool call"), "the retry carries the continuation nudge"); + assert.ok(out.includes(ANNOUNCE_STUB), "the stub itself reached the client (the host already rendered it)"); + assert.ok(out.includes("continued after nudge"), "the retried turn's content was delivered"); +}); + +test("#3905 loop: one-shot bound β€” an announcement RETRY is not retried again", async () => { + const { fetchCalls } = await drainOpenai(OPENAI_ANNOUNCE, [OPENAI_ANNOUNCE], "at-l2"); + assert.equal(fetchCalls, 1, "one retry max; a second announcement falls through to the plain completion"); +}); + +test("#3905 loop: a long answer ending on a colon is NOT retried", async () => { + const { fetchCalls } = await drainOpenai(OPENAI_ANSWER_END_COLON, [OPENAI_GOOD], "at-l3"); + assert.equal(fetchCalls, 0, "the 400-char cap keeps real prose out of the retry"); +}); + +test("#3905 loop: a normal completed turn is NOT retried", async () => { + const normal = openaiSse([ + { id: "chatcmpl_z1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_z1", choices: [{ index: 0, delta: { content: "all steps finished, nothing pending" }, finish_reason: null }] }, + { id: "chatcmpl_z1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, + ]); + const { fetchCalls } = await drainOpenai(normal, [OPENAI_GOOD], "at-l4"); + assert.equal(fetchCalls, 0); +}); + +test("#3905 loop: an announcement WITH a tool call is NOT retried", async () => { + const withCall = openaiSse([ + { id: "chatcmpl_t1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_t1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] }, + { id: "chatcmpl_t1", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "bash", arguments: "{}" } }] }, finish_reason: null }] }, + { id: "chatcmpl_t1", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }, + ]); + const { fetchCalls } = await drainOpenai(withCall, [OPENAI_GOOD], "at-l5"); + assert.equal(fetchCalls, 0, "a tool call means the step converges"); +}); + +test("#3905 loop: a length-cut announcement retries like the #2303 sibling", async () => { + const lengthCut = openaiSse([ + { id: "chatcmpl_l1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_l1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] }, + { id: "chatcmpl_l1", choices: [{ index: 0, delta: {}, finish_reason: "length" }] }, + ]); + const { fetchCalls } = await drainOpenai(lengthCut, [OPENAI_GOOD], "at-l6"); + // Verified against the shipped #2303 implementation: a draft tail ending on + // finish=length is retried there too (fetchCalls === 1). The loop's gate + // excludes only failed/incomplete/error, so `length` is in scope for both + // shapes β€” matching the sibling rather than inventing a stricter rule. + assert.equal(fetchCalls, 1, "matches the #2303 sibling's treatment of finish=length"); +}); From fa60f8f7f57fcf65153d20f52f8c8108370af5c9 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 27 Oct 2026 16:25:07 +0800 Subject: [PATCH 2/5] =?UTF-8?q?refactor(loop):=20strip=20#3906=20streamMar?= =?UTF-8?q?kers=20hunks=20=E2=80=94=20owned=20by=20PR=20#4934?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Align-refactor (review of #4935): this PR is scoped to the bare-announcement terminal-turn retry (#3905 symptom), but it also carried the LoopCtx streamMarkers field and the emitMarker consumption gate that belong to the streamMarkers setting feature. That feature has its own PR (#4934, which wires the config surface but lacks these two hunks) β€” keeping them here makes #4934 unable to compile standalone and creates a merge-order dependency between two independent features. The hunks move to #4934 so each PR is a closed loop. --- src/loop/core.ts | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/src/loop/core.ts b/src/loop/core.ts index 2bd8e041ab..9eeb167323 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -218,13 +218,6 @@ export interface LoopCtx { * rebuilt history. Default (undefined) keeps markers on. Paired * tool-call/tool-result messages are unaffected. */ visibilityMarkers?: boolean; - /** #3906: when `false`, keep the πŸ“¦/❌ ACP receipt in rebuilt history (and in - * the round-N+1 system message the model sees) but stop emitting it into - * the client's content stream. Independent of `visibilityMarkers`: this is - * the cosmetic-only switch for clients that merge the marker into the - * assistant's single text part, which makes the answer render above the - * reasoning that produced it. Default (undefined) keeps streaming. */ - streamMarkers?: boolean; /** #1455: tee loop-originated upstream responses (re-request and every * retry fetch) to raw SSE files β€” the outer request's ACP_DUMP_SSE tee * only covers the FIRST response, so an internal re-request that dies @@ -1240,18 +1233,7 @@ export async function* runCompressLoop( ctx.log(`[acp-loop] suppressed duplicate ${call.name} status marker (identical failure repeated this request)`); } else { seenMarkers.add(markerKey); - // #3906: streamMarkers=false keeps the receipt in the - // rebuilt history (and in the round-N+1 system message - // below) while keeping it OUT of the client's content - // stream. The marker is an assistant-prose delta emitted - // before the continuation re-request, so on a client that - // keys one text part per assistant message (opencode's - // openai-compatible transform uses a fixed txt-0) it opens - // the text part and the round-2 answer merges into it while - // round-2 reasoning opens a NEW part after it β€” the answer - // renders above the thinking that produced it and the turn - // appears to end mid-thought. - if (ctx.streamMarkers !== false) yield adapter.emitMarker(call.name, result.text); + yield adapter.emitMarker(call.name, result.text); } } } else { From aec1e1b01db5586dca3e0e6865602c49e95a035c Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 27 Oct 2026 16:25:07 +0800 Subject: [PATCH 3/5] fix(degenerate-turn): implement the action-cue + closed-fence gates the PR body describes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Align-refactor (review of #4935): the PR body promises detection is 'accompanied by common action announcement verbs' and requires 'no markdown code fence open', but the shipped detector was tail-char + length only β€” any turn under 400 chars ending in ':' or ellipsis qualified, including legitimate short answers ('The answer is 42:') that would now cost an extra billed completion call each. Implement both promised gates: an ANNOUNCE_CUE word list (progressing forms + intent phrases only, mirroring the body's examples) and a reject on odd backtick-fence count (an unclosed fence is the #1755/#2190 truncation class, not a stall). English-first by design: non-English announcements keep the pre-#3905 no-retry behavior until traffic evidence justifies extending the cue list. --- src/degenerate-turn.ts | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/degenerate-turn.ts b/src/degenerate-turn.ts index 7bb11d922b..346f7ee7c4 100644 --- a/src/degenerate-turn.ts +++ b/src/degenerate-turn.ts @@ -73,23 +73,38 @@ export function endsWithDraftClose(text: string): boolean { } // #3905: the announcement-tail shape. Unlike #2303 there is no draft tag: the -// ENTIRE visible output of the turn is a one-line promise of the next action +// ENTIRE visible output of the turn is a short promise of the next action // ("Running verify after formatting:") that ends on a colon or ellipsis, with // no tool call and a clean stop. The upstream reports a healthy turn, the host // gets nothing actionable, and the session stalls until the user types // something. Observed verbatim at 24 output tokens / 32 visible chars behind a // deepseek-v4.1-flash combo member. // -// The character cap is the whole precision boundary, not a performance guard: -// a genuine answer that happens to end on a colon is prose, and prose is long. -// 400 chars sits an order of magnitude above the observed stub and well below -// any real answer tail. -const ANNOUNCE_TAIL = /(?::|\u2026|\.\.\.)\s*$/; +// Three precision boundaries β€” each one denies a real answer class that the +// raw tail shape alone would misread as a stall (a false positive burns the +// one-shot BILLED retry on a turn that was already complete): +// 1. length cap: a genuine answer that happens to end on a colon is prose, +// and prose is long. 400 chars sits an order of magnitude above the +// observed stub and well below any real answer tail. +// 2. action-intent cue: a bare colon/ellipsis appears in legitimate short +// answers ("The answer is 42:", "I'm not sure…"). Only progressive-form +// action verbs and first-person intent phrases count as cues β€” the forms +// the production stubs actually use. The list is English-first by design: +// non-English announcements keep pre-#3905 behavior (no retry) until +// traffic evidence justifies more languages. +// 3. closed code fence: an UNCLOSED fence means the output was cut inside a +// code block β€” the truncated-output defect class (#1755/#2190), not a +// stalled promise; retrying it as an announcement would double-bill a +// length cut. +const ANNOUNCE_TAIL = /(?::|…|\.\.\.)\s*$/; const ANNOUNCE_MAX_CHARS = 400; +const ANNOUNCE_CUE = /\b(?:let me|i(?:'ll| will)|going to|gonna|running|checking|testing|inspecting|examining|looking|applying|adding|removing|updating|fixing|building|installing|scanning|verifying|formatting|cleaning|writing|reading|searching|starting|committing|pushing|deploying|restarting|compiling|linting|patching)\b/i; export function endsWithAnnouncement(text: string): boolean { const t = text.trimEnd(); if (t.length === 0 || t.length > ANNOUNCE_MAX_CHARS) return false; - return ANNOUNCE_TAIL.test(t); + if ((t.match(/```/g)?.length ?? 0) % 2 === 1) return false; + if (!ANNOUNCE_TAIL.test(t)) return false; + return ANNOUNCE_CUE.test(t); } // #2612: the #2303 draft-tail shape has a legitimate producer β€” the CLIENT's From 206ddc973178f753ab85e3a6b9bbf2721ec76780 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 27 Oct 2026 16:25:07 +0800 Subject: [PATCH 4/5] test(issue3905): cover plugin chat/responses lanes like the #2303 sibling; pin the 400-char cap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Align-refactor (review of #4935): the suite only covered unit + compress-loop lanes while the change also rewires pipePluginChatWithStrip and pipePluginResponsesWithStrip terminal classification β€” the #2303 sibling suite covers all three lanes, so match that bar: plugin chat positive (#3905 log line, one [DONE], single finish_reason stop), colon-answer and ellipsis-answer negatives, tool-call exclusion, retry-degenerates in-band error (#870); responses-pipe mirror set. Also fix at-l3, whose 'long answer' fixture did not actually end on the tail char and passed for the wrong reason β€” the rewritten fixture (441 chars, cue-bearing, colon tail) pins the length cap itself at loop level. Drop dead imports. --- tests/issue3905-announcement-tail.test.ts | 305 +++++++++++++++++++--- 1 file changed, 271 insertions(+), 34 deletions(-) diff --git a/tests/issue3905-announcement-tail.test.ts b/tests/issue3905-announcement-tail.test.ts index f3e93216cf..75c4f1635b 100644 --- a/tests/issue3905-announcement-tail.test.ts +++ b/tests/issue3905-announcement-tail.test.ts @@ -8,43 +8,280 @@ import type { Session } from "../src/session.ts"; import { runCompressLoop, createOpenaiAdapter } from "../src/loop/index.ts"; import { buildCompressSystemPrompt } from "../src/compress-tool.ts"; -// #2303: a terminal turn whose visible prose ends with a compression-draft -// closing tag ( / ) and no tool call used to read as a -// healthy completed turn β€” the model wrote a handoff/compression draft in prose -// instead of issuing the action it described (149 silent stops / 70 sessions, -// DSH native). All three terminal-verdict lanes must now treat it as non- -// converged and spend their one-shot continuation nudge on it: the plugin chat -// pipe, the plugin responses pipe, and the compress loop. - -// ---------- helper ---------- - -test("endsWithAnnouncement: the production stub, its ellipsis forms, and the prose boundary", () => { - // Verbatim production stub (ses_eb6da0d60ffeYpnNQDoGz000Pc, 2026-10-19 11:21:43Z, - // 24 output tokens / 32 visible chars, finish=stop, no tool call). - assert.equal(endsWithAnnouncement("\nRunning verify after formatting:"), true); - assert.equal(endsWithAnnouncement("Running verify after formatting:"), true); +// #3905: a terminal turn whose ENTIRE visible output is a short promise of the +// next action ("Running verify after formatting:") ending on a colon or +// ellipsis, with no tool call and a clean stop, used to read as a healthy +// completed turn β€” the model announced the action instead of issuing it, and +// the session stalls until the user types something (verbatim production stub: +// ses_eb6da0d60ffeYpnNQDoGz000Pc, deepseek-v4.1-flash combo member, 24 output +// tokens / 32 visible chars, finish=stop). All three terminal-verdict lanes +// must treat it as non-converged and spend their one-shot continuation nudge +// on it: the plugin chat pipe, the plugin responses pipe, and the compress +// loop β€” mirroring the #2303 draft-tail suite. + +// ---------- detector unit ---------- + +const ANNOUNCE_STUB = "Running verify after formatting:"; + +test("endsWithAnnouncement: the production stubs and their ellipsis forms", () => { + assert.equal(endsWithAnnouncement("\n" + ANNOUNCE_STUB), true, "leading newline is stream residue"); + assert.equal(endsWithAnnouncement(ANNOUNCE_STUB), true); assert.equal(endsWithAnnouncement("Now I'll check the three suites:"), true); assert.equal(endsWithAnnouncement("Let me look at that output\u2026"), true, "unicode ellipsis"); assert.equal(endsWithAnnouncement("Let me look at that output..."), true, "ascii ellipsis"); - assert.equal(endsWithAnnouncement("Running verify after formatting: \r\n"), true, "trailing whitespace"); + assert.equal(endsWithAnnouncement(`${ANNOUNCE_STUB} \r\n`), true, "trailing whitespace"); }); -test("endsWithAnnouncement: rejects everything that is not a stub", () => { +test("endsWithAnnouncement: legitimate short answers ending on a colon or ellipsis are NOT stubs", () => { assert.equal(endsWithAnnouncement(""), false); assert.equal(endsWithAnnouncement(" \n\t "), false, "whitespace-only is the empty-turn shape, not this one"); assert.equal(endsWithAnnouncement("All done."), false, "a normal sentence end is not a promise"); assert.equal(endsWithAnnouncement("Deleted."), false); - assert.equal(endsWithAnnouncement("The answer is 42:"), true, "documented cost: a very short answer ending on a colon is indistinguishable from a stub"); - // The 400-char cap is the entire recall/precision boundary: a long answer - // that happens to end on a colon is prose. - assert.equal(endsWithAnnouncement("x".repeat(399) + ":"), true, "exactly 400 chars is still inside the cap"); - assert.equal(endsWithAnnouncement("x".repeat(400) + ":"), false, "401 chars is past the cap"); + assert.equal(endsWithAnnouncement("The answer is 42:"), false, "colon without an action-intent cue is a complete short answer"); + assert.equal(endsWithAnnouncement("I'm not sure\u2026"), false, "ellipsis without a cue is prose"); + assert.equal(endsWithAnnouncement("I'm not sure..."), false); + assert.equal(endsWithAnnouncement("Here is how to run it:"), false, "base-form 'run' inside an explanation is not a cue (progressive forms + intent phrases only)"); +}); + +test("endsWithAnnouncement: the 400-char cap stays the length boundary once a cue is present", () => { + const pad = (total: number) => `${ANNOUNCE_STUB.slice(0, -1)}${"a".repeat(total - ANNOUNCE_STUB.length)}:`; + assert.equal(endsWithAnnouncement(pad(400)), true, "exactly 400 chars is still inside the cap"); + assert.equal(endsWithAnnouncement(pad(401)), false, "401 chars is past the cap"); assert.equal(endsWithAnnouncement("y".repeat(400)), false, "no promise tail at all"); }); +test("endsWithAnnouncement: an unclosed code fence is the truncation class, not a stall (#1755/#2190)", () => { + assert.equal(endsWithAnnouncement("Running the tests:\n```\nstep one:"), false, "odd fence count β€” cut inside a code block"); + assert.equal(endsWithAnnouncement("Running the tests:\n```\nconst a = 1;\n```"), false, "closed fence, and no promise tail either"); +}); + test("endsWithAnnouncement: disjoint from endsWithDraftClose", () => { assert.equal(endsWithAnnouncement("handoff draft\n"), false, "#2303 owns the draft-close shape"); - assert.equal(endsWithDraftClose("Running verify after formatting:"), false, "#3905 owns the announcement shape"); + assert.equal(endsWithDraftClose(ANNOUNCE_STUB), false, "#3905 owns the announcement shape"); +}); + +// ---------- shared fixtures ---------- + +function makeSession(): Session { + return { + id: "testsess", + protocol: "openai", + upstreamOrigin: "http://127.0.0.1:9/v1", + label: "test", + createdAt: 0, + lastUsedAt: 0, + requests: 0, + lastInputTokens: 0, + stats: {}, + dirty: false, + } as unknown as Session; +} + +function makeRes(chunks: string[]) { + return { + writes: chunks, + write(b: Buffer | string) { + chunks.push(typeof b === "string" ? b : b.toString("utf8")); + return true; + }, + end(b?: Buffer | string) { + if (b !== undefined) chunks.push(typeof b === "string" ? b : b.toString("utf8")); + }, + once() {}, + destroyed: false, + writableEnded: false, + } as unknown as import("node:http").ServerResponse; +} + +function streamOf(events: string[]): ReadableStream { + const enc = new TextEncoder(); + let i = 0; + return new ReadableStream({ + pull(controller) { + if (i < events.length) { + controller.enqueue(enc.encode(events[i])); + i += 1; + } else { + controller.close(); + } + }, + }); +} + +function chatChunk(delta: Record): string { + return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`; +} + +const DONE = "data: [DONE]\n\n"; + +function chatStop(reason = "stop"): string { + return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta: {}, finish_reason: reason }] })}\n\n`; +} + +const sse = (event: string, data: unknown): string => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; + +/** The production shape (sanitized): the whole visible output is the one-line + * promise, delivered as the message's text with no tool call. */ +function announceTurn(): string[] { + return [chatChunk({ role: "assistant" }), chatChunk({ content: `\n${ANNOUNCE_STUB}` }), chatStop(), DONE]; +} + +function proseTurn(text: string): string[] { + return [chatChunk({ role: "assistant" }), chatChunk({ content: text }), chatStop(), DONE]; +} + +function textDeltas(raw: string): string { + return [...raw.matchAll(/"content":"((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse(`"${m[1]}"`) as string).join(""); +} + +// ---------- plugin chat pipe (the DSH native evidence lane) ---------- + +test("#3905 chat(openai): bare-announcement terminal turn spends the continuation nudge once", async () => { + const out: string[] = []; + const logs: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(proseTurn("real action issued after the nudge"))); + }; + await pipePluginChatWithStrip(streamOf(announceTurn()), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch); + const text = out.join(""); + assert.equal(calls, 1, "exactly one re-issue"); + assert.ok(textDeltas(text).includes(ANNOUNCE_STUB), "the first attempt's stub still reaches the client"); + assert.ok(textDeltas(text).endsWith("real action issued after the nudge"), "the retry's content appends to the same stream"); + assert.equal((text.match(/\[DONE\]/g) ?? []).length, 1, "one turn, one terminal"); + assert.equal((text.match(/"finish_reason":"stop"/g) ?? []).length, 1, "the first attempt's terminal is dropped, not doubled"); + assert.ok(logs.some((l) => l.includes("#3905")), `the distinct #3905 log line fired, got: ${JSON.stringify(logs)}`); +}); + +test("#3905 chat: a legitimate short answer ending on a colon is NOT retried", async () => { + const out: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(proseTurn("unwanted"))); + }; + await pipePluginChatWithStrip(streamOf(proseTurn("The answer is 42:")), makeRes(out), "openai", makeSession(), undefined, refetch); + assert.equal(calls, 0, "no action-intent cue β€” the delivered answer is never duplicated or re-billed"); +}); + +test("#3905 chat: a legitimate short answer ending on an ellipsis is NOT retried", async () => { + const out: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(proseTurn("unwanted"))); + }; + await pipePluginChatWithStrip(streamOf(proseTurn("I'm not sure\u2026")), makeRes(out), "openai", makeSession(), undefined, refetch); + assert.equal(calls, 0, "ellipsis without a cue is prose, not a promise"); +}); + +test("#3905 chat: a bare announcement WITH a tool call is NOT retried", async () => { + const out: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(proseTurn("unwanted"))); + }; + const events = [ + chatChunk({ role: "assistant" }), + chatChunk({ content: ANNOUNCE_STUB }), + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "compress", arguments: "{}" } }] }, finish_reason: null }] })}\n\n`, + chatStop("tool_calls"), + DONE, + ]; + await pipePluginChatWithStrip(streamOf(events), makeRes(out), "openai", makeSession(), undefined, refetch); + assert.equal(calls, 0, "a tool call means the step converges"); + assert.ok(out.join("").includes("compress"), "the agent's own tool call still passes through"); +}); + +test("#3905 chat: an announcement RETRY degenerates into the in-band error (#870 path)", async () => { + const out: string[] = []; + const refetch = () => Promise.resolve(streamOf(announceTurn())); + await pipePluginChatWithStrip(streamOf(announceTurn()), makeRes(out), "openai", makeSession(), undefined, refetch); + const text = out.join(""); + assert.ok( + text.includes("[ACP] stream error"), + "the client is told, rather than left with a second silent announcement", + ); +}); + +// ---------- plugin responses pipe ---------- + +function responsesAnnounceTurn(responseId = "resp_1", itemId = "item_1"): string[] { + const text = ANNOUNCE_STUB; + return [ + sse("response.created", { type: "response.created", response: { id: responseId, status: "in_progress" } }), + sse("response.output_item.added", { type: "response.output_item.added", output_index: 0, item: { id: itemId, type: "message", content: [] } }), + sse("response.content_part.added", { type: "response.content_part.added", item_id: itemId, output_index: 0, part: { type: "output_text", text: "" } }), + sse("response.output_text.delta", { type: "response.output_text.delta", item_id: itemId, output_index: 0, delta: text }), + sse("response.output_text.done", { type: "response.output_text.done", item_id: itemId, output_index: 0, text }), + sse("response.output_item.done", { type: "response.output_item.done", output_index: 0, item: { id: itemId, type: "message", content: [{ type: "output_text", text }] } }), + sse("response.completed", { type: "response.completed", response: { id: responseId, status: "completed", output: [{ id: itemId, type: "message", content: [{ type: "output_text", text }] }] } }), + ]; +} + +function responsesProseTurn(text: string, responseId = "resp_2", itemId = "item_2"): string[] { + return [ + sse("response.created", { type: "response.created", response: { id: responseId, status: "in_progress" } }), + sse("response.output_item.added", { type: "response.output_item.added", output_index: 0, item: { id: itemId, type: "message", content: [] } }), + sse("response.content_part.added", { type: "response.content_part.added", item_id: itemId, output_index: 0, part: { type: "output_text", text: "" } }), + sse("response.output_text.delta", { type: "response.output_text.delta", item_id: itemId, output_index: 0, delta: text }), + sse("response.output_text.done", { type: "response.output_text.done", item_id: itemId, output_index: 0, text }), + sse("response.output_item.done", { type: "response.output_item.done", output_index: 0, item: { id: itemId, type: "message", content: [{ type: "output_text", text }] } }), + sse("response.completed", { type: "response.completed", response: { id: responseId, status: "completed", output: [{ id: itemId, type: "message", content: [{ type: "output_text", text }] }] } }), + ]; +} + +function responsesDeltas(raw: string): string { + return [...raw.matchAll(/"delta":"((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse(`"${m[1]}"`) as string).join(""); +} + +test("#3905 responses: bare-announcement completed turn spends the continuation nudge once", async () => { + const out: string[] = []; + const logs: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(responsesProseTurn("recovered after the nudge"))); + }; + await pipePluginResponsesWithStrip(streamOf(responsesAnnounceTurn()), makeRes(out), makeSession(), (m) => logs.push(m), refetch); + const text = out.join(""); + assert.equal(calls, 1, "exactly one re-issue"); + assert.ok(responsesDeltas(text).includes(ANNOUNCE_STUB), "the first attempt's stub still reaches the client"); + assert.ok(responsesDeltas(text).endsWith("recovered after the nudge"), "the retry's prose appends to the same item"); + assert.equal((text.match(/"type":"response\.created"/g) ?? []).length, 1, "the retry does not open a second response"); + assert.equal((text.match(/"type":"response\.completed"/g) ?? []).length, 1, "one turn, one terminal"); + assert.ok(!text.includes("item_2") && !text.includes("resp_2"), `the retry's ids are rewritten onto the client's, got: ${text}`); + assert.ok(logs.some((l) => l.includes("#3905")), `the distinct #3905 log line fired, got: ${JSON.stringify(logs)}`); +}); + +test("#3905 responses: a legitimate short answer ending on an ellipsis is NOT retried", async () => { + const out: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(responsesProseTurn("unwanted"))); + }; + await pipePluginResponsesWithStrip(streamOf(responsesProseTurn("I'm not sure...")), makeRes(out), makeSession(), undefined, refetch); + assert.equal(calls, 0, "ellipsis without a cue is prose, not a promise"); +}); + +test("#3905 responses: a bare announcement WITH a function call is NOT retried", async () => { + const out: string[] = []; + let calls = 0; + const refetch = () => { + calls += 1; + return Promise.resolve(streamOf(responsesProseTurn("unwanted"))); + }; + const events = [ + sse("response.created", { type: "response.created", response: { id: "resp_1", status: "in_progress" } }), + sse("response.output_item.added", { type: "response.output_item.added", output_index: 0, item: { id: "item_1", type: "function_call", name: "read" } }), + sse("response.output_text.delta", { type: "response.output_text.delta", item_id: "item_1", output_index: 0, delta: ANNOUNCE_STUB }), + sse("response.completed", { type: "response.completed", response: { id: "resp_1", status: "completed", output: [{ id: "item_1", type: "function_call" }] } }), + ]; + await pipePluginResponsesWithStrip(streamOf(events), makeRes(out), makeSession(), undefined, refetch); + assert.equal(calls, 0, "a function call means the step converges"); }); // ---------- compress loop (proxy mode) ---------- @@ -75,21 +312,12 @@ function openaiSse(frames: Array>): string { return frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n"; } -const ANNOUNCE_STUB = "Running verify after formatting:"; - const OPENAI_ANNOUNCE = openaiSse([ { id: "chatcmpl_a1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, { id: "chatcmpl_a1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] }, { id: "chatcmpl_a1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, ]); -const OPENAI_ANSWER_END_COLON = openaiSse([ - { id: "chatcmpl_n1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, - { id: "chatcmpl_n1", choices: [{ index: 0, delta: { content: "Here is the full explanation of the three failing suites:" }, finish_reason: null }] }, - { id: "chatcmpl_n1", choices: [{ index: 0, delta: { content: " 1) aaaa 2) bbbb 3) cccc and the remainder of a genuinely long answer that keeps going well past the cap" }, finish_reason: null }] }, - { id: "chatcmpl_n1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, -]); - const OPENAI_GOOD = openaiSse([ { id: "chatcmpl_g1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, { id: "chatcmpl_g1", choices: [{ index: 0, delta: { content: "continued after nudge" }, finish_reason: null }] }, @@ -138,8 +366,17 @@ test("#3905 loop: one-shot bound β€” an announcement RETRY is not retried again" assert.equal(fetchCalls, 1, "one retry max; a second announcement falls through to the plain completion"); }); -test("#3905 loop: a long answer ending on a colon is NOT retried", async () => { - const { fetchCalls } = await drainOpenai(OPENAI_ANSWER_END_COLON, [OPENAI_GOOD], "at-l3"); +test("#3905 loop: a cue-bearing answer PAST the 400-char cap is NOT retried", async () => { + // 441 chars with a real action cue ("Running") and a colon tail: ONLY the + // length cap can deny it, so this pins the cap itself at loop level. + const longCueAnswer = ("Running through the failing suites: " + "lorem ipsum dolor sit amet ".repeat(15)).trimEnd() + ":"; + assert.ok(longCueAnswer.length > 400, `fixture drifted: ${longCueAnswer.length}`); + const longTurn = openaiSse([ + { id: "chatcmpl_n1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_n1", choices: [{ index: 0, delta: { content: longCueAnswer }, finish_reason: null }] }, + { id: "chatcmpl_n1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, + ]); + const { fetchCalls } = await drainOpenai(longTurn, [OPENAI_GOOD], "at-l3"); assert.equal(fetchCalls, 0, "the 400-char cap keeps real prose out of the retry"); }); From 76c98b8aec00e59c33bcb1976abbc0e3380fd514 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 27 Oct 2026 16:35:39 +0800 Subject: [PATCH 5/5] fix(plugin): announcement-tail detector must read answer prose, not proseAcc (#3905) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit proseAcc accumulates every streamed text field including the thinking/ reasoning channel. endsWithAnnouncement(proseAcc) therefore saw the tail of the model's internal monologue: a thought ending mid-sentence on ':' or an ellipsis followed by a whitespace-only answer was reclassified as a bare announcement (the new #3905 branch) instead of the #2756 degenerate shape β€” the retry still fired but under the wrong log line, and a whitespace-only turn on an unclean finish lost its 'not retried ... not a clean stop' refusal log entirely (stalledTail suppressed it). Two subtests in tests/issue2756-degenerate-gate.test.ts went red on every shard-3 CI leg. Operand swap to answerProse in both plugin pipes (chat + responses). The compress-loop twin already tests text-only assistantText and is unaffected. --- src/plugin.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/plugin.ts b/src/plugin.ts index 70e5efeefe..80b27ee6fc 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -2600,7 +2600,12 @@ export async function pipePluginChatWithStrip( // output is a one-line promise of the next action ("Running verify after // formatting:"). Without this branch the answerChars gate below would read // that promise as a delivered answer and refuse the retry. - const announceTail = !draftTail && visibleTextChars > 0 && !sawToolUse && endsWithAnnouncement(proseAcc) && !requestExpectsProseSummary(requestText); + // The detector reads ANSWER prose, not proseAcc: proseAcc also carries + // the thinking/reasoning channel, and a thought that ends mid-sentence on + // ":" or "…" is internal monologue, not an announcement β€” feeding it here + // reclassified #2756's whitespace-only degenerate stops as announcements + // and swallowed their refusal/retry logs. + const announceTail = !draftTail && visibleTextChars > 0 && !sawToolUse && endsWithAnnouncement(answerProse) && !requestExpectsProseSummary(requestText); const stalledTail = draftTail || announceTail; // #2756: the gate asks "did the host receive ANSWER text?" β€” prose that // is nothing but whitespace (a bare "\n\n" from a degenerate stop, the @@ -4010,8 +4015,9 @@ export async function pipePluginResponsesWithStrip( // #2612: except when the request itself demands that shape (client // compaction summary instruction) β€” see the chat-pipe twin. const draftTail = (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithDraftClose(proseAcc) && !requestExpectsProseSummary(requestText); - // #3905: bare-announcement twin β€” see the chat-pipe twin above. - const announceTail = !draftTail && (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithAnnouncement(proseAcc) && !requestExpectsProseSummary(requestText); + // #3905: bare-announcement twin β€” see the chat-pipe twin above + // (including why the detector reads answerProse, not proseAcc). + const announceTail = !draftTail && (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithAnnouncement(answerProse) && !requestExpectsProseSummary(requestText); const stalledTail = draftTail || announceTail; // #2756: same question as the chat-pipe twin β€” "did the host receive // ANSWER text?". Reasoning inlined into item.content[] (vLLM/