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
fix: add write failure reporter for agent transcript files (#8429)
[._.]/ Adam Eivy78c1fb5ef818
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex a68614940c..9f62932ce3 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -38,6 +38,7 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { buildVendorSpawnConfig } from '../lib/providerVendors.js';import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';import { resolveForgeTokenEnv } from './forgeAuth.js';+import { createTranscriptWriteReporter } from './agentTuiSpawning/outputSpooler.js';import { resolveAgentCliCwd } from '../lib/spawnCwd.js';import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';@@ -403,6 +404,7 @@ export async function spawnDirectly({const isStreamJson = cliConfig.streamFormat === 'stream-json';const streamParser = isStreamJson ? createStreamJsonParser() : null;const codexStderrFormatter = provider.id === 'codex' ? createCodexStderrFormatter(prompt) : null;+ const transcriptWriteReporter = createTranscriptWriteReporter({ agentId });// A headless CLI still colors its progress output: `opencode run` emits bare// `\x1B[0m` resets around its status line. Those bytes reached output.txt and// the live tail verbatim, and the browser drops only the ESC itself — so the@@ -522,7 +524,7 @@ export async function spawnDirectly({const lines = streamParser.processChunk(text);for (const line of lines) outputBuffer += line + '\n';outputBatcher.push(lines);- await writeFileGuarded(outputFile, outputBuffer).catch(() => {});+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));} else {// Non-stream providers: emit stdout as-is once decolored. A chunk that// was purely terminal control has nothing left to show. Unlike stderr@@ -530,7 +532,7 @@ export async function spawnDirectly({// formatting when it isn't wearing an `[stderr]` tag.if (!text) return;outputBuffer += text;- await writeFileGuarded(outputFile, outputBuffer).catch(() => {});+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));outputBatcher.push(text);}});@@ -552,7 +554,7 @@ export async function spawnDirectly({const lines = codexStderrFormatter.processChunk(text);for (const line of lines) outputBuffer += line + '\n';outputBatcher.push(lines);- await writeFileGuarded(outputFile, outputBuffer).catch(() => {});+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));return;}// A chunk that decolors down to whitespace was pure terminal control@@ -561,7 +563,7 @@ export async function spawnDirectly({const trimmed = text.trim();if (!trimmed || isKnownCliStderrNoise(trimmed)) return;outputBuffer += `[stderr] ${text}`;- await writeFileGuarded(outputFile, outputBuffer).catch(() => {});+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));outputBatcher.push(`[stderr] ${text}`);});} catch (err) {@@ -724,7 +726,7 @@ export async function spawnDirectly({// below too, since output.txt is written next).await outputBatcher.flush();- await writeFileGuarded(outputFile, outputBuffer).catch(() => {});+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));// The teardown both in-process spawners share: paused early return, then// the host-shutdown abandon gate, the user-termination consume, thediff --git a/server/services/agentTuiSpawning/outputSpooler.js b/server/services/agentTuiSpawning/outputSpooler.jsindex d7050e748b..b2c92b3189 100644--- a/server/services/agentTuiSpawning/outputSpooler.js+++ b/server/services/agentTuiSpawning/outputSpooler.js@@ -24,6 +24,37 @@ import { OUTPUT_BUFFER_CAP, OUTPUT_BUFFER_HEADROOM, RAW_SPOOL_MAX_BYTES } from '// 250ms is invisible to the live tail but cuts I/O by 1-2 orders of magnitude.const OUTPUT_FLUSH_INTERVAL_MS = 250;+/**+ * Create a per-run transcript write failure reporter. Logs the first failure+ * per (agentId, fileLabel) and updates agent metadata to flag the transcript+ * as incomplete, deduplicating multiple errors from a failing disk.+ *+ * @param {object} opts+ * @param {string} opts.agentId Agent id (used in logs and metadata updates).+ * @returns {object} Reporter with `report(fileLabel, err)` method.+ */+export function createTranscriptWriteReporter({ agentId }) {+ const reportedFailures = new Set();++ return {+ report(fileLabel, err) {+ const failureKey = `${fileLabel}`;+ if (reportedFailures.has(failureKey)) {+ // Already reported this failure — skip duplicate logging+ return;+ }+ reportedFailures.add(failureKey);++ // Log the first failure with error code and message+ console.error(`❌ agent ${agentId} ${fileLabel} write failed (${err.code || 'error'}): ${err.message}`);++ // Update agent metadata to flag transcript as incomplete+ updateAgent(agentId, { metadata: { transcriptWriteFailed: { file: fileLabel, code: err.code || 'unknown' } } })+ .catch(metaErr => console.error(`❌ agent ${agentId} transcriptWriteFailed metadata write failed: ${metaErr.message}`));+ },+ };+}+// RAW_SPOOL_MAX_BYTES lives in tuiHandshake.js so the test suite can shrink the// cap via the same vi.mock pattern that overrides the output-buffer thresholds// — saves the truncation test from having to push hundreds of MB through the@@ -63,14 +94,16 @@ export function createOutputSpooler({ agentId, outputFile, rawFile }) {let rawBytesWritten = 0;let rawSpoolTruncationWarned = false;+ const reporter = createTranscriptWriteReporter({ agentId });+const flushPendingLines = async () => {if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; }if (pendingLines.length === 0) return;const batch = pendingLines;pendingLines = [];await Promise.all([- appendAgentOutputLines(agentId, batch).catch(() => {}),- appendFile(outputFile, batch.map(l => `${l}\n`).join('')).catch(() => {})+ appendAgentOutputLines(agentId, batch).catch((err) => reporter.report('state', err)),+ appendFile(outputFile, batch.map(l => `${l}\n`).join('')).catch((err) => reporter.report('output.txt', err))]);};@@ -134,11 +167,17 @@ export function createOutputSpooler({ agentId, outputFile, rawFile }) {// Only update the byte counter on successful write — a failed write// would otherwise inflate rawBytesWritten and make subsequent flush// decisions race the actual on-disk state.- const wrote = await writeFile(rawFile, writeBuf).then(() => true).catch(() => false);+ const wrote = await writeFile(rawFile, writeBuf).then(() => true).catch((err) => {+ reporter.report('raw.txt', err);+ return false;+ });if (wrote) rawBytesWritten = writeBytes;return;}- const wrote = await appendFile(rawFile, batch).then(() => true).catch(() => false);+ const wrote = await appendFile(rawFile, batch).then(() => true).catch((err) => {+ reporter.report('raw.txt', err);+ return false;+ });if (wrote) rawBytesWritten += batchBytes;};diff --git a/server/services/agentTuiSpawning/outputSpooler.test.js b/server/services/agentTuiSpawning/outputSpooler.test.jsindex 6f289b0b9e..1860d54ea5 100644--- a/server/services/agentTuiSpawning/outputSpooler.test.js+++ b/server/services/agentTuiSpawning/outputSpooler.test.js@@ -21,7 +21,7 @@ vi.mock('../../lib/tuiHandshake.js', () => ({import { appendFile, writeFile } from 'fs/promises';import { appendAgentOutputLines, updateAgent } from '../cosAgentLifecycle.js';-import { createOutputSpooler } from './outputSpooler.js';+import { createOutputSpooler, createTranscriptWriteReporter } from './outputSpooler.js';const OUTPUT_FILE = '/tmp/agent/output.txt';const RAW_FILE = '/tmp/agent/raw.txt';@@ -107,4 +107,128 @@ describe('createOutputSpooler', () => {expect(appendFile).not.toHaveBeenCalled();expect(appendAgentOutputLines).not.toHaveBeenCalled();});++ it('reports output.txt write failures once per file', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const s = makeSpooler();+ const err = new Error('ENOSPC: no space');+ err.code = 'ENOSPC';+ vi.mocked(appendFile).mockRejectedValueOnce(err);++ s.appendLine('line 1');+ await s.drainLines();++ // First failure should be logged+ const logs = errorSpy.mock.calls.filter(([msg]) => msg.includes('output.txt write failed'));+ expect(logs).toHaveLength(1);+ expect(logs[0][0]).toContain('ENOSPC');++ // Metadata should be updated+ const metaCalls = vi.mocked(updateAgent).mock.calls.filter(+ ([, p]) => p?.metadata?.transcriptWriteFailed?.file === 'output.txt'+ );+ expect(metaCalls).toHaveLength(1);++ errorSpy.mockRestore();+ });++ it('reports raw.txt write failures once per file', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const s = makeSpooler();+ const err = new Error('EACCES: permission denied');+ err.code = 'EACCES';+ vi.mocked(appendFile).mockRejectedValueOnce(err);++ s.pushRaw('chunk 1');+ await s.drainRaw();++ // First failure should be logged+ const logs = errorSpy.mock.calls.filter(([msg]) => msg.includes('raw.txt write failed'));+ expect(logs).toHaveLength(1);+ expect(logs[0][0]).toContain('EACCES');++ errorSpy.mockRestore();+ });+});++describe('createTranscriptWriteReporter', () => {+ let errorSpy;++ beforeEach(() => {+ vi.clearAllMocks();+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ errorSpy.mockRestore();+ });++ it('logs the first failure for a file with error code and message', async () => {+ const reporter = createTranscriptWriteReporter({ agentId: 'agent-1' });+ const err = new Error('ENOSPC: no space left on device');+ err.code = 'ENOSPC';++ reporter.report('output.txt', err);++ expect(errorSpy).toHaveBeenCalledWith(+ '❌ agent agent-1 output.txt write failed (ENOSPC): ENOSPC: no space left on device'+ );+ expect(vi.mocked(updateAgent)).toHaveBeenCalledWith('agent-1', {+ metadata: { transcriptWriteFailed: { file: 'output.txt', code: 'ENOSPC' } },+ });+ });++ it('logs fallback to error string when err.code is undefined', async () => {+ const reporter = createTranscriptWriteReporter({ agentId: 'agent-1' });+ const err = new Error('unknown failure');++ reporter.report('output.txt', err);++ expect(errorSpy).toHaveBeenCalledWith(+ '❌ agent agent-1 output.txt write failed (error): unknown failure'+ );+ expect(vi.mocked(updateAgent)).toHaveBeenCalledWith('agent-1', {+ metadata: { transcriptWriteFailed: { file: 'output.txt', code: 'unknown' } },+ });+ });++ it('logs only once per file — subsequent failures on the same file are silent', async () => {+ const reporter = createTranscriptWriteReporter({ agentId: 'agent-1' });+ const err = new Error('disk full');+ err.code = 'ENOSPC';++ reporter.report('output.txt', err);+ reporter.report('output.txt', err);+ reporter.report('output.txt', err);++ const logs = errorSpy.mock.calls.filter(([msg]) => msg.includes('output.txt write failed'));+ expect(logs).toHaveLength(1);+ expect(vi.mocked(updateAgent)).toHaveBeenCalledTimes(1);+ });++ it('reports different files independently', async () => {+ const reporter = createTranscriptWriteReporter({ agentId: 'agent-1' });+ const err = new Error('disk full');+ err.code = 'ENOSPC';++ reporter.report('output.txt', err);+ reporter.report('raw.txt', err);+ reporter.report('state', err);++ const logs = errorSpy.mock.calls.filter(([msg]) => msg.includes('write failed'));+ expect(logs).toHaveLength(3);+ expect(vi.mocked(updateAgent)).toHaveBeenCalledTimes(3);+ });++ it('handles state append failures', async () => {+ const reporter = createTranscriptWriteReporter({ agentId: 'agent-1' });+ const err = new Error('state write failed');+ err.code = 'EIO';++ reporter.report('state', err);++ expect(errorSpy).toHaveBeenCalledWith(+ '❌ agent agent-1 state write failed (EIO): state write failed'+ );+ });});