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

fix([cos-runner-client-non-json-response-handling]): tolerate non-JSON runner responses

[._.]/ Adam Eivyd17a97d1f31e
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index 5bbac495a2..47a780499f 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -10,6 +10,28 @@ import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
const COS_RUNNER_URL = process.env.COS_RUNNER_URL || 'http://localhost:5558';
+/**
+ * Read a runner response body as JSON, tolerating a non-JSON body.
+ *
+ * The runner can answer with an HTML error page (e.g. a 500 while PM2 is
+ * restarting it mid-request) instead of JSON. Calling `response.json()` directly
+ * on that body throws `Unexpected token <` and masks the runner's actual error.
+ * We read the raw text and parse it ourselves, falling back to
+ * `{ error: <raw text> }` so callers surface the runner's real message.
+ *
+ * The try/catch here is intentional tolerant-parsing — it deliberately converts
+ * a parse failure into a value rather than letting it bubble, which is the point.
+ */
+async function readRunnerJson(response) {
+ const text = await response.text();
+ if (!text) return {};
+ try {
+ return JSON.parse(text);
+ } catch {
+ return { error: text.trim() };
+ }
+}
+
// Socket.IO client for real-time events
let socket = null;
// Map of event name -> array of handlers (supports multiple listeners per event)
@@ -98,7 +120,7 @@ export async function getRunnerHealth() {
if (!response || !response.ok) {
return { available: false, error: 'Runner not available' };
}
- const data = await response.json();
+ const data = await readRunnerJson(response);
return { available: true, ...data };
}
@@ -137,11 +159,11 @@ export async function spawnAgentViaRunner(options) {
}, 60000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to spawn agent');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -152,7 +174,7 @@ export async function getActiveAgentsFromRunner() {
if (!response.ok) {
throw new Error('Failed to get agents');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -163,10 +185,10 @@ export async function terminateAgentViaRunner(agentId) {
method: 'POST'
}, 30000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to terminate agent');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -177,10 +199,10 @@ export async function killAgentViaRunner(agentId) {
method: 'POST'
}, 30000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to kill agent');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -193,10 +215,10 @@ export async function pauseAgentViaRunner(agentId, reason = null) {
body: JSON.stringify({ reason })
}, 30000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to pause agent');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -207,7 +229,7 @@ export async function getAgentStatsFromRunner(agentId) {
if (!response.ok) {
return null;
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -220,7 +242,7 @@ export async function terminateAllAgentsViaRunner() {
if (!response.ok) {
throw new Error('Failed to terminate agents');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -229,10 +251,10 @@ export async function terminateAllAgentsViaRunner() {
export async function getAgentOutputFromRunner(agentId) {
const response = await fetchWithTimeout(`${COS_RUNNER_URL}/agents/${agentId}/output`, {}, 10000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to get agent output');
}
- return response.json();
+ return readRunnerJson(response);
}
// ============================================
@@ -268,11 +290,11 @@ export async function executeCliRunViaRunner(options) {
}, 60000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to execute run');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -283,7 +305,7 @@ export async function getActiveRunsFromRunner() {
if (!response.ok) {
throw new Error('Failed to get runs');
}
- return response.json();
+ return readRunnerJson(response);
}
/**
@@ -294,7 +316,7 @@ export async function isRunActiveInRunner(runId) {
if (!response.ok) {
return false;
}
- const data = await response.json();
+ const data = await readRunnerJson(response);
return data.active;
}
@@ -306,7 +328,7 @@ export async function getRunOutputFromRunner(runId) {
if (!response.ok) {
return null;
}
- const data = await response.json();
+ const data = await readRunnerJson(response);
return data.output;
}
@@ -318,8 +340,8 @@ export async function stopRunViaRunner(runId) {
method: 'POST'
}, 30000);
if (!response.ok) {
- const error = await response.json();
+ const error = await readRunnerJson(response);
throw new Error(error.error || 'Failed to stop run');
}
- return response.json();
+ return readRunnerJson(response);
}
diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.js
index 24bf363a15..ca36232000 100644
--- a/server/services/cosRunnerClient.test.js
+++ b/server/services/cosRunnerClient.test.js
@@ -42,9 +42,14 @@ import {
stopRunViaRunner
} from './cosRunnerClient.js';
+// The client reads the body via text() and tolerantly JSON.parses it, so a
+// non-JSON runner response (e.g. an HTML 500 page) becomes a synthesized
+// { error: <raw text> } instead of crashing with "Unexpected token <".
+// A string `data` is treated as a raw (possibly non-JSON) body; an object is
+// serialized to JSON the way the real runner would respond.
const mockResponse = (ok, data) => ({
ok,
- json: vi.fn().mockResolvedValue(data)
+ text: vi.fn().mockResolvedValue(typeof data === 'string' ? data : JSON.stringify(data))
});
describe('cosRunnerClient', () => {
@@ -221,6 +226,28 @@ describe('cosRunnerClient', () => {
expect(callBody.cliCommand).toBe('claude');
expect(callBody.cliArgs).toEqual(['--model', 'opus']);
});
+
+ it('surfaces a non-JSON error body instead of crashing on "Unexpected token <"', async () => {
+ // Simulates the runner returning an HTML 500 page (e.g. PM2 restarting it
+ // mid-request) rather than JSON. Parsing it as JSON used to throw.
+ fetchWithTimeout.mockResolvedValue(
+ mockResponse(false, '<!DOCTYPE html><html><body>502 Bad Gateway</body></html>')
+ );
+ await expect(spawnAgentViaRunner({ agentId: 'a1' }))
+ .rejects.toThrow('502 Bad Gateway');
+ });
+
+ it('falls back to the default message when an error body is empty', async () => {
+ fetchWithTimeout.mockResolvedValue(mockResponse(false, ''));
+ await expect(spawnAgentViaRunner({ agentId: 'a1' }))
+ .rejects.toThrow('Failed to spawn agent');
+ });
+
+ it('does not crash on a non-JSON success body', async () => {
+ fetchWithTimeout.mockResolvedValue(mockResponse(true, 'not json'));
+ const result = await spawnAgentViaRunner({ agentId: 'a1' });
+ expect(result).toEqual({ error: 'not json' });
+ });
});
// ===========================================================================