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: read a dropped provider stream as a network fault, not an unknown one

Adam Eivy08686368e43a
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index da63799daa..be3dd99577 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -43,4 +43,6 @@ Both numbers and the `Math.max` live in `internal/runTimeouts.js`, a leaf module
Both bounds finalize through the same `markSettled()` / `finalizeTimeout(bound)` pair, so the single-settlement gate and Stop-marker handling are shared. **All three non-success terminal paths — cancel, timeout, mid-stream throw — open their record through `openTerminalMetadata()`**, which salvages the reasoning channel, persists `output.txt`, and stamps `outputSize` / `hadReasoning` / `usedReasoningAsFallback`. Stating that sequence per-path is how the cancel path went without the salvage entirely; a fourth terminal path must reuse the helper rather than restate it. **`finalizeTimeout` names which bound fired** in the message and in `metadata.timeoutBound` (`'stall'` | `'absolute'`), because the two are different diagnoses — a provider that went quiet is a bench candidate, one that outran its budget while producing is not. Neither message may contain the literal `"timeout"`: `analyzeError`'s NETWORK_ERROR pattern matches that substring and is tested BEFORE the timeout pattern, so it would misclassify the run as a connectivity fault. `"timed out"` is the phrase that reaches `ERROR_CATEGORIES.TIMEOUT`.
+**The mid-stream throw is classified through `describeTransportError(err)`, never `err.message`** — the same rule the pre-header fetch already follows, applied to the half of the run that reads the body. A peer that drops the connection mid-body rejects the reader with undici's opaque `TypeError: terminated` and hangs the actionable code (`UND_ERR_SOCKET` / `other side closed`) off `.cause`, so classifying the bare message matched no pattern: an NVIDIA NIM nemotron persistent-mind run that streamed reasoning for 319s and then lost its socket persisted `errorCategory: null`, which the host cascade reads as UNKNOWN and escalates to a tier-4 investigation task instead of the bounded retry a connectivity fault earns. A rejection with no `.cause` flattens to exactly the message it always was, so the helper is a safe superset for the non-transport throws (a bad frame, a finalization failure) that reach the same catch. `analyzeError` also recognizes a cause-less bare `terminated`, anchored to the WHOLE string because that scan reads an agent's entire CLI screen, where "… terminated" is ordinary prose.
+
The worked example for "barrel + documented exports" (see root `AGENTS.md` → Module Organization) is this directory's `index.js`.
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index 26daaefd8f..3d9298dda1 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -193,7 +193,16 @@ const ERROR_PATTERNS = [
// remote gateway retiring a pooled connection classified as UNKNOWN and was
// escalated to an open-ended tier-4 investigation, when the honest reading
// is a transient connectivity fault with a 2m bench.
- pattern: /ECONNREFUSED|ENOTFOUND|network error|connection refused|timeout|ETIMEDOUT|GOAWAY|UND_ERR_SOCKET/i,
+ //
+ // `terminated` is the same family seen from the other half of a run: undici
+ // raises `TypeError: terminated` when the peer drops the connection while
+ // the RESPONSE BODY is streaming, normally with the code on `.cause` (so
+ // `UND_ERR_SOCKET` above already matches the flattened chain) but not
+ // always. It is anchored to the WHOLE string rather than line-anchored on
+ // purpose — `analyzeError` also scans an agent's entire CLI screen, where
+ // "… terminated" is ordinary prose, and only a cause-less transport
+ // rejection ever arrives as that single word on its own.
+ pattern: /ECONNREFUSED|ENOTFOUND|network error|connection refused|timeout|ETIMEDOUT|GOAWAY|UND_ERR_SOCKET|ERR_STREAM_PREMATURE_CLOSE|^terminated$|TypeError: terminated/i,
category: ERROR_CATEGORIES.NETWORK_ERROR,
requiresFallback: false,
actionable: false,
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index 75ea6e7b7c..055a429527 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -177,6 +177,26 @@ describe('Error Detection', () => {
expect(result.category).toBe(ERROR_CATEGORIES.NETWORK_ERROR);
});
+ it('classifies undici\'s bare mid-stream "terminated" as a network error', () => {
+ // A peer that drops the connection while the response body is streaming
+ // rejects the reader with `TypeError: terminated`, and the actionable
+ // code is only on `.cause` — which a cause-less rejection does not carry
+ // at all. That single word used to reach UNKNOWN, escalating a 319s
+ // NVIDIA NIM nemotron run to a tier-4 investigation task.
+ expect(analyzeError('terminated').category).toBe(ERROR_CATEGORIES.NETWORK_ERROR);
+ expect(analyzeError('TypeError: terminated').category).toBe(ERROR_CATEGORIES.NETWORK_ERROR);
+ expect(analyzeError('terminated: UND_ERR_SOCKET: other side closed').category)
+ .toBe(ERROR_CATEGORIES.NETWORK_ERROR);
+ });
+
+ it('does not read an agent\'s prose about a terminated process as a network error', () => {
+ // `analyzeError` also scans a CLI agent's entire screen, so the bare-word
+ // clause is anchored to the WHOLE string: only a cause-less transport
+ // rejection ever arrives as that one word by itself.
+ const result = analyzeError('The build script terminated\nand I restarted it', 1);
+ expect(result.category).toBe(ERROR_CATEGORIES.UNKNOWN);
+ });
+
it('should detect timeout errors', () => {
const result = analyzeError('Process timed out after 300000ms');
expect(result.hasError).toBe(true);
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 60ea267687..c143ea2456 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -1077,8 +1077,22 @@ export function createRunnerService(config = {}) {
const { metadata, partialOutput } = await openTerminalMetadata();
- const errorAnalysis = analyzeError(err.message);
- metadata.error = errorAnalysis.message || err.message;
+ // `describeTransportError`, not `err.message` — the same reason the
+ // pre-header fetch uses it, applied to the half the run that reads
+ // the body. undici reports a connection dropped MID-STREAM as
+ // `TypeError: terminated` and hangs the actionable reason
+ // (`UND_ERR_SOCKET` / `other side closed`) off `.cause`, so
+ // classifying the bare message matched no pattern: an NVIDIA NIM
+ // nemotron run that streamed reasoning for 319s and then lost its
+ // socket persisted `errorCategory: null`, which the host's cascade
+ // reads as UNKNOWN and escalates to a tier-4 investigation task
+ //. The flattened chain classifies it as NETWORK_ERROR — a
+ // transient connectivity fault with a bounded retry. Non-transport
+ // rejections have no `.cause`, so the chain flattens to exactly the
+ // message this always passed.
+ const errorDescription = describeTransportError(err);
+ const errorAnalysis = analyzeError(errorDescription);
+ metadata.error = errorAnalysis.message || errorDescription;
metadata.errorCategory = errorAnalysis.category;
metadata.errorAnalysis = errorAnalysis;
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 1a7b59a785..e37c568677 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -1168,6 +1168,49 @@ describe('AI Toolkit runner service', () => {
.toBe('thought so far');
});
+ // A peer dropping the connection MID-BODY is the same transport family the
+ // pre-header fetch already flattens, but the reader's rejection was
+ // classified on `err.message` alone — `terminated`, with the code hidden on
+ // `.cause`. It matched nothing, so the run persisted `errorCategory: null`,
+ // which the host's cascade reads as UNKNOWN and escalates to a tier-4
+ // investigation task instead of a bounded retry.
+ it('classifies a mid-stream transport drop as a network error, not UNKNOWN', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const encoder = new TextEncoder();
+ const chunks = [
+ encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'Here' } }] })}\n`),
+ ];
+ let i = 0;
+ // undici's exact shape: an opaque outer TypeError over a coded cause.
+ const midStreamDrop = () => Object.assign(new TypeError('terminated'), {
+ cause: Object.assign(new Error('other side closed'), { code: 'UND_ERR_SOCKET' }),
+ });
+ vi.stubGlobal('fetch', vi.fn(async () => ({
+ ok: true,
+ body: { getReader: () => ({ read: async () => (i < chunks.length
+ ? { done: false, value: chunks[i++] }
+ : Promise.reject(midStreamDrop())) }) },
+ })));
+ const runner = createRunnerService({
+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },
+ });
+ let complete;
+ const completed = new Promise(resolve => { complete = resolve; });
+
+ await runner.executeApiRun({
+ runId: 'run-midstream-drop', provider: runReady(), model: null, prompt: 'hi',
+ workspacePath: process.cwd(), screenshots: [], onData: undefined, onComplete: complete,
+ });
+ const metadata = await completed;
+
+ expect(metadata.success).toBe(false);
+ expect(metadata.errorCategory).toBe('network-error');
+ // The flattened chain, not the opaque outer message, is what the run record
+ // and any investigation task quote.
+ expect(metadata.error).toContain('UND_ERR_SOCKET');
+ });
+
// The hidden channel is named `reasoning_content` by NVIDIA NIM, vLLM and the
// DeepSeek-R1-compatible servers — only OpenRouter-style endpoints say
// `reasoning`. Reading the one name discarded every reasoning token from NIM