Multiplayer agent harness for work.
Record a stopped turn as a system note, not a fake assistant reply (#2363)
Regan Bell4e26d469a5e9
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 647ac886a..d203f7fa1 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -2040,6 +2040,8 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):let pending: ToolActivity[] = [];let deliveryFiles: DeliveredFile[] = [];let posted = false;+ // Whether this turn already rendered its stopped state (a stopped partial reply).+ let stoppedShown = false;const heldPosts = new Map<string, { text: string; activity: ToolActivity }>();const spillHeldPosts = (): void => {for (const held of heldPosts.values()) pending.push(held.activity);@@ -2082,6 +2084,7 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):entrySeqs: number[] = [],): void => {if (!text && !pending.length && !deliveryFiles.length && !stopped) return;+ if (stopped) stoppedShown = true;entrySeqs = [...entrySeqs, ...pending.map((entry) => entry.seq)];const deliveredSilence = (a: ToolActivity): boolean => {if (a.type !== "tool_result") return false;@@ -2200,6 +2203,7 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):continue;}if (e.type === "user") {+ if (!payload?.steered) stoppedShown = false;if (payload?.hidden) continue;if (!payload?.steered) {posted = false;@@ -2245,6 +2249,14 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):} else if (e.type === "delivery") {appendDeliveryFiles(deliveredFilesFromAttachments(payload?.files));} else if (e.type === "system") {+ if ((e.payload as { kind?: unknown } | null)?.kind === "turn_stopped") {+ // The stop record closes the turn: show the stopped state once, never as a message.+ spillHeldPosts();+ if (pending.length || !stoppedShown)+ flushWork("", e.createdAt, !posted, undefined, true, e.seq === undefined ? [] : [e.seq]);+ posted = false;+ continue;+ }const goalNote = goalCancelledPayload(e.payload);if (goalNote) {spillHeldPosts();diff --git a/plugins/web-ui/test/stopped-history.test.ts b/plugins/web-ui/test/stopped-history.test.tsindex bde5714a2..4956f3439 100644--- a/plugins/web-ui/test/stopped-history.test.ts+++ b/plugins/web-ui/test/stopped-history.test.ts@@ -33,3 +33,44 @@ test("legacy stopped placeholders are recognized without treating ordinary repliassert.equal(message.stopReason, reason);}});++test("a turn_stopped record renders as the stopped state, once, and never as a message", () => {+ const stop = (seq: number): SessionEntry => ({+ type: "system",+ payload: { kind: "turn_stopped", reason: "by user" },+ createdAt: 5000,+ seq,+ });+ const request = (seq: number): SessionEntry => ({+ type: "user",+ payload: { text: "do the thing" },+ createdAt: 1000,+ seq,+ });++ const bare = entriesToMessages([request(1), stop(2)]);+ assert.equal(bare.length, 2);+ assert.equal((bare[1] as AssistantWork).stopReason, "aborted");+ assert.deepEqual((bare[1] as AssistantWork).content, [{ type: "text", text: "" }]);++ const withPartial = entriesToMessages([+ request(1),+ { type: "assistant", payload: { text: "Partial answer", stopped: true }, createdAt: 4000, seq: 2 },+ stop(3),+ ]);+ assert.equal(withPartial.length, 2, "the partial answer already shows the stopped state");+ assert.deepEqual((withPartial[1] as AssistantWork).content, [{ type: "text", text: "Partial answer" }]);++ const twoStoppedTurns = entriesToMessages([+ request(1),+ { type: "assistant", payload: { text: "Partial answer", stopped: true }, createdAt: 4000, seq: 2 },+ stop(3),+ { type: "user", payload: { text: "continue", hidden: true }, createdAt: 6000, seq: 4 },+ stop(5),+ ]);+ assert.equal(+ twoStoppedTurns.filter((m) => (m as AssistantWork).stopReason === "aborted").length,+ 2,+ "a later stopped turn after a hidden prompt still shows its own stopped state",+ );+});diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 2f219a44f..cab9c94a0 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -914,7 +914,8 @@ export function createSessionMethods(if (!lease) {if (before.status === "active")for (const run of await deps.runs.inFlightForThread(session.threadRef))- if (run.status === "running") await deps.signals?.send(run.id, { kind: "abort" });+ if (run.status === "running")+ await deps.signals?.send(run.id, { kind: "abort", reason: "because its goal was cancelled" });({ lease } = await acquireLeaseWithin(deps.sessions, session.id, "backfill", GOAL_CANCEL_LEASE_WAIT_MS));}if (!lease) return { cancelled: false as const, reason: "busy" as const };diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex 1f6bd645e..5d7dfcf02 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -41,6 +41,8 @@ import { unscreenedNotice } from "../security/security-posture.ts";import type { AppHelpers } from "./app-helpers.ts";import type { AmbientHelpers } from "./app-ambient.ts";+const USER_STOP = "by user";+export function attributedSteerText(steerer: { id: string; displayName?: string | undefined },runOwnerId: string | null,@@ -92,8 +94,8 @@ export function createTurnMethods(const signals = deps.signals;const stop = async () => {const session = await deps.sessions.getByThread(run.sessionId);- if (session) return stopSessionTree({ sessions: deps.sessions, runs: deps.runs, signals }, session);- await signals.send(run.id, { kind: "abort" });+ if (session) return stopSessionTree({ sessions: deps.sessions, runs: deps.runs, signals }, session, USER_STOP);+ await signals.send(run.id, { kind: "abort", reason: USER_STOP });if (run.status === "pending") await deps.runs.withdraw(run.id);return true;};@@ -795,7 +797,7 @@ export function createTurnMethods(const stop = async () => {const session = await deps.sessions.getByThread(threadRef);if (!session || !deps.signals || (viewer && !(await sessionForViewer(session.id, viewer)))) return false;- return stopSessionTree({ sessions: deps.sessions, runs: deps.runs, signals: deps.signals }, session);+ return stopSessionTree({ sessions: deps.sessions, runs: deps.runs, signals: deps.signals }, session, USER_STOP);};return deps.advisoryLock ? deps.advisoryLock.withLock("session-tree-admission", stop) : stop();},diff --git a/src/core/turn-resume.ts b/src/core/turn-resume.tsindex ab75713cc..3bd878858 100644--- a/src/core/turn-resume.ts+++ b/src/core/turn-resume.ts@@ -1,3 +1,4 @@+import { TURN_STOPPED_KIND } from "../harness/replay.ts";import type { RuntimeChoice } from "../harness/harness.ts";import { unrecordedToolResult } from "../harness/context-compaction.ts";@@ -26,6 +27,11 @@ export function isResumeNote(text: string): boolean {return [RESUME_HEAD, RUNTIME_HEAD, TRIMMED_HEAD, LEGACY_NOTE_HEAD].some((head) => t.startsWith(head));}+/** A stop record closes its turn, like a final answer: a later attempt must not resume it. */+function isTurnStoppedEntry(e: SessionEntry): boolean {+ return e.type === "system" && (e.payload as { kind?: unknown } | null)?.kind === TURN_STOPPED_KIND;+}+const MODEL_TURN_ENTRY_TYPES = new Set<SessionEntry["type"]>(["user", "assistant", "tool_call", "tool_result"]);export function findTrailingPartialTurn(entries: readonly SessionEntry[], inputText: string): PartialTurn | null {@@ -34,7 +40,7 @@ export function findTrailingPartialTurn(entries: readonly SessionEntry[], inputTlet workEntries = 0;for (let i = entries.length - 1; i >= 0; i--) {const e = entries[i]!;- if (e.type === "assistant") return null;+ if (e.type === "assistant" || isTurnStoppedEntry(e)) return null;if (e.type === "tool_call" || e.type === "tool_result") {workEntries += 1;continue;@@ -111,7 +117,7 @@ export function resumeStrategy(entries: readonly SessionEntry[], partial: Partia(e) => e.type === "tool_call" && !answered.has((e.payload as { callId?: unknown } | null)?.callId),);if (dangling.length === 0) {- const last = turn.findLast((e) => MODEL_TURN_ENTRY_TYPES.has(e.type));+ const last = turn.findLast((e) => MODEL_TURN_ENTRY_TYPES.has(e.type) || isTurnStoppedEntry(e));return last?.type === "tool_result" ? { kind: "continue" } : { kind: "note" };}// Calls with no result at all get one recording what happened; a call whose re-run was itself cut offdiff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.tsindex 262459257..18961c3d4 100644--- a/src/harness/claude-harness.ts+++ b/src/harness/claude-harness.ts@@ -45,7 +45,7 @@ import {oneShotModelUtilities,oneShotRunner,recordSteerIntake,- recordStoppedReply,+ recordStoppedTurn,type SteerIntake,type HarnessToolPlumbing,withResumedToolCall,@@ -468,8 +468,10 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {},});active.add(sdkQuery);- const interrupt = async (fromUser: boolean) => {+ let stopReason: string | undefined;+ const interrupt = async (fromUser: boolean, reason?: string) => {stopped ||= fromUser;+ if (fromUser && reason) stopReason ??= reason;interrupted = true;queue.close();await sdkQuery.interrupt().catch(() => undefined);@@ -492,7 +494,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {opts.signals,turn.runId,{- onAbort: async () => interrupt(true),+ onAbort: async (reason) => interrupt(true, reason),onSteer: async (steer, ts, request, acknowledge) => {if (ts && recordedMessageTimestamps(turn.history).has(ts)) return;const prepared = await turn.prepareSteer?.(steer, request);@@ -719,9 +721,8 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {const terminal = ref.runtimeHandoff || ref.silentRequested || ref.pausedOnApproval;const reply = terminal ? "" : streamedText.trim();await flushThinking();- if (reply && !terminal) {- await recordStoppedReply(turn, reply);- }+ if (!terminal && (reply || stopped))+ await recordStoppedTurn(turn, reply, stopped ? stopReason : "because the run was cancelled");return {reply,...(!ref.runtimeHandoff || stopped ? { stopped: true as const } : {}),diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.tsindex d116b3d9d..b65e789f1 100644--- a/src/harness/harness-shared.ts+++ b/src/harness/harness-shared.ts@@ -1,4 +1,4 @@-import type { ReplayImageRef } from "./replay.ts";+import { TURN_STOPPED_KIND, type ReplayImageRef } from "./replay.ts";import { randomBytes } from "node:crypto";import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";import {@@ -73,13 +73,33 @@ export async function recordSteerIntake(turn: HarnessTurnInput, steer: SteerIntaawait steer.acknowledge?.().catch(swallowAs("steer acknowledge", undefined));}-export async function recordStoppedReply(+const STOPPED_FALLBACK_REASON = "unexpectedly";++/**+ * Records a stopped turn: whatever the model actually wrote before the stop (never a placeholder),+ * then a system entry naming who or what stopped it. Replay shows the model that entry as a+ * "[system] Turn stopped: …" message; it is never a user or assistant entry.+ */+export async function recordStoppedTurn(turn: HarnessTurnInput,- text: string,+ partial: string,+ reason: string = STOPPED_FALLBACK_REASON,replay: Record<string, unknown> = {},): Promise<SessionEntry | null> {if (turn.shutdown?.aborted) return null;- return turn.emit({ type: "assistant", payload: { text, stopped: true, ...replay }, scopeLabel: turn.scopeLabel });+ const answer = partial.trim()+ ? await turn.emit({+ type: "assistant",+ payload: { text: partial, stopped: true, ...replay },+ scopeLabel: turn.scopeLabel,+ })+ : null;+ const note = await turn.emit({+ type: "system",+ payload: { kind: TURN_STOPPED_KIND, reason },+ scopeLabel: turn.scopeLabel,+ });+ return note ?? answer;}export function harnessToolContext(turn: HarnessTurnInput): ToolContextRef {diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.tsindex 967730698..a3c171501 100644--- a/src/harness/mock-harness.ts+++ b/src/harness/mock-harness.ts@@ -12,7 +12,7 @@ import { NonRetryableTurnError, ProviderTurnError, TitleRejected } from "../coreimport { NeedsApproval } from "../tools/primitives.ts";import { deterministicCompactSummary, estimateHistoryTokens } from "./context-compaction.ts";import { countTokens } from "../util/tokens.ts";-import { recordStoppedReply } from "./harness-shared.ts";+import { recordStoppedTurn } from "./harness-shared.ts";import {SECURITY_SCREEN_STEP,SECURITY_SCREEN_SYSTEM_PROMPT,@@ -217,7 +217,7 @@ export function createMockHarness(): Harness {if (!turn.cancel || turn.cancel.aborted) resolve();else turn.cancel.addEventListener("abort", () => resolve(), { once: true });});- await recordStoppedReply(turn, "(stopped)");+ await recordStoppedTurn(turn, "");return { reply: "(stopped)", stopped: true, modelCalls: 1 };} else if (command0.startsWith("!post-lost-result ")) {const msg = cmd.slice(cmd.indexOf("!post-lost-result ") + "!post-lost-result ".length);diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.tsindex 96d3fe1ad..c2101a9b3 100644--- a/src/harness/pi-harness.ts+++ b/src/harness/pi-harness.ts@@ -1,6 +1,6 @@import {recordSteerIntake,- recordStoppedReply,+ recordStoppedTurn,imageRefs,resumeInterruptedToolCall,type BridgedTool,@@ -2004,6 +2004,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {return last?.stopReason;};let userAborted = false;+ let abortReason: string | undefined;let recoveryDead = false;entry.ref.abortSignal = toolAbort.signal;const onCancel = (): void => {@@ -2057,8 +2058,9 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {}return false;},- onAbort: async () => {+ onAbort: async (reason) => {userAborted = true;+ abortReason ??= reason;toolAbort.abort();entry.agentSession.clearQueue();await entry.agentSession.abort();@@ -2334,7 +2336,12 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {await turn.saveGoal?.(g);if (g.status === "complete") entry.ref.goal = null;}- await recordStoppedReply(turn, reply, steps.closing(reply));+ await recordStoppedTurn(+ turn,+ partial,+ userAborted ? abortReason : "because the run was cancelled",+ steps.closing(reply),+ );const cacheUsage = sumCacheUsage(callStats);const base = {reply,diff --git a/src/harness/replay.ts b/src/harness/replay.tsindex 2f8b16fc4..c177ba01a 100644--- a/src/harness/replay.ts+++ b/src/harness/replay.ts@@ -17,6 +17,51 @@ import { contextSummaryPayload } from "../sessions/session-store.ts";import { isoFromTs, messageTag } from "../util/message-tag.ts";import { isObj } from "../util/objects.ts";+/** System entry kind recording that a turn was stopped and who or what stopped it. */+export const TURN_STOPPED_KIND = "turn_stopped";++/** How a stopped turn reads to the model on replay. `reason` reads after "Turn stopped", e.g. "by user". */+function turnStoppedNote(reason: string): string {+ return `[system] Turn stopped ${reason}.`;+}++/** The result of a tool call that was still running when its turn was stopped. */+function stoppedToolResult(reason: string): string {+ return `[system] Turn stopped ${reason} while this call was running; its outcome wasn't recorded. Check what happened before retrying.`;+}++/**+ * For each stop record that cut off running tool calls, the stop explanation becomes those calls'+ * results, and the stop record itself adds nothing more.+ */+function stoppedToolCalls(+ history: readonly SessionEntry[],+ resultByCallId: ReadonlyMap<string, SessionEntry>,+): { results: Map<string, string>; folded: Set<SessionEntry> } {+ const results = new Map<string, string>();+ const folded = new Set<SessionEntry>();+ let open: string[] = [];+ for (const e of history) {+ const p = (e.payload ?? {}) as {+ callId?: unknown;+ kind?: unknown;+ reason?: unknown;+ steered?: unknown;+ overheard?: unknown;+ };+ // Steers and overheard channel traffic arrive mid-turn; only a new ask (or a hidden resume note) ends it.+ if (e.type === "user" && p.steered !== true && p.overheard !== true) open = [];+ else if (e.type === "tool_call" && typeof p.callId === "string" && !resultByCallId.has(p.callId))+ open.push(p.callId);+ else if (e.type === "system" && p.kind === TURN_STOPPED_KIND && typeof p.reason === "string") {+ if (open.length) folded.add(e);+ for (const callId of open) results.set(callId, stoppedToolResult(p.reason));+ open = [];+ }+ }+ return { results, folded };+}+export { INTERRUPTED_TOOL_RESULT };export interface SeededMessage {@@ -224,10 +269,15 @@ function resultContent(content: StoredResultContent[]): ToolResultMessage["conte);}-function toolResultMessage(call: ToolCall, re: SessionEntry | undefined, at: number): ToolResultMessage {+function toolResultMessage(+ call: ToolCall,+ re: SessionEntry | undefined,+ at: number,+ missing: string = INTERRUPTED_TOOL_RESULT,+): ToolResultMessage {const base = { role: "toolResult" as const, toolCallId: call.id, toolName: call.name };const text = (value: string) => [{ type: "text" as const, text: value }];- if (!re) return { ...base, content: text(INTERRUPTED_TOOL_RESULT), isError: true, timestamp: at };+ if (!re) return { ...base, content: text(missing), isError: true, timestamp: at };const p = (re.payload ?? {}) as {interrupted?: unknown;stop?: { kind?: unknown };@@ -259,6 +309,7 @@ export function reconstructMessagesFromHistory(history: readonly SessionEntry[])const cid = (e.payload as { callId?: unknown } | null)?.callId;if (typeof cid === "string" && cid) resultByCallId.set(cid, e);}+ const stopped = stoppedToolCalls(history, resultByCallId);const raw: PiReplayMessage[] = [];const stepped = new Set<PiReplayMessage>();const steps = new Map<string, AssistantMessage>();@@ -331,11 +382,13 @@ export function reconstructMessagesFromHistory(history: readonly SessionEntry[])if (t) raw.push(userMsg(deliveryNote(t), e.createdAt));} else if (e.type === "system") {const revision = messageRevision(e);- const p = (e.payload ?? {}) as { kind?: unknown; text?: unknown; objective?: unknown };+ const p = (e.payload ?? {}) as { kind?: unknown; text?: unknown; objective?: unknown; reason?: unknown };if (revision) raw.push(userMsg(renderMessageRevision(revision), e.createdAt));else if (p.kind === WAKE_KIND && typeof p.text === "string") raw.push(userMsg(p.text, e.createdAt));else if (p.kind === "goal_cancelled" && typeof p.objective === "string")raw.push(userMsg(goalCancelledNote(p.objective), e.createdAt));+ else if (p.kind === TURN_STOPPED_KIND && typeof p.reason === "string" && !stopped.folded.has(e))+ raw.push(userMsg(turnStoppedNote(p.reason), e.createdAt));} else if (e.type === "tool_call") {const p = (e.payload ?? {}) as Record<string, unknown>;const cid = typeof p.callId === "string" ? p.callId : "";@@ -371,7 +424,8 @@ export function reconstructMessagesFromHistory(history: readonly SessionEntry[])out.push(m);if (m.role !== "assistant") continue;for (const c of m.content)- if (c.type === "toolCall") out.push(toolResultMessage(c, resultByCallId.get(c.id), m.timestamp));+ if (c.type === "toolCall")+ out.push(toolResultMessage(c, resultByCallId.get(c.id), m.timestamp, stopped.results.get(c.id)));}if (out[0] && out[0].role !== "user")out.unshift({ role: "user", content: [{ type: "text", text: AGENT_OPENED_TEXT }], timestamp: out[0].timestamp });diff --git a/src/runs/run-signal-store.ts b/src/runs/run-signal-store.tsindex 634ece615..842a0c2c6 100644--- a/src/runs/run-signal-store.ts+++ b/src/runs/run-signal-store.ts@@ -15,6 +15,8 @@ export interface RunSignal {queuedRunId?: string;callId?: string;result?: ClientToolResult;+ /** abort only: who or what stopped the run, in words, for the stopped session's record. */+ reason?: string;}export interface RunSignalStore {@@ -157,7 +159,7 @@ const SIGNAL_POLL_MS = 5_000;export interface SignalPollHandlers {onSteer(text: string, ts?: string, request?: TurnRequest, acknowledge?: () => Promise<void>): Promise<void | boolean>;- onAbort(): Promise<void>;+ onAbort(reason?: string): Promise<void>;}export function startSignalPoll(@@ -185,7 +187,7 @@ export function startSignalPoll(try {if (s.kind === "abort") {if (!abortDelivered) {- await handlers.onAbort();+ await handlers.onAbort(s.reason);abortDelivered = true;}} else if (!declined.has(id)) {diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.tsindex f4c46112f..81b69333b 100644--- a/src/sessions/session-syscalls.ts+++ b/src/sessions/session-syscalls.ts@@ -1,4 +1,5 @@import { memoryContextPayload, type MemoryContextSnapshot } from "../memory/context-boundary.ts";+import { TURN_STOPPED_KIND } from "../harness/replay.ts";import { principalDestination } from "../reach/reach.ts";import type { DeliveryStore } from "../delivery/delivery-store.ts";import { deliveryCandidatesFor } from "../core/orchestrator/turn-helpers.ts";@@ -274,6 +275,15 @@ function entryText(entry: SessionEntry): string | undefined {function lastAssistantText(entries: readonly SessionEntry[]): string | undefined {for (let i = entries.length - 1; i >= 0; i--) {const e = entries[i]!;+ const stop = e.type === "system" ? (e.payload as { kind?: unknown; reason?: unknown } | null) : null;+ if (stop?.kind === TURN_STOPPED_KIND) {+ // A partial reply recorded just before the stop is still the last thing said.+ const before = entries[i - 1];+ const partial = before?.type === "assistant" ? entryText(before) : "";+ return (+ partial || `[system] Subagent stopped${typeof stop.reason === "string" ? ` ${stop.reason}` : ""}. No reply.`+ );+ }if (e.type !== "assistant" && e.type !== "text") continue;const text = entryText(e);if (text) return text;@@ -467,12 +477,13 @@ export async function stopSessionTree(signals: Pick<RunSignalStore, "send">;},root: Session,+ reason?: string,): Promise<boolean> {let stopped = false;for (const session of await treeSessions(deps.sessions, root)) {if (session.scopeId !== root.scopeId) continue;for (const run of await deps.runs.inFlightForThread(session.threadRef)) {- await deps.signals.send(run.id, { kind: "abort" });+ await deps.signals.send(run.id, { kind: "abort", ...(reason ? { reason } : {}) });if (run.status === "pending") await deps.runs.withdraw(run.id);stopped = true;}@@ -805,7 +816,7 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscallsreturn { ok: false, message: "ordinary sessions accept private messages, not interrupts" };if (caller.readOnly && !target.spawnMeta?.readOnly)return { ok: false, message: "a read-only session cannot interrupt a writable task" };- const stopped = await stopSessionTree(deps, target);+ const stopped = await stopSessionTree(deps, target, "by the parent agent");return stopped? { ok: true, sessionId: target.id, title, delivered: "interrupted" }: { ok: false, message: `subagent "${title}" is not running — nothing to interrupt.` };diff --git a/src/swarms/swarm-service.ts b/src/swarms/swarm-service.tsindex 03745c71a..5b5017c44 100644--- a/src/swarms/swarm-service.ts+++ b/src/swarms/swarm-service.ts@@ -795,7 +795,8 @@ export function createSwarmService(deps: {runIds.map(async (runId) => {if (await runs.withdraw(runId, { unstartedOnly: true }).catch(() => false)) return;const run = await runs.get(runId);- if (run?.status === "running") await deps.signals?.send(runId, { kind: "abort" }).catch(() => false);+ if (run?.status === "running")+ await deps.signals?.send(runId, { kind: "abort", reason: "by the swarm" }).catch(() => false);}),);}diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.tsindex 7f45df535..c1b4f0477 100644--- a/test/claude-harness-turn.test.ts+++ b/test/claude-harness-turn.test.ts@@ -795,7 +795,7 @@ for (const shutdown of [false, true]) {assert.equal(result.stoppedByUser, undefined);assert.deepEqual(entries.map((entry) => entry.type).filter((type) => type !== "thinking"),- shutdown ? ["user", "tool_call", "tool_result"] : ["user", "tool_call", "tool_result", "assistant"],+ shutdown ? ["user", "tool_call", "tool_result"] : ["user", "tool_call", "tool_result", "assistant", "system"],);const partial = findTrailingPartialTurn(entries, turn.input);if (shutdown) {@@ -803,7 +803,11 @@ for (const shutdown of [false, true]) {assert.notEqual(resumeStrategy(entries, partial).kind, "restart");assert.equal(turnAtSeq(entries, partial.userSeq)?.answer, undefined);} else {- assert.deepEqual(entries.at(-1)!.payload, { text: "Visible partial", stopped: true });+ assert.deepEqual(entries.at(-2)!.payload, { text: "Visible partial", stopped: true });+ assert.deepEqual(entries.at(-1)!.payload, {+ kind: "turn_stopped",+ reason: "because the run was cancelled",+ });assert.equal(partial, null);}});diff --git a/test/pi-harness-cancel-exit.test.ts b/test/pi-harness-cancel-exit.test.tsindex 2044280a4..00522c1b1 100644--- a/test/pi-harness-cancel-exit.test.ts+++ b/test/pi-harness-cancel-exit.test.ts@@ -59,10 +59,14 @@ test("a mid-prompt cancel takes the stopped exit and persists the stopped partiaassert.equal(result.stopped, true, "the cancelled turn reports itself stopped");assert.equal(result.reply, "(stopped)");+ assert.equal(+ sink.entries.filter((entry) => entry.type === "assistant").length,+ 0,+ "no placeholder assistant reply is recorded when the model wrote nothing",+ );const finalEntry = sink.entries.at(-1);- assert.equal(finalEntry?.type, "assistant");- assert.equal((finalEntry?.payload as { text?: unknown } | undefined)?.text, "(stopped)");- assert.equal((finalEntry?.payload as { stopped?: boolean } | undefined)?.stopped, true);+ assert.equal(finalEntry?.type, "system");+ assert.deepEqual(finalEntry?.payload, { kind: "turn_stopped", reason: "because the run was cancelled" });} finally {globalThis.fetch = realFetch;}@@ -204,7 +208,12 @@ test("Pi preserves the session's active goal when the worker cancels", async ()});const result = await harness.turns.runTurn(turn);assert.equal(result.stopped, true);- assert.ok(!sink.entries.some((entry) => entry.type === "system"), "no goal snapshot entries");+ assert.ok(+ !sink.entries.some(+ (entry) => entry.type === "system" && (entry.payload as { kind?: unknown } | null)?.kind !== "turn_stopped",+ ),+ "no goal snapshot entries",+ );const { activeMs, ...persisted } = saved.at(-1)!;assert.deepEqual(persisted, goal);assert.ok(activeMs! >= 0 && activeMs! < 60_000, "the cancelled turn banks only its own running time");@@ -266,7 +275,9 @@ for (const shutdown of [false, true]) {const entries = sink.entries as unknown as SessionEntry[];const types = entries.map((entry) => entry.type);assert.deepEqual(types.slice(0, 3), ["user", "tool_call", "tool_result"]);- const stoppedEntries = entries.filter((entry) => entry.type === "assistant");+ const stoppedEntries = entries.filter(+ (entry) => entry.type === "assistant" || (entry.payload as { kind?: unknown } | null)?.kind === "turn_stopped",+ );const partial = findTrailingPartialTurn(entries, "do the thing");if (shutdown) {assert.deepEqual(stoppedEntries, [], "shutdown must not close the turn with a stop marker");@@ -276,7 +287,7 @@ for (const shutdown of [false, true]) {assert.equal(turnAtSeq(entries, partial.userSeq)?.answer, undefined);} else {assert.equal(stoppedEntries.length, 1);- assert.equal((stoppedEntries[0]!.payload as { text?: unknown }).text, "(stopped)");+ assert.equal(stoppedEntries[0]!.type, "system");assert.equal(partial, null, "a user-facing stop closes the turn");}} finally {diff --git a/test/replay.test.ts b/test/replay.test.tsindex 1c2d6f787..7d7f1c6bd 100644--- a/test/replay.test.ts+++ b/test/replay.test.ts@@ -597,6 +597,52 @@ test("reconstructMessagesFromHistory keeps parallel tool calls in one assistant);});+test("reconstructMessagesFromHistory replays a stopped turn as a system note in user voice, after the real partial", () => {+ const history: SessionEntry[] = [+ ent("user", { text: "write the report" }, 1),+ ent("assistant", { text: "Draft so far", stopped: true }, 2),+ ent("system", { kind: "turn_stopped", reason: "by the parent agent" }, 3),+ ent("user", { text: "carry on" }, 4),+ ];+ const msgs = reconstructMessagesFromHistory(history);+ assertValidWire(msgs);+ assert.deepEqual(+ msgs.map((m) => m.role),+ ["user", "assistant", "user", "user"],+ );+ assert.deepEqual(msgs[1]!.content, [{ type: "text", text: "Draft so far" }]);+ assert.deepEqual(msgs[2]!.content, [{ type: "text", text: "[system] Turn stopped by the parent agent." }]);+});++test("a turn stopped while a tool call ran explains the stop in that call's result, once", () => {+ const history: SessionEntry[] = [+ ent("user", { text: "deploy it" }, 1),+ ent("tool_call", { tool: "execute", callId: "c1", command: "make deploy" }, 2),+ ent("system", { kind: "turn_stopped", reason: "by user" }, 3),+ ent("user", { text: "what happened?" }, 4),+ ];+ const msgs = reconstructMessagesFromHistory(history);+ assertValidWire(msgs);+ assert.deepEqual(+ msgs.map((m) => m.role),+ ["user", "assistant", "toolResult", "user"],+ );+ assert.match(JSON.stringify(msgs[2]!.content), /Turn stopped by user while this call was running/);+ assert.ok(!JSON.stringify(msgs).includes("[system] Turn stopped by user."), "no separate stop note");+});++test("overheard traffic between a cut-off call and the stop does not split the stop from that call", () => {+ const history: SessionEntry[] = [+ ent("user", { text: "deploy it" }, 1),+ ent("tool_call", { tool: "execute", callId: "c1", command: "make deploy" }, 2),+ ent("user", { overheard: true, ts: "3", name: "Alice", text: "lunch?" }, 3),+ ent("system", { kind: "turn_stopped", reason: "by user" }, 4),+ ];+ const text = JSON.stringify(reconstructMessagesFromHistory(history));+ assert.match(text, /Turn stopped by user while this call was running/);+ assert.ok(!text.includes("[system] Turn stopped by user."), "no separate stop note");+});+test("a tool result cut off by a deploy says so in its replayed result", () => {const history: SessionEntry[] = [ent("user", { text: "deploy it" }, 1),diff --git a/test/session-syscalls.test.ts b/test/session-syscalls.test.tsindex c49c2f29f..9753eaf82 100644--- a/test/session-syscalls.test.ts+++ b/test/session-syscalls.test.ts@@ -20,6 +20,7 @@ import {delegatedAuthorizationOrigin,stopSessionTree,} from "../src/sessions/session-syscalls.ts";+import type { Run } from "../src/runs/run-store.ts";import { scopeId, type Conversation, type Principal, type ScopeId, type Session } from "../src/types.ts";import type { SessionStore } from "../src/sessions/session-store.ts";import type { RunStore } from "../src/runs/run-store.ts";@@ -1902,3 +1903,36 @@ test("sessions list shows only sidebar sessions the whole audience can see and c}assert.equal(started.length, 4);});++test("stopping a session tree tells every stopped run who stopped it", async () => {+ const sent: Array<{ runId: string; signal: unknown }> = [];+ const root = { id: "root", scopeId: "personal:a", threadRef: "web:root" } as unknown as Session;+ const child = { id: "child", scopeId: "personal:a", threadRef: "agent:main:subagent:child" } as unknown as Session;+ const stopped = await stopSessionTree(+ {+ sessions: { childrenOf: async (id: string) => (id === "root" ? [child] : []) },+ runs: {+ inFlightForThread: async (threadRef: string) =>+ [{ id: `run-${threadRef}`, status: "running" }] as unknown as Run[],+ withdraw: async () => true,+ get: async () => null,+ },+ signals: {+ send: async (runId: string, signal: unknown) => {+ sent.push({ runId, signal });+ return true;+ },+ },+ },+ root,+ "by the parent agent",+ );+ assert.equal(stopped, true);+ assert.deepEqual(+ sent.map((s) => s.signal),+ [+ { kind: "abort", reason: "by the parent agent" },+ { kind: "abort", reason: "by the parent agent" },+ ],+ );+});