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

refactor: replace aiToolkit runner monkey-patching with declared extension points (#1834)

[._.]/ Adam Eivyb463a92aea86
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7d63ef059a..c75a9c7669 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,7 @@
## Internal
+- **Replaced aiToolkit runner monkey-patching with declared extension points** — `server/index.js` previously reached into the toolkit runner's private surface, overwriting `executeCliRun`/`executeTuiRun` and re-wrapping `stopRun`/`isRunActive`/`deleteRun` to consult an ad-hoc `_portosActiveRuns` map, plus inlining a 34-line update-marker IIFE in bootstrap. The toolkit runner (`server/lib/aiToolkit/runner.js`) now exposes `setCliRunner()`/`setTuiRunner()` and an external-run registry (`registerExternalRun`/`unregisterExternalRun`/`hasExternalRun`) that its own `stopRun`/`isRunActive`/`deleteRun` consult first — so the host registers its CLI/TUI runners through a documented contract instead of mutating private props, and adding a new lifecycle method no longer requires a matching monkey-patch. `server/services/runner.js` tracks its child processes via the registry, and the update-marker read/validate/record/cleanup lifecycle moved into a unit-tested `processUpdateMarker()` in `server/services/updateChecker.js`. Behavior-preserving; the aiToolkit override contract (`server/lib/aiToolkit/CLAUDE.md`) is updated to match. (#1834)
- **Decomposed two remaining large files: `server/routes/meatspace.js` + `server/services/videoGen/local.js`** — the 1,069-line `meatspace.js` router (14 health sub-domains, each backed by its own service import) is split one concern per file (`meatspaceCoreRoutes.js` overview/config/birth-date/death-clock/LEV, `meatspaceAlcoholRoutes.js`, `meatspaceNicotineRoutes.js`, `meatspaceHealthRoutes.js` blood/body/BP/workouts/epigenetic/eyes, `meatspacePostRoutes.js` POST drills + training + memory builder, `meatspaceCalendarRoutes.js` life calendar/activities/events, `meatspaceExportRoutes.js` MortalLoom export), assembled by a thin `meatspace.js` barrel that mounts each under `/api/meatspace` — the same pattern `routes/cos.js`/`routes/brain.js` use; the split is wiring-only (the 70-route surface is byte-identical, verified). The 1,805-line `videoGen/local.js` had its BYOV runtime management (venv/helper-script path constants, `BYOV_RUNTIME_INFO`, install/ready/fingerprint probes) extracted to `videoGen/runtimes.js` and its render-history I/O (`loadHistory`/`saveHistory`) to `videoGen/history.js`; `local.js` keeps generation + post-processing and re-exports the extracted surface so every existing deep import (`from '../videoGen/local.js'`) keeps resolving unchanged (all 30 prior exports preserved, verified). (#1833)
- **Decomposed `server/routes/brain.js` (1,149-line router covering 13 sub-domains)** — the monolithic Brain router that mixed capture/inbox, four entity CRUD collections + memories, digest/review, settings/summary, links + buckets, graph, federation sync, and the daily log is now split one concern per file (`brainCapture.js`, `brainCrud.js`, `brainDigest.js`, `brainSettings.js`, `brainLinks.js`, `brainGraph.js`, `brainSync.js`, `brainDailyLog.js`), assembled by a thin `brain.js` barrel that mounts each sub-router under `/api/brain` — the same pattern `routes/cos.js` already uses. The split is wiring-only: route paths, ordering (literal-before-`:id` routes stay within their owning sub-router), validation, and the barrel's default export are unchanged, so `server/index.js` and the existing `brain.test.js` (105 tests) pass without edits. (#1832)
- **Split `server/lib/validation.js` (1,897-line multi-domain Zod barrel)** — the catch-all schema file that mixed 15+ unrelated domains is decomposed (continuing the #1151 `peerSyncValidation.js`/`creativeDirectorValidation.js` precedent) into four per-domain files: `agentValidation.js` (social-bot agent personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads, CoS Feature Agents), `cosValidation.js` (CoS tasks/jobs/loops/learning, the Review-Loop reviewer vocabulary + `normalizeReviewers`/`buildReviewWithArgs`, the Code-Review settings slice, and the task-metadata sanitizer), `mediaValidation.js` (LoRA training, local-LLM/Ollama/LM Studio management, CyberCity snapshots, media-collection bulk ops), and `pipelineValidation.js` (Writers Room, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). `validation.js` (~550 lines) keeps the app/process/provider, social-account, GitHub, backup/sharing, and document/legacy-export core plus the `validateRequest`/`validate`/`parsePagination` helpers, and re-exports the four new files (flat) so every existing deep `import { x } from '../lib/validation.js'` callsite keeps working unchanged; the barrel surfaces each as a namespace export. The new domain files import only `zodCompat.js` + leaf constant modules (never back through `validation.js`), keeping the transitional re-export cycle-safe under ESM. (#1831)
diff --git a/server/index.js b/server/index.js
index b14a746add..5a89ee7a2f 100644
--- a/server/index.js
+++ b/server/index.js
@@ -5,7 +5,6 @@ import { dirname, join } from 'path';
import { PATHS } from './lib/fileUtils.js';
import { PORTS } from './lib/ports.js';
import { existsSync } from 'fs';
-import { readFile, unlink } from 'fs/promises';
import { createTailscaleServers } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
import { getSelfHost } from './lib/peerSelfHost.js';
@@ -166,7 +165,7 @@ import * as telegramBridge from './services/telegramBridge.js';
import { getSettings as getInitSettings } from './services/settings.js';
import { setUserCatalogTypes } from './lib/catalogTypes.js';
import { readUserTypes as readUserTypeSlice } from './services/catalogUserTypes/store.js';
-import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';
+import { startUpdateScheduler, clearStaleUpdateInProgress, processUpdateMarker } from './services/updateChecker.js';
import { captureBootCommit } from './services/installState.js';
import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
@@ -343,51 +342,21 @@ if (activeLocalLlmBackend === 'ollama') {
console.error(`⚠️ Failed to start Ollama for active local LLM backend: ${err.message}`));
}
-// Swap the toolkit's generic executeCliRun for PortOS's variant that adds
-// CLI-provider-specific args building (Codex `exec -`, Antigravity `agy --print`,
-// Claude Code `-p -`). The toolkit's in-tree implementation is also safe
-// (no shell, prompt via stdin) — the PortOS variant exists for the per-CLI
-// invocation conventions, not for security.
+// Register PortOS's CLI + TUI runners through the toolkit's declared extension
+// points (setCliRunner / setTuiRunner) instead of overwriting private props.
+// The CLI variant adds per-provider argv building (Codex `exec -`, Antigravity
+// `agy --print`, Claude Code `-p -`); the toolkit's in-tree implementation is
+// also safe (no shell, prompt via stdin) — the variant exists for the per-CLI
+// invocation conventions, not for security. The TUI runner has no toolkit
+// built-in: registering it lets POST /api/runs with a TUI provider dispatch
+// here instead of 400ing. Both runners track their child process / pty via the
+// toolkit's external-run registry, so the toolkit's own stopRun/isRunActive/
+// deleteRun account for live runs without any sibling-method monkey-patching.
import { executeCliRun as executeCliRunFixed } from './services/runner.js';
import { executeTuiRun as executeTuiRunFixed } from './lib/tuiPromptRunner.js';
-aiToolkit.services.runner.executeCliRun = executeCliRunFixed;
-// Attach the TUI executor so POST /api/runs with a TUI provider dispatches
-// here instead of erroring. The toolkit's runs router checks for
-// `runnerService.executeTuiRun` and 400s otherwise — without this patch,
-// runs UI would be unable to start TUI runs even though the staged-LLM path
-// (promptRunner.js) already routes TUI internally.
-aiToolkit.services.runner.executeTuiRun = executeTuiRunFixed;
-// Also patch stopRun + isRunActive so they consult `_portosActiveRuns`
-// (where the PortOS CLI variant tracks child processes), not just the
-// toolkit's internal `activeRuns` map. Without this, the runs router
-// would report live CLI runs as inactive and refuse to stop them.
-const originalStopRun = aiToolkit.services.runner.stopRun.bind(aiToolkit.services.runner);
-aiToolkit.services.runner.stopRun = async (runId) => {
- const portosActive = aiToolkit.services.runner._portosActiveRuns?.get(runId);
- if (portosActive) {
- if (portosActive.kill) portosActive.kill('SIGTERM');
- aiToolkit.services.runner._portosActiveRuns.delete(runId);
- return true;
- }
- return originalStopRun(runId);
-};
-const originalIsRunActive = aiToolkit.services.runner.isRunActive.bind(aiToolkit.services.runner);
-aiToolkit.services.runner.isRunActive = (runId) => {
- if (aiToolkit.services.runner._portosActiveRuns?.has(runId)) return true;
- return originalIsRunActive(runId);
-};
-// Patch deleteRun so that deleting an in-flight PortOS CLI run also kills the
-// child process before removing the on-disk directory. Without this patch,
-// deleteRun only checks the toolkit's internal `activeRuns` map (which is
-// empty for PortOS CLI runs) and silently leaves a zombie child process running.
-const originalDeleteRun = aiToolkit.services.runner.deleteRun.bind(aiToolkit.services.runner);
-aiToolkit.services.runner.deleteRun = async function (runId, ...args) {
- if (this._portosActiveRuns?.has?.(runId)) {
- await this.stopRun(runId);
- }
- return originalDeleteRun.call(this, runId, ...args);
-};
-console.log('🔧 Patched aiToolkit runner.executeCliRun + stopRun + isRunActive + deleteRun with PortOS CLI variants');
+aiToolkit.services.runner.setCliRunner(executeCliRunFixed);
+aiToolkit.services.runner.setTuiRunner(executeTuiRunFixed);
+console.log('🔧 Registered PortOS CLI + TUI runners via aiToolkit runner extension points');
// Note: prompts service is initialized automatically by createAIToolkit()
@@ -635,46 +604,9 @@ getVoiceConfig().then(reconcileVoice).catch(err => console.error(`❌ Voice reco
// Re-arm any voice timers that survived a restart (independent of voice.enabled —
// a pending reminder should still fire even if voice is currently off).
initVoiceTimers().catch(err => console.error(`❌ Voice timer init failed: ${err.message}`));
-// Check for update completion marker from a previous update cycle
-const updateMarkerPath = join(PATHS.data, 'update-complete.json');
-const removeMarker = () => unlink(updateMarkerPath).catch(e => {
- if (e?.code !== 'ENOENT') console.error(`❌ Failed to remove update marker: ${e.message}`);
-});
-
-(async () => {
- let raw;
- try { raw = await readFile(updateMarkerPath, 'utf-8'); }
- catch (err) {
- if (err?.code === 'ENOENT') return; // No marker = no recent update
- console.error(`❌ Failed to read update marker: ${err?.message ?? err}`);
- return removeMarker();
- }
-
- let marker;
- try { marker = JSON.parse(raw); }
- catch (err) {
- console.error(`❌ Corrupted update marker (invalid JSON): ${err?.message ?? err}`);
- return removeMarker();
- }
-
- if (!marker.version || !marker.completedAt) {
- console.error(`❌ Update marker missing required fields (version: ${marker.version}, completedAt: ${marker.completedAt})`);
- return removeMarker();
- }
-
- const runningVersion = await getCurrentVersion();
- if (marker.version !== runningVersion) {
- console.error(`❌ Update marker version (${marker.version}) doesn't match running version (${runningVersion}) — recording as failed`);
- await recordUpdateResult({ version: marker.version, success: false, completedAt: marker.completedAt, log: `Version mismatch: expected ${marker.version}, running ${runningVersion}` })
- .catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
- return removeMarker();
- }
-
- console.log(`✅ Update to v${marker.version} completed at ${marker.completedAt}`);
- await recordUpdateResult({ version: marker.version, success: true, completedAt: marker.completedAt, log: '' })
- .catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
- return removeMarker();
-})().catch(err => console.error(`❌ Update marker processing failed: ${err.message}`));
+// Check for update completion marker from a previous update cycle. The full
+// read/validate/record/cleanup lifecycle lives in updateChecker.js.
+processUpdateMarker().catch(err => console.error(`❌ Update marker processing failed: ${err.message}`));
// Clear stale updateInProgress if the server was killed mid-update
clearStaleUpdateInProgress().catch(err => console.error(`❌ Stale update recovery failed: ${err.message}`));
diff --git a/server/lib/aiToolkit/CLAUDE.md b/server/lib/aiToolkit/CLAUDE.md
index 161e483f00..86e3a58a43 100644
--- a/server/lib/aiToolkit/CLAUDE.md
+++ b/server/lib/aiToolkit/CLAUDE.md
@@ -10,9 +10,10 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous
- When adding new provider fields (e.g., `fallbackProvider`, `lightModel`), update `createProvider()` in `providers.js`
- `updateProvider()` uses spread so existing providers preserve custom fields, but `createProvider()` has an explicit field list
-**Override consistency.** PortOS replaces `aiToolkit.services.runner.executeCliRun` in `server/index.js` with a stdin-based variant that knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`). Two patches follow from this:
+**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:
-- The PortOS variant tracks live child processes in `_portosActiveRuns`, not the toolkit's internal `activeRuns`. **Every sibling method that reads or writes the runner's process map must be patched together** — `stopRun` and `isRunActive` are already overridden alongside `executeCliRun`; if you add a new method (e.g. `pauseRun`, `getActiveRunCount`), add a matching override or the runs router will report inconsistent state.
+- `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.
- 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/routes/runs.js b/server/lib/aiToolkit/routes/runs.js
index 75e3745883..326ef5e675 100644
--- a/server/lib/aiToolkit/routes/runs.js
+++ b/server/lib/aiToolkit/routes/runs.js
@@ -128,7 +128,7 @@ export function createRunsRoutes(runnerService, options = {}) {
status: 400,
context: {
details: provider.type === 'tui'
- ? 'TUI executor not attached to runner — check that executeTuiRun is patched in index.js'
+ ? 'TUI executor not attached to runner — check that setTuiRunner() was called in index.js'
: `Known types: cli, api, tui (received: ${provider.type})`,
},
});
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index ff9c7765f5..b715a550a0 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -37,6 +37,17 @@ export function createRunnerService(config = {}) {
const RUNS_PATH = join(dataDir, runsDir);
const activeRuns = new Map();
+ // ── Declared extension points ────────────────────────────────────────────
+ // PortOS supplies a CLI runner that knows per-CLI argv conventions (Codex
+ // `exec -`, Antigravity `agy --print`, Claude Code `-p -`) and a TUI runner
+ // the toolkit has no built-in for. Rather than reaching into private props
+ // from server/index.js, the host registers them via setCliRunner/setTuiRunner.
+ // Externally-spawned runs (the host owns their child process / pty) are tracked
+ // in `externalRuns` so the toolkit's stopRun/isRunActive/deleteRun see them.
+ // See server/lib/aiToolkit/CLAUDE.md (override contract).
+ let cliRunnerOverride = null;
+ const externalRuns = new Map();
+
async function ensureRunsDir() {
if (!existsSync(RUNS_PATH)) {
await mkdir(RUNS_PATH, { recursive: true });
@@ -99,7 +110,34 @@ export function createRunnerService(config = {}) {
}
}
- return {
+ const service = {
+ // ── Extension-point setters / external-run registry ──────────────────
+ // Register a host CLI runner. Pass `null` to revert to the toolkit's
+ // built-in executeCliRun. The override receives the same args the built-in
+ // would and must return the runId.
+ setCliRunner(fn) {
+ if (fn != null && typeof fn !== 'function') {
+ throw new Error('setCliRunner expects a function or null');
+ }
+ cliRunnerOverride = fn;
+ },
+ // Register a host TUI runner. The toolkit has no built-in TUI executor, so
+ // the runs router gates on `typeof runnerService.executeTuiRun === 'function'`.
+ // Attaching/detaching the method keeps that gate honest.
+ setTuiRunner(fn) {
+ if (fn != null && typeof fn !== 'function') {
+ throw new Error('setTuiRunner expects a function or null');
+ }
+ if (fn) service.executeTuiRun = fn;
+ else delete service.executeTuiRun;
+ },
+ // 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); },
+ hasExternalRun(runId) { return externalRuns.has(runId); },
+
async createRun(options) {
const {
providerId,
@@ -218,7 +256,12 @@ export function createRunnerService(config = {}) {
return { runId, runDir, provider, metadata, timeout: effectiveTimeout, usedFallback, fallbackModel: fallbackModelHint };
},
- async executeCliRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout }) {
+ async executeCliRun(opts) {
+ // A host-registered CLI runner (see setCliRunner) wins — it tracks its own
+ // child process via registerExternalRun, so stopRun/isRunActive/deleteRun
+ // still account for it.
+ if (cliRunnerOverride) return cliRunnerOverride(opts);
+ const { runId, provider, prompt, workspacePath, onData, onComplete, timeout } = opts;
const runDir = join(RUNS_PATH, runId);
const outputPath = join(runDir, 'output.txt');
const metadataPath = join(runDir, 'metadata.json');
@@ -540,6 +583,16 @@ export function createRunnerService(config = {}) {
},
async stopRun(runId) {
+ // Host-spawned runs (CLI/TUI) take precedence — kill the registered handle
+ // and drop it so a later isRunActive reports false.
+ const external = externalRuns.get(runId);
+ if (external) {
+ if (external.kill && !external.killed) external.kill('SIGTERM');
+ else if (external.abort) external.abort();
+ externalRuns.delete(runId);
+ return true;
+ }
+
const active = activeRuns.get(runId);
if (!active) return false;
@@ -607,6 +660,12 @@ export function createRunnerService(config = {}) {
},
async deleteRun(runId) {
+ // Kill an in-flight host-spawned run before removing its dir so deleting a
+ // live run doesn't leave a zombie child process behind.
+ if (externalRuns.has(runId)) {
+ await service.stopRun(runId);
+ }
+
const runDir = join(RUNS_PATH, runId);
if (!existsSync(runDir)) return false;
@@ -636,7 +695,9 @@ export function createRunnerService(config = {}) {
},
async isRunActive(runId) {
- return activeRuns.has(runId);
+ return externalRuns.has(runId) || activeRuns.has(runId);
}
};
+
+ return service;
}
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 5efab961ee..c7963f3ac2 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -126,3 +126,83 @@ describe('AI Toolkit runner service', () => {
expect('num_ctx' in JSON.parse(fetch.mock.calls[0][1].body)).toBe(false);
});
});
+
+describe('AI Toolkit runner — declared extension points', () => {
+ it('setCliRunner delegates executeCliRun to the host runner and back to the built-in on null', async () => {
+ const runner = createRunnerService({ dataDir: './data' });
+ const builtin = runner.executeCliRun;
+
+ const hostRunner = vi.fn(async (opts) => `host:${opts.runId}`);
+ runner.setCliRunner(hostRunner);
+ const result = await runner.executeCliRun({ runId: 'r1', provider: { command: 'noop' } });
+ expect(result).toBe('host:r1');
+ expect(hostRunner).toHaveBeenCalledTimes(1);
+ // The override receives the full opts object verbatim.
+ expect(hostRunner).toHaveBeenCalledWith(expect.objectContaining({ runId: 'r1' }));
+
+ // Reverting restores the built-in implementation.
+ runner.setCliRunner(null);
+ expect(runner.executeCliRun).toBe(builtin);
+ });
+
+ it('setCliRunner / setTuiRunner reject non-function, non-null values', () => {
+ const runner = createRunnerService({ dataDir: './data' });
+ expect(() => runner.setCliRunner(42)).toThrow(/expects a function/);
+ expect(() => runner.setTuiRunner('nope')).toThrow(/expects a function/);
+ });
+
+ it('setTuiRunner attaches/detaches executeTuiRun so the runs-router gate stays honest', async () => {
+ const runner = createRunnerService({ dataDir: './data' });
+ // No built-in TUI executor — the runs router gates on typeof === 'function'.
+ expect(typeof runner.executeTuiRun).toBe('undefined');
+
+ const tui = vi.fn(async () => 'tui-run');
+ runner.setTuiRunner(tui);
+ expect(typeof runner.executeTuiRun).toBe('function');
+ await runner.executeTuiRun({ runId: 'tui-1' });
+ expect(tui).toHaveBeenCalledTimes(1);
+
+ runner.setTuiRunner(null);
+ expect(typeof runner.executeTuiRun).toBe('undefined');
+ });
+
+ it('external-run registry drives isRunActive / stopRun and reports unknown ids as inactive', async () => {
+ const runner = createRunnerService({ dataDir: './data' });
+ expect(await runner.isRunActive('x')).toBe(false);
+
+ const child = { kill: vi.fn(), killed: false };
+ runner.registerExternalRun('x', child);
+ expect(runner.hasExternalRun('x')).toBe(true);
+ expect(await runner.isRunActive('x')).toBe(true);
+
+ expect(await runner.stopRun('x')).toBe(true);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ // stopRun drops the entry, so a follow-up reports inactive.
+ expect(await runner.isRunActive('x')).toBe(false);
+ expect(await runner.stopRun('x')).toBe(false);
+ });
+
+ it('stopRun aborts an AbortController-style external run', async () => {
+ const runner = createRunnerService({ dataDir: './data' });
+ const controller = { abort: vi.fn() };
+ runner.registerExternalRun('api-run', controller);
+ expect(await runner.stopRun('api-run')).toBe(true);
+ expect(controller.abort).toHaveBeenCalledTimes(1);
+ });
+
+ it('deleteRun kills an in-flight external run before removing its dir', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-del-'));
+ const runner = createRunnerService({ dataDir });
+ const child = { kill: vi.fn(), killed: false };
+ runner.registerExternalRun('live', child);
+
+ // No on-disk dir for this run, but the live process must still be killed.
+ const deleted = await runner.deleteRun('live');
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(runner.hasExternalRun('live')).toBe(false);
+ // deleteRun returns false when the run dir doesn't exist on disk.
+ expect(deleted).toBe(false);
+
+ await rm(dataDir, { recursive: true, force: true });
+ });
+});
diff --git a/server/services/runner.js b/server/services/runner.js
index cb6dc1a290..ee4691ee0b 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -201,11 +201,9 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
childProcess.stdin.write(prompt);
childProcess.stdin.end();
- // Track active run (store on the runner service itself for stopRun to access)
- if (!toolkit.services.runner._portosActiveRuns) {
- toolkit.services.runner._portosActiveRuns = new Map();
- }
- toolkit.services.runner._portosActiveRuns.set(runId, childProcess);
+ // Track active run via the toolkit's declared external-run registry so its
+ // stopRun/isRunActive/deleteRun account for this host-spawned child process.
+ toolkit.services.runner.registerExternalRun(runId, childProcess);
// Call hooks
runnerConfig.hooks?.onRunStarted?.({ runId, provider: provider.name, model: provider.defaultModel });
@@ -235,7 +233,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
childProcess.on('error', async (err) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
- toolkit.services.runner._portosActiveRuns?.delete(runId);
+ toolkit.services.runner.unregisterExternalRun(runId);
console.error(`❌ Run ${runId} spawn error: ${err.message}`);
const metadata = {
@@ -263,7 +261,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
// the whole body and log via the emoji-prefixed convention.
try {
if (timeoutHandle) clearTimeout(timeoutHandle);
- toolkit.services.runner._portosActiveRuns?.delete(runId);
+ toolkit.services.runner.unregisterExternalRun(runId);
await writeFile(outputPath, output);
@@ -329,34 +327,26 @@ export async function executeApiRun(options) {
/**
* Register an in-flight run's killable process (ChildProcess or IPty) in the
- * same `_portosActiveRuns` map the patched `stopRun`/`isRunActive` consult.
- * Used by `executeTuiRun` so TUI runs can be stopped from /runs the same way
- * CLI runs can. Both ChildProcess and node-pty IPty expose `.kill(signal?)`.
+ * toolkit's declared external-run registry the toolkit `stopRun`/`isRunActive`/
+ * `deleteRun` consult. Used by `executeTuiRun` so TUI runs can be stopped from
+ * /runs the same way CLI runs can. Both ChildProcess and node-pty IPty expose
+ * `.kill(signal?)`.
*/
export function registerActiveRun(runId, killable) {
- const toolkit = requireToolkit();
- if (!toolkit.services.runner._portosActiveRuns) {
- toolkit.services.runner._portosActiveRuns = new Map();
- }
- toolkit.services.runner._portosActiveRuns.set(runId, killable);
+ requireToolkit().services.runner.registerExternalRun(runId, killable);
}
export function unregisterActiveRun(runId) {
// No-throw read: cleanup paths may run after the toolkit is gone (e.g.
// shutdown), so use `getAIToolkitInstance()` rather than `requireToolkit()`.
- getAIToolkitInstance()?.services?.runner?._portosActiveRuns?.delete(runId);
+ getAIToolkitInstance()?.services?.runner?.unregisterExternalRun?.(runId);
}
export async function stopRun(runId) {
- const toolkit = requireToolkit();
- // Check local active runs first (CLI runs spawned by this override)
- const localProcess = toolkit.services.runner._portosActiveRuns?.get(runId);
- if (localProcess && !localProcess.killed) {
- localProcess.kill('SIGTERM');
- toolkit.services.runner._portosActiveRuns.delete(runId);
- return { stopped: true, runId };
- }
- return toolkit.services.runner.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), so
+ // this is a thin pass-through.
+ return requireToolkit().services.runner.stopRun(runId);
}
export async function getRun(runId) {
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 29180537d8..f694562603 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -22,11 +22,20 @@ const runner = await import('./runner.js');
const { analyzeError, ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');
const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedModel, emitRunStarted } = runner;
-// Minimal toolkit stub that satisfies executeCliRun's expectations
+// Minimal toolkit stub that satisfies executeCliRun's expectations. Mirrors the
+// real toolkit runner's declared external-run registry (registerExternalRun /
+// unregisterExternalRun) that the override now drives instead of poking a
+// private `_portosActiveRuns` map.
function fakeToolkit(errorDetection = null) {
+ const externalRuns = new Map();
return {
services: {
- runner: { _portosActiveRuns: new Map() },
+ runner: {
+ registerExternalRun: (runId, killable) => externalRuns.set(runId, killable),
+ unregisterExternalRun: (runId) => externalRuns.delete(runId),
+ hasExternalRun: (runId) => externalRuns.has(runId),
+ _externalRuns: externalRuns,
+ },
errorDetection,
},
};
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index 7b397caac3..65b2780737 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -1,4 +1,5 @@
import { join } from 'path';
+import { readFile, unlink } from 'fs/promises';
import { EventEmitter } from 'events';
import { readJSONFile, PATHS, ensureDir, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
@@ -313,6 +314,58 @@ export async function recordUpdateResult(result) {
});
}
+/**
+ * Process the update-completion marker an `update.sh` cycle leaves behind.
+ *
+ * After a self-update restarts the server, the previous process writes
+ * `data/update-complete.json` ({ version, completedAt }); on boot we read it,
+ * record success/failure against the now-running version, and remove the
+ * marker. Extracted from a bootstrap IIFE in `server/index.js` so the update
+ * lifecycle lives in one service (and can be unit-tested) rather than inline at
+ * the boot site. Best-effort and self-contained — never throws; every failure
+ * branch removes the marker so a corrupt/mismatched file can't wedge boot into
+ * re-processing it forever.
+ */
+export async function processUpdateMarker() {
+ const updateMarkerPath = join(PATHS.data, 'update-complete.json');
+ const removeMarker = () => unlink(updateMarkerPath).catch(e => {
+ if (e?.code !== 'ENOENT') console.error(`❌ Failed to remove update marker: ${e.message}`);
+ });
+
+ let raw;
+ try { raw = await readFile(updateMarkerPath, 'utf-8'); }
+ catch (err) {
+ if (err?.code === 'ENOENT') return; // No marker = no recent update
+ console.error(`❌ Failed to read update marker: ${err?.message ?? err}`);
+ return removeMarker();
+ }
+
+ let marker;
+ try { marker = JSON.parse(raw); }
+ catch (err) {
+ console.error(`❌ Corrupted update marker (invalid JSON): ${err?.message ?? err}`);
+ return removeMarker();
+ }
+
+ if (!marker.version || !marker.completedAt) {
+ console.error(`❌ Update marker missing required fields (version: ${marker.version}, completedAt: ${marker.completedAt})`);
+ return removeMarker();
+ }
+
+ const runningVersion = await getCurrentVersion();
+ if (marker.version !== runningVersion) {
+ console.error(`❌ Update marker version (${marker.version}) doesn't match running version (${runningVersion}) — recording as failed`);
+ await recordUpdateResult({ version: marker.version, success: false, completedAt: marker.completedAt, log: `Version mismatch: expected ${marker.version}, running ${runningVersion}` })
+ .catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
+ return removeMarker();
+ }
+
+ console.log(`✅ Update to v${marker.version} completed at ${marker.completedAt}`);
+ await recordUpdateResult({ version: marker.version, success: true, completedAt: marker.completedAt, log: '' })
+ .catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
+ return removeMarker();
+}
+
const STALE_UPDATE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
/**
diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.js
index e6156248d9..7b5dc3c0ea 100644
--- a/server/services/updateChecker.test.js
+++ b/server/services/updateChecker.test.js
@@ -20,6 +20,11 @@ vi.mock('./github.js', () => ({
execGh: vi.fn()
}));
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(),
+ unlink: vi.fn().mockResolvedValue(undefined)
+}));
+
vi.mock('../lib/gitRemote.js', () => ({
getOriginInfo: vi.fn(),
UPSTREAM_OWNER: 'atomantic',
@@ -34,6 +39,7 @@ vi.mock('./installState.js', () => ({
}));
import { readJSONFile, ensureDir, atomicWrite } from '../lib/fileUtils.js';
+import { readFile, unlink } from 'fs/promises';
import { execGh } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import {
@@ -46,6 +52,7 @@ import {
clearStaleUpdateInProgress,
getRemoteInfo,
syncFork,
+ processUpdateMarker,
updateEvents
} from './updateChecker.js';
@@ -755,3 +762,52 @@ describe('syncFork', () => {
expect(saved.lastForkSync.syncedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
});
+
+describe('processUpdateMarker', () => {
+ const ENOENT = Object.assign(new Error('not found'), { code: 'ENOENT' });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // getCurrentVersion + loadState both read via readJSONFile — distinguish by path.
+ readJSONFile.mockImplementation((p) =>
+ String(p).endsWith('package.json') ? { version: '1.2.3' } : {});
+ });
+
+ it('returns silently and records nothing when no marker exists', async () => {
+ readFile.mockRejectedValueOnce(ENOENT);
+ await processUpdateMarker();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(unlink).not.toHaveBeenCalled();
+ });
+
+ it('records success and removes the marker when versions match', async () => {
+ readFile.mockResolvedValueOnce(JSON.stringify({ version: '1.2.3', completedAt: '2026-06-30T00:00:00Z' }));
+ await processUpdateMarker();
+ const saved = JSON.parse(atomicWrite.mock.calls.at(-1)[1]);
+ expect(saved.lastUpdateResult).toMatchObject({ version: '1.2.3', success: true });
+ expect(unlink).toHaveBeenCalledTimes(1);
+ });
+
+ it('records failure when the marker version mismatches the running version', async () => {
+ readFile.mockResolvedValueOnce(JSON.stringify({ version: '9.9.9', completedAt: '2026-06-30T00:00:00Z' }));
+ await processUpdateMarker();
+ const saved = JSON.parse(atomicWrite.mock.calls.at(-1)[1]);
+ expect(saved.lastUpdateResult).toMatchObject({ version: '9.9.9', success: false });
+ expect(saved.lastUpdateResult.log).toMatch(/mismatch/i);
+ expect(unlink).toHaveBeenCalledTimes(1);
+ });
+
+ it('removes a corrupt (invalid JSON) marker without recording a result', async () => {
+ readFile.mockResolvedValueOnce('{ not json');
+ await processUpdateMarker();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(unlink).toHaveBeenCalledTimes(1);
+ });
+
+ it('removes a marker missing required fields without recording a result', async () => {
+ readFile.mockResolvedValueOnce(JSON.stringify({ version: '1.2.3' })); // no completedAt
+ await processUpdateMarker();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ expect(unlink).toHaveBeenCalledTimes(1);
+ });
+});