Skip to content

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

classify a stopped API run as canceled, not an unknown provider failure

[._.]/ Adam Eivy856df0372fd1
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index d5851f13e3..931d938b54 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -26,7 +26,7 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy
**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. `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. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. 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. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. **`executeApiRun` keeps its own equivalent marker internally**, because its killable is an `AbortController` whose reason-less `abort()` reaches the finalizer as Node's bare `AbortError: This operation was aborted` — a message no pattern matches, so every Stop of an API run finalized as an UNKNOWN provider failure, fired `onRunFailed`, and was escalated to a tier-4 investigation task. It now writes the same `canceled` / `completionReason` terminal shape the CLI path does and fires no failure hook; the wall-clock timeout still outranks it, since the timer's own abort is what ended that run. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.
- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.
- 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.
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 2859285fef..996aa89bad 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -188,6 +188,20 @@ export function createRunnerService(config = {}) {
// 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();
+ // The same one-shot marker for the toolkit's OWN in-flight runs (`activeRuns`
+ // — an API fetch's AbortController). `controller.abort()` with no reason
+ // surfaces to the reader as Node's bare `AbortError: This operation was
+ // aborted`, which no error pattern matches and which is indistinguishable
+ // from a provider transport fault. Without this marker every Stop of an API
+ // run finalized as an UNKNOWN provider failure, fired `onRunFailed`, and was
+ // escalated to a tier-4 investigation task — a post-mortem over a human
+ // pressing Stop. CLI/TUI runs already avoid that via `externalStopRequests`.
+ const activeStopRequests = new Set();
+ const consumeActiveStop = (runId) => {
+ const requested = activeStopRequests.has(runId);
+ activeStopRequests.delete(runId);
+ return requested;
+ };
async function ensureRunsDir() {
if (!existsSync(RUNS_PATH)) {
@@ -596,6 +610,10 @@ export function createRunnerService(config = {}) {
}
const controller = new AbortController();
+ // Clear any stale marker a previous run of this id left behind, matching
+ // registerExternalRun's contract — a stop only ever describes the run
+ // that was in flight when it was requested.
+ activeStopRequests.delete(runId);
activeRuns.set(runId, controller);
// Wall-clock timeout with a single-settlement gate. Without a ceiling a
@@ -620,9 +638,38 @@ export function createRunnerService(config = {}) {
}
return true;
};
+ // A Stop is a lifecycle outcome, not a failed AI attempt. Finalize it as
+ // ERROR_CATEGORIES.CANCELED and fire NO `onRunFailed` hook, so the host
+ // neither benches the provider nor escalates a tier-4 investigation task
+ // over a human pressing Stop. This writes the same terminal shape the
+ // CLI/TUI path already does (`canceled` + `completionReason`), which is
+ // what promptRunner reads to stamp `code: 'RUN_CANCELED'` on its
+ // rejection so `isRunCanceledError` callers skip the fallback cascade.
+ // Every persistence step is best-effort: `onComplete` must settle the
+ // caller even if a write fails, or a canceled run hangs its awaiter.
+ const finalizeCanceled = async () => {
+ activeRuns.delete(runId);
+ if (output) await atomicWrite(outputPath, output).catch(() => {});
+ const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.success = false;
+ metadata.canceled = true;
+ metadata.completionReason = 'canceled';
+ metadata.error = 'API run canceled';
+ metadata.errorCategory = ERROR_CATEGORIES.CANCELED;
+ metadata.outputSize = Buffer.byteLength(output);
+ await atomicWrite(metadataPath, metadata).catch((err) => {
+ console.error(`❌ API run ${runId} cancel finalize error: ${err.message}`);
+ });
+ safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);
+ };
const finalizeTimeout = async () => {
if (!markSettled()) return;
activeRuns.delete(runId);
+ // The timer's own abort caused this, so TIMEOUT stays authoritative
+ // even if a Stop raced it — just drop the marker so it can't leak.
+ consumeActiveStop(runId);
const error = `API execution timed out after ${effectiveTimeout}ms`;
try {
if (output) await atomicWrite(outputPath, output).catch(() => {});
@@ -729,6 +776,14 @@ export function createRunnerService(config = {}) {
// a rejected fetch, or the read above was aborted) — if so it has
// finalized as a TIMEOUT; don't double-complete or reclassify.
if (!markSettled()) return runId;
+
+ // A Stop that lands before the response headers arrives here as the
+ // fetch's AbortError, not as a provider status.
+ if (consumeActiveStop(runId)) {
+ await finalizeCanceled();
+ return runId;
+ }
+
activeRuns.delete(runId);
const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
metadata.endTime = new Date().toISOString();
@@ -810,6 +865,9 @@ export function createRunnerService(config = {}) {
// disk, rename failure) — otherwise the caller would hang forever.
if (!markSettled()) return;
activeRuns.delete(runId);
+ // A Stop that lost the race to the last chunk leaves a marker no
+ // failure path will consume; drop it so it can't outlive the run.
+ consumeActiveStop(runId);
try {
await atomicWrite(outputPath, output);
@@ -857,6 +915,15 @@ export function createRunnerService(config = {}) {
// If the timeout won the race (this catch is the aborted reader
// rejecting), it already finalized as a TIMEOUT — bail out.
if (!markSettled()) return;
+
+ // A Stop mid-stream rejects the reader with Node's bare
+ // `AbortError: This operation was aborted` — no pattern matches it,
+ // so without this check it is classified UNKNOWN and escalated.
+ if (consumeActiveStop(runId)) {
+ await finalizeCanceled();
+ return;
+ }
+
activeRuns.delete(runId);
if (output) {
@@ -925,6 +992,13 @@ export function createRunnerService(config = {}) {
if (active.kill) {
killProcessTree(active);
} else if (active.abort) {
+ // Mark BEFORE aborting: the abort rejects the in-flight reader
+ // synchronously enough that the finalizer can already be running by
+ // the time this returns, and it must see an intentional stop. Only the
+ // AbortController (API) branch marks — the built-in CLI executor's
+ // exit-code classification is unchanged by this, so a marker there
+ // would never be consumed.
+ activeStopRequests.add(runId);
active.abort();
}
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 83574eb3c1..7c4802d0db 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -668,6 +668,192 @@ describe('AI Toolkit runner service', () => {
expect(await runner.isRunActive('run-hung-setup')).toBe(false);
expect(metadata).toMatchObject({ success: false, errorCategory: 'timeout' });
});
+
+ // A Stop of an API run reaches the finalizer as Node's bare
+ // `AbortError: This operation was aborted` — a string no error pattern
+ // matches. Classified as UNKNOWN it fired the host's failure hook, which
+ // escalates to a tier-4 investigation task: a post-mortem over a human
+ // pressing Stop. CLI/TUI runs already finalize a Stop as `canceled`.
+ it('finalizes a mid-stream Stop as canceled, without firing the failure hook', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+
+ const fetch = vi.fn(async (_url, opts) => {
+ const { signal } = opts;
+ return {
+ ok: true,
+ body: {
+ getReader: () => ({
+ read: () => new Promise((_resolve, reject) => {
+ // Reject with the signal's own reason, exactly as undici does —
+ // for a reason-less `abort()` that is Node's DOMException whose
+ // message is "This operation was aborted".
+ const fail = () => reject(signal.reason);
+ if (signal.aborted) return fail();
+ signal.addEventListener('abort', fail, { once: true });
+ }),
+ cancel: async () => {}
+ })
+ }
+ };
+ });
+ vi.stubGlobal('fetch', fetch);
+
+ const onRunFailed = vi.fn();
+ const runner = createRunnerService({
+ dataDir,
+ hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed }
+ });
+
+ let done;
+ const completed = new Promise((resolve) => { done = resolve; });
+ await runner.executeApiRun({
+ runId: 'run-stopped',
+ provider: runReady(),
+ model: null,
+ prompt: 'hi',
+ workspacePath: process.cwd(),
+ screenshots: [],
+ // Far beyond the test's lifetime, so a timeout can't be what finalizes it.
+ timeout: 600_000,
+ onData: undefined,
+ onComplete: (m) => done(m)
+ });
+
+ expect(await runner.stopRun('run-stopped')).toBe(true);
+
+ const metadata = await completed;
+ expect(metadata).toMatchObject({
+ success: false,
+ canceled: true,
+ completionReason: 'canceled',
+ errorCategory: 'canceled',
+ });
+ // A cancellation is evidence about the operator, not the provider: no
+ // failure hook, so nothing benches the provider or escalates a task.
+ expect(onRunFailed).not.toHaveBeenCalled();
+ expect(await runner.isRunActive('run-stopped')).toBe(false);
+ // Persisted too — /runs replays the record, not the in-memory result.
+ const persisted = JSON.parse(await readFile(join(dataDir, 'runs', 'run-stopped', 'metadata.json'), 'utf-8'));
+ expect(persisted).toMatchObject({ canceled: true, errorCategory: 'canceled' });
+ });
+
+ it('finalizes a Stop that lands before the response headers as canceled', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+
+ // The provider never sends headers, so the abort rejects `fetch` itself and
+ // the run finalizes through the non-OK branch rather than the stream reader.
+ const fetch = vi.fn((_url, opts) => new Promise((_resolve, reject) => {
+ const { signal } = opts;
+ const fail = () => reject(signal.reason);
+ if (signal.aborted) return fail();
+ signal.addEventListener('abort', fail, { once: true });
+ }));
+ vi.stubGlobal('fetch', fetch);
+
+ const onRunFailed = vi.fn();
+ const runner = createRunnerService({
+ dataDir,
+ hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed }
+ });
+
+ let done;
+ const completed = new Promise((resolve) => { done = resolve; });
+ // `fetch` never settles until the stop, so `executeApiRun` does not return
+ // on its own — the run is registered synchronously before the first await.
+ runner.executeApiRun({
+ runId: 'run-stopped-early',
+ provider: runReady(),
+ model: null,
+ prompt: 'hi',
+ workspacePath: process.cwd(),
+ screenshots: [],
+ timeout: 600_000,
+ onData: undefined,
+ onComplete: (m) => done(m)
+ }).catch(() => {});
+
+ // Let the readiness hook resolve so the run is parked inside `fetch`.
+ await Promise.resolve();
+ expect(await runner.stopRun('run-stopped-early')).toBe(true);
+
+ const metadata = await completed;
+ expect(metadata).toMatchObject({
+ success: false,
+ canceled: true,
+ errorCategory: 'canceled',
+ });
+ expect(onRunFailed).not.toHaveBeenCalled();
+ expect(await runner.isRunActive('run-stopped-early')).toBe(false);
+ });
+
+ // The stop marker is one-shot and describes only the run that was in flight
+ // when Stop was pressed. A Stop that loses the race to the last chunk (it
+ // lands while the final `read()` is still awaited, so the run is registered
+ // but the success path has not released it yet) must neither retro-cancel
+ // the answer that was delivered nor leak into a later run of the same id.
+ it('drops a stop marker that lost the race to the final chunk', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+
+ let runner;
+ let stopDuringFinalRead = true;
+ const frame = (text) => new TextEncoder()
+ .encode(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n`);
+ vi.stubGlobal('fetch', vi.fn(async () => {
+ let sent = false;
+ return {
+ ok: true,
+ body: {
+ getReader: () => ({
+ read: async () => {
+ if (sent) {
+ // Stop lands inside the await boundary that precedes the
+ // success finalizer, while `activeRuns` still holds the run.
+ if (stopDuringFinalRead) {
+ stopDuringFinalRead = false;
+ expect(await runner.stopRun('run-reused')).toBe(true);
+ }
+ return { done: true };
+ }
+ sent = true;
+ return { done: false, value: frame('answer') };
+ },
+ cancel: async () => {}
+ })
+ }
+ };
+ }));
+
+ const onRunFailed = vi.fn();
+ runner = createRunnerService({
+ dataDir,
+ hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed }
+ });
+
+ const runOnce = async () => {
+ let done;
+ const completed = new Promise((resolve) => { done = resolve; });
+ await runner.executeApiRun({
+ runId: 'run-reused', provider: runReady(), model: null, prompt: 'hi',
+ workspacePath: process.cwd(), screenshots: [], timeout: 600_000,
+ onData: undefined, onComplete: (m) => done(m)
+ });
+ return completed;
+ };
+
+ // The chunk was already delivered, so the run is a success despite the Stop.
+ const first = await runOnce();
+ expect(first).toMatchObject({ success: true });
+ expect(first.canceled).toBeUndefined();
+
+ // The stale marker must not make the next run of this id report canceled.
+ const second = await runOnce();
+ expect(second).toMatchObject({ success: true });
+ expect(second.canceled).toBeUndefined();
+ expect(onRunFailed).not.toHaveBeenCalled();
+ });
});
describe('AI Toolkit runner — declared extension points', () => {