Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(core): stop is final (ADR-038); say what was done instead of "(no text response)"
Salman Qureshi646d19302e12
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea6ea51e..7576e32c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,8 @@### Chats at the same time- **Mercury answers several chats at once.** A long research run or coding task in one chat no longer makes the terminal, Telegram, the desktop app or a scheduled task wait. Each chat still handles its own messages in order.- **Sized to your machine.** Up to 4 chats run at once, 3 under 8 GB of RAM, and 2 on Termux or under 4 GB. When memory runs short, new chats wait for a free slot, and if memory keeps growing the most recently started task stops while the rest carry on. Set `concurrency.maxTurns` in `mercury.yaml` (or `MERCURY_MAX_CONCURRENT_TURNS`) to choose the limit; `1` restores one chat at a time.+- **Stop really stops.** A stopped task no longer comes back a few seconds later. Before, it could resume through an automatic retry after a tool had run, through a stall retry, or through the next message waiting in that chat. Stop also ends everything a running command started (`npm run build` and the like keep going no more) and drops the messages that chat had waiting. A stopped sub-agent stays stopped.+- **No more "(no text response)".** When Mercury Code (or a sub-agent or bot) finishes by writing files or running commands without a closing message, you now get what it did: the files it wrote or edited, and each command with whether it succeeded.- **`/stop` stops the chat you're in.** Esc in the terminal, the Stop button in Mercury Desktop and `/stop` in Telegram stop that chat's task and the sub-agents it started. `/halt` still stops everything.### Providersdiff --git a/DECISIONS.md b/DECISIONS.mdindex 53806623..fa1fdaf2 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -387,3 +387,22 @@- **One governor.** `TurnGovernor` sets the limit: heap headroom divided by a 192 MB per-turn budget, capped at 4, 3 under 8 GB of RAM, 2 on Termux or under 4 GB. `concurrency.maxTurns` / `MERCURY_MAX_CONCURRENT_TURNS` overrides it (1–16). It admits a turn only while the heap leaves that turn its budget (and, on Linux/Android, while the OS still has memory available), and always admits one when nothing runs. A single process-wide timer replaces the per-turn guard. The stop line is the old single-task line with one turn running and widens by one budget per extra turn. Past it, the newest turn is stopped, one per 5 s cooldown, after each turn has first compacted its own conversation. Past the exit line the process exits with a crash flag, so the work ledger recovers every interrupted chat.- **Stopping.** `/stop`, Esc, the desktop Stop button and a cloud `task.stop` stop that chat's turn and the sub-agents it started. With nothing else running, `/stop` is the full stop it was (locks released, task board cleared). `/halt` stops everything.- **Consequence**: Chats no longer block each other, up to the limit. What stays shared is deliberate: the owner's Allow All, approved scopes, token budget, provider fallback state and permission-answer evidence for learning. The terminal's live feed shows the terminal's own turn and mirrors another chat's only while the terminal is idle. A `/workspace` or `cd` from a remote chat now moves only that chat, not the terminal. Recovered interrupted work resumes concurrently after a restart, still one turn per chat.++## ADR-038: A stop is final — sticky cancellation, nothing retries, the whole command dies++- **Context**: Owners reported that Stop "doesn't stop — it resumes again", most often in the middle of multi-step work. Five separate paths let stopped work come back:+ 1. When an attempt aborted after a tool had run, the turn scheduled a durable continuation. `WorkLedger.markRetry` turned the cancelled entry back to `queued`, and a timer re-ran it seconds later.+ 2. A stop that arrived while the stall watchdog had already aborted the attempt was dropped, because the controller was already aborted. The stall branch then cleared the reason and retried with a fresh controller.+ 3. A stop during a continuation or verification round delivered the earlier answer as if it were complete.+ 4. Messages the chat had waiting started right after the stop.+ 5. Only the shell of a command was killed, so `npm run build` and similar kept running. The SIGKILL escalation was cleared before it could ever fire.++ On top of these, a halted sub-agent could still step-budget auto-resume.+- **Decision**:+ - **Sticky cancellation.** An owner stop (`stopped`, `halted`, `backgrounded`) sets `TurnState.cancelled` once and nothing clears it. The turn's abort reason always reads as that stop, internal handlers (stall, time limit, memory) can't overwrite it, and any abort controller made after it is created already aborted. It is recorded even when the controller was already aborted.+ - **Nothing retries stopped work.** `scheduleDurableRetry` is a no-op for a cancelled turn or entry, and a cancelled ledger entry is terminal for retry, pause and failure. A queued item whose entry is cancelled never runs. However the attempt ended, a stopped turn delivers the stop note: never a continuation notice, a failure report or an earlier answer.+ - **The chat's line is cleared.** `/stop` (and the Stop button) also drops that chat's waiting messages and cancels their entries, as OpenClaw's `/stop` does. "Do mine first" passes `keepQueued`. `/halt` empties the whole line.+ - **Whole process trees.** On POSIX each command runs in its own process group (`detached`) and is signalled as a group: SIGTERM, then SIGKILL after 5 s to whatever ignored it. On Windows the tree is ended with `taskkill /T /F`. Groups still alive when Mercury exits get SIGTERM.+ - **Final sub-agent halts.** Halted ids are remembered: no step-budget auto-resume, no start from the wait queue.+ - Research "write the report now" stays a non-cancelling abort: that turn goes on to write the report.+- **Consequence**: Stop means stopped. "Continue" or sending the request again is the only way back. A command that needs the terminal's `/dev/tty` (an interactive password prompt) no longer gets it, since commands run in their own session. They never could answer through Mercury anyway.diff --git a/apps/desktop/src/api/mercury.ts b/apps/desktop/src/api/mercury.tsindex f8663607..1cfa5920 100644--- a/apps/desktop/src/api/mercury.ts+++ b/apps/desktop/src/api/mercury.ts@@ -81,7 +81,8 @@ export const chat = {* turn stops (runtimes that run chats at once); without one, everything.* Needs the "chat.stop" feature.*/- stop: (threadId?: string | null) => http.post<{ ok: boolean; note?: string }>("/api/chat/stop", threadId ? { threadId } : {}),+ stop: (threadId?: string | null, opts?: { keepQueued?: boolean }) =>+ http.post<{ ok: boolean; note?: string }>("/api/chat/stop", threadId ? { threadId, ...(opts?.keepQueued ? { keepQueued: true } : {}) } : {}),/** Take back your last message and the reply (stop the turn first); returns your text. */save: (threadId: string, saved: boolean) => http.post<{ id: string; saved: boolean; savedAt: string | null }>(`/api/chat/threads/${encodeURIComponent(threadId)}/save`, { saved }),undo: (threadId: string, content: string) => http.post<{ ok: boolean; content: string; removed: number }>(`/api/chat/threads/${encodeURIComponent(threadId)}/undo`, { content }),diff --git a/apps/desktop/src/views/chat/Waiting.tsx b/apps/desktop/src/views/chat/Waiting.tsxindex a7fb66b8..007908e2 100644--- a/apps/desktop/src/views/chat/Waiting.tsx+++ b/apps/desktop/src/views/chat/Waiting.tsx@@ -26,8 +26,9 @@ export function WaitingNotice({ threadId, waiting }: { threadId: string | null;setProblem(null);try {await api.chat.queueFirst(threadId);- // Stop only the chat this one waits for, not every running chat.- await api.chat.stop(waiting.busySessionId);+ // Stop only the turn this one waits for — not every running chat, and+ // not the messages that chat has waiting.+ await api.chat.stop(waiting.busySessionId, { keepQueued: true });} catch (e) {setProblem(e instanceof Error ? e.message : String(e));} finally {diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 0bafe117..d60bf0d1 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -1,4 +1,5 @@import { streamText, stepCountIs, tool, zodSchema } from 'ai';+import { summarizeSilentTurn } from '../core/silent-turn.js';import { z } from 'zod';import { withAttachments } from '../core/attachments.js';import type { ChannelAttachment } from '../types/channel.js';@@ -547,7 +548,12 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {}// The bot's own report is what the owner reads; its last words are the fallback.- const output = (report?.summary || lastResult?.text || '').trim() || '(no text response)';+ // Neither a report nor last words: say what the run did, from its own trace.+ const output = (report?.summary || lastResult?.text || '').trim() || summarizeSilentTurn(trace.map((t) => ({+ tool: t.name,+ input: t.arg === undefined ? {} : t.name === 'run_command' ? { command: t.arg } : { path: t.arg },+ ok: t.ok,+ })));const outcome = outcomeNow(lastResult?.text ?? '');const claimedWithoutAction = outcome === 'none' && CLAIM_PATTERN.test(output);diff --git a/src/capabilities/shell/process-tree.test.ts b/src/capabilities/shell/process-tree.test.tsnew file mode 100644index 00000000..de189d81--- /dev/null+++ b/src/capabilities/shell/process-tree.test.ts@@ -0,0 +1,70 @@+import { mkdtempSync, readFileSync, existsSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { executeCommand } from './run-command.js';++/**+ * ADR-038: a stop ends the whole command, not just its shell. `npm run build`+ * or `python train.py` used to keep running after Stop because only `sh`+ * was killed; and the SIGKILL escalation was cleared before it could fire.+ */++const posix = process.platform !== 'win32';+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++const tick = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));++function alive(pid: number): boolean {+ try { process.kill(pid, 0); return true; } catch { return false; }+}++async function pidFrom(file: string): Promise<number> {+ for (let i = 0; i < 200; i++) {+ if (existsSync(file)) {+ const text = readFileSync(file, 'utf8').trim();+ if (text) return Number(text);+ }+ await tick(10);+ }+ throw new Error('grandchild never started');+}++describe.runIf(posix)('stopping a command ends its whole process tree', () => {+ it('a background grandchild dies with the command', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-tree-'));+ dirs.push(dir);+ const pidFile = join(dir, 'pid');+ const controller = new AbortController();+ const run = executeCommand(`sleep 60 & echo $! > "${pidFile}"; wait`, dir, 60_000, { signal: controller.signal });+ const grandchild = await pidFrom(pidFile);+ expect(alive(grandchild)).toBe(true);+ controller.abort();+ const result = await run;+ expect(result.aborted).toBe(true);+ for (let i = 0; i < 100 && alive(grandchild); i++) await tick(20);+ expect(alive(grandchild)).toBe(false);+ });++ it('a grandchild that ignores SIGTERM is killed after the grace period', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-tree-'));+ dirs.push(dir);+ const pidFile = join(dir, 'pid');+ const controller = new AbortController();+ const run = executeCommand(`trap '' TERM; sleep 60 & echo $! > "${pidFile}"; wait`, dir, 60_000, { signal: controller.signal });+ const grandchild = await pidFrom(pidFile);+ controller.abort();+ await run;+ await tick(500);+ expect(alive(grandchild)).toBe(true); // ignored SIGTERM...+ for (let i = 0; i < 80 && alive(grandchild); i++) await tick(100);+ expect(alive(grandchild)).toBe(false); // ...but not SIGKILL+ }, 15_000);++ it('a command that finishes normally is untouched', async () => {+ const result = await executeCommand('echo done', tmpdir(), 10_000);+ expect(result).toMatchObject({ exitCode: 0, aborted: false, timedOut: false });+ expect(result.stdout.trim()).toBe('done');+ });+});diff --git a/src/capabilities/shell/process-tree.ts b/src/capabilities/shell/process-tree.tsnew file mode 100644index 00000000..48682a6e--- /dev/null+++ b/src/capabilities/shell/process-tree.ts@@ -0,0 +1,77 @@+/**+ * Stopping a command means stopping everything it started (ADR-038).+ *+ * A shell command (`npm run build`, `python train.py`, `a && b`) is a tree:+ * the shell, and the processes it runs, and theirs. Killing only the shell+ * left the real work running after the owner pressed Stop. So on POSIX each+ * command starts in its own process group (`detached`) and is signalled as+ * a group; on Windows the tree is ended with `taskkill /T /F`.+ *+ * Groups still alive when Mercury exits are terminated too, since a detached+ * group no longer receives the terminal's Ctrl+C.+ */+import { spawn, type ChildProcess } from 'node:child_process';++const IS_WINDOWS = process.platform === 'win32';+const liveGroups = new Set<number>();+let exitHookInstalled = false;++/** Spawn options that give the command its own process group (POSIX). */+export function processTreeSpawnOptions(): { detached: boolean } {+ return { detached: !IS_WINDOWS };+}++/** Remember a started command so Mercury's exit can end it. */+export function trackProcessTree(child: ChildProcess): void {+ if (IS_WINDOWS || !child.pid) return;+ liveGroups.add(child.pid);+ if (!exitHookInstalled) {+ exitHookInstalled = true;+ process.on('exit', () => {+ for (const pgid of liveGroups) {+ try { process.kill(-pgid, 'SIGTERM'); } catch { /* already gone */ }+ }+ });+ }+}++/** The command is over and nothing of it needs ending at exit. */+export function untrackProcessTree(child: ChildProcess): void {+ if (child.pid) liveGroups.delete(child.pid);+}++/** Is any process of this command's group still alive? */+export function processTreeAlive(child: ChildProcess): boolean {+ if (!child.pid) return false;+ if (IS_WINDOWS) return child.exitCode === null && child.signalCode === null;+ try {+ process.kill(-child.pid, 0);+ return true;+ } catch {+ return false;+ }+}++/**+ * Signal the whole tree. POSIX: the process group (falls back to the child+ * alone if it has no group). Windows: `taskkill /T /F` (no graceful step+ * exists for console trees there, so both signals end it).+ */+export function killProcessTree(child: ChildProcess, signal: 'SIGTERM' | 'SIGKILL'): void {+ const pid = child.pid;+ if (!pid) return;+ if (IS_WINDOWS) {+ try {+ const killer = spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });+ killer.on('error', () => { try { child.kill(signal); } catch { /* gone */ } });+ } catch {+ try { child.kill(signal); } catch { /* gone */ }+ }+ return;+ }+ try {+ process.kill(-pid, signal);+ } catch {+ try { child.kill(signal); } catch { /* gone */ }+ }+}diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.tsindex c2a729c5..66b247a2 100644--- a/src/capabilities/shell/run-command.ts+++ b/src/capabilities/shell/run-command.ts@@ -9,6 +9,7 @@ import { redactSecrets } from '../../utils/redact.js';import { logger } from '../../utils/logger.js';import { pulseProgress, TOOL_PULSE_INTERVAL_MS } from '../../core/progress-pulse.js';import { planArgvExecution, minimalEnv, type ArgvPlan } from './argv-lane.js';+import { killProcessTree, processTreeAlive, processTreeSpawnOptions, trackProcessTree, untrackProcessTree } from './process-tree.js';const DEFAULT_TIMEOUT_MS = 120_000;const MAX_BUFFER = 1024 * 1024;@@ -41,6 +42,8 @@ export function executeCommand(command: string, cwd: string, timeoutMs: number,cwd,shell: true,stdio: ['pipe', 'pipe', 'pipe'],+ // Its own process group, so a stop ends everything it started.+ ...processTreeSpawnOptions(),}), timeoutMs, options);}@@ -55,6 +58,7 @@ export function executeArgv(file: string, args: readonly string[], cwd: string,env: minimalEnv(),shell: false,windowsHide: true,+ ...processTreeSpawnOptions(),// Output is bounded by the stream handlers below; execFile's own buffer// limit would kill a long but legitimate listing.maxBuffer: Number.MAX_SAFE_INTEGER,@@ -79,27 +83,32 @@ function superviseChild(start: () => ChildProcess, timeoutMs: number, options: Ereturn;}+ trackProcessTree(child);const onAbort = () => terminate('abort');const finish = (exitCode: number | null, timedOut: boolean, aborted = false) => {if (settled) return;settled = true;if (timeoutHandle) clearTimeout(timeoutHandle);- if (sigkillHandle) clearTimeout(sigkillHandle);+ // NOT the SIGKILL timer: a terminated tree still gets its escalation.if (pulseHandle) clearInterval(pulseHandle);signal?.removeEventListener('abort', onAbort);+ if (!sigkillHandle) untrackProcessTree(child);resolve({ stdout, stderr, exitCode, timedOut, aborted });};- // SIGTERM, then SIGKILL after a grace period. Used for both the tool's- // own timeout and an abort from the agent loop — previously an aborted- // turn left the child running to completion.+ // SIGTERM to the whole tree, then SIGKILL to whatever of it is still+ // alive after a grace period (ADR-038). Used for the tool's own timeout+ // and for an abort from the agent loop (the owner's Stop). Killing only+ // the shell used to leave `npm run build` and friends running.const terminate = (reason: 'timeout' | 'abort') => {if (settled) return;- child.kill('SIGTERM');+ killProcessTree(child, 'SIGTERM');sigkillHandle = setTimeout(() => {- if (!child.killed || child.exitCode === null) child.kill('SIGKILL');+ if (processTreeAlive(child)) killProcessTree(child, 'SIGKILL');+ untrackProcessTree(child);}, SIGTERM_GRACE_MS);+ sigkillHandle.unref?.();finish(null, reason === 'timeout', reason === 'abort');};diff --git a/src/core/agent.ts b/src/core/agent.tsindex 06808e3e..5e75e308 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -2,7 +2,6 @@ import { generateText, streamText, stepCountIs } from 'ai';import path from 'node:path';import { homedir } from 'node:os';import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';-import { getHeapStatistics } from 'node:v8';import type { ChannelMessage, ChannelType } from '../types/channel.js';import type { ProviderRegistry } from '../providers/registry.js';import type { Identity } from '../soul/identity.js';@@ -98,6 +97,7 @@ import { requiresFinalSend } from './response-delivery.js';import { updateCliProviderStatus } from './provider-status.js';import { compactConversation } from './memory-governor.js';import { writeCrashFlag } from './crash-flag.js';+import { summarizeSilentTurn, type TurnAction } from './silent-turn.js';import { classifyStreamCompletion, isLengthTruncation, truncationContinuationPrompt, toolTruncationContinuationPrompt } from './stream-completion.js';import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeContinuationPrompt, shouldForceExecuteContinuation, isFailedToolResult, shouldRequireVerification, isVerificationOutputOk, verificationPrompt, responseAsksUser, EXECUTE_MUTATING_TOOLS, VERIFICATION_COMMAND_PATTERN, wakeUpPrompt } from './execute-guard.js';import { classifyTurnEnd, stepsExhaustedPrompt, STEPS_PAUSED_BANNER, WORK_NOT_STARTED_BANNER, VERIFICATION_FAILED_BANNER, type LoopEndCause } from './completion-verdict.js';@@ -578,6 +578,15 @@ export function looksLikeCodingTask(text: string): boolean {export type AbortReason = 'stalled' | 'time-limit' | 'memory-pressure' | 'backgrounded' | 'stopped' | 'halted';+/** Aborts that come from the owner: final for the turn, never retried or resumed (ADR-038). */+export type CancelReason = 'stopped' | 'halted' | 'backgrounded';++/** What the chat is told when the owner ended its turn. */+export function stopNoteFor(reason: CancelReason): string {+ if (reason === 'backgrounded') return 'This task was moved to the background and will report back when it finishes.';+ return `⏹ Task ${reason}. Its work entry was cancelled — a restart will not resume it. Send the request again or ask me to continue if you change your mind.`;+}+const CANCEL_REASONS: ReadonlySet<AbortReason> = new Set<AbortReason>(['stopped', 'halted', 'backgrounded']);/** One running turn (ADR-037): everything that used to be a single field on the agent. */interface TurnState {@@ -587,6 +596,13 @@ interface TurnState {readonly startedAt: number;abort: AbortController | null;abortReason: AbortReason | null;+ /**+ * Set once the owner stops this turn (/stop, /halt, Stop button, /bg+ * current) and never cleared (ADR-038). Internal recovery (stall retry,+ * provider fallback, continuation rounds, durable retry) checks it and+ * gives up; a new abort controller is born aborted.+ */+ cancelled: CancelReason | null;activity: string;completedStepCount: number;stepNarrative: import('../utils/tool-label.js').NarrativeStep[];@@ -667,15 +683,30 @@ export class Agent {}set currentAbort(value: AbortController | null) {const t = this.turn();- if (t) t.abort = value;+ if (!t) return;+ t.abort = value;+ // A stopped turn never gets a live controller back: a retry that makes a+ // fresh one (stall recovery) finds it already aborted.+ if (t.cancelled && value && !value.signal.aborted) value.abort(new Error(`Task ${t.cancelled} by the user`));}+ /** The calling turn's abort reason; once the owner stopped it, always that (ADR-038). */get currentAbortReason(): AbortReason | null {- return this.turn()?.abortReason ?? null;+ const t = this.turn();+ return t?.cancelled ?? t?.abortReason ?? null;}set currentAbortReason(value: AbortReason | null) {const t = this.turn();- if (t) t.abortReason = value;+ if (!t) return;+ // Internal handling (stall, time limit, memory) may set or clear its own+ // reason; it can never overwrite or clear the owner's stop.+ if (t.cancelled) return;+ t.abortReason = value;+ }++ /** Has the owner stopped the calling turn? Every retry/continue path asks this. */+ private turnCancelled(): boolean {+ return this.turn()?.cancelled != null;}private get lastProgressAt(): number {@@ -1444,12 +1475,22 @@ export class Agent {* false when it was already stopping.*/abortTurn(t: TurnState, reason: AbortReason, ledgerNote?: string): boolean {+ if (t.done) return false;+ if (CANCEL_REASONS.has(reason)) {+ // The owner's stop is recorded even when the controller is already+ // aborted (a stall retry in flight): that retry must not carry on.+ const first = t.cancelled === null;+ if (first) t.cancelled = reason as CancelReason;+ t.abortReason = reason;+ if (t.abort && !t.abort.signal.aborted) t.abort.abort(new Error(`Task ${reason} by the user`));+ if (ledgerNote && t.workKey) {+ try { this.workLedger.markCancelled(t.workKey, ledgerNote); } catch { /* entry may not exist */ }+ }+ return first;+ }if (!t.abort || t.abort.signal.aborted) return false;t.abortReason = reason;t.abort.abort();- if (ledgerNote && t.workKey) {- try { this.workLedger.markCancelled(t.workKey, ledgerNote); } catch { /* entry may not exist */ }- }return true;}@@ -1622,7 +1663,9 @@ export class Agent {const turn = this.turnForChannel(sessionId);if (!turn?.abort || turn.abort.signal.aborted) return { ok: false, reason: 'The research is already finishing.' };run.finishRequested = true;- this.abortTurn(turn, 'stopped');+ // Not a cancellation: the turn goes on to write the report from what it read.+ turn.abortReason = 'stopped';+ turn.abort.abort();return { ok: true };}@@ -1695,7 +1738,7 @@ export class Agent {* going (ADR-037). Without one (`/halt`, or a caller that names no chat)* every running turn and every sub-agent stops.*/- async stopAllWork(reason: 'stopped' | 'halted', target?: { channelId?: string; sessionId?: string }): Promise<string> {+ async stopAllWork(reason: 'stopped' | 'halted', target?: { channelId?: string; sessionId?: string; keepQueued?: boolean }): Promise<string> {// The user deliberately killed this work — cancel its ledger entry so// a restart never tries to resume it. (Only real crashes auto-resume.)const label = reason === 'stopped' ? 'Stopped by the user (/stop).' : 'Halted by the user (/halt).';@@ -1706,6 +1749,13 @@ export class Agent {?? (target.sessionId ? this.turnForSession(target.sessionId) : undefined);if (turn && caller && turn.id === caller.id) turn = undefined;if (turn) this.abortTurn(turn, reason, label);+ // Messages this chat had waiting go too (unless the caller only wants+ // the running turn gone, e.g. "do mine first"): a stop that let the+ // next queued message start would look like the task resuming.+ const dropped = target.keepQueued ? 0 : this.dropWaiting((m) =>+ (target.channelId !== undefined && m.channelId === target.channelId)+ || (target.sessionId !== undefined && (m.sessionId ?? m.metadata?.sessionId) === target.sessionId)+ || (turn !== undefined && laneKeyFor(m) === turn.laneKey), label);const channelId = turn?.message.channelId ?? target.channelId;const halted = this.supervisor && channelId ? await this.supervisor.haltForChannel(channelId) : [];const others = [...this.activeTurns.values()]@@ -1720,12 +1770,18 @@ export class Agent {}const tail = cleared ? ' Locks released, task board cleared.' : '';const elsewhere = others > 0 ? ` ${others} task${others === 1 ? '' : 's'} in other chats keep${others === 1 ? 's' : ''} running — /halt stops everything.` : '';- if (!turn && halted.length === 0) {+ if (!turn && halted.length === 0 && dropped === 0) {return cleared ? `Nothing was running.${tail}` : `Nothing is running in this chat.${elsewhere}`;}- const parts = [turn ? 'Stopped this chat\'s task' : null, halted.length ? `halted ${halted.length} sub-agent${halted.length === 1 ? '' : 's'} it started` : null].filter(Boolean);+ const parts = [+ turn ? 'Stopped this chat\'s task' : null,+ halted.length ? `halted ${halted.length} sub-agent${halted.length === 1 ? '' : 's'} it started` : null,+ dropped ? `dropped ${dropped} waiting message${dropped === 1 ? '' : 's'}` : null,+ ].filter(Boolean) as string[];+ parts[0] = parts[0].charAt(0).toUpperCase() + parts[0].slice(1);return `${parts.join(', ')}.${tail}${elsewhere}`;}+ this.dropWaiting(() => true, label);let stoppedTurns = 0;for (const turn of this.activeTurns.values()) {if (caller && turn.id === caller.id) continue;@@ -1744,6 +1800,23 @@ export class Agent {return reason === 'halted' ? 'Foreground task halted.' : 'Foreground task stopped, locks released, task board cleared.';}+ /**+ * Take waiting messages out of the line and cancel their work entries+ * (never started: a restart must not run them after all). Returns how many.+ */+ private dropWaiting(match: (m: ChannelMessage) => boolean, reason: string): number {+ const dropped = this.messageQueue.filter((i) => match(i.message));+ if (dropped.length === 0) return 0;+ this.messageQueue = this.messageQueue.filter((i) => !match(i.message));+ for (const item of dropped) {+ if (!item.workKey) continue;+ this.queuedWorkKeys.delete(item.workKey);+ try { this.workLedger.markCancelled(item.workKey, reason); } catch { /* entry may not exist */ }+ }+ this.announceQueue();+ return dropped.length;+ }+/** Resolves when this lane has no running turn (or after the deadline). */private waitUntilLaneIdle(laneKey: string, maxMs: number): Promise<void> {const deadline = Date.now() + maxMs;@@ -2548,6 +2621,7 @@ export class Agent {startedAt: Date.now(),abort: null,abortReason: null,+ cancelled: null,activity: '',completedStepCount: 0,stepNarrative: [],@@ -2589,6 +2663,11 @@ export class Agent {/** One queued message, start to finish: the work ledger and scheduled-run bookkeeping around handleMessage. */private async runQueuedItem(item: { message: ChannelMessage; workKey?: string }): Promise<void> {const msg = item.message;+ // Cancelled while it waited (or a retry timer that raced a stop): never run it.+ if (item.workKey && this.workLedger.get(item.workKey)?.status === 'cancelled') {+ logger.info({ workKey: item.workKey }, 'Skipping cancelled work');+ return;+ }try {if (item.workKey) this.workLedger.markRunning(item.workKey);await this.withSessionProgramming(msg, () => this.handleMessage(msg));@@ -2624,7 +2703,7 @@ export class Agent {id: t.id,startedAt: t.startedAt,label: `${t.laneKey}: ${this.describeTurn(t)}`,- isStopping: () => t.done || !t.abort || t.abort.signal.aborted,+ isStopping: () => t.done || t.cancelled !== null || !t.abort || t.abort.signal.aborted,shed: (error: Error) => {if (!t.abort || t.abort.signal.aborted) return;t.abortReason = 'memory-pressure';@@ -2815,6 +2894,8 @@ export class Agent {}private scheduleDurableRetry(msg: ChannelMessage, workKey: string, error: unknown, continuation = false): number {+ // Stopped work is never retried or continued (ADR-038).+ if (this.turnCancelled() || this.workLedger.get(workKey)?.status === 'cancelled') return 0;const attempts = this.workLedger.get(workKey)?.attempts ?? 1;const delayMs = continuation? Math.min(2_000 * 2 ** Math.min(attempts - 1, 5), 60_000)@@ -3722,6 +3803,9 @@ export class Agent {// Compact per-turn tool trace, written to the session at turn end so// the next turn's history carries what was read and written.const turnToolTrace: string[] = [];+ // The same steps as data: a turn that ends without text is answered+ // with what it did instead of "(no text response)".+ const turnActions: TurnAction[] = [];// Files this turn makes that are worth keeping (images, PDFs, reports…): artifacts of the conversation.const artifactCollector = new ArtifactCollector({startedAt: Date.now(),@@ -3748,6 +3832,7 @@ export class Agent {args: summarizeToolArgs(tc.input),outcome: summarizeToolResult(raw, !isFailedToolResult(text)),}));+ turnActions.push({ tool: tc.toolName, input: tc.input, ok: !isFailedToolResult(text) });}};let lastStepHadToolCalls = false;@@ -4524,7 +4609,7 @@ export class Agent {}if (this.currentAbortReason === 'backgrounded') {researchRun?.end('stopped', 'it was moved to the background');- result = { text: 'This task was moved to the background and will report back when it finishes.', usage: undefined };+ result = { text: stopNoteFor('backgrounded'), usage: undefined };break;}if (this.currentAbortReason === 'stopped' && researchRun?.finishRequested && researchRun.readCount() > 0) {@@ -4535,7 +4620,7 @@ export class Agent {}if (this.currentAbortReason === 'stopped' || this.currentAbortReason === 'halted') {researchRun?.end('stopped', 'you stopped it');- result = { text: `⏹ Task ${this.currentAbortReason}. Its work entry was cancelled — a restart will not resume it. Send the request again or ask me to continue if you change your mind.`, usage: undefined };+ result = { text: stopNoteFor(this.currentAbortReason), usage: undefined };this.currentAbortReason = null;break;}@@ -4590,6 +4675,15 @@ export class Agent {}}+ // Stopped by the owner however the attempt ended (mid-tool, between+ // steps, in a fallback): the answer is the stop note — never a retry,+ // a continuation or a failure report (ADR-038).+ const ownerStop = this.turn()?.cancelled ?? null;+ if (!result && ownerStop) {+ researchRun?.end('stopped', ownerStop === 'backgrounded' ? 'it was moved to the background' : 'you stopped it');+ result = { text: stopNoteFor(ownerStop), usage: undefined };+ }+if (!result && researchRun && !memoryPressureStop) {const cut = researchCut ?? (lastError ? `of an error (${whitelabelProviderError(lastError)})` : 'it was interrupted');if (await deliverResearchReport(cut)) return;@@ -5100,7 +5194,18 @@ export class Agent {// Recompute AFTER the guard: the continuation's output (not the// original narration) must be what reaches the session store, the// work ledger, and the final delivery.- let finalText = (result.text || '').trim() || '(no text response)';+ // Stopped during a continuation or verification round: deliver the+ // stop note, never the earlier answer dressed up as complete.+ {+ const stoppedAs = this.turn()?.cancelled ?? null;+ if (stoppedAs && (result.text || '').trim() !== stopNoteFor(stoppedAs)) {+ if (researchRun?.outcome === 'running') researchRun.end('stopped', stoppedAs === 'backgrounded' ? 'it was moved to the background' : 'you stopped it');+ result = { ...result, text: stopNoteFor(stoppedAs) };+ }+ }+ // No text from the model (it ended on tool calls): say what was done.+ const modelWroteText = (result.text || '').trim().length > 0;+ let finalText = modelWroteText ? (result.text || '').trim() : summarizeSilentTurn(turnActions);let researchReportText: string | null = null;// A research run: an empty answer still gets a report from what was@@ -5267,7 +5372,9 @@ export class Agent {meta: completionMeta,verificationNote: lastVerificationNote || undefined,traceId,- alreadyStreamed: !requiresFinalSend(msg.channelType, cliResponseStreamed),+ // Nothing was streamed when the model wrote no text: the summary+ // of what was done must be sent, or the screen shows nothing.+ alreadyStreamed: modelWroteText && !this.turnCancelled() && !requiresFinalSend(msg.channelType, cliResponseStreamed),forceBanner: isMercuryCodeExecution,});replyDelivered();@@ -5750,15 +5857,7 @@ export class Agent {* queued for it. Other chats keep going. Returns whether anything stopped.*/stopWorkFor(channelPrefix: string, reason = 'Stopped by the owner.'): boolean {- const dropped = this.messageQueue.filter((i) => i.message.channelId.startsWith(channelPrefix));- this.messageQueue = this.messageQueue.filter((i) => !i.message.channelId.startsWith(channelPrefix));- // Never started: cancel them, or a restart would run them after all.- for (const item of dropped) {- if (!item.workKey) continue;- this.queuedWorkKeys.delete(item.workKey);- try { this.workLedger.markCancelled(item.workKey, reason); } catch { /* entry may not exist */ }- }- let stopped = dropped.length > 0;+ let stopped = this.dropWaiting((m) => m.channelId.startsWith(channelPrefix), reason) > 0;for (const turn of this.activeTurns.values()) {if (turn.message.channelId.startsWith(channelPrefix) && this.abortTurn(turn, 'stopped', reason)) stopped = true;}diff --git a/src/core/commands/bg-command.ts b/src/core/commands/bg-command.tsindex bcf0c954..44bd1588 100644--- a/src/core/commands/bg-command.ts+++ b/src/core/commands/bg-command.ts@@ -24,7 +24,7 @@ export async function handleBgCommand(agent: Agent, trimmed: string, msg: Channeconst sourceChannelId = turn.message.channelId;const sourceChannelType = turn.message.channelType as any;- agent.abortTurn(turn, 'backgrounded');+ agent.abortTurn(turn, 'backgrounded', 'Moved to the background (/bg current).');if (agent.supervisor) {const agentId = await agent.supervisor.spawn({diff --git a/src/core/silent-turn.test.ts b/src/core/silent-turn.test.tsnew file mode 100644index 00000000..2dda7129--- /dev/null+++ b/src/core/silent-turn.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { summarizeSilentTurn } from './silent-turn.js';++/** A turn that ends on tool calls says what it did — never "(no text response)". */+describe('summarizeSilentTurn', () => {+ it('lists files written and edited and commands with their result', () => {+ const text = summarizeSilentTurn([+ { tool: 'list_dir', input: { path: '.' }, ok: true },+ { tool: 'create_file', input: { path: 'src/index.html' }, ok: true },+ { tool: 'write_file', input: { path: '/abs/styles.css' }, ok: true },+ { tool: 'edit_file', input: { path: 'src/app.ts' }, ok: true },+ { tool: 'edit_file', input: { path: 'src/index.html' }, ok: true },+ { tool: 'run_command', input: { command: 'npm test' }, ok: true },+ ]);+ expect(text).toBe([+ "Done. Here's what I did:",+ '- Wrote `index.html`, `styles.css`',+ '- Edited `app.ts`',+ '- Ran `npm test` — succeeded',+ ].join('\n'));+ });++ it('says honestly when something failed, and a later success clears an earlier failure', () => {+ const text = summarizeSilentTurn([+ { tool: 'run_command', input: { command: 'npm test' }, ok: false },+ { tool: 'edit_file', input: { path: 'a.ts' }, ok: false },+ { tool: 'edit_file', input: { path: 'a.ts' }, ok: true },+ { tool: 'write_file', input: { path: 'b.ts' }, ok: false },+ ]);+ expect(text).toMatch(/^Here's what I did — not everything succeeded:/);+ expect(text).toContain('- Edited `a.ts`');+ expect(text).toContain("- Couldn't change `b.ts`");+ expect(text).toContain('- Ran `npm test` — failed');+ });++ it('a command that failed and then passed counts as passed', () => {+ const text = summarizeSilentTurn([+ { tool: 'run_command', input: { command: 'npm test' }, ok: false },+ { tool: 'run_command', input: { command: 'npm test' }, ok: true },+ ]);+ expect(text).toBe("Done. Here's what I did:\n- Ran `npm test` — succeeded");+ });++ it('caps long lists', () => {+ const files = Array.from({ length: 9 }, (_, i) => ({ tool: 'create_file', input: { path: `f${i}.ts` }, ok: true }));+ expect(summarizeSilentTurn(files)).toContain('and 3 more');+ });++ it('only looked around, or did other things, or nothing at all: still a real sentence', () => {+ expect(summarizeSilentTurn([{ tool: 'read_file', input: { path: 'a' }, ok: true }])).toContain('Looked through 1 file');+ expect(summarizeSilentTurn([{ tool: 'fetch_url', input: { url: 'x' }, ok: true }])).toMatch(/^I finished 1 step/);+ expect(summarizeSilentTurn([])).toMatch(/^I didn't get a written answer/);+ for (const t of [summarizeSilentTurn([]), summarizeSilentTurn([{ tool: 'x', input: {}, ok: true }])]) {+ expect(t).not.toContain('(no text response)');+ }+ });+});diff --git a/src/core/silent-turn.ts b/src/core/silent-turn.tsnew file mode 100644index 00000000..7b3ed126--- /dev/null+++ b/src/core/silent-turn.ts@@ -0,0 +1,110 @@+/**+ * A turn whose model ended on tool calls without writing a word (common in+ * Mercury Code: write the files, run the tests, stop). The owner used to see+ * "(no text response)". Instead they get what was actually done, built from+ * the turn's own tool calls: files written, edited and deleted, commands run+ * and whether they passed — never invented, never empty.+ */+import { basename } from 'node:path';++export interface TurnAction {+ tool: string;+ input: unknown;+ /** The tool reported success. */+ ok: boolean;+}++const MAX_ITEMS = 6;++function arg(input: unknown, key: string): string | undefined {+ if (!input || typeof input !== 'object') return undefined;+ const v = (input as Record<string, unknown>)[key];+ return typeof v === 'string' && v.trim() ? v.trim() : undefined;+}++function list(items: string[]): string {+ const unique = [...new Set(items)];+ const shown = unique.slice(0, MAX_ITEMS).map((i) => `\`${i}\``).join(', ');+ return unique.length > MAX_ITEMS ? `${shown} and ${unique.length - MAX_ITEMS} more` : shown;+}++function oneLine(command: string): string {+ const flat = command.replace(/\s+/g, ' ').trim();+ return flat.length > 60 ? `${flat.slice(0, 59)}…` : flat;+}++/** The reply for a turn that produced no text. */+export function summarizeSilentTurn(actions: readonly TurnAction[]): string {+ const created: string[] = [];+ const edited: string[] = [];+ const deleted: string[] = [];+ const commands: Array<{ command: string; ok: boolean }> = [];+ const failedFiles: string[] = [];+ let looked = 0;+ let other = 0;++ for (const a of actions) {+ const path = arg(a.input, 'path') ?? arg(a.input, 'file_path') ?? arg(a.input, 'filePath');+ const name = path ? basename(path) : undefined;+ switch (a.tool) {+ case 'write_file':+ case 'create_file':+ if (!name) { other++; break; }+ if (a.ok) created.push(name); else failedFiles.push(name);+ break;+ case 'edit_file':+ if (!name) { other++; break; }+ if (a.ok) edited.push(name); else failedFiles.push(name);+ break;+ case 'delete_file':+ if (name && a.ok) deleted.push(name); else if (name) failedFiles.push(name);+ break;+ case 'run_command': {+ const command = arg(a.input, 'command');+ if (command) commands.push({ command: oneLine(command), ok: a.ok });+ else other++;+ break;+ }+ case 'read_file':+ case 'list_dir':+ case 'git_status':+ case 'git_diff':+ case 'git_log':+ looked++;+ break;+ default:+ other++;+ }+ }++ const lines: string[] = [];+ // Written then edited in the same turn: say it once, as written.+ const editedOnly = edited.filter((f) => !created.includes(f));+ if (created.length) lines.push(`- Wrote ${list(created)}`);+ if (editedOnly.length) lines.push(`- Edited ${list(editedOnly)}`);+ if (deleted.length) lines.push(`- Deleted ${list(deleted)}`);+ if (commands.length) {+ // The last run of each command is the one that counts.+ const last = new Map<string, boolean>();+ for (const c of commands) { last.delete(c.command); last.set(c.command, c.ok); }+ const runs = [...last.entries()];+ for (const [command, ok] of runs.slice(-MAX_ITEMS)) lines.push(`- Ran \`${command}\` — ${ok ? 'succeeded' : 'failed'}`);+ if (runs.length > MAX_ITEMS) lines.push(`- …and ${runs.length - MAX_ITEMS} more commands`);+ }+ // A file whose later attempt worked isn't a failure.+ const stillFailed = failedFiles.filter((f) => !created.includes(f) && !edited.includes(f) && !deleted.includes(f));+ if (stillFailed.length) lines.push(`- Couldn't change ${list(stillFailed)}`);+ if (lines.length === 0 && looked > 0) lines.push(`- Looked through ${looked} file${looked === 1 ? '' : 's'} and folder${looked === 1 ? '' : 's'}`);+ if (other > 0 && lines.length > 0) lines.push(`- Plus ${other} other step${other === 1 ? '' : 's'}`);++ if (lines.length === 0) {+ return other > 0+ ? `I finished ${other} step${other === 1 ? '' : 's'} but didn't write a summary. Ask me what I did, or say "continue" if there's more to do.`+ : 'I didn\'t get a written answer this time. Send your message again, or say "continue" if I should keep going.';+ }+ const lastRuns = new Map<string, boolean>();+ for (const c of commands) lastRuns.set(c.command, c.ok);+ const anyFailed = [...lastRuns.values()].some((ok) => !ok) || stillFailed.length > 0;+ const head = anyFailed ? 'Here\'s what I did — not everything succeeded:' : 'Done. Here\'s what I did:';+ return `${head}\n${lines.join('\n')}`;+}diff --git a/src/core/stop-contract.test.ts b/src/core/stop-contract.test.tsnew file mode 100644index 00000000..5fa3e0e6--- /dev/null+++ b/src/core/stop-contract.test.ts@@ -0,0 +1,154 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { ChannelMessage } from '../types/channel.js';+import { Agent, stopNoteFor } from './agent.js';+import { WorkLedger } from './work-ledger.js';+import { bareTurnFields, startFakeTurn } from './testing/fake-turns.js';++/**+ * ADR-038: a stop is final. Whatever the turn was doing (a stall retry in+ * flight, a provider fallback, a continuation round, a durable retry), it+ * never carries on, and nothing the chat had waiting starts in its place.+ */++const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function msg(id: string, channelId: string): ChannelMessage {+ return { id, channelId, channelType: 'web', senderId: 'u', content: `do ${id}`, timestamp: Date.now(), metadata: {} };+}++function bare() {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-stop-'));+ dirs.push(dir);+ const workLedger = new WorkLedger({ filePath: join(dir, 'work-ledger.json') });+ const agent = Object.create(Agent.prototype) as Agent;+ Object.assign(agent, { ...bareTurnFields(), workLedger, running: true, channels: { get: () => undefined }, globalLifecycle: { is: () => true } });+ const internals = agent as unknown as {+ turnStore: { run<T>(s: unknown, fn: () => T): T };+ currentAbort: AbortController | null;+ currentAbortReason: string | null;+ scheduleDurableRetry(m: ChannelMessage, key: string, err: unknown, continuation?: boolean): number;+ runQueuedItem(item: { message: ChannelMessage; workKey?: string }): Promise<void>;+ messageQueue: Array<{ message: ChannelMessage; workKey?: string }>;+ capabilities: { getCwd(): string };+ };+ return { agent, workLedger, internals };+}++describe('a stop is sticky for the turn', () => {+ it('lands even while a stall retry has the controller aborted, and the retry gets a dead controller', () => {+ const { agent, internals } = bare();+ const t = startFakeTurn(agent, msg('a', 'chat-a')) as unknown as { abort: AbortController; cancelled: string | null };+ internals.turnStore.run(t, () => {+ // The stall watchdog aborted the attempt to retry it...+ internals.currentAbortReason = 'stalled';+ t.abort.abort();+ // ...and the owner presses Stop in that window.+ agent.abortTurn(t as never, 'stopped', 'Stopped by the user (/stop).');+ expect(t.cancelled).toBe('stopped');+ // The stall branch clears its reason and makes a fresh controller:+ internals.currentAbortReason = null;+ const fresh = new AbortController();+ internals.currentAbort = fresh;+ expect(fresh.signal.aborted).toBe(true);+ expect(internals.currentAbortReason).toBe('stopped');+ // Internal reasons can never overwrite it either.+ internals.currentAbortReason = 'time-limit';+ expect(internals.currentAbortReason).toBe('stopped');+ });+ });++ it('a second stop is a no-op', async () => {+ const { agent } = bare();+ const t = startFakeTurn(agent, msg('a', 'chat-a')) as unknown as { cancelled: string | null };+ expect(agent.abortTurn(t as never, 'stopped')).toBe(true);+ expect(agent.abortTurn(t as never, 'halted')).toBe(false);+ expect(t.cancelled).toBe('stopped');+ });++ it('the stop note is the one desktop recognises', () => {+ expect(stopNoteFor('stopped')).toMatch(/^⏹ Task stopped\b/);+ expect(stopNoteFor('halted')).toMatch(/^⏹ Task halted\b/);+ });+});++describe('stopped work is never retried or resumed', () => {+ it('a durable retry from a stopped turn does nothing and the entry stays cancelled', () => {+ vi.useFakeTimers();+ try {+ const { agent, workLedger, internals } = bare();+ const m = msg('a', 'chat-a');+ const key = workLedger.accept(m).entry.key;+ workLedger.markRunning(key);+ const t = startFakeTurn(agent, m) as unknown as { workKey: string | null };+ t.workKey = key;+ internals.turnStore.run(t, () => {+ agent.abortTurn(t as never, 'stopped', 'Stopped by the user (/stop).');+ expect(internals.scheduleDurableRetry(m, key, new Error('aborted after a tool completed'), true)).toBe(0);+ });+ vi.advanceTimersByTime(10 * 60_000);+ expect(workLedger.get(key)?.status).toBe('cancelled');+ expect(internals.messageQueue).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('the ledger refuses to turn a cancelled entry back into a retry', () => {+ const { workLedger } = bare();+ const key = workLedger.accept(msg('a', 'chat-a')).entry.key;+ workLedger.markRunning(key);+ workLedger.markCancelled(key, 'stopped');+ workLedger.markRetry(key, new Error('x'), Date.now() + 1000, { continuation: true });+ workLedger.markPaused(key, 'x');+ workLedger.markFailed(key, new Error('x'));+ expect(workLedger.get(key)?.status).toBe('cancelled');+ });++ it('a cancelled entry that was already back in line never runs', async () => {+ const { agent, workLedger, internals } = bare();+ const handle = vi.fn();+ Object.assign(agent, { handleMessage: handle, withSessionProgramming: (_m: unknown, run: () => Promise<void>) => run() });+ const m = msg('a', 'chat-a');+ const key = workLedger.accept(m).entry.key;+ workLedger.markCancelled(key, 'stopped');+ await internals.runQueuedItem({ message: m, workKey: key });+ expect(handle).not.toHaveBeenCalled();+ });+});++describe("a stop clears the chat's line", () => {+ it("drops this chat's waiting messages (cancelled, never replayed); other chats keep theirs", async () => {+ const { agent, workLedger, internals } = bare();+ const running = startFakeTurn(agent, msg('a1', 'chat-a'));+ const queue = (m: ChannelMessage) => { const key = workLedger.accept(m).entry.key; agent.queueMessage(m, key); return key; };+ const a2 = queue(msg('a2', 'chat-a'));+ const b1 = queue(msg('b1', 'chat-b'));+ const note = await agent.stopAllWork('stopped', { channelId: 'chat-a' });+ expect(running.abort.signal.aborted).toBe(true);+ expect(note).toMatch(/^Stopped this chat's task, dropped 1 waiting message\./);+ expect(internals.messageQueue.map((i) => i.message.id)).toEqual(['b1']);+ expect(workLedger.get(a2)?.status).toBe('cancelled');+ expect(workLedger.get(b1)?.status).toBe('queued');+ });++ it('"do mine first" (keepQueued) stops the running turn only', async () => {+ const { agent, workLedger, internals } = bare();+ startFakeTurn(agent, msg('a1', 'chat-a'));+ const key = workLedger.accept(msg('a2', 'chat-a')).entry.key;+ agent.queueMessage(msg('a2', 'chat-a'), key);+ await agent.stopAllWork('stopped', { channelId: 'chat-a', keepQueued: true });+ expect(internals.messageQueue.map((i) => i.message.id)).toEqual(['a2']);+ });++ it('/halt empties the whole line', async () => {+ const { agent, workLedger, internals } = bare();+ startFakeTurn(agent, msg('a1', 'chat-a'));+ for (const m of [msg('a2', 'chat-a'), msg('b1', 'chat-b')]) agent.queueMessage(m, workLedger.accept(m).entry.key);+ await agent.stopAllWork('halted');+ expect(internals.messageQueue).toEqual([]);+ });+});diff --git a/src/core/sub-agent.ts b/src/core/sub-agent.tsindex e81cf90a..4dfe84fa 100644--- a/src/core/sub-agent.ts+++ b/src/core/sub-agent.ts@@ -1,4 +1,6 @@import { generateText, stepCountIs } from 'ai';+import { isFailedToolResult } from './execute-guard.js';+import { summarizeSilentTurn, type TurnAction } from './silent-turn.js';import type { ChannelMessage } from '../types/channel.js';import type { SubAgentConfig, SubAgentResult, SubAgentStatus } from '../types/agent.js';import type { ProviderRegistry } from '../providers/registry.js';@@ -29,6 +31,8 @@ export class SubAgent {readonly config: SubAgentConfig;private status: SubAgentStatus = 'pending';private abortController: AbortController;+ /** Every tool step, for a report when the model ends without text. */+ private actions: TurnAction[] = [];private startTime: number = 0;private result: SubAgentResult | null = null;private filesModified: string[] = [];@@ -291,6 +295,16 @@ export class SubAgent {for (let i = 0; i < toolCalls.length; i++) {const tc = toolCalls[i];const toolName = tc.toolName as string;+ {+ type StepResult = { toolCallId?: string; output?: unknown; result?: unknown };+ const results = toolResults as unknown as StepResult[];+ const callId = (tc as { toolCallId?: string }).toolCallId;+ const tr = results.find((r) => r?.toolCallId !== undefined && r.toolCallId === callId) ?? results[i];+ const out = (tr?.output ?? tr?.result) as { type?: string; value?: unknown } | string | undefined;+ const text = typeof out === 'string' ? out : typeof out?.value === 'string' ? out.value : JSON.stringify(out ?? '');+ const failed = (typeof out === 'object' && (out?.type === 'error-text' || out?.type === 'error-json')) || isFailedToolResult(text);+ this.actions.push({ tool: toolName, input: tc.input, ok: tr !== undefined && !failed });+ }if (['write_file', 'edit_file', 'create_file', 'delete_file'].includes(toolName)) {const filePath = (tc.input as any)?.path || (tc.input as any)?.filePath;@@ -433,7 +447,8 @@ export class SubAgent {return this.result;}- const finalText = (result?.text || '').trim() || '(no text response)';+ // Ended on tool calls without a word: report what it did instead.+ const finalText = (result?.text || '').trim() || summarizeSilentTurn(this.actions);this.tokenBudget.recordUsage({provider: provider.name,diff --git a/src/core/supervisor-halt.test.ts b/src/core/supervisor-halt.test.tsnew file mode 100644index 00000000..1b24fecd--- /dev/null+++ b/src/core/supervisor-halt.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';+import { SubAgentSupervisor } from './supervisor.js';+import type { SubAgentConfig } from '../types/agent.js';++/** ADR-038: a halted sub-agent is never started again (step-budget resume, wait queue). */+describe('sub-agent halt is final', () => {+ function bare() {+ const sup = Object.create(SubAgentSupervisor.prototype) as SubAgentSupervisor;+ Object.assign(sup, {+ haltedIds: new Set<string>(),+ stepResumeCounts: new Map(),+ agentConfigs: new Map(),+ activeAgents: new Map(),+ waitQueue: [],+ taskBoard: { update: () => {} },+ });+ const internals = sup as unknown as {+ startAgentInBackground(c: SubAgentConfig): void;+ agentConfigs: Map<string, SubAgentConfig>;+ waitQueue: SubAgentConfig[];+ };+ return { sup, internals };+ }++ it('a halted id is refused by the starter', async () => {+ const { sup, internals } = bare();+ const config = { id: 'agent-1', task: 't', sourceChannelId: 'chat-a', sourceChannelType: 'web' } as SubAgentConfig;+ internals.waitQueue.push(config);+ expect(await sup.haltForChannel('chat-a')).toEqual(['agent-1']);+ expect(sup.wasHalted('agent-1')).toBe(true);+ internals.startAgentInBackground(config);+ expect(internals.agentConfigs.has('agent-1')).toBe(false);+ });++ it("halting one chat leaves another chat's agents alone", async () => {+ const { sup, internals } = bare();+ internals.waitQueue.push({ id: 'a', task: 't', sourceChannelId: 'chat-a' } as SubAgentConfig, { id: 'b', task: 't', sourceChannelId: 'chat-b' } as SubAgentConfig);+ await sup.haltForChannel('chat-a');+ expect(internals.waitQueue.map((c) => c.id)).toEqual(['b']);+ expect(sup.wasHalted('b')).toBe(false);+ });+});diff --git a/src/core/supervisor.ts b/src/core/supervisor.tsindex ea014ed0..ad25d2dd 100644--- a/src/core/supervisor.ts+++ b/src/core/supervisor.ts@@ -196,7 +196,32 @@ export class SubAgentSupervisor {});}+ /**+ * Agents the owner halted (ADR-038). A halt is final: no step-budget+ * auto-resume, no start from the wait queue, however the halt raced them.+ * Bounded; ids are unique per spawn.+ */+ private readonly haltedIds = new Set<string>();++ private markHalted(agentId: string): void {+ this.haltedIds.add(agentId);+ this.stepResumeCounts.delete(agentId);+ if (this.haltedIds.size > 1000) {+ const oldest = this.haltedIds.values().next().value;+ if (oldest !== undefined) this.haltedIds.delete(oldest);+ }+ }++ /** Was this agent halted by the owner? */+ wasHalted(agentId: string): boolean {+ return this.haltedIds.has(agentId);+ }+private startAgentInBackground(config: SubAgentConfig): void {+ if (this.haltedIds.has(config.id)) {+ logger.info({ agentId: config.id }, 'Not starting a halted sub-agent');+ return;+ }this.agentConfigs.set(config.id, config);const subAgent = new SubAgent(config, {agentConfig: this.agentConfig,@@ -291,7 +316,7 @@ export class SubAgentSupervisor {if (result.status === 'paused') {const config = this.agentConfigs.get(agentId);const resumes = this.stepResumeCounts.get(agentId) ?? 0;- if (config && resumes < MAX_SUBAGENT_STEP_RESUMES) {+ if (config && resumes < MAX_SUBAGENT_STEP_RESUMES && !this.haltedIds.has(agentId)) {this.stepResumeCounts.set(agentId, resumes + 1);const entry = this.taskBoard.get(agentId);if (entry) {@@ -399,6 +424,7 @@ export class SubAgentSupervisor {return false;}+ this.markHalted(agentId);agent?.abort();this.waitQueue = this.waitQueue.filter(c => c.id !== agentId);@@ -425,6 +451,7 @@ export class SubAgentSupervisor {for (const [agentId, agent] of this.activeAgents.entries()) {if (!owned(agentId)) continue;+ this.markHalted(agentId);agent.abort();halted.push(agentId);}@@ -435,6 +462,7 @@ export class SubAgentSupervisor {remaining.push(config);continue;}+ this.markHalted(config.id);this.taskBoard.update(config.id, {status: 'halted',completedAt: Date.now(),@@ -456,6 +484,7 @@ export class SubAgentSupervisor {const halted: string[] = [];for (const [agentId, agent] of this.activeAgents.entries()) {if (!fromChannel(agent.config)) continue;+ this.markHalted(agentId);agent.abort();halted.push(agentId);}@@ -465,6 +494,7 @@ export class SubAgentSupervisor {remaining.push(config);continue;}+ this.markHalted(config.id);this.taskBoard.update(config.id, { status: 'halted', completedAt: Date.now(), progress: 'Halted while queued' });halted.push(config.id);}diff --git a/src/core/testing/fake-turns.ts b/src/core/testing/fake-turns.tsindex c19daf5d..96226f6e 100644--- a/src/core/testing/fake-turns.ts+++ b/src/core/testing/fake-turns.ts@@ -50,6 +50,7 @@ export function startFakeTurn(agent: Agent, message: ChannelMessage, activity =startedAt,abort: new AbortController(),abortReason: null,+ cancelled: null,activity,completedStepCount: 0,stepNarrative: [],diff --git a/src/core/work-ledger.ts b/src/core/work-ledger.tsindex 02571e5e..9bf02847 100644--- a/src/core/work-ledger.ts+++ b/src/core/work-ledger.ts@@ -196,6 +196,9 @@ export class WorkLedger {markRetry(key: string, error: unknown, nextAttemptAt: number, context: WorkContinuationContext = {}): WorkEntry {return this.update(key, (entry) => {+ // A user-cancelled entry is terminal: a retry scheduled by a turn the+ // owner stopped must never bring it back (ADR-038).+ if (entry.status === 'cancelled') return;entry.status = 'queued';entry.error = error instanceof Error ? error.message : String(error);entry.nextAttemptAt = nextAttemptAt;diff --git a/src/eval/scenarios/chat.test.ts b/src/eval/scenarios/chat.test.tsindex 4146ee76..f43e5f7a 100644--- a/src/eval/scenarios/chat.test.ts+++ b/src/eval/scenarios/chat.test.ts@@ -87,4 +87,27 @@ describe('eval · chat mode never forces guard rounds', () => {expect(JSON.stringify(turn.providerCalls[1].prompt)).toContain('tool-result');expectTimings(turn);});++ it('the model writes a file and ends without a word → the owner is told what was done, never "(no text response)"', async () => {+ const result = await runScenario({+ name: 'chat-silent-turn',+ turns: [{+ message: 'write my notes to notes.md',+ steps: [+ toolStep([call('create_file', { path: 'notes.md', content: '# Notes\n- buy milk\n' })]),+ textStep(''),+ ],+ expect: {+ deliveredCount: 1,+ finalTextIncludes: ['Wrote `notes.md`'],+ noEventIncludes: ['(no text response)'],+ toolsUsed: ['create_file'],+ },+ }],+ });+ expect(result.failures).toEqual([]);+ const [turn] = result.turns;+ // What the session remembers is the summary too, not a placeholder.+ expect(turn.sessionEntries.filter((m) => m.kind === 'message').map((m) => m.content).join('\n')).not.toContain('(no text response)');+ });});diff --git a/src/eval/scenarios/stop.test.ts b/src/eval/scenarios/stop.test.tsnew file mode 100644index 00000000..9a700369--- /dev/null+++ b/src/eval/scenarios/stop.test.ts@@ -0,0 +1,86 @@+import { afterAll, describe, expect, it } from 'vitest';+import { MockLanguageModelV3 } from 'ai/test';+import type { LanguageModelV3CallOptions, LanguageModelV3StreamPart } from '@ai-sdk/provider';+import type { ChannelMessage } from '../../types/channel.js';+import { EvalHarness } from '../runner.js';++/**+ * ADR-038 end to end, the reported bug: the owner presses Stop in the middle+ * of a multi-step task (a tool already ran) and a few seconds later the task+ * "resumes". The aborted attempt used to schedule a durable continuation+ * that flipped the cancelled work entry back to queued and re-ran it.+ */++const tick = (ms = 5) => new Promise<void>((r) => setTimeout(r, ms));+const USAGE = { inputTokens: { total: 10, noCache: 10, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 5, text: 5, reasoning: 0 } };++function stream(parts: LanguageModelV3StreamPart[]) {+ return { stream: new ReadableStream<LanguageModelV3StreamPart>({ start(c) { for (const p of parts) c.enqueue(p); c.close(); } }) };+}++/** Call 1: a tool call (list_dir). Every later call: hangs until aborted. */+async function multiStepHarness(name: string) {+ const harness = await EvalHarness.create({ name, turns: [], channel: { type: 'telegram', style: 'plain' } }, { fakeTimers: false });+ let calls = 0;+ const model = new MockLanguageModelV3({+ provider: 'eval.stop',+ modelId: 'stop-model',+ doStream: async (options: LanguageModelV3CallOptions) => {+ calls++;+ if (calls === 1) {+ return stream([+ { type: 'stream-start', warnings: [] },+ { type: 'tool-call', toolCallId: 'call-1', toolName: 'list_dir', input: JSON.stringify({ path: '.' }) },+ { type: 'finish', usage: USAGE, finishReason: { unified: 'tool-calls', raw: 'tool_calls' } },+ ]);+ }+ await new Promise<never>((_resolve, reject) => {+ const signal = options.abortSignal;+ if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));+ signal?.addEventListener('abort', () => reject(signal.reason ?? new Error('Aborted')), { once: true });+ });+ throw new Error('unreachable');+ },+ });+ for (const p of harness.providers) (p as unknown as { getModelInstance: () => unknown }).getModelInstance = () => model;+ const send = (id: string, chat: string, text: string) => {+ const message: ChannelMessage = { id, channelId: chat, channelType: 'telegram', senderId: 'eval-user', content: text, timestamp: Date.now() };+ harness.channel.inject(message);+ };+ const delivered = (chat: string) => harness.channel.events.filter((e) => e.kind === 'delivered' && e.targetId === chat).map((e) => e.text);+ return { harness, send, delivered, calls: () => calls };+}++describe('eval · stop is final (ADR-038)', () => {+ afterAll(async () => {+ const { removeEvalRoot } = await import('../env.js');+ removeEvalRoot();+ });++ it('Stop after a tool ran: the task ends and does not come back', async () => {+ const { harness, send, delivered, calls } = await multiStepHarness('stop-after-tool');+ try {+ send('m-1', 'chat-a', 'list the files and then summarise every one of them');+ // The tool step ran and the model is now on its second step.+ for (let i = 0; i < 400 && calls() < 2; i++) await tick();+ expect(calls()).toBe(2);+ // A follow-up the owner typed before stopping must not start either.+ send('m-2', 'chat-a', 'and also count the lines');+ await tick(20);+ send('m-stop', 'chat-a', '/stop');+ await harness.agent.whenIdle();+ const text = delivered('chat-a').join('\n');+ expect(text).toMatch(/Stopped this chat's task/);+ expect(text).toMatch(/⏹ Task stopped/);+ // Past the first continuation delay (2 s) the old code re-ran it.+ await tick(3_500);+ expect(calls()).toBe(2);+ expect(harness.agent.activeTurnCount).toBe(0);+ expect(harness.agent.isIdle()).toBe(true);+ // No "checkpointed… will continue in N seconds" / retry notice either.+ expect(delivered('chat-a').join('\n')).not.toMatch(/checkpointed|continue in \d|retry in \d|safely queued/i);+ } finally {+ await harness.dispose();+ }+ }, 20_000);+});diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex 6d176509..796bb5d2 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -398,7 +398,7 @@ export function getTelegramHelp(): string {lines.push('/models — List providers or switch AI model (saved across restarts)');lines.push('/cloud models — List Mercury Cloud models and switch');lines.push('/stream — Toggle text streaming on/off');- lines.push("/stop — Stop this chat's task and its agents now (other chats keep going)");+ lines.push("/stop — Stop this chat's task, its agents and waiting messages now (other chats keep going)");lines.push("/halt — Emergency: stop every chat's task and all agents");lines.push('');diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex bced2192..0003a300 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -80,7 +80,7 @@ export function setCurrentProviderCallback(fn: () => { name: string; model: stricurrentProviderFn = fn;}-let stopFn: ((target?: { channelId?: string; sessionId?: string }) => Promise<string>) | null = null;+let stopFn: ((target?: { channelId?: string; sessionId?: string; keepQueued?: boolean }) => Promise<string>) | null = null;let busyFn: ((sessionId: string) => boolean) | null = null;/** Whether a session has a turn running or queued (undo waits for it). */export function setSessionBusyLookup(fn: ((sessionId: string) => boolean) | null): void {@@ -107,7 +107,7 @@ export function setResearchControls(controls: typeof researchControls): void {* cancel its work entry. Given a thread or session, only that chat's work* stops (other chats keep running, ADR-037); given neither, everything does.*/-export function setStopCallback(fn: (target?: { channelId?: string; sessionId?: string }) => Promise<string>): void {+export function setStopCallback(fn: (target?: { channelId?: string; sessionId?: string; keepQueued?: boolean }) => Promise<string>): void {stopFn = fn;}@@ -381,10 +381,12 @@ chat.put('/api/chat/settings', async (c) => {chat.post('/api/chat/stop', async (c) => {if (!stopFn) return c.json({ error: 'Stop is not available on this runtime' }, 503);try {- const body = await c.req.json<{ threadId?: unknown; sessionId?: unknown }>().catch(() => ({} as { threadId?: unknown; sessionId?: unknown }));+ const body = await c.req.json<{ threadId?: unknown; sessionId?: unknown; keepQueued?: unknown }>().catch(() => ({} as { threadId?: unknown; sessionId?: unknown; keepQueued?: unknown }));const threadId = typeof body.threadId === 'string' && body.threadId ? body.threadId.slice(0, 200) : undefined;const sessionId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId.slice(0, 200) : undefined;- const note = await stopFn(threadId || sessionId ? { channelId: threadId, sessionId } : undefined);+ // keepQueued: stop only the running turn ("do mine first"); by default a+ // stop also drops the chat's waiting messages (ADR-038).+ const note = await stopFn(threadId || sessionId ? { channelId: threadId, sessionId, keepQueued: body.keepQueued === true } : undefined);return c.json({ ok: true, note });} catch (err) {return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdxindex c6a5d91f..098d366d 100644--- a/website/docs/cli-commands/in-chat-commands.mdx+++ b/website/docs/cli-commands/in-chat-commands.mdx@@ -148,7 +148,7 @@ Persistent persona-scoped agents that run outside your conversation — each wit| Command | Description ||---------|-------------|| `/halt` | Emergency: stop every chat's task and all agents |-| `/stop` | Stop this chat's task and the agents it started. When nothing else is running, also release file locks and clear the task board |+| `/stop` | Stop this chat's task, the commands and agents it started, and the messages it had waiting. When nothing else is running, also release file locks and clear the task board || `/reset` | Full reset: stop all + clear conversation context (requires confirmation) |:::tip[Fast-path commands]diff --git a/website/docs/integrations/telegram.mdx b/website/docs/integrations/telegram.mdxindex c705e6b4..1cc9b1ae 100644--- a/website/docs/integrations/telegram.mdx+++ b/website/docs/integrations/telegram.mdx@@ -51,7 +51,7 @@ Mercury registers 15 commands in Telegram's bot menu for quick access:| `/help` | Show Telegram-specific command reference || `/status` | Config, budget, and uptime || `/progress` | Live status for the current task |-| `/stop` | Stop this chat's task and the agents it started (other chats keep going) |+| `/stop` | Stop this chat's task, the agents it started and its waiting messages (other chats keep going) || `/budget` | Token budget status and management || `/stream` | Toggle text streaming on/off || `/memory` | Second brain memory |