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

address review: spool raw PTY bytes to raw.txt, guard handleData after finalize

Adam Eivye18b531797d2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9523515ca1..60b22f36cd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,4 +17,4 @@
- Federated peer-sync category toggles for **Universe** and **Pipeline** silently no-op'd. The Zod `syncCategoriesSchema` in `server/routes/instances.js` was missing both keys; Zod's default object parsing strips unknown keys, so the PATCH validated as an empty `syncCategories` object, the service-side merge became a no-op, and the checkbox stayed unchecked with no server-side error. Added `universe` and `pipeline` to the schema to restore parity with `DEFAULT_SYNC_CATEGORIES` and the UI's `SYNC_CATEGORY_META`.
- Auto-run the world → universe data rename on server boot. The conversion previously shipped as a manual CLI script (`server/scripts/migrateWorldToUniverse.js`) that nobody knew to invoke, so installs upgrading from the World Builder era kept stale `data/world-builder.json` files and never saw their worlds appear as universes. The new migration `031-world-to-universe-data-rename.js` does the file rename, top-level key rename (`worlds`→`universes`), `worldId`→`universeId` rewrite in `pipeline-series.json`, `worldRun`→`universeRun` rewrite in `media-jobs.json`, and also relinks any `"World: <name>"` render collections in `media-collections.json` to their universe by canonical-name match.
- Universe Builder picker dropdown rendered beneath the tab subnav and downstream section cards in Lumen Glass / Blueprint Ops themes. Those themes ship a non-`none` `--port-backdrop-filter`, and the global rule in `index.css` applies it to every `.bg-port-card.border.rounded*` — which turns each such card into its own stacking context. The picker's `absolute z-30` dropdown was trapped inside the header card's context and couldn't paint over later sibling cards. Adding `relative z-30` to the picker's `<header>` lets that stacking context win against subsequent siblings so the dropdown overlays them as intended.
-- TUI agent raw-PTY buffer no longer truncates the head at ~640KB ("⚠️ raw PTY buffer exceeded 1MB — head dropped"). The buffer feeds `analyzeAgentFailure` at finalize, so silently slicing the head was the exact behavior the warning admitted to ("failure analysis may miss earlier symptoms"). `server/services/agentTuiSpawning.js` now stores raw PTY output as an array of chunks (joined lazily, only on failure, to avoid O(n²) string-concat under chatty TUIs); `outputBuffer` keeps its existing 8MB cap / 10MB headroom (it has an authoritative on-disk source via the line-batched `output.txt` append). The `rawBufferTruncated` agent-metadata flag is gone with the truncation logic.
+- TUI agent raw-PTY buffer no longer truncates the head at ~640KB ("⚠️ raw PTY buffer exceeded 1MB — head dropped"). The buffer feeds `analyzeAgentFailure` at finalize, so silently slicing the head was the exact behavior the warning admitted to ("failure analysis may miss earlier symptoms"). `server/services/agentTuiSpawning.js` now spools raw PTY bytes to a per-agent `raw.txt` file in 250ms-debounced batches (mirroring the existing parsed-output pipeline that writes `output.txt`), so the in-memory footprint stays bounded regardless of run length. `analyzeAgentFailure` reads the file on failure — successful runs skip the read entirely. The paste-marker poll keeps only a small post-paste accumulator that lives for the paste window (a few seconds). The `rawBufferTruncated` agent-metadata flag is gone with the truncation logic.
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 12d550b3f6..7e58f1187f 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -123,19 +123,20 @@ export async function spawnTuiAgent({
isTruthyMetaFn,
}) {
const outputFile = join(agentDir, 'output.txt');
+ // Raw PTY bytes spool to disk continuously rather than accumulate in-memory.
+ // A chatty TUI (token-tick repaints, status lines) emits hundreds of chunks
+ // /sec; a per-run in-memory buffer would grow without bound on long agents
+ // and the join-into-single-string at finalize would double peak RAM. The
+ // disk file is appended in 250ms-debounced batches (same pattern as
+ // `flushPendingLines` for parsed output — see CLAUDE.md "High-frequency
+ // state writes must batch"), and `analyzeAgentFailure` reads the file on
+ // failure so it gets the full PTY stream regardless of run length.
+ const rawFile = join(agentDir, 'raw.txt');
const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : PATHS.root;
const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
const commandName = tuiConfig.command.split('/').pop();
let outputBuffer = '';
- // rawBuffer is stored as an array of chunks (not `let rawBuffer = ''` with
- // `+=`) because a chatty TUI emits hundreds of chunks/sec and `string += x`
- // is O(n²) — every append reallocates and copies the full prior string.
- // The array is joined lazily: only on failure (analyzeAgentFailure needs
- // a single string) and during the brief paste-marker polling window
- // (`rawChunks.slice(pasteChunkStart).join('')`), so successful runs never
- // pay the linear-time join.
- const rawChunks = [];
let finalized = false;
let hasStartedWorking = false;
let promptSentAt = null;
@@ -146,16 +147,22 @@ export async function spawnTuiAgent({
// True once outputBuffer crossed its HEADROOM and the head was dropped.
// Mirrors `outputBufferTruncated` in `tuiPromptRunner.js`: warn once per
// buffer and surface via agent metadata so the agent record distinguishes
- // a long-run-with-overflow from a clean short run. rawChunks is intentionally
- // uncapped — it feeds analyzeAgentFailure at finalize, and head-truncation
- // would lose the earlier failure context once later progress redraws push
- // it out of the retained window (chatty TUIs emit constant token-count /
- // status-line repaints that quickly fill any fixed-size tail).
+ // a long-run-with-overflow from a clean short run.
let outputBufferTruncated = false;
+ // Bounded post-paste accumulator. Lives only while pasteEnterTimer is
+ // running (a few seconds at most), so the in-memory cost is bounded by
+ // however much the TUI emits during the paste-marker window — typically
+ // a few KB. Set to '' when sendPrompt fires; nulled when paste detection
+ // resolves or the agent finalizes.
+ let postPasteBuffer = null;
+
let pendingLines = [];
let flushTimer = null;
let flushing = null;
+ let pendingRawChunks = [];
+ let rawFlushTimer = null;
+ let rawFlushing = null;
let pasteEnterTimer = null;
const streamingStrip = createStreamingAnsiStripper();
@@ -179,6 +186,25 @@ export async function spawnTuiAgent({
}, OUTPUT_FLUSH_INTERVAL_MS);
};
+ // 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.
+ const flushPendingRawChunks = async () => {
+ if (rawFlushTimer) { clearTimeout(rawFlushTimer); rawFlushTimer = null; }
+ if (pendingRawChunks.length === 0) return;
+ const batch = pendingRawChunks.join('');
+ pendingRawChunks = [];
+ await appendFile(rawFile, batch).catch(() => {});
+ };
+
+ const scheduleRawFlush = () => {
+ if (rawFlushTimer || rawFlushing) return;
+ rawFlushTimer = setTimeout(() => {
+ rawFlushTimer = null;
+ rawFlushing = flushPendingRawChunks().finally(() => { rawFlushing = null; });
+ }, OUTPUT_FLUSH_INTERVAL_MS);
+ };
+
// TUI agents only emit a handful of internal status lines (session-started,
// prompt-pasted, completion) — see handleData for why per-line capture of
// the PTY stream itself is intentionally dropped.
@@ -211,10 +237,12 @@ export async function spawnTuiAgent({
if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);
if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }
- // Drain pending parsed lines before the final state writes so completion
- // events don't beat the last output batch to disk.
+ // Drain pending parsed lines AND raw chunks before the final state
+ // writes so completion events don't beat the last output batch to disk.
if (flushing) await flushing.catch(() => {});
await flushPendingLines();
+ if (rawFlushing) await rawFlushing.catch(() => {});
+ await flushPendingRawChunks();
const duration = Date.now() - (agentData?.startedAt || Date.now());
const terminatedByUser = userTerminatedAgents.has(agentId);
@@ -242,20 +270,16 @@ export async function spawnTuiAgent({
// capped at OUTPUT_BUFFER_CAP and would silently truncate the on-disk
// record for long runs. The append-only stream is the authoritative copy.
//
- // The raw chunks are only joined when analyzeAgentFailure will actually
- // run — successful runs skip the join entirely (large PTY streams can
- // be tens of MB; joining + the analyzer's linear scan would double peak
- // memory on every clean completion).
+ // For failure analysis: read the full raw PTY stream from raw.txt rather
+ // than holding it in memory. Successful runs skip the read entirely.
+ // raw.txt stays in agentDir alongside output.txt as the persistent record
+ // of the agent's full PTY transcript.
+ const rawAnalysisText = finalSuccess
+ ? null
+ : await readFile(rawFile, 'utf8').catch(() => null);
const errorAnalysis = finalSuccess
? null
- : analyzeAgentFailure(
- rawChunks.length ? rawChunks.join('') : outputBuffer,
- task,
- model
- );
- // Drop chunk refs once the analyzer is done so GC can reclaim them
- // before the heavier finalizeAgent / cleanupWorktreeFn chain runs.
- rawChunks.length = 0;
+ : analyzeAgentFailure(rawAnalysisText || outputBuffer, task, model);
// try/finally so a throw from finalizeAgent (e.g. processAgentCompletion
// hook crash) still runs the local cleanup — sentinel removal, worktree
@@ -302,8 +326,15 @@ export async function spawnTuiAgent({
};
const handleData = async (data) => {
+ // The PTY can emit chunks between finalize starting and the shell session
+ // actually being killed in the finally block. Once finalized, skip them —
+ // 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();
- rawChunks.push(text);
+ pendingRawChunks.push(text);
+ scheduleRawFlush();
+ if (postPasteBuffer !== null) postPasteBuffer += text;
lastOutputAt = Date.now();
if (firstOutputAt === null) firstOutputAt = lastOutputAt;
@@ -317,9 +348,9 @@ export async function spawnTuiAgent({
// status line (`thinking with…`, token counters, footer) and gets
// re-captured if we parse it line-by-line. The attached shell session
// shows the live TUI faithfully — see-the-shell is the user-facing
- // path. We still buffer the raw stream into rawBuffer for error
- // analysis on failure, and we detect early "command not found" so a
- // missing binary fails fast instead of idling.
+ // path. We still spool the raw stream to raw.txt for error analysis
+ // on failure, and we detect early "command not found" so a missing
+ // binary fails fast instead of idling.
if (!promptSentAt) {
const lowerStripped = streamingStrip(text).toLowerCase();
if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {
@@ -385,11 +416,11 @@ export async function spawnTuiAgent({
const sendPrompt = (reason) => {
if (finalized || promptSentAt) return;
promptSentAt = Date.now();
- // rawChunks index AT the moment the paste is written — every chunk
- // pushed at or after this index is post-paste output the marker poll
- // needs to scan. Storing the index (not a string length) avoids re-
- // joining the full buffer on every poll tick.
- const pasteChunkStart = rawChunks.length;
+ // Start capturing post-paste output. Set BEFORE writing the paste so
+ // every chunk that arrives in response gets appended. Cleared the moment
+ // detection resolves (marker seen or fallback elapsed) so the accumulator
+ // never lives beyond the paste-marker window.
+ postPasteBuffer = '';
shellService.writeToSession(sessionId, `\x1b[200~${prompt}\x1b[201~`);
appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)} (${reason})`);
@@ -403,16 +434,13 @@ export async function spawnTuiAgent({
if (finalized) {
clearInterval(pasteEnterTimer);
pasteEnterTimer = null;
+ postPasteBuffer = null;
return;
}
const elapsed = Date.now() - pasteSentAt;
- // Join only the chunks that arrived since the paste was written —
- // bounded by the paste-marker window (PASTE_TO_ENTER_FALLBACK_MS),
- // so the cost stays small even if the run has been going for hours.
- const postPasteOutput = rawChunks.length > pasteChunkStart
- ? rawChunks.slice(pasteChunkStart).join('')
- : '';
- const markerSeen = PASTE_MARKER_PATTERN.test(postPasteOutput);
+ const markerSeen = postPasteBuffer
+ ? PASTE_MARKER_PATTERN.test(postPasteBuffer)
+ : false;
// Submit when EITHER the paste-commit marker appears (preferred) or
// the fallback window elapses (covers small prompts that don't render
// the marker).
@@ -420,6 +448,7 @@ export async function spawnTuiAgent({
|| elapsed >= PASTE_TO_ENTER_FALLBACK_MS) {
clearInterval(pasteEnterTimer);
pasteEnterTimer = null;
+ postPasteBuffer = null;
submitEnter();
}
}, PASTE_MARKER_POLL_MS);
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index b571bbc60a..f76637c3d3 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -71,6 +71,7 @@ vi.mock('./agentState.js', () => ({
vi.mock('fs/promises', () => ({
writeFile: vi.fn().mockResolvedValue(undefined),
appendFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue(''),
rm: vi.fn().mockResolvedValue(undefined)
}));
@@ -427,12 +428,13 @@ describe('spawnTuiAgent runtime', () => {
);
});
- // ── 6. Raw-buffer growth (no cap) ───────────────────────────────────────────
- // rawBuffer feeds analyzeAgentFailure at finalize. Capping/slicing it would
- // lose the earlier failure context once later chatty progress redraws push
- // it past the retained tail, so the buffer is allowed to grow for the
- // duration of the run. No warn, no metadata flag.
- it('rawBuffer grows without truncation warn or metadata flag', async () => {
+ // ── 6. Raw PTY stream spools to disk (no in-memory cap, no warn) ───────────
+ // Raw chunks are written to raw.txt via the debounced flush pipeline so
+ // memory stays bounded regardless of run length. analyzeAgentFailure
+ // reads the file on failure. No warn, no metadata flag, even when the
+ // chunk total dwarfs the previous 640KB in-memory cap.
+ it('rawBuffer grows without truncation warn or metadata flag, spools to raw.txt', async () => {
+ const { appendFile } = await import('fs/promises');
runSpawn();
await flushMicrotasks();
@@ -444,6 +446,10 @@ describe('spawnTuiAgent runtime', () => {
await capturedOnData(Buffer.alloc(2 * 1024 * 1024, 0x79)); // 'y'
await flushMicrotasks();
+ // Fire the 250ms debounced raw flush.
+ await vi.advanceTimersByTimeAsync(300);
+ await flushMicrotasks();
+
const truncWarns = warnSpy.mock.calls.filter(args =>
typeof args[0] === 'string' && args[0].includes('raw PTY buffer exceeded')
);
@@ -453,6 +459,12 @@ describe('spawnTuiAgent runtime', () => {
([_id, payload]) => payload?.metadata?.rawBufferTruncated === true
);
expect(truncMetaCalls).toHaveLength(0);
+
+ // raw.txt got the chunks via the batched flush.
+ const rawAppendCalls = vi.mocked(appendFile).mock.calls.filter(
+ ([path]) => typeof path === 'string' && path.endsWith('raw.txt')
+ );
+ expect(rawAppendCalls.length).toBeGreaterThan(0);
});
// ── 7. Output-buffer truncation warning + metadata flag ─────────────────────