Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: treat intentional AI stops as cancellations
[._.]/ Adam Eivya00eab4fb8df
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b9c1ad572b..dd7b53aaf1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -36,6 +36,8 @@## Fixed+- **Stopping a one-shot AI run no longer poisons provider health or repeats the work on a fallback.** PortOS restarts and the Runs UI both terminate an in-flight TUI with a signal. That intentional exit was previously finalized as an ordinary provider failure; worse, the error classifier scanned the whole prompt/screen, so an unrelated story word such as “credit” could relabel the stop as quota exhaustion, bench a healthy provider for an hour, queue an investigation, and begin the same expensive stage on a fallback while the server was already shutting down. External run stops are now tracked explicitly, host shutdown uses the existing process lifecycle latch, and both paths finalize as canceled: the run remains diagnosable in history but skips provider error analysis, failure hooks, fallback tiers, and health penalties. An unexpected PTY signal remains a real failure.+- **iCloud materialization logs now say a download was *requested*, not that the file is local.** `brctl download` returns exit 0 the moment it accepts and queues the request — it does not block until the bytes arrive, and it returns 0 even when the sync layer ultimately can't fetch the file. The on-demand materialize path logged that exit 0 as "materialized from iCloud", so an operator reading these lines during an iCloud outage would conclude a file was readable when it was still dataless. The logs now report the request, and the code comments spell out that the read path (`readStoreAtPathResult`/`readIfMaterialized`) fails closed — rejecting a dataless file rather than reading it — which is the reason the subsequent re-read stays safe and must not be removed. No behavior change.- Preserve a Series Autopilot run's reasoning-effort override when the foundation gate delegates a worldbuilding repair to Universe Builder.diff --git a/server/lib/aiToolkit/CLAUDE.md b/server/lib/aiToolkit/CLAUDE.mdindex 86e3a58a43..e32248d1a6 100644--- a/server/lib/aiToolkit/CLAUDE.md+++ b/server/lib/aiToolkit/CLAUDE.md@@ -13,7 +13,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.-- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.+- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.The worked example for "barrel + documented exports" (see root `CLAUDE.md` → Module Organization) is this directory's `index.js`.diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 50f5698084..0e95e1b250 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -6,6 +6,7 @@*/export const ERROR_CATEGORIES = {+ CANCELED: 'canceled',RATE_LIMIT: 'rate-limit',USAGE_LIMIT: 'usage-limit',AUTH_ERROR: 'auth-error',diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 996af2dd53..c9e65636a3 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -160,6 +160,10 @@ export function createRunnerService(config = {}) {// See server/lib/aiToolkit/CLAUDE.md (override contract).let cliRunnerOverride = null;const externalRuns = new Map();+ // A host runner sees only the child/PTY exit event. Remember when that exit+ // was initiated through stopRun so it can distinguish a user cancellation+ // from an unexpected provider crash and avoid fallback/bench telemetry.+ const externalStopRequests = new Set();async function ensureRunsDir() {if (!existsSync(RUNS_PATH)) {@@ -261,9 +265,20 @@ export function createRunnerService(config = {}) {// Track a host-spawned run's killable handle (ChildProcess or node-pty IPty —// both expose `.kill(signal?)`; AbortController exposes `.abort()`) so// stopRun/isRunActive/deleteRun account for it alongside the toolkit's own.- registerExternalRun(runId, killable) { externalRuns.set(runId, killable); },- unregisterExternalRun(runId) { externalRuns.delete(runId); },+ registerExternalRun(runId, killable) {+ externalStopRequests.delete(runId);+ externalRuns.set(runId, killable);+ },+ unregisterExternalRun(runId) {+ externalRuns.delete(runId);+ externalStopRequests.delete(runId);+ },hasExternalRun(runId) { return externalRuns.has(runId); },+ consumeExternalRunStop(runId) {+ const requested = externalStopRequests.has(runId);+ externalStopRequests.delete(runId);+ return requested;+ },async createRun(options) {const {@@ -833,6 +848,7 @@ export function createRunnerService(config = {}) {// and drop it so a later isRunActive reports false.const external = externalRuns.get(runId);if (external) {+ externalStopRequests.add(runId);if (external.kill && !external.killed) killProcessTree(external);else if (external.abort) external.abort();externalRuns.delete(runId);diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex f9cb3729d9..78b6c963d8 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -329,6 +329,8 @@ describe('AI Toolkit runner — declared extension points', () => {expect(await runner.stopRun('x')).toBe(true);expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ expect(runner.consumeExternalRunStop('x')).toBe(true);+ expect(runner.consumeExternalRunStop('x')).toBe(false);// stopRun drops the entry, so a follow-up reports inactive.expect(await runner.isRunActive('x')).toBe(false);expect(await runner.stopRun('x')).toBe(false);@@ -340,6 +342,16 @@ describe('AI Toolkit runner — declared extension points', () => {runner.registerExternalRun('api-run', controller);expect(await runner.stopRun('api-run')).toBe(true);expect(controller.abort).toHaveBeenCalledTimes(1);+ expect(runner.consumeExternalRunStop('api-run')).toBe(true);+ });++ it('unregisterExternalRun clears a stale explicit-stop marker', async () => {+ const runner = createRunnerService({ dataDir: './data' });+ const child = { kill: vi.fn(), killed: false };+ runner.registerExternalRun('done', child);+ await runner.stopRun('done');+ runner.unregisterExternalRun('done');+ expect(runner.consumeExternalRunStop('done')).toBe(false);});it('deleteRun kills an in-flight external run before removing its dir', async () => {diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex 65f4631eee..b672f83da1 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -607,6 +607,13 @@ export async function runPromptThroughProvider(args) {}}+ // An explicit Stop or host shutdown is a lifecycle outcome, not a failed AI+ // attempt. Do not enter any correction/fallback tier, mark the provider+ // unavailable, or escalate an investigation task.+ if (firstError?.canceled || firstError?.code === 'RUN_CANCELED') {+ throw stripFallbackContext(firstError);+ }+{// Only retry when the failure came from the execution layer (annotated// by safeReject with effectiveProvider) or is a synthetic schema/type@@ -1192,6 +1199,10 @@ async function executeProviderRunOnce({ provider, prompt, source, model, effortconst onComplete = (result) => {if (result?.error || result?.success === false) {const err = new Error(result?.error || `${labelByType[effectiveProvider.type] || effectiveProvider.type} execution failed`);+ if (result?.canceled === true) {+ err.code = 'RUN_CANCELED';+ err.canceled = true;+ }if (result?.errorAnalysis && typeof result.errorAnalysis === 'object') {err.errorAnalysis = result.errorAnalysis;}diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.jsindex ca21bfeb72..0cd6997a77 100644--- a/server/lib/promptRunner.test.js+++ b/server/lib/promptRunner.test.js@@ -753,6 +753,30 @@ describe('promptRunner — retry-with-fallback', () => {return { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider };}+ it('does not retry, bench, or escalate a canceled TUI run', async () => {+ const status = mockToolkitWithFallback();+ const primaryTui = tuiProvider({ id: 'primary-tui', name: 'Primary TUI', defaultModel: 'primary-model' });+ tuiRunner.executeTuiRun.mockImplementation(async ({ onComplete }) => {+ onComplete({+ success: false,+ canceled: true,+ error: 'TUI interrupted by PortOS shutdown (signal 2)',+ });+ });++ await expect(runPromptThroughProvider({+ provider: primaryTui,+ prompt: 'p',+ source: 'test',+ })).rejects.toMatchObject({ code: 'RUN_CANCELED', canceled: true });++ expect(runner.executeApiRun).not.toHaveBeenCalled();+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ expect(autoFixer.noteFallbackStarted).not.toHaveBeenCalled();+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();+ });+it('retries with the configured fallback and resolves with usedFallback flag when primary CLI fails', async () => {const status = mockToolkitWithFallback();diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 6f98d6e01f..ed088c2d24 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -38,8 +38,9 @@ import { join, resolve } from 'path';import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';import { createStreamingAnsiStripper, stripAnsi } from './ansiStrip.js';import { createImmediateFallbackSignalDetector, createTerminalModelErrorDetector } from './aiToolkit/errorDetection.js';-import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, resolveRunCwd } from '../services/runner.js';+import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, consumeRunStopRequested, resolveRunCwd } from '../services/runner.js';import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached } from '../services/shell.js';+import { isHostShuttingDown } from './hostShutdown.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,PASTE_MARKER_POLL_MS,@@ -309,7 +310,7 @@ ${prompt}`;};return new Promise((resolve) => {- const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {+ const finish = async ({ success, exitCode = 0, error = null, reason = 'completed', canceled = false }) => {if (finalized) return;finalized = true;// Tracks whether the normal-path onComplete was reached, so the catch@@ -351,12 +352,18 @@ ${prompt}`;// set post-write and never made it to disk → /runs replay missed it).const metadata = await finalizeRunRecord({runId, output: responseText, exitCode, success, error, startTime,- extras: { completionReason: reason, usedResponseFile, outputTruncated: outputBufferTruncated },+ extras: {+ completionReason: reason,+ usedResponseFile,+ outputTruncated: outputBufferTruncated,+ ...(canceled ? { canceled: true } : {}),+ },}).catch((err) => {console.error(`❌ TUI run ${runId} finalize failed: ${err.message}`);return {exitCode, success, error: error || err.message,duration: Date.now() - startTime, completionReason: reason,+ ...(canceled ? { canceled: true } : {}),};});onCompleteInvoked = true;@@ -387,6 +394,7 @@ ${prompt}`;onComplete?.({runId, success: false, exitCode, error: `finish() failed: ${err?.message || err}`,duration: Date.now() - startTime, completionReason: reason,+ ...(canceled ? { canceled: true } : {}),});} catch (cbErr) {console.error(`❌ TUI run ${runId} onComplete threw during finish() error handling: ${cbErr?.message || cbErr}`);@@ -476,6 +484,13 @@ ${prompt}`;ptyProcess.onExit(({ exitCode, signal }) => {const killed = !!signal;+ // pm2 tree-kills descendants during a PortOS restart, while /runs Stop+ // kills this registered PTY through runner.stopRun. Both are intentional+ // interruptions, not provider failures: never scan the story transcript+ // for a bogus quota marker, bench the provider, or launch a fallback.+ const stopRequested = consumeRunStopRequested(runId);+ const hostInterrupted = killed && isHostShuttingDown();+ const canceled = killed && (stopRequested || hostInterrupted);const finalExitCode = typeof exitCode === 'number' ? exitCode : (killed ? 130 : 0);const success = !killed && finalExitCode === 0;// Always set an explicit error string when finishing as failure. The@@ -486,7 +501,11 @@ ${prompt}`;// captured output so failures are actionable from /runs without// re-running.let error = null;- if (killed) {+ if (hostInterrupted) {+ error = `TUI interrupted by PortOS shutdown (signal ${signal})`;+ } else if (stopRequested) {+ error = `TUI canceled (signal ${signal})`;+ } else if (killed) {error = `TUI killed (signal ${signal})`;} else if (!success) {const tail = outputBuffer.slice(-200).trim();@@ -498,7 +517,8 @@ ${prompt}`;success,exitCode: finalExitCode,error,- reason: killed ? 'killed' : 'exit'+ reason: hostInterrupted ? 'host-shutdown' : (stopRequested ? 'canceled' : (killed ? 'killed' : 'exit')),+ canceled,});});diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 0b1f6c33cc..791f48c459 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -23,6 +23,7 @@ const { ptyInstances, ptySpawnMock, runnerMocks, shellMocks, runsTmpDirRef } = vemitRunStarted: vi.fn(),registerActiveRun: vi.fn(),unregisterActiveRun: vi.fn(),+ consumeRunStopRequested: vi.fn(() => false),getRunsPath: vi.fn(),// Real implementation (and its bad-workspace failure path) is covered by// lib/spawnCwd.test.js + services/runner.test.js; here it just needs to@@ -50,6 +51,7 @@ vi.mock('./fileUtils.js', async () => {});import { cleanTuiResponse, resolveTuiResponseText, executeTuiRun } from './tuiPromptRunner.js';+import { markHostShuttingDown, resetHostShutdownFlagForTests } from './hostShutdown.js';const makeFakePty = () => {const fake = {@@ -270,7 +272,10 @@ describe('executeTuiRun', () => {runnerMocks.emitRunStarted.mockClear();runnerMocks.registerActiveRun.mockClear();runnerMocks.unregisterActiveRun.mockClear();+ runnerMocks.consumeRunStopRequested.mockReset();+ runnerMocks.consumeRunStopRequested.mockReturnValue(false);runnerMocks.getRunsPath.mockClear();+ resetHostShutdownFlagForTests();shellMocks.registerExternalSession.mockClear();shellMocks.unregisterExternalSession.mockClear();shellMocks.isExternalSessionAttached.mockReset();@@ -281,6 +286,7 @@ describe('executeTuiRun', () => {afterEach(async () => {vi.useRealTimers();+ resetHostShutdownFlagForTests();vi.restoreAllMocks();await rm(runsTmpDirRef.current, { recursive: true, force: true }).catch(() => null);});@@ -839,6 +845,42 @@ describe('executeTuiRun', () => {}));});+ it('finalizes an explicit stop as canceled instead of a provider failure', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const onComplete = vi.fn();+ runnerMocks.consumeRunStopRequested.mockReturnValueOnce(true);+ const promise = executeTuiRun({ runId: 'run-stopped', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onComplete, timeout: 60000 });+ await flushAsync();++ ptyInstances[0].emitExit({ exitCode: null, signal: 'SIGTERM' });++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-stopped',+ success: false,+ error: expect.stringContaining('canceled'),+ extras: expect.objectContaining({ completionReason: 'canceled', canceled: true }),+ }));+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ canceled: true }));+ });++ it('finalizes a host-shutdown signal as an interruption instead of a provider failure', async () => {+ const provider = { id: 'codex', type: 'tui', command: 'echo' };+ markHostShuttingDown();+ const promise = executeTuiRun({ runId: 'run-restart', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, timeout: 60000 });+ await flushAsync();++ ptyInstances[0].emitExit({ exitCode: null, signal: 2 });++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-restart',+ success: false,+ error: expect.stringContaining('PortOS shutdown'),+ extras: expect.objectContaining({ completionReason: 'host-shutdown', canceled: true }),+ }));+ });+it('finishes with a tail-bearing error message when the PTY exits non-zero with prior output', async () => {const provider = { id: 'claude', type: 'tui', command: 'echo' };const promise = executeTuiRun({ runId: 'run-nonzero', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });diff --git a/server/services/runner.js b/server/services/runner.jsindex 37a6ada3fc..927d2864fb 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -10,8 +10,9 @@ import { resolveSpawnCwd } from '../lib/spawnCwd.js';import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';-import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';+import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';+import { isHostShuttingDown } from '../lib/hostShutdown.js';import {setAIToolkitInstance,getAIToolkitInstance,@@ -107,8 +108,14 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, errometadata.outputSize = Buffer.byteLength(output);if (error) metadata.error = error;if (extras && typeof extras === 'object') Object.assign(metadata, extras);-- if (!success && toolkit.services.errorDetection) {+ const canceled = metadata.canceled === true;++ if (!success && canceled) {+ // Cancellation is an operator/host lifecycle outcome, not evidence about+ // provider health. Keep it explicit for /runs without scanning story text+ // (which may contain quota-like words) or firing the provider-failure hook.+ metadata.errorCategory = ERROR_CATEGORIES.CANCELED;+ } else if (!success && toolkit.services.errorDetection) {// Exit 124 is the host's authoritative wall-clock timeout. Do not scan the// model's entire TUI screen/prompt for a competing category in that case:// story text can legitimately contain words such as "credit" or@@ -132,7 +139,7 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro// already persisted by this point, so a failing hook must not un-finalize it.if (success) {safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), 'onRunCompleted');- } else {+ } else if (!canceled) {safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), 'onRunFailed');}@@ -330,7 +337,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// exactly once. The finalizer always merges into createRun's metadata instead// of replacing attribution fields on the spawn-error path.let finalizationPromise = null;- const finalizeTerminal = async ({ exitCode, spawnError = null }) => {+ const finalizeTerminal = async ({ exitCode, signal = null, spawnError = null }) => {const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');let metadata = {};try {@@ -351,6 +358,13 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// workspace the run never used is the confusion this fixes (#3180).metadata.workspacePath ??= effectiveCwd;+ // Consume before unregistering: unregisterExternalRun deliberately clears+ // stale markers, while this close event is the one place that can turn the+ // marker into a canceled terminal outcome.+ const stopRequested = toolkit.services.runner.consumeExternalRunStop?.(runId) === true;+ const hostInterrupted = !!signal && isHostShuttingDown();+ const canceled = !spawnError && !immediateFallbackAnalysis && (stopRequested || hostInterrupted);+try {if (timeoutHandle) clearTimeout(timeoutHandle);toolkit.services.runner.unregisterExternalRun(runId);@@ -362,12 +376,19 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onmetadata.endTime = new Date().toISOString();metadata.duration = Date.now() - startTime;metadata.exitCode = exitCode;- metadata.success = spawnError ? false : exitCode === 0 && !immediateFallbackAnalysis;+ metadata.success = spawnError ? false : exitCode === 0 && !immediateFallbackAnalysis && !canceled;metadata.outputSize = Buffer.byteLength(output);if (spawnError) {metadata.error = `Spawn failed: ${spawnError.message}`;metadata.errorCategory = 'spawn_error';+ } else if (canceled) {+ metadata.canceled = true;+ metadata.completionReason = hostInterrupted ? 'host-shutdown' : 'canceled';+ metadata.error = hostInterrupted+ ? `CLI interrupted by PortOS shutdown${signal ? ` (signal ${signal})` : ''}`+ : `CLI canceled${signal ? ` (signal ${signal})` : ''}`;+ metadata.errorCategory = ERROR_CATEGORIES.CANCELED;} else if (!metadata.success && toolkit.services.errorDetection) {// A mid-stream fallback signal (e.g. usage-limit hit) SIGTERM-kills the// child; even an exit 0 must remain a failure so fallback can run.@@ -383,7 +404,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// the terminal result or prevents the caller from settling.if (metadata.success) {safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);- } else {+ } else if (!canceled) {safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);}safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);@@ -400,8 +421,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onerror: `Run finalization failed: ${err.message}`,errorCategory: 'finalization_error',outputSize: Buffer.byteLength(output),+ ...(canceled ? { canceled: true, completionReason: hostInterrupted ? 'host-shutdown' : 'canceled' } : {}),};- safeSettle(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);+ if (!canceled) {+ safeSettle(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);+ }safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);return failMetadata;}@@ -415,8 +439,8 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onvoid finalizeOnce({ exitCode: -1, spawnError: err });});- childProcess.on('close', (code) => {- void finalizeOnce({ exitCode: code });+ childProcess.on('close', (code, signal) => {+ void finalizeOnce({ exitCode: code, signal });});return runId;@@ -443,6 +467,15 @@ export function unregisterActiveRun(runId) {getAIToolkitInstance()?.services?.runner?.unregisterExternalRun?.(runId);}+/**+ * Consume the toolkit's one-shot marker that says stopRun initiated this+ * external child/PTY exit. The TUI runner reads it inside onExit before its+ * normal cleanup unregisters the run.+ */+export function consumeRunStopRequested(runId) {+ return getAIToolkitInstance()?.services?.runner?.consumeExternalRunStop?.(runId) === true;+}+export async function stopRun(runId) {// The toolkit's stopRun now consults the external-run registry first (it kills// the registered child/pty before falling back to its own activeRuns map), sodiff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 721b35db0f..d2d4742a39 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -64,12 +64,32 @@ const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedMod// private `_portosActiveRuns` map.function fakeToolkit(errorDetection = null) {const externalRuns = new Map();+ const externalStopRequests = new Set();return {services: {runner: {- registerExternalRun: (runId, killable) => externalRuns.set(runId, killable),- unregisterExternalRun: (runId) => externalRuns.delete(runId),+ registerExternalRun: (runId, killable) => {+ externalStopRequests.delete(runId);+ externalRuns.set(runId, killable);+ },+ unregisterExternalRun: (runId) => {+ externalRuns.delete(runId);+ externalStopRequests.delete(runId);+ },hasExternalRun: (runId) => externalRuns.has(runId),+ consumeExternalRunStop: (runId) => {+ const requested = externalStopRequests.has(runId);+ externalStopRequests.delete(runId);+ return requested;+ },+ stopRun: async (runId) => {+ const child = externalRuns.get(runId);+ if (!child) return false;+ externalStopRequests.add(runId);+ child.kill('SIGTERM');+ externalRuns.delete(runId);+ return true;+ },_externalRuns: externalRuns,},errorDetection,@@ -115,6 +135,76 @@ describe('finalizeRunRecord — authoritative timeout classification', () => {errorAnalysis: expect.objectContaining({ category: ERROR_CATEGORIES.TIMEOUT }),});});++ it('records cancellation without scanning output or firing the provider-failure hook', async () => {+ const errorDetection = { analyzeError: vi.fn() };+ const onRunFailed = vi.fn();+ setAIToolkit(fakeToolkit(errorDetection), {+ dataDir: '/tmp/test-runner',+ hooks: { onRunFailed },+ });++ const metadata = await finalizeRunRecord({+ runId: 'run-canceled-story',+ output: 'A character debates billing, payment, and insufficient credit.',+ exitCode: 130,+ success: false,+ error: 'TUI canceled (signal SIGTERM)',+ startTime: Date.now(),+ extras: { canceled: true, completionReason: 'canceled' },+ });++ expect(metadata).toMatchObject({+ success: false,+ canceled: true,+ errorCategory: ERROR_CATEGORIES.CANCELED,+ });+ expect(errorDetection.analyzeError).not.toHaveBeenCalled();+ expect(onRunFailed).not.toHaveBeenCalled();+ });+});++describe('executeCliRun — intentional cancellation', () => {+ it('skips output classification and provider-failure hooks after stopRun', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const errorDetection = { analyzeError: vi.fn() };+ const onRunFailed = vi.fn();+ const toolkit = fakeToolkit(errorDetection);+ setAIToolkit(toolkit, {+ dataDir: '/tmp/test-runner',+ hooks: { onRunFailed },+ });+ const onComplete = vi.fn();+ const provider = {+ id: 'codex',+ name: 'Codex',+ command: 'codex',+ args: [],+ defaultModel: 'gpt-test',+ timeout: 5000,+ };++ await executeCliRun({+ runId: 'run-cli-canceled',+ provider,+ prompt: 'A story about billing and credit.',+ workspacePath: TEST_WORKSPACE,+ onComplete,+ });+ await toolkit.services.runner.stopRun('run-cli-canceled');+ child.emit('close', null, 'SIGTERM');+ await flushMicrotasks();++ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({+ success: false,+ canceled: true,+ completionReason: 'canceled',+ errorCategory: ERROR_CATEGORIES.CANCELED,+ }));+ expect(errorDetection.analyzeError).not.toHaveBeenCalled();+ expect(onRunFailed).not.toHaveBeenCalled();+ });});describe('executeCliRun — Codex sentinel suppression', () => {