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
address review (codex): preserve runner-side 404 in pause/kill error mapping
[._.]/ Adam Eivy173c745d9eb2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 045ff13e23..17d9e247b1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,7 +31,7 @@- **[issue-2592] Add an adaptive render budget and visibility-aware frameloop to CyberCity.** City gains an **Auto quality mode** (City Settings → Performance): new installs default to Auto starting at High, while existing saved settings load as **Manual** and keep their preset (adaptation never touches a chosen fixed preset, and never rewrites localStorage). A pure state machine, `client/src/utils/cityRenderBudget.js`, watches p75 frame time over 2s rolling windows — ignoring the startup warm-up and frame gaps above 250ms — and steps the effective detail tier **down** after two windows above 25ms, **up** after five below 18ms, with a 10s cooldown and never more than one tier per decision (the 18–25ms dead band is the anti-oscillation gap); sustained sub-cutoff frames still downshift via a synthetic pressure window. The runtime effective tier is separate from persisted settings and drives reflections, particle density, DPR, interior-window shaders, and set dressing via an explicit `effectiveTier` (replacing the old `particleDensity`-as-quality proxy in `cityShowDetail`/`cityShowInteriorWindows`). The live City frameloop now **pauses while the tab is hidden** (`frameloop="never"`) and resumes with a fresh warm-up when visible again — Photo mode keeps its demand loop and capture behavior untouched. The Performance tab shows the effective tier (`AUTO · HIGH`) plus a local-only diagnostics readout (tier, FPS, p75) that is never persisted or transmitted, and disables the Auto-controlled Reflections/Particle-density fields. New unit tests cover downshift, recovery, cooldown, ignored samples (warm-up/gap), sustained slowness, storage compatibility, Manual mode, and visibility transitions.- **[issue-2534] Unify service errors on `ServerError` and delete the duplicated `mapServiceError` copies.** Routes now speak one error model. A single `createServiceErrorMapper(statusMap, buildContext?)` factory in `server/lib/errorHandler.js` replaces the nine near-identical local `mapServiceError` bodies that had accreted across the pipeline / builder / media routers (`pipeline/shared.js`, `storyBuilder.js`, `universeBuilder.js`, `importer.js`, `dashboardLayouts.js`, `conflictJournal.js`, `mediaSketches.js`, `mediaCollections.js`, `mediaAnnotations.js`) — each now just wires its own domain `code → status` map (and optional diagnostic-context builder) through the shared factory. Separately, the CoS agent service functions that returned result-shaped `{ error }` payloads (`getAgentPrompt`, `deleteAgent`, `submitAgentFeedback`, `sendBtwToAgent`) now throw `ServerError` with an explicit `status`/`code`, so `cosAgentRoutes.js` no longer string-matches `result.error === 'Agent not found'` to guess 404-vs-400 — the errors bubble straight to the centralized middleware and every route returns the same `{ error, code, timestamp, context? }` envelope. No client-visible behavior change (the same statuses/codes are preserved). Pure architecture refactor.-- **[issue-2534] Finish the CoS agent error unification: `pauseAgent` and `killAgent` now throw `ServerError` too.** The prior pass left the agent-lifecycle `pauseAgent` and `killAgent` returning `{ success: false, error }` result shapes, so the pause and kill routes still string-matched `result.error` into a blanket 404. Both now throw `ServerError` — **404 `NOT_FOUND`** for a missing/not-running agent, **500 `AGENT_PAUSE_FAILED` / `AGENT_KILL_FAILED`** for a runner-RPC or persist failure (previously mis-reported as 404). The `pause`/`kill` routes drop their result-shape checks and just return the success payload. `killProcess`'s CoS-delegation path falls back to a raw `kill` via `.then(ok, err)` so a now-throwing `killAgent` still degrades gracefully. `terminateAgent` intentionally stays result-shaped: its route is fire-and-forget (the lifecycle wrapper emits `agent:terminate` and returns before termination runs), and its other callers (the event handler, `killAllAgents`' bulk sweep) inspect the result rather than a thrown error. Behavior-preserving apart from the more-correct 500 (not 404) on kill infra failures.+- **[issue-2534] Finish the CoS agent error unification: `pauseAgent` and `killAgent` now throw `ServerError` too.** The prior pass left the agent-lifecycle `pauseAgent` and `killAgent` returning `{ success: false, error }` result shapes, so the pause and kill routes still string-matched `result.error` into a blanket 404. Both now throw `ServerError` — **404 `NOT_FOUND`** for a missing/not-running agent (including a genuine runner-side 404 when the runner has restarted out of sync, whose HTTP status `cosRunnerClient` now preserves on the thrown error), **500 `AGENT_PAUSE_FAILED` / `AGENT_KILL_FAILED`** for a runner-RPC or persist failure (previously *every* runner failure was mis-reported as 404). The `pause`/`kill` routes drop their result-shape checks and just return the success payload. `killProcess`'s CoS-delegation path falls back to a raw `kill` via `.then(ok, err)` so a now-throwing `killAgent` still degrades gracefully. `terminateAgent` intentionally stays result-shaped: its route is fire-and-forget (the lifecycle wrapper emits `agent:terminate` and returns before termination runs), and its other callers (the event handler, `killAllAgents`' bulk sweep) inspect the result rather than a thrown error. Behavior-preserving apart from the more-correct 500 (not 404) on kill infra failures.- **[issue-2591] Responsive City HUD + City settings on the shared Drawer.** The CyberCity HUD now adapts to the viewport instead of stacking every desktop panel on top of the 3D scene at phone width. A new `useCityViewport` hook brackets the window into desktop (≥1024, unchanged cockpit), compact (640–1023) and phone (<640); below desktop the HUD collapses to a small clock/health chip, a status chip and a bottom dock of 44×44 launchers, keeping ≥70% of the scene unobscured on load. Secondary surfaces (vitals, attention, timeline, activity, map, filter, legend) open as ONE mutually-exclusive disclosure sheet driven by a `cityPane` URL param, so only one shows at a time and the open one is deep-linkable, reload-safe and restored by browser back/forward (the desktop Intel pane's active tab reads the same param). City settings moved off the bespoke bottom-right scroller onto the shared tabbed `Drawer` (`size="sm"`, Performance/Audio/Visual/Explore, active tab deep-linked via `useDrawerTab`'s `cityTab` param, `TabPills` mobile dropdown), preserving the `/city/settings` route.- **[issue-2550] Add direct unit tests for `telegramClient`, the telegram service, and `errorHandler.asyncHandler`.** Three previously under-covered modules gain colocated `*.test.js` suites, all driven with an injected/mock `fetch` (no network): `server/lib/telegramClient.test.js` now covers the poll loop (getUpdates dispatch to matching/non-matching `onText` + `message`/`callback_query` listeners, offset advance, `stopPolling` abort, and non-ok retry via fake timers) and the `apiCall` methods (`getMe`/`sendMessage` happy path, `reply_markup` string→object parse, non-ok throw); a new `server/services/telegram.test.js` exercises the token-bucket rate limiter (30-message cap then `Rate limit exceeded`) and unauthorized-chat rejection (message/command/callback_query paths) through `init()` with all deps mocked; and `server/lib/errorHandler.test.js` adds `asyncHandler` coverage (thrown ServerError → status+body+emit, plain Error → 500 normalization, success no-op, and the no-io path). Test-only change — no runtime behavior change.diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex dc9dcc380b..99689c5db9 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -30,17 +30,33 @@ const MAX_ORPHAN_RETRIES = 3;// Minimum cooldown between orphan retries (30 minutes)const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;+/**+ * Map a failed runner-op result (`{ error?, status? }`) to a ServerError.+ * A genuine runner 404 — the agent is gone / the runner restarted out of sync+ * with `runnerAgents` — preserves the missing-agent contract (404 NOT_FOUND);+ * any other runner/RPC failure is a 500 operational error under `failCode`.+ */+function runnerFailureError(result, fallbackMessage, failCode) {+ const notFound = result?.status === 404;+ return new ServerError(result?.error || fallbackMessage, {+ status: notFound ? 404 : 500,+ code: notFound ? 'NOT_FOUND' : failCode,+ });+}+/*** Shared runner-mode termination path for terminateAgent and killAgent.* Calls runnerFn, marks the task blocked, and cleans up. Returns the runner- * result shape (`{ success, error? }`) — callers decide whether a failure- * throws (killAgent, whose route surfaces status) or is returned for internal- * orchestration to inspect (terminateAgent, whose route is fire-and-forget).+ * result shape (`{ success, error?, status? }`) — callers decide whether a+ * failure throws (killAgent, whose route surfaces status) or is returned for+ * internal orchestration to inspect (terminateAgent, whose route is+ * fire-and-forget). The runner's HTTP `status` is preserved on failure so+ * killAgent can distinguish a genuine 404 from a 5xx infra error.*/async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReason) {const agentInfo = runnerAgents.get(agentId);if (agentInfo?.initializationTimeout) clearTimeout(agentInfo.initializationTimeout);- const result = await runnerFn(agentId).catch(err => ({ success: false, error: err.message }));+ const result = await runnerFn(agentId).catch(err => ({ success: false, error: err.message, status: err.status }));if (result.success) {// Drain + drop this agent's runner output batcher before the terminal// record so pending ~250ms-batched output lands first, and the Map entry@@ -117,13 +133,10 @@ export async function pauseAgent(agentId, reason = null) {const agentInfo = runnerAgents.get(agentId);if (agentInfo?.initializationTimeout) clearTimeout(agentInfo.initializationTimeout);pausedAgents.set(agentId, { pausedAt, reason });- const result = await pauseAgentViaRunner(agentId, reason).catch(err => ({ success: false, error: err.message }));+ const result = await pauseAgentViaRunner(agentId, reason).catch(err => ({ success: false, error: err.message, status: err.status }));if (!result.success) {pausedAgents.delete(agentId);- throw new ServerError(result.error || 'Failed to pause runner agent', {- status: 500,- code: 'AGENT_PAUSE_FAILED',- });+ throw runnerFailureError(result, 'Failed to pause runner agent', 'AGENT_PAUSE_FAILED');}// Persist failure must roll back the in-memory flag too, or the maps drift// (pausedAgents set, runnerAgents never deleted) until the next restart.@@ -286,15 +299,12 @@ export async function killAgent(agentId) {// Check if agent is in runner modeif (runnerAgents.has(agentId)) {const result = await terminateRunnerAgent(agentId, killAgentViaRunner, 'Agent force killed by user (SIGKILL)', 'Force killed by user');- // The agent was present in runnerAgents, so a failure here is an- // operational runner-RPC error (not a missing agent) — surface it as a- // 500 so the kill route renders the standard envelope instead of the old- // result-shape 404 string-match (issue #2534).+ // Surface a runner failure to the kill route as a ServerError instead of+ // the old result-shape 404 string-match (issue #2534): a genuine runner+ // 404 (agent gone / runner out of sync) stays NOT_FOUND, any other+ // runner-RPC failure is a 500 AGENT_KILL_FAILED.if (!result.success) {- throw new ServerError(result.error || 'Failed to kill runner agent', {- status: 500,- code: 'AGENT_KILL_FAILED',- });+ throw runnerFailureError(result, 'Failed to kill runner agent', 'AGENT_KILL_FAILED');}return result;}diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex b38d10f851..6b3628dec6 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -431,6 +431,27 @@ describe('pauseAgent — runner branch', () => {// runnerAgents must still contain the agent (not prematurely deleted)expect(runnerAgents.has('runner-agent-2')).toBe(true);});++ it('runner 404: a genuine runner-side 404 stays NOT_FOUND (not remapped to 500)', async () => {+ runnerAgents.set('runner-agent-3', {+ taskId: 'task-r3',+ task: { id: 'task-r3', taskType: 'user', description: 'Runner task 3', metadata: {} },+ workspacePath: '/repo/worktree-r3'+ });+ // pauseAgentViaRunner rejects with a status-carrying Error (runner restarted+ // out of sync with runnerAgents), which must be preserved as a 404.+ pauseAgentViaRunner.mockRejectedValue(+ Object.assign(new Error('Agent not found'), { status: 404 }),+ );++ await expect(pauseAgent('runner-agent-3', 'test-pause')).rejects.toMatchObject({+ message: 'Agent not found',+ status: 404,+ code: 'NOT_FOUND',+ });+ expect(pausedAgents.has('runner-agent-3')).toBe(false);+ expect(runnerAgents.has('runner-agent-3')).toBe(true);+ });});// ─── pauseAgent — TUI branch ─────────────────────────────────────────────────diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 2d5a809f54..118f3877d4 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -175,7 +175,9 @@ export async function terminateAgentViaRunner(agentId) {}, 30000);if (!response.ok) {const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to terminate agent');+ // Preserve the runner's HTTP status so callers can distinguish a genuine+ // 404 (agent gone / runner restarted out of sync) from a 5xx infra failure.+ throw Object.assign(new Error(error.error || 'Failed to terminate agent'), { status: response.status });}return readRunnerJson(response);}@@ -189,7 +191,7 @@ export async function killAgentViaRunner(agentId) {}, 30000);if (!response.ok) {const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to kill agent');+ throw Object.assign(new Error(error.error || 'Failed to kill agent'), { status: response.status });}return readRunnerJson(response);}@@ -205,7 +207,7 @@ export async function pauseAgentViaRunner(agentId, reason = null) {}, 30000);if (!response.ok) {const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to pause agent');+ throw Object.assign(new Error(error.error || 'Failed to pause agent'), { status: response.status });}return readRunnerJson(response);}