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): keep terminateAgent result-shaped, don't swallow throws
[._.]/ Adam Eivy4f8650c27f96
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c4b26c00fa..045ff13e23 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`, `killAgent`, and `terminateAgent` now throw `ServerError` too.** The prior pass left the last three agent-lifecycle functions returning `{ success: false, error }` result shapes, so the pause and kill routes still string-matched `result.error` into a blanket 404. All three now throw `ServerError` — **404 `NOT_FOUND`** for a missing/not-running agent, **500 `AGENT_PAUSE_FAILED` / `AGENT_TERMINATE_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. Internal callers that legitimately depend on graceful failure are preserved: `killProcess` falls back to a raw `kill` via `.then(ok, err)`, `killAllAgents` uses `Promise.allSettled`, and the `agent:terminate` event handler swallows-and-logs (it runs outside the request lifecycle). Behavior-preserving apart from the more-correct 500 (not 404) on 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, **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-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 f97e1fb915..dc9dcc380b 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -32,43 +32,38 @@ const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;/*** Shared runner-mode termination path for terminateAgent and killAgent.- * Calls runnerFn, marks the task blocked, and cleans up.+ * 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).*/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 }));- // The agent is present in runnerAgents, so a failure here is an operational- // runner-RPC error (not a missing agent) — surface it as a 500 ServerError- // so the route renders the standard envelope instead of string-matching the- // result shape into a misleading 404.- if (!result.success) {- throw new ServerError(result.error || 'Failed to terminate runner agent', {- status: 500,- code: 'AGENT_TERMINATE_FAILED',- });- }- // Drain + drop this agent's runner output batcher before the terminal- // record so pending ~250ms-batched output lands first, and the Map entry- // doesn't leak if the runner never emits a later completion event. Dynamic- // import avoids a static cycle (subAgentSpawner statically re-exports this- // module). flushRunnerOutputBatcher is a no-op if no batcher exists.- const { flushRunnerOutputBatcher } = await import('./subAgentSpawner.js');- await flushRunnerOutputBatcher(agentId);- await completeAgent(agentId, { success: false, error: errorMessage });- const task = agentInfo?.task;- if (task) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason,- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user');+ 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+ // doesn't leak if the runner never emits a later completion event. Dynamic+ // import avoids a static cycle (subAgentSpawner statically re-exports this+ // module). flushRunnerOutputBatcher is a no-op if no batcher exists.+ const { flushRunnerOutputBatcher } = await import('./subAgentSpawner.js');+ await flushRunnerOutputBatcher(agentId);+ await completeAgent(agentId, { success: false, error: errorMessage });+ const task = agentInfo?.task;+ if (task) {+ await updateTask(task.id, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason,+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user');+ }+ runnerAgents.delete(agentId);}- runnerAgents.delete(agentId);return result;}@@ -197,8 +192,14 @@ export async function terminateAgent(agentId) {// Direct modeconst agent = activeAgents.get(agentId);+ // terminateAgent stays result-shaped (not a throw): its route path is+ // fire-and-forget (cosAgentLifecycle emits `agent:terminate` and returns+ // `{ success: true }` before termination runs), and its other callers are+ // internal orchestration (the event handler, killAllAgents' bulk sweep) that+ // inspect the result rather than a thrown ServerError. Only pauseAgent and+ // killAgent — whose routes surface an HTTP status — throw (issue #2534).if (!agent) {- throw new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' });+ return { success: false, error: 'Agent not found or not running' };}// Track as user-terminated so the close handler doesn't re-queue@@ -284,7 +285,18 @@ export function getActiveAgents() {export async function killAgent(agentId) {// Check if agent is in runner modeif (runnerAgents.has(agentId)) {- return terminateRunnerAgent(agentId, killAgentViaRunner, 'Agent force killed by user (SIGKILL)', 'Force killed by user');+ 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).+ if (!result.success) {+ throw new ServerError(result.error || 'Failed to kill runner agent', {+ status: 500,+ code: 'AGENT_KILL_FAILED',+ });+ }+ return result;}// Direct mode@@ -425,10 +437,7 @@ export async function killAllAgents() {const directIds = Array.from(activeAgents.keys());const runnerIds = Array.from(runnerAgents.keys());- // Best-effort bulk cleanup: terminateAgent now throws (404/500) on a missing- // or failed agent, so use allSettled — one agent that has already exited must- // not abort termination of the rest.- await Promise.allSettled([...directIds, ...runnerIds].map(agentId => terminateAgent(agentId)));+ await Promise.all([...directIds, ...runnerIds].map(agentId => terminateAgent(agentId)));return { killed: directIds.length + runnerIds.length };}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 81b260c0b4..ddf0fc9a54 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -221,12 +221,7 @@ async function runInitSpawner() {});cosEvents.on('agent:terminate', async (agentId) => {- // terminateAgent throws (404/500) when the agent is already gone or the- // runner call fails; this runs outside the request lifecycle, so swallow- // and log rather than letting the rejection escape the event handler.- await terminateAgent(agentId).catch((err) => {- emitLog('error', `❌ Failed to terminate agent ${agentId}: ${err.message}`, { agentId });- });+ await terminateAgent(agentId);});// Clean up orphaned agents after a short delay (let other services finish init).