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([issue-2534]): throw ServerError from CoS pause/kill/terminate agent

[._.]/ Adam Eivy0f4985f5f0d1
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 2aa3c450b7..1f1674d31f 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -601,7 +601,9 @@ describe('CoS Routes', () => {
});
it('should return 404 if agent not found', async () => {
- cos.pauseAgent.mockResolvedValue({ error: 'Agent not found or not running' });
+ cos.pauseAgent.mockRejectedValue(
+ new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' }),
+ );
const response = await request(app).post('/api/cos/agents/agent-999/pause');
@@ -620,7 +622,9 @@ describe('CoS Routes', () => {
});
it('should return 404 if agent not found', async () => {
- cos.killAgent.mockResolvedValue({ error: 'Agent not found or not running' });
+ cos.killAgent.mockRejectedValue(
+ new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' }),
+ );
const response = await request(app).post('/api/cos/agents/agent-999/kill');
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 442adca2cb..a79f2c371e 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -74,21 +74,19 @@ router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {
}));
// POST /api/cos/agents/:id/pause - Stop process, preserve task/worktree for later resume
+// pauseAgent throws a ServerError — 404 when the agent is missing, 500 when the
+// runner/persist step fails — so no result-shape string-matching here.
router.post('/agents/:id/pause', asyncHandler(async (req, res) => {
const { reason } = validateRequest(pauseBodySchema, req.body ?? {});
const result = await cos.pauseAgent(req.params.id, reason || null);
- if (result?.error) {
- throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });
- }
res.json(result);
}));
// POST /api/cos/agents/:id/kill - Force kill agent (immediate SIGKILL)
+// killAgent throws a ServerError — 404 when the agent is missing, 500 when the
+// runner termination fails — so no result-shape string-matching here.
router.post('/agents/:id/kill', asyncHandler(async (req, res) => {
const result = await cos.killAgent(req.params.id);
- if (result?.error) {
- throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });
- }
res.json(result);
}));
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 37147d8eae..f97e1fb915 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -6,6 +6,7 @@
*/
import { join } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
import { emitLog } from './cosEvents.js';
import { completeAgent, updateAgent } from './cosAgents.js';
import { updateTask, addTask, getTaskById } from './cos.js';
@@ -37,29 +38,37 @@ async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReas
const agentInfo = runnerAgents.get(agentId);
if (agentInfo?.initializationTimeout) clearTimeout(agentInfo.initializationTimeout);
const result = await runnerFn(agentId).catch(err => ({ success: false, error: err.message }));
- 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);
+ // 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');
}
+ runnerAgents.delete(agentId);
return result;
}
@@ -116,7 +125,10 @@ export async function pauseAgent(agentId, reason = null) {
const result = await pauseAgentViaRunner(agentId, reason).catch(err => ({ success: false, error: err.message }));
if (!result.success) {
pausedAgents.delete(agentId);
- return result;
+ throw new ServerError(result.error || 'Failed to pause runner agent', {
+ status: 500,
+ code: '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.
@@ -125,7 +137,9 @@ export async function pauseAgent(agentId, reason = null) {
emitLog('error', `❌ Failed to persist pause for runner agent ${agentId}: ${err.message}`, { agentId });
return false;
});
- if (!persistedRunner) return { success: false, error: 'Failed to persist paused state' };
+ if (!persistedRunner) {
+ throw new ServerError('Failed to persist paused state', { status: 500, code: 'AGENT_PAUSE_FAILED' });
+ }
runnerAgents.delete(agentId);
emitLog('info', `⏸️ Paused runner agent ${agentId}${reason ? `: ${reason}` : ''}`, { agentId, reason });
return { success: true, agentId, pausedAt, mode: 'runner' };
@@ -133,7 +147,7 @@ export async function pauseAgent(agentId, reason = null) {
const agent = activeAgents.get(agentId);
if (!agent) {
- return { success: false, error: 'Agent not found or not running' };
+ throw new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' });
}
pausedAgents.set(agentId, { pausedAt, reason });
@@ -145,7 +159,9 @@ export async function pauseAgent(agentId, reason = null) {
emitLog('error', `❌ Failed to persist pause for agent ${agentId}: ${err.message}`, { agentId });
return false;
});
- if (!persisted) return { success: false, error: 'Failed to persist paused state' };
+ if (!persisted) {
+ throw new ServerError('Failed to persist paused state', { status: 500, code: 'AGENT_PAUSE_FAILED' });
+ }
if (agent.tuiSessionId) {
shellService.writeToSession(agent.tuiSessionId, '\x1b');
@@ -182,7 +198,7 @@ export async function terminateAgent(agentId) {
const agent = activeAgents.get(agentId);
if (!agent) {
- return { success: false, error: 'Agent not found or not running' };
+ throw new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' });
}
// Track as user-terminated so the close handler doesn't re-queue
@@ -275,7 +291,7 @@ export async function killAgent(agentId) {
const agent = activeAgents.get(agentId);
if (!agent) {
- return { success: false, error: 'Agent not found or not running' };
+ throw new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' });
}
// Track as user-terminated so the close handler doesn't re-queue
@@ -409,7 +425,10 @@ export async function killAllAgents() {
const directIds = Array.from(activeAgents.keys());
const runnerIds = Array.from(runnerAgents.keys());
- await Promise.all([...directIds, ...runnerIds].map(agentId => terminateAgent(agentId)));
+ // 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)));
return { killed: directIds.length + runnerIds.length };
}
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index d3563b2ed2..b38d10f851 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -413,7 +413,7 @@ describe('pauseAgent — runner branch', () => {
}), 'user');
});
- it('failure path: pauseAgentViaRunner rejects → pausedAgents rolled back, runnerAgents intact', async () => {
+ it('failure path: pauseAgentViaRunner rejects → throws, pausedAgents rolled back, runnerAgents intact', async () => {
runnerAgents.set('runner-agent-2', {
taskId: 'task-r2',
task: { id: 'task-r2', taskType: 'user', description: 'Runner task 2', metadata: {} },
@@ -421,9 +421,11 @@ describe('pauseAgent — runner branch', () => {
});
pauseAgentViaRunner.mockResolvedValue({ success: false, error: 'runner unreachable' });
- const result = await pauseAgent('runner-agent-2', 'test-pause');
-
- expect(result).toMatchObject({ success: false, error: 'runner unreachable' });
+ await expect(pauseAgent('runner-agent-2', 'test-pause')).rejects.toMatchObject({
+ message: 'runner unreachable',
+ status: 500,
+ code: 'AGENT_PAUSE_FAILED',
+ });
// pausedAgents must be rolled back when runner call fails
expect(pausedAgents.has('runner-agent-2')).toBe(false);
// runnerAgents must still contain the agent (not prematurely deleted)
@@ -511,9 +513,12 @@ describe('pauseAgent — agent not found', () => {
pausedAgents.clear();
});
- it('returns failure when agent is not in activeAgents or runnerAgents', async () => {
- const result = await pauseAgent('nonexistent-agent');
- expect(result).toMatchObject({ success: false, error: 'Agent not found or not running' });
+ it('throws a 404 ServerError when agent is not in activeAgents or runnerAgents', async () => {
+ await expect(pauseAgent('nonexistent-agent')).rejects.toMatchObject({
+ message: 'Agent not found or not running',
+ status: 404,
+ code: 'NOT_FOUND',
+ });
});
});
diff --git a/server/services/agents.js b/server/services/agents.js
index 0b10826ddc..3945cf30bb 100644
--- a/server/services/agents.js
+++ b/server/services/agents.js
@@ -284,10 +284,14 @@ export async function killProcess(pid) {
if (spawnedData?.agentId) {
console.log(`🔪 PID ${safePid} is CoS agent ${spawnedData.agentId}, delegating to CoS killAgent`);
const { killAgent } = await import('./subAgentSpawner.js');
- const result = await killAgent(spawnedData.agentId);
- if (result.success) return true;
- // Fall through to raw kill if CoS kill failed (agent may have already exited)
- console.log(`⚠️ CoS killAgent failed for ${spawnedData.agentId}: ${result.error}, falling back to raw kill`);
+ // killAgent throws a ServerError when the agent is missing or the kill
+ // fails; treat that as "already gone" and fall through to the raw kill
+ // below rather than surfacing it — this path is a best-effort cleanup.
+ const killed = await killAgent(spawnedData.agentId).then(() => true, (err) => {
+ console.log(`⚠️ CoS killAgent failed for ${spawnedData.agentId}: ${err.message}, falling back to raw kill`);
+ return false;
+ });
+ if (killed) return true;
}
const platform = process.platform;
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index ddf0fc9a54..81b260c0b4 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -221,7 +221,12 @@ async function runInitSpawner() {
});
cosEvents.on('agent:terminate', async (agentId) => {
- await terminateAgent(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 });
+ });
});
// Clean up orphaned agents after a short delay (let other services finish init).