Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Make Stop respond immediately and suppress post-stop replies (#1477)

Regan Bell63ea6d422e34
diff --git a/docs/screenshots/responsive-stop/running.png b/docs/screenshots/responsive-stop/running.png
new file mode 100644
index 000000000..1b49d1090
Binary files /dev/null and b/docs/screenshots/responsive-stop/running.png differ
diff --git a/docs/screenshots/responsive-stop/stopped.png b/docs/screenshots/responsive-stop/stopped.png
new file mode 100644
index 000000000..a08fbe408
Binary files /dev/null and b/docs/screenshots/responsive-stop/stopped.png differ
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 81a7afe69..c7701917f 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -27,6 +27,7 @@ import { repeat } from "lit/directives/repeat.js";
import { ref } from "lit/directives/ref.js";
import {
Activity,
+ Ban,
BookOpen,
Search,
Brain,
@@ -1352,7 +1353,7 @@ export function createChatSurface(
if (activePendingApprovals().length) return "Needs your approval";
if (agent.state.isStreaming || chatState.resolvingApprovals.size > 0) {
const work = chatState.liveWork ?? { status: "thinking", activity: [] };
- if (runSlot.stopGeneration === runSlot.generation) return "Stopping…";
+ if (runSlot.stopGeneration === runSlot.generation) return "Stop requested";
if (currentTextPhase(work)?.phase === "final_answer") return "Responding…";
const summary = liveWorkSummary(work);
if (!summary) return "Thinking…";
@@ -1870,6 +1871,7 @@ export function createChatSurface(
}
function assistantContent(message: AssistantMessage, isStreaming = false, hasWork = false): TemplateResult[] {
+ const animating = isStreaming && runSlot.stopGeneration !== runSlot.generation;
const parts: TemplateResult[] = [];
for (const [chunkIndex, chunk] of message.content.entries()) {
if (chunk.type === "text") {
@@ -1900,8 +1902,8 @@ export function createChatSurface(
const body = links.length ? stripConnectorLinks(shown, links) : shown;
if (body.trim())
parts.push(
- html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}" dir="auto">
- ${markdown(body, isStreaming, streamingFinal ? ((message as AssistantWork).streamingBaseline ?? "").slice(phase.streamOffset) : ((message as AssistantWork).streamingBaseline ?? ""))}
+ html`<div class="streaming-text ${animating ? "live-stream" : ""}" dir="auto">
+ ${markdown(body, animating, streamingFinal ? ((message as AssistantWork).streamingBaseline ?? "").slice(phase.streamOffset) : ((message as AssistantWork).streamingBaseline ?? ""))}
</div>`,
);
for (const link of links) parts.push(connectorWidget(link));
@@ -1910,7 +1912,7 @@ export function createChatSurface(
if (chunk.type === "thinking" && chunk.thinking.trim()) {
parts.push(
html`<details class="thinking">
- <summary>${sheenLabel("Thinking", isStreaming)}</summary>
+ <summary>${sheenLabel("Thinking", animating)}</summary>
${markdown(chunk.thinking)}
</details>`,
);
@@ -2254,11 +2256,12 @@ export function createChatSurface(
function liveWorkStatus(agent: Agent): TemplateResult | typeof nothing {
if (!agent.state.isStreaming && chatState.resolvingApprovals.size === 0) return nothing;
+ if (runSlot.stopGeneration === runSlot.generation)
+ return html`<div class="stopped-head" role="status">${icon(Ban, 13)}<span>Stop requested</span></div>`;
const work = chatState.liveWork ?? { status: "thinking", activity: [] };
if (work.status !== "thinking" && work.status !== "working") return nothing;
if (currentTextPhase(work)?.phase === "final_answer" || shouldShowWork(work, "")) return nothing;
- const stopping = runSlot.stopGeneration === runSlot.generation;
- const summary = stopping ? null : liveWorkSummary(work);
+ const summary = liveWorkSummary(work);
const expandable = Boolean(summary?.detail);
const expanded = expandable && liveWorkExpanded;
let title = "";
@@ -2275,7 +2278,7 @@ export function createChatSurface(
>
${summary ? html`<span class="tool-icon">${icon(summary.icon, 15)}</span>` : nothing}
<span class="live-work-label"
- >${summary ? summary.label : sheenLabel(stopping ? "Stopping…" : `Thinking${usedToolsSuffix(work)}`, true)}</span
+ >${summary ? summary.label : sheenLabel(`Thinking${usedToolsSuffix(work)}`, true)}</span
>
${summary?.detail ? html`<span class="live-work-detail">${summary.detail}</span>` : nothing}
${expandable ? html`<span class="live-work-toggle">${icon(ChevronRight, 14)}</span>` : nothing}
@@ -2378,8 +2381,9 @@ export function createChatSurface(
return false;
});
const tail = active ? streamingTextTail(text, work.activity) : "";
- const stopping = active && runSlot.stopGeneration === runSlot.generation;
- let label = stopping ? "Stopping…" : workLabel(work);
+ const stopping = isStreaming && runSlot.stopGeneration === runSlot.generation;
+ const animating = active && !stopping;
+ let label = stopping ? "Stop requested" : workLabel(work);
if (stopped) label = `You stopped after ${goalElapsedLabel(0, workSeconds(work) * 1000)}`;
let fold =
timeline.length || tail.trim() || work.pendingApprovals?.length
@@ -2388,7 +2392,7 @@ export function createChatSurface(
?open=${active || !!work.pendingApprovals?.length}
>
<summary class=${stopped ? "stopped-head" : "work-head"}>
- ${sheenLabel(label, active)}<span class="activity-chevron">${icon(ChevronRight, 14)}</span>
+ ${sheenLabel(label, animating)}<span class="activity-chevron">${icon(ChevronRight, 14)}</span>
</summary>
${stopped ? nothing : html`<div class="work-divider"></div>`}
<div class="work-rows">
@@ -2410,7 +2414,7 @@ export function createChatSurface(
</details>`;
},
)}
- ${tail.trim() ? html`<div class="work-said streaming-text live-stream">${markdown(tail, true, streamingTextTail(baseline, work.activity))}</div>` : nothing}
+ ${tail.trim() ? html`<div class="work-said streaming-text ${animating ? "live-stream" : ""}">${markdown(tail, animating, streamingTextTail(baseline, work.activity))}</div>` : nothing}
</div>
</details>`
: nothing;
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index 4bd3f217b..e349fa10d 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -685,7 +685,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
}
function sendControls(agent: Agent): TemplateResult {
- if (!agent.state.isStreaming) {
+ if (!agent.state.isStreaming || ctx.chat.isStopping()) {
return html`<button
class="send-btn"
type="submit"
@@ -697,14 +697,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
</button>`;
}
return html`
- <button
- class="stop-btn"
- type="button"
- aria-label="Stop"
- ${tip("Stop")}
- ?disabled=${ctx.chat.isStopping()}
- @click=${() => stopStreaming(agent)}
- >
+ <button class="stop-btn" type="button" aria-label="Stop" ${tip("Stop")} @click=${() => stopStreaming(agent)}>
${icon(Square, 16)}
</button>
<button
@@ -725,7 +718,10 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
queued.push({ runId: queuedEdit.runId, text: queuedEdit.original });
if (!queued.length) return nothing;
const steerable =
- agent.state.isStreaming && ctx.chat.hasLiveRun() && harnessSupportsSteer(currentModelOption()?.harnessId ?? "");
+ agent.state.isStreaming &&
+ !ctx.chat.isStopping() &&
+ ctx.chat.hasLiveRun() &&
+ harnessSupportsSteer(currentModelOption()?.harnessId ?? "");
const steerTip = (): string => {
if (steerable) return "Steer the running task with this instead of waiting";
return "Nothing running can take this. It will go out as its own turn";
@@ -1154,7 +1150,6 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
return (
Boolean(composerState.draft.trim() || composerState.attachments.length) &&
!composerState.processingFiles &&
- !ctx.chat.isStopping() &&
getRuntimeConfig(scopeKey()) !== null &&
ctx.chat.state.resolvingApprovals.size === 0 &&
!ctx.chat.hasUnresolvedApproval()
@@ -1224,6 +1219,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
composerState.error = "Could not request stop. Try again.";
ctx.chat.drawActiveChat(agent);
});
+ focusComposerEnd();
}
let failedQueueSend: { threadRef: string; text: string; filesKey: string; idempotencyKey: string } | null = null;
diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.ts
index 11cb4d6ce..14582b8ec 100644
--- a/plugins/web-ui/test/approval-handoff.test.ts
+++ b/plugins/web-ui/test/approval-handoff.test.ts
@@ -4,7 +4,7 @@ import { test } from "node:test";
import { JSDOM } from "jsdom";
import { createServer } from "vite";
import type { Conversation } from "../src/conv-types.ts";
-import type { PendingApproval } from "../src/core-bridge.ts";
+import type { AssistantWork, PendingApproval } from "../src/core-bridge.ts";
function deferred<T>() {
let resolve!: (value: T) => void;
@@ -72,6 +72,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"
let decision = deferred<Response>();
let continuation = deferredRun();
const handoff = deferred<void>();
+ let stopAck = deferred<Response>();
let refreshGate: ReturnType<typeof deferred<void>> | undefined;
let submitted = false;
const requests: Array<{ path: string; body?: Record<string, unknown> }> = [];
@@ -105,7 +106,8 @@ test("approval handoff unlocks queue and steer without losing pending decisions"
if (path === "/api/runs/q1") return Response.json({ status: "done", result: { status: "ok", reply: "done" } });
if (path === "/api/turn") return Response.json({ runId: "q1" });
if (path === "/api/runs/q1/withdraw") return Response.json({ withdrawn: true });
- if (path === "/api/runs/r1/signal") return Response.json({ accepted: true });
+ if (path === "/api/runs/r1/signal")
+ return JSON.parse(String(init?.body)).kind === "abort" ? stopAck.promise : Response.json({ accepted: true });
if (path.endsWith("/approvals")) return Response.json({ approvals: pending });
if (path.startsWith("/api/sessions/s1")) {
if (submitted) await handoff.promise;
@@ -193,6 +195,91 @@ test("approval handoff unlocks queue and steer without losing pending decisions"
assert.equal(chat.state.agent!.state.isStreaming, true);
});
+ await t.test("Stop restores Send and queues during a stalled acknowledgment, then recovers for retry", async () => {
+ const streaming = chat.state.agent!.state.streamingMessage as AssistantWork;
+ const originalContent = streaming.content;
+ const originalWork = streaming.work;
+ streaming.content = [
+ { type: "text", text: "Investigating the command" },
+ { type: "thinking", thinking: "Checking the output" },
+ ];
+ streaming.work = {
+ status: "working",
+ activity: [
+ {
+ seq: 1,
+ parentSeq: null,
+ type: "tool_call",
+ createdAt: Date.now(),
+ payload: { tool: "exec", command: "sleep 5" },
+ },
+ ],
+ };
+ chat.drawActiveChat();
+ assert.ok(host.querySelector(".thinking-sheen"));
+ assert.ok(host.querySelector(".live-stream"));
+ const input = host.querySelector<HTMLTextAreaElement>("textarea")!;
+ input.value = "my next instruction";
+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));
+ host.querySelector<HTMLButtonElement>('[aria-label="Stop"]')!.click();
+ assert.equal(host.querySelector('[aria-label="Stop"]'), null);
+ assert.equal(host.querySelector<HTMLButtonElement>('[aria-label="Send"]')?.disabled, false);
+ assert.match(host.querySelector('[role="status"]')?.textContent ?? "", /Stop requested/);
+ assert.equal(host.querySelector(".live-work-status"), null);
+ assert.equal(host.querySelector(".thinking-sheen"), null);
+ assert.equal(host.querySelector(".live-stream"), null);
+ assert.match(host.querySelector(".work-head")?.textContent ?? "", /Stop requested/);
+ streaming.work.activity.push({
+ seq: 2,
+ parentSeq: null,
+ type: "text_start",
+ createdAt: Date.now(),
+ payload: { phase: "final_answer", streamOffset: 0 },
+ });
+ chat.drawActiveChat();
+ assert.equal(
+ host.querySelector<HTMLElement & { content: string; isStreaming: boolean }>(
+ ".assistant-body > .streaming-text qm-markdown",
+ )?.content,
+ "Investigating the command",
+ );
+ assert.ok(
+ [...host.querySelectorAll<HTMLElement & { isStreaming: boolean }>("qm-markdown")].every(
+ (element) => !element.isStreaming,
+ ),
+ );
+ assert.equal(host.querySelector(".thinking-sheen"), null);
+ assert.equal(host.querySelector(".live-stream"), null);
+ await until(() => document.activeElement === input);
+ assert.equal(input.value, "my next instruction");
+ assert.equal(chat.state.agent!.state.isStreaming, true);
+ const queuedBefore = requests.filter((r) => r.path === "/api/turn").length;
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
+ await until(() => requests.filter((r) => r.path === "/api/turn").length === queuedBefore + 1);
+ await until(() => !!host.querySelector(".queued-steer"));
+ assert.equal(host.querySelector<HTMLButtonElement>(".queued-steer")?.disabled, true);
+ assert.equal(chat.state.agent!.state.isStreaming, true);
+ assert.equal(chat.isStopping(), true);
+ stopAck.resolve(Response.json({ error: "unavailable" }, { status: 503 }));
+ await until(() => !!host.querySelector('[aria-label="Stop"]'));
+ assert.match(chat.composer.state.error, /Could not request stop/);
+ assert.equal(host.querySelector<HTMLButtonElement>('[aria-label="Stop"]')?.disabled, false);
+ stopAck = deferred<Response>();
+ host.querySelector<HTMLButtonElement>('[aria-label="Stop"]')!.click();
+ assert.equal(chat.composer.state.error, "");
+ assert.equal(host.querySelector('[aria-label="Stop"]'), null);
+ stopAck.resolve(Response.json({ accepted: true }));
+ await until(
+ () => requests.filter((r) => r.path === "/api/runs/r1/signal" && r.body?.kind === "abort").length === 2,
+ );
+ assert.equal(chat.isStopping(), true);
+ assert.equal(chat.state.agent!.state.isStreaming, true);
+ streaming.content = originalContent;
+ streaming.work = originalWork;
+ input.value = "";
+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));
+ });
+
await t.test("a subsequent pause still requires and accepts another decision", async () => {
pending = [{ ...approval, requestId: "a2" }];
continuation.resolve(
diff --git a/plugins/web-ui/test/composer-stopping.test.ts b/plugins/web-ui/test/composer-stopping.test.ts
index cde327a48..0d6e06d74 100644
--- a/plugins/web-ui/test/composer-stopping.test.ts
+++ b/plugins/web-ui/test/composer-stopping.test.ts
@@ -6,7 +6,7 @@ import { JSDOM } from "jsdom";
import { createServer } from "vite";
import type { ComposerSurface, ConvCtx } from "../src/conv-types.ts";
-test("stopping blocks send and queue through render, input, keyboard, and form without blocking drafting", async (t) => {
+test("stopping returns Send immediately and queues every submit path without interrupting the live run", async (t) => {
const dom = new JSDOM('<!doctype html><div id="app"></div><div id="composer"></div>', {
url: "http://localhost/",
pretendToBeVisual: true,
@@ -122,38 +122,40 @@ test("stopping blocks send and queue through render, input, keyboard, and form w
assert.equal(button(".send-btn").disabled, false);
button(".stop-btn").click();
assert.equal(stops, 1);
- assert.equal(button(".stop-btn").disabled, true);
- button(".stop-btn").click();
- assert.equal(stops, 1, "stop cannot be clicked twice");
- await t.test("queue stays disabled after rendering and input", () => {
- assert.equal(button(".send-btn").disabled, true);
- type("Edited while stopping");
- assert.equal(composer!.state.draft, "Edited while stopping");
- assert.equal(host.querySelector<HTMLTextAreaElement>("textarea")!.disabled, false);
- assert.equal(button(".send-btn").disabled, true);
- });
- for (const streaming of [true, false]) {
- agentState.isStreaming = streaming;
- composer!.state.draft = "Keep this draft";
- draw();
- await t.test(`${streaming ? "queue" : "send"} remains blocked for input and every submit path`, async () => {
- type("Edited while stopping");
- const disabled = button(".send-btn").disabled;
- for (const modifiers of [{}, { ctrlKey: true }, { metaKey: true }]) {
+ assert.equal(host.querySelector(".stop-btn"), null);
+ assert.equal(button(".send-btn").getAttribute("aria-label"), "Send");
+ assert.equal(button(".send-btn").disabled, false);
+ assert.equal(composer!.state.draft, "Keep this draft");
+ assert.equal(agentState.isStreaming, true);
+ for (const submit of ["enter", "ctrl-enter", "meta-enter", "form"]) {
+ await t.test(`${submit} queues while stopping`, async () => {
+ type(`Next instruction via ${submit}`);
+ assert.equal(button(".send-btn").disabled, false);
+ assert.equal(host.querySelector<HTMLTextAreaElement>("textarea")!.disabled, false);
+ const before = requests.length;
+ if (submit === "form") {
host
- .querySelector("textarea")!
- .dispatchEvent(
- new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...modifiers }),
- );
+ .querySelector("form")!
+ .dispatchEvent(new dom.window.Event("submit", { bubbles: true, cancelable: true }));
+ } else {
+ host.querySelector("textarea")!.dispatchEvent(
+ new dom.window.KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: submit === "ctrl-enter",
+ metaKey: submit === "meta-enter",
+ }),
+ );
}
- host.querySelector("form")!.dispatchEvent(new dom.window.Event("submit", { bubbles: true, cancelable: true }));
await new Promise((resolve) => setTimeout(resolve, 20));
- const actual = { disabled, draft: composer!.state.draft, prompts, requests: requests.length };
- console.log("stopping probe", streaming, actual);
- assert.deepEqual(actual, { disabled: true, draft: "Edited while stopping", prompts: 0, requests: 0 });
+ assert.deepEqual(requests.slice(before), ["/api/turn"]);
+ assert.equal(prompts, 0);
+ assert.equal(composer!.state.draft, "");
+ assert.equal(agentState.isStreaming, true);
+ assert.equal(stopping, true);
});
}
- composer!.state.draft = "";
const attachment = {
id: "test-file",
type: "document" as const,
@@ -164,12 +166,11 @@ test("stopping blocks send and queue through render, input, keyboard, and form w
};
composer!.state.attachments = [attachment];
draw();
- assert.equal(button(".send-btn").disabled, true, "attachment-only send remains blocked");
- host.querySelector("form")!.dispatchEvent(new dom.window.Event("submit", { cancelable: true }));
- assert.deepEqual(composer!.state.attachments, [attachment], "stopping preserves attachments");
- assert.equal(requests.length, 0);
+ assert.equal(button(".send-btn").disabled, false, "attachments can be queued while stopping");
+ assert.deepEqual(composer!.state.attachments, [attachment]);
composer!.state.attachments = [];
stopping = false;
+ agentState.isStreaming = false;
composer!.state.draft = "Resume sending";
draw();
assert.equal(button(".send-btn").disabled, false, "sending recovers after stop completes");
@@ -182,7 +183,7 @@ test("stopping blocks send and queue through render, input, keyboard, and form w
assert.equal(button(".send-btn").disabled, false);
host.querySelector("form")!.dispatchEvent(new dom.window.Event("submit", { cancelable: true }));
await new Promise((resolve) => setTimeout(resolve, 20));
- assert.deepEqual(requests, ["/api/turn"], "normal queue submission still works");
+ assert.deepEqual(requests, Array(5).fill("/api/turn"), "normal queue submission still works");
composer!.state.draft = "Preparing attachment";
composer!.state.processingFiles = true;
draw();
@@ -198,7 +199,6 @@ test("stopping blocks send and queue through render, input, keyboard, and form w
}
});
-// Match the same visual affordance as disabled Send, including the cursor.
test("disabled Stop shares Send's muted styling", () => {
const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
assert.match(css, /\.send-btn:disabled,\s*\.stop-btn:disabled\s*\{[^}]*opacity: 0\.35;[^}]*cursor: not-allowed;/);
diff --git a/plugins/web-ui/test/queue-by-default.test.ts b/plugins/web-ui/test/queue-by-default.test.ts
index 64a641ac5..4fcfad04e 100644
--- a/plugins/web-ui/test/queue-by-default.test.ts
+++ b/plugins/web-ui/test/queue-by-default.test.ts
@@ -87,7 +87,7 @@ test("steering is reachable only as an explicit act on a queued row", () => {
assert.match(strip, /class="chip-x"[\s\S]{0,240}removeQueued\(agent, q\)/);
assert.match(
composer,
- /const steerable =\s*agent\.state\.isStreaming && ctx\.chat\.hasLiveRun\(\) &&\s*harnessSupportsSteer\(currentModelOption\(\)\?\.harnessId \?\? ""\);/,
+ /const steerable =\s*agent\.state\.isStreaming &&\s*!ctx\.chat\.isStopping\(\) &&\s*ctx\.chat\.hasLiveRun\(\) &&\s*harnessSupportsSteer\(currentModelOption\(\)\?\.harnessId \?\? ""\);/,
"Steer acts only against a live run on a harness that can fold one in",
);
});
diff --git a/plugins/web-ui/test/rtl-direction.test.ts b/plugins/web-ui/test/rtl-direction.test.ts
index c000f89bc..dd3b137c7 100644
--- a/plugins/web-ui/test/rtl-direction.test.ts
+++ b/plugins/web-ui/test/rtl-direction.test.ts
@@ -19,8 +19,8 @@ test("settled and streaming transcript blocks select direction from their conten
messageMarkdown,
/<qm-markdown\s+dir="auto"[^>]*?\.content=\$\{escapeLoneDollars\(normalizePlainTextFences\(text\)\)\}/,
);
- assert.match(chat, /\$\{markdown\(body, isStreaming, /);
- assert.match(chat, /class="streaming-text \$\{isStreaming \? "live-stream" : ""\}" dir="auto"/);
+ assert.match(chat, /\$\{markdown\(body, animating, /);
+ assert.match(chat, /class="streaming-text \$\{animating \? "live-stream" : ""\}" dir="auto"/);
});
test("search group headers select direction from the authored session title", async () => {
diff --git a/plugins/web-ui/test/work-fold-source.test.ts b/plugins/web-ui/test/work-fold-source.test.ts
index 202624b58..ef4f55b25 100644
--- a/plugins/web-ui/test/work-fold-source.test.ts
+++ b/plugins/web-ui/test/work-fold-source.test.ts
@@ -8,7 +8,9 @@ const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
test("live and completed work share one chronological duration fold", () => {
assert.match(chat, /class=\$\{stopped \? "stopped-work" : `work work-fold work-\$\{work.status\}`\}/);
assert.match(chat, /messageWorkTimeline\(work, active \? "" : text\)/);
- assert.match(chat, /let label = stopping \? "Stopping…" : workLabel\(work\)/);
+ assert.match(chat, /let label = stopping \? "Stop requested" : workLabel\(work\)/);
+ assert.match(chat, /const animating = active && !stopping;/);
+ assert.match(chat, /sheenLabel\(label, animating\)/);
assert.match(chat, /\?open=\$\{active \|\| !!work.pendingApprovals\?\.length\}/);
assert.doesNotMatch(chat, /function segmentSummaryLabel/);
});
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 6d8d49b10..a35f41d0b 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -3525,11 +3525,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
spine.surfaceOutboundCount === 0 &&
spine.staySilentReason === undefined &&
!result.silent &&
- !(result.runtimeHandoff && result.stopped)
+ !result.stopped
) {
await latchCoverage();
- const primaryStopped = !!result.stopped;
- const primaryStoppedTapeComplete = !!result.stoppedTapeComplete;
// The model already wrote a reply as plain assistant text — deliver that text
// directly instead of nudging it to re-post (a nudge here re-sends near-identical
// text, which surfaces that render assistant entries show twice).
@@ -3595,13 +3593,12 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
nudgeTape?.mode !== "serve" && inbound.images.length ? { images: inbound.images } : {},
{ history: nudgeHistory, ...(nudgeTape ? { tape: nudgeTape } : {}) },
);
- if (primaryStopped && !result.stopped)
- result = {
- ...result,
- stopped: true,
- ...(primaryStoppedTapeComplete ? { stoppedTapeComplete: true as const } : {}),
- };
- if (spine.surfaceOutboundCount === 0 && spine.staySilentReason === undefined && !result.silent) {
+ if (
+ spine.surfaceOutboundCount === 0 &&
+ spine.staySilentReason === undefined &&
+ !result.silent &&
+ !result.stopped
+ ) {
const fallback = stripAckPrefix(result.reply ?? "", spineAckText).trim();
if (fallback && defaultDestination && deps.deliveries) {
try {
diff --git a/test/tape-nudge-continuation.test.ts b/test/tape-nudge-continuation.test.ts
index 09ee976da..b0236efcb 100644
--- a/test/tape-nudge-continuation.test.ts
+++ b/test/tape-nudge-continuation.test.ts
@@ -57,6 +57,7 @@ async function runScenario(
failDirectDelivery?: boolean;
failPrimaryTapeMessage?: boolean;
nudgeCrash?: boolean;
+ nudgeStopped?: boolean;
omitPrimaryCheckpoint?: boolean;
staleNudgeRead?: boolean;
stoppedPartial?: boolean;
@@ -91,6 +92,15 @@ async function runScenario(
meta: { bareText: turn.input },
});
if (turn.input.startsWith("[system] You were addressed")) {
+ if (options.nudgeStopped) {
+ const reply = "Interrupted nudge partial";
+ await turn.emit({
+ type: "assistant",
+ payload: { text: reply, stopped: true },
+ scopeLabel: turn.scopeLabel,
+ });
+ return { reply, stopped: true, modelCalls: 1 };
+ }
await turn.tape?.({
kind: "message",
harness: "pi",
@@ -427,11 +437,13 @@ test("consecutive stopped turns heal one import each and converge once a turn co
assert.equal(await countImports(), 3, "no further imports once coverage is restored");
});
-test("a stopped partial keeps withholding coverage when the direct delivery fails and the nudge replaces the result", async () => {
- const { sessions, session, entries, orchestrator, input } = await runScenario({
+test("a user-stopped turn skips direct delivery and the reply nudge while preserving replay coverage", async () => {
+ const { modes, deliveries, sessions, session, entries, orchestrator, input } = await runScenario({
stoppedPartial: true,
failDirectDelivery: true,
});
+ assert.deepEqual(modes, ["shadow", "serve"], "Stop must not invoke the harness again");
+ assert.deepEqual(await deliveries.pending("slack"), [], "Stop must not enqueue a reply");
const partial = entries.find(
(entry) =>
entry.type === "assistant" && (entry.payload as { text?: unknown } | null)?.text === "worklog without a post",
@@ -439,7 +451,7 @@ test("a stopped partial keeps withholding coverage when the direct delivery fail
assert.ok(partial);
assert.ok(
(await sessions.tapeCoverage(session.id)) < partial.seq,
- "the nudge result must not launder the stopped primary into an advanced watermark",
+ "the stopped primary must not advance the watermark",
);
await orchestrator.handleTurn(input("continue after stop"));
@@ -645,3 +657,10 @@ test("a cancel-stopped turn delivers nothing anywhere and returns silent", async
assert.equal(result.status, "silent", "the losing side of a cancellation never completes as deliverable");
assert.deepEqual(posted, [], "no direct reply, no nudge, no fallback delivery from the cancelled turn");
});
+
+test("Stop during the reply nudge suppresses its fallback delivery", async () => {
+ const { modes, deliveries, entries } = await runScenario({ nudgeStopped: true });
+ assert.deepEqual(modes, ["shadow", "serve", "serve"]);
+ assert.deepEqual(await deliveries.pending("slack"), []);
+ assert.ok(entries.some((entry) => entry.type === "assistant" && (entry.payload as { stopped?: boolean }).stopped));
+});