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: bytesRead-aware tail-read, raw-buffer spool, finalize-IO tests
Adam Eivy9068032f1d14
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 818f1f9232..d7dd9e1898 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -49,7 +49,9 @@ const RAW_TAIL_ANALYSIS_BYTES = 1024 * 1024;* Read at most `maxBytes` from the end of a file. Returns null when the file* doesn't exist or can't be opened; an empty string for a zero-byte file.* Used to bound the memory footprint of failure-analysis reads against the- * uncapped raw PTY spool.+ * uncapped raw PTY spool. Non-throwing — any failure surfaces as null so+ * the caller's failure-analysis path can fall back to outputBuffer instead+ * of aborting `finish()` before finalizeAgent runs.*/async function readFileTail(path, maxBytes) {const st = await fsStat(path).catch(() => null);@@ -61,8 +63,11 @@ async function readFileTail(path, maxBytes) {if (!fh) return null;try {const buf = Buffer.alloc(length);- await fh.read(buf, 0, length, start);- return buf.toString('utf8');+ // Honour bytesRead — the file can shrink between stat and read, or the+ // OS can return a short read; decoding the whole `buf` would otherwise+ // append NULs to the returned string.+ const { bytesRead } = await fh.read(buf, 0, length, start).catch(() => ({ bytesRead: 0 }));+ return buf.toString('utf8', 0, bytesRead);} finally {await fh.close().catch(() => {});}@@ -222,12 +227,15 @@ export async function spawnTuiAgent({};// Raw PTY-bytes flush pipeline. Parallel to flushPendingLines but appends- // unprocessed chunks (no ANSI strip, no line semantics) to raw.txt. Joined- // once per batch, never accumulating in memory beyond a single 250ms tick.+ // unprocessed chunks (no ANSI strip, no line semantics) to raw.txt. Chunks+ // are queued as Node Buffers — NOT pre-decoded strings — so that a+ // multi-byte UTF-8 sequence split across two PTY chunks doesn't get a+ // U+FFFD replacement char in the persisted spool. Buffer.concat happens+ // once per 250ms batch, never accumulating in memory beyond a single tick.const flushPendingRawChunks = async () => {if (rawFlushTimer) { clearTimeout(rawFlushTimer); rawFlushTimer = null; }if (pendingRawChunks.length === 0) return;- const batch = pendingRawChunks.join('');+ const batch = Buffer.concat(pendingRawChunks);pendingRawChunks = [];await appendFile(rawFile, batch).catch(() => {});};@@ -379,9 +387,14 @@ export async function spawnTuiAgent({// disk-spool would race the rm of raw.txt (if we did remove it), and the// post-paste accumulator + state mutations are pointless after finish.if (finalized) return;- const text = data.toString();- pendingRawChunks.push(text);+ // Queue the raw Buffer so the disk spool preserves the exact PTY bytes —+ // a multi-byte UTF-8 char split across two chunks would otherwise corrupt+ // raw.txt with U+FFFD replacement chars at the boundary. The per-chunk+ // decode below is only used for ASCII-byte marker matching, which is+ // unaffected by boundary splits.+ pendingRawChunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data));scheduleRawFlush();+ const text = data.toString();if (postPasteBuffer !== null) postPasteBuffer += text;lastOutputAt = Date.now();if (firstOutputAt === null) firstOutputAt = lastOutputAt;diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 6d4971331e..29ffabee86 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -497,4 +497,85 @@ describe('spawnTuiAgent runtime', () => {expect(truncMetaCalls).toHaveLength(1);expect(truncMetaCalls[0][0]).toBe('agent-1');});++ // ── 8. Failure-path tail-read of raw.txt ────────────────────────────────────+ // analyzeAgentFailure needs the recent PTY tail; finalize MUST read it from+ // raw.txt via readFileTail (NOT readFile, which would load the whole spool).+ // This test wires stat to report a >1MB spool and asserts the tail-read+ // pattern: stat → open → read at offset (size - RAW_TAIL_ANALYSIS_BYTES).+ it('failure finalize: reads only the tail of raw.txt for analyzeAgentFailure', async () => {+ const fsPromises = await import('fs/promises');+ const RAW_TAIL_BYTES = 1024 * 1024;+ const SPOOL_SIZE = 5 * 1024 * 1024; // 5MB on disk++ vi.mocked(fsPromises.stat).mockResolvedValueOnce({ size: SPOOL_SIZE });+ const readMock = vi.fn().mockResolvedValue({ bytesRead: RAW_TAIL_BYTES });+ const closeMock = vi.fn().mockResolvedValue(undefined);+ vi.mocked(fsPromises.open).mockResolvedValueOnce({ read: readMock, close: closeMock });++ const spawnPromise = runSpawn();+ await flushMicrotasks();++ // Trigger a failure finalize via the shell-exit path.+ await capturedOnExit({ exitCode: 1, killed: false });+ await flushMicrotasks();+ await spawnPromise;++ const statCalls = vi.mocked(fsPromises.stat).mock.calls.filter(+ ([p]) => typeof p === 'string' && p.endsWith('raw.txt')+ );+ expect(statCalls.length).toBeGreaterThan(0);++ const openCalls = vi.mocked(fsPromises.open).mock.calls.filter(+ ([p]) => typeof p === 'string' && p.endsWith('raw.txt')+ );+ expect(openCalls.length).toBeGreaterThan(0);++ // read() must be called with offset = size - tailBytes (5MB - 1MB = 4MB)+ // so analyzeAgentFailure sees only the most-recent 1MB, not the full spool.+ expect(readMock).toHaveBeenCalledWith(+ expect.any(Buffer),+ 0,+ RAW_TAIL_BYTES,+ SPOOL_SIZE - RAW_TAIL_BYTES+ );+ expect(closeMock).toHaveBeenCalled();+ });++ // ── 9. Success-path skips the tail read ─────────────────────────────────────+ // Successful finalize must not touch raw.txt — that's what makes the+ // disk-spool's bounded-memory guarantee hold for healthy long runs.+ it('success finalize: skips raw.txt tail read entirely', async () => {+ const fsPromises = await import('fs/promises');++ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ runSpawn();+ await flushMicrotasks();++ // Drive the idle-complete success path (mirrors test 1).+ await capturedOnData(Buffer.from('Codex booting...\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();+ await capturedOnData(Buffer.from('Agent post-paste activity\n'));+ await vi.advanceTimersByTimeAsync(21000);+ vi.useRealTimers();+ await completeDone;++ // No raw.txt stat / open should fire on the success path. (The mock+ // for fs.promises.stat / open was reset between tests by clearAllMocks,+ // so any calls here are from this run.)+ const statCalls = vi.mocked(fsPromises.stat).mock.calls.filter(+ ([p]) => typeof p === 'string' && p.endsWith('raw.txt')+ );+ expect(statCalls).toHaveLength(0);++ const openCalls = vi.mocked(fsPromises.open).mock.calls.filter(+ ([p]) => typeof p === 'string' && p.endsWith('raw.txt')+ );+ expect(openCalls).toHaveLength(0);+ });});