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

perf: cap getAgent transcript hydration to a bounded tail read (#3498)

[._.]/ Adam Eivy014c67c791af
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c398274525..1614da84f3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -99,3 +99,4 @@
- **[issue-3497] The Chief of Staff no longer re-reads and re-parses its task lists on every scheduler tick** — an unchanged list is served from memory instead, which matters most on installs whose task history has grown large. Edits made outside PortOS (a text editor, a restore, a sync peer) are still picked up immediately.
- **[issue-3506] Typing in the ⌘K search bar no longer re-reads every Brain record off disk.** Brain keeps one file per record — people, projects, ideas, admin items, memory entries, links and inbox captures each live in their own directory — and unified search was opening and parsing all of them, across all seven stores, for every single character typed. On a Brain that has been in use for a while that is thousands of file reads per keystroke, which is exactly why the palette got slower the more you put into it. Search now reads a small in-memory projection of just the fields it matches on, refreshed as records change rather than rebuilt per query, so the disk is touched once per store instead of once per character. A store that is legitimately empty counts as read — otherwise the one case with nothing to cache would have kept re-scanning forever. Records arriving from a sync peer, which deliberately land without firing the usual change events so they cannot echo back around the network, now raise a local-only signal so the projection refreshes for them too; without it an inbound sync would have left search answering from a stale snapshot indefinitely. The old cap that only ever searched your 200 most recent inbox captures is gone with it — it existed solely to bound the disk cost that no longer exists.
+- **[issue-3498] Opening a long-running agent's transcript no longer loads the entire log into memory.** A completed agent's `output.txt` has no size ceiling — a multi-hour TUI run writes tens of megabytes — and every request for that agent's details read the whole file and turned each of its 50,000+ lines into its own object, spiking memory and churning the garbage collector for a view that only ever shows the end of the log. The agent detail now hydrates the tail: at most the last 1,000 lines, and never more than 512KB read off disk. Both caps are needed, not just the line one — a repaint-heavy TUI transcript spools as effectively a single enormous line with no newlines in it, so a line count alone bounds nothing. When the log is longer than that, the view says so and reports the full size on disk rather than presenting a clipped transcript as the whole thing. The bounded tail read is now one shared helper instead of the two near-identical private copies that had grown up in the TUI failure analyzer and the Codex usage scan.
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index a32015cb0b..752068fa61 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -32,7 +32,7 @@ import toast from '../../ui/Toast';
import { copyToClipboard } from '../../../lib/clipboard';
import { extractCosTaskType } from '../../../lib/cosTaskType';
import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';
-import { formatDurationMs, formatDateTime } from '../../../utils/formatters';
+import { formatBytes, formatDurationMs, formatDateTime } from '../../../utils/formatters';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
@@ -84,6 +84,30 @@ function TaskDescription({ text }) {
);
}
+// `GET /api/cos/agents/:id` hydrates a completed agent's transcript as a capped
+// TAIL rather than the whole output.txt (#3498), so keep the truncation marker
+// alongside the lines — the reader has to know the log was clipped.
+function toTranscript(data) {
+ return {
+ lines: data?.output || [],
+ truncated: Boolean(data?.outputTruncated),
+ totalBytes: data?.outputTotalBytes || 0
+ };
+}
+
+function TranscriptTruncationNotice({ transcript }) {
+ if (!transcript?.truncated) return null;
+ return (
+ <div className="flex items-center gap-1.5 text-xs text-yellow-500 mb-2">
+ <AlertTriangle size={12} aria-hidden="true" className="shrink-0" />
+ <span>
+ Showing the last {transcript.lines.length.toLocaleString()} {transcript.lines.length === 1 ? 'line' : 'lines'} — the full transcript
+ {transcript.totalBytes > 0 ? ` (${formatBytes(transcript.totalBytes)})` : ''} is on disk in the agent&apos;s output.txt.
+ </span>
+ </div>
+ );
+}
+
export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName }) {
const [expanded, setExpanded] = useState(false);
const [now, setNow] = useState(Date.now());
@@ -227,11 +251,11 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
setLoadingOutput(true);
api.getCosAgent(agent.id)
.then(data => {
- setFullOutput(data.output || []);
+ setFullOutput(toTranscript(data));
})
.catch(() => {
// Fall back to agent's stored output
- setFullOutput(agent.output || []);
+ setFullOutput(toTranscript(agent));
})
.finally(() => setLoadingOutput(false));
}
@@ -293,10 +317,10 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
return { remaining, overBy: 0, isOvertime: false };
}, [duration, durationEstimate, inactive]);
- // For running agents, use live output; for completed, use fetched full output or stored
+ // For running agents, use live output; for completed, use the fetched transcript tail or stored
const output = useMemo(() => (
inactive
- ? (fullOutput || agent.output || [])
+ ? (fullOutput?.lines || agent.output || [])
: (liveOutput || agent.output || [])
), [inactive, fullOutput, liveOutput, agent.output]);
const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;
@@ -351,7 +375,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
if (!stageAgentId || stageOutputs[stageAgentId] || loadingStageId) return;
setLoadingStageId(stageAgentId);
const data = await api.getCosAgent(stageAgentId).catch(() => null);
- setStageOutputs(prev => ({ ...prev, [stageAgentId]: data?.output || [] }));
+ setStageOutputs(prev => ({ ...prev, [stageAgentId]: toTranscript(data) }));
setLoadingStageId(null);
}, [stageOutputs, loadingStageId]);
@@ -948,8 +972,13 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
</div>
);
}
- if (stageOut && stageOut.length > 0) {
- return <OutputBlocks key={activeStage.agentId} output={stageOut} />;
+ if (stageOut?.lines.length > 0) {
+ return (
+ <>
+ <TranscriptTruncationNotice transcript={stageOut} />
+ <OutputBlocks key={activeStage.agentId} output={stageOut.lines} />
+ </>
+ );
}
return <div className="text-gray-500 text-sm">No output captured for this stage</div>;
}
@@ -967,7 +996,12 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
);
}
if (output.length > 0) {
- return <OutputBlocks output={output} />;
+ return (
+ <>
+ {inactive && <TranscriptTruncationNotice transcript={fullOutput} />}
+ <OutputBlocks output={output} />
+ </>
+ );
}
return <div className="text-gray-500 text-sm">No output captured</div>;
})()}
diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsx
index bb7446bd70..69df3e8470 100644
--- a/client/src/components/cos/tabs/AgentCard.test.jsx
+++ b/client/src/components/cos/tabs/AgentCard.test.jsx
@@ -147,3 +147,47 @@ describe('AgentCard feedback', () => {
);
});
});
+
+describe('AgentCard transcript truncation (#3498)', () => {
+ it('says the transcript was clipped when the server returns a capped tail', async () => {
+ const user = userEvent.setup();
+ api.getCosAgent.mockResolvedValue({
+ ...agent,
+ output: [{ line: 'last line', timestamp: agent.completedAt }],
+ outputTruncated: true,
+ outputTotalBytes: 12 * 1024 * 1024,
+ });
+
+ render(
+ <MemoryRouter>
+ <AgentCard agent={agent} completed />
+ </MemoryRouter>
+ );
+
+ await user.click(screen.getByRole('button', { name: 'Show' }));
+
+ expect(await screen.findByText(/Showing the last 1 line —/)).toBeInTheDocument();
+ expect(screen.getByText(/12 MB/)).toBeInTheDocument();
+ });
+
+ it('stays quiet when the whole transcript fit under the cap', async () => {
+ const user = userEvent.setup();
+ api.getCosAgent.mockResolvedValue({
+ ...agent,
+ output: [{ line: 'only line', timestamp: agent.completedAt }],
+ outputTruncated: false,
+ outputTotalBytes: 10,
+ });
+
+ render(
+ <MemoryRouter>
+ <AgentCard agent={agent} completed />
+ </MemoryRouter>
+ );
+
+ await user.click(screen.getByRole('button', { name: 'Show' }));
+
+ await waitFor(() => expect(api.getCosAgent).toHaveBeenCalledWith(agent.id));
+ expect(screen.queryByText(/Showing the last/)).not.toBeInTheDocument();
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 880237f1bb..031160b70a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -140,7 +140,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, `readFileTail(path, maxBytes)` (bounded-memory tail read for append-only logs/spools with no size ceiling — null on error vs `''` for an empty file; shared by the agent-transcript cap, the TUI failure analyzer, and the Codex rollout scan), JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
| `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index a487156687..ca60ef99d5 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -4,7 +4,7 @@
* Shared utilities for file operations used across services.
*/
-import { access, appendFile, chmod, mkdir, readFile, readdir, stat, writeFile, rename, unlink, copyFile } from 'fs/promises';
+import { access, appendFile, chmod, mkdir, open, readFile, readdir, stat, writeFile, rename, unlink, copyFile } from 'fs/promises';
import { existsSync, statSync, createReadStream } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
@@ -435,6 +435,48 @@ export async function tryReadFile(filePath, encoding = 'utf8') {
return readFile(filePath, encoding).catch(() => null);
}
+/**
+ * Read at most `maxBytes` from the END of a file, as UTF-8.
+ *
+ * The bounded-memory counterpart to `tryReadFile` for append-only logs and
+ * spools that have no upper size bound (agent transcripts, PTY spools, CLI
+ * rollout JSONL). `readFile` on one of those loads the whole thing into heap;
+ * this reads only the trailing window.
+ *
+ * Non-throwing, with the sentinel distinction the CLAUDE.md rule demands:
+ * - missing / unopenable / read error → `null`
+ * - zero-byte file → `''`
+ * so a caller can tell "nothing to read" from "couldn't read".
+ *
+ * The window starts at a BYTE offset, so when the file is larger than
+ * `maxBytes` the first line comes back partial (and can begin mid-multibyte
+ * character). Callers that split on newlines should drop that leading fragment.
+ *
+ * @param {string} path - File to read
+ * @param {number} maxBytes - Maximum trailing bytes to read
+ * @returns {Promise<string|null>} Trailing text, `''` for an empty file, or null on error
+ */
+export async function readFileTail(path, maxBytes) {
+ const info = await stat(path).catch(() => null);
+ if (!info) return null;
+ if (info.size === 0) return '';
+ const start = Math.max(0, info.size - maxBytes);
+ const length = info.size - start;
+ const handle = await open(path, 'r').catch(() => null);
+ if (!handle) return null;
+ try {
+ const buffer = Buffer.alloc(length);
+ // Honour bytesRead — the file can shrink between stat and read, or the OS
+ // can return a short read; decoding the whole `buffer` would append NULs.
+ // A read failure surfaces as null so callers keep the ''-vs-null contract.
+ const result = await handle.read(buffer, 0, length, start).catch(() => null);
+ if (result === null) return null;
+ return buffer.toString('utf8', 0, result.bytesRead);
+ } finally {
+ await handle.close().catch(() => {});
+ }
+}
+
// Private sentinel for "the parse produced nothing usable". A unique Symbol, NOT
// null/undefined — a file whose real contents parse to the caller's defaultValue
// must stay distinguishable from a file that failed to parse at all, and any
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 4850e1b743..8da5a9a4dd 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -38,6 +38,7 @@ import {
readJSONLines,
writeJSONLines,
formatDuration,
+ readFileTail,
sha256File,
resolveImageInputPath,
resolveScreenshot,
@@ -1076,6 +1077,41 @@ describe('fileUtils', () => {
});
});
+ describe('readFileTail', () => {
+ let dir;
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'portos-tail-')); });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+ it('returns null for a missing file so it stays distinct from an empty one', async () => {
+ expect(await readFileTail(join(dir, 'nope.txt'), 1024)).toBeNull();
+ });
+
+ it('returns an empty string for a zero-byte file', async () => {
+ const p = join(dir, 'empty.txt');
+ writeFileSync(p, '');
+ expect(await readFileTail(p, 1024)).toBe('');
+ });
+
+ it('returns the whole file when it fits under maxBytes', async () => {
+ const p = join(dir, 'small.txt');
+ writeFileSync(p, 'hello');
+ expect(await readFileTail(p, 1024)).toBe('hello');
+ });
+
+ it('returns only the trailing window when the file is larger than maxBytes', async () => {
+ const p = join(dir, 'big.txt');
+ writeFileSync(p, 'abcdefghij');
+ expect(await readFileTail(p, 4)).toBe('ghij');
+ });
+
+ it('does not load the whole file for a multi-MB log', async () => {
+ const p = join(dir, 'huge.log');
+ writeFileSync(p, Buffer.alloc(4 * 1024 * 1024, 0x61));
+ const tail = await readFileTail(p, 128);
+ expect(tail).toHaveLength(128);
+ });
+ });
+
describe('expandHome', () => {
it('expands a bare `~` to the homedir', () => {
expect(expandHome('~')).toBe(homedir());
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 74b2d0985e..b713700342 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -16,6 +16,13 @@ const router = Router();
// shape so a non-string body can't store `[object Object]`.
const pauseBodySchema = z.object({ reason: z.string().max(500).optional() });
+// GET /agents/:id?lines=N — how many TAIL transcript lines to hydrate. The
+// service defaults to `AGENT_OUTPUT_TAIL_LINES` and the ceiling here keeps a
+// hand-written query from re-opening the unbounded read this cap closed (#3498).
+const agentQuerySchema = z.object({
+ lines: z.coerce.number().int().positive().max(10000).optional()
+});
+
// GET /api/cos/health - Get health status
router.get('/health', asyncHandler(async (req, res) => {
const health = await cos.getHealthStatus();
@@ -52,9 +59,10 @@ router.get('/agents/history/:date', asyncHandler(async (req, res) => {
res.json(agents);
}));
-// GET /api/cos/agents/:id - Get agent by ID
+// GET /api/cos/agents/:id - Get agent by ID (transcript hydrated as a capped tail)
router.get('/agents/:id', asyncHandler(async (req, res) => {
- const agent = await cos.getAgent(req.params.id);
+ const { lines } = validateRequest(agentQuerySchema, req.query);
+ const agent = await cos.getAgent(req.params.id, lines ? { limit: lines } : {});
if (!agent) {
throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
}
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 9fd4ee8cd5..da61a4a458 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -665,9 +665,10 @@ export async function cleanupOrphanedAgents() {
if (agent.taskId) {
// Carry the agent's metadata forward rather than re-reading the record
- // later: `getAgent` on a completed agent re-splits its whole output.txt
- // transcript, and the worktree fields the resume pointer needs are
- // stamped once at registerAgent and never mutated.
+ // later: `getAgent` on a completed agent still hits the disk to hydrate
+ // its output.txt tail (capped since #3498, but not free), and the
+ // worktree fields the resume pointer needs are stamped once at
+ // registerAgent and never mutated.
orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id, agentMetadata: agent.metadata });
}
}
diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.js
index c64bf21618..2ac97df903 100644
--- a/server/services/agentTuiSpawning/finalizeHelpers.js
+++ b/server/services/agentTuiSpawning/finalizeHelpers.js
@@ -9,10 +9,16 @@
*/
import { join } from 'path';
-import { open, stat as fsStat, writeFile } from 'fs/promises';
+import { writeFile } from 'fs/promises';
import * as git from '../git.js';
+import { readFileTail } from '../../lib/fileUtils.js';
import { analyzeAgentFailure } from '../agentErrorAnalysis.js';
+// Re-exported so this module's existing importers (and its tests) keep their
+// entry point after the implementation moved to lib/fileUtils.js (#3498) —
+// `getAgent`'s transcript cap needed the same bounded tail read.
+export { readFileTail };
+
// Tail-read window for raw.txt at failure analysis. analyzeAgentFailure narrows
// further (ANSI-stripped, last ~200 lines AND ≤16K chars), so reading the whole
// file (which has no upper bound for long-running agents) would reintroduce the
@@ -22,37 +28,6 @@ import { analyzeAgentFailure } from '../agentErrorAnalysis.js';
// peak finalize memory bounded.
export 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. 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.
- */
-export async function readFileTail(path, maxBytes) {
- const st = await fsStat(path).catch(() => null);
- if (!st) return null;
- if (st.size === 0) return '';
- const start = Math.max(0, st.size - maxBytes);
- const length = st.size - start;
- const fh = await open(path, 'r').catch(() => null);
- if (!fh) return null;
- try {
- const buf = Buffer.alloc(length);
- // 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. Read failures surface as null so
- // callers can distinguish "empty file" ('') from "read error" (null) —
- // a `bytesRead: 0` fallback would conflate the two.
- const readResult = await fh.read(buf, 0, length, start).catch(() => null);
- if (readResult === null) return null;
- return buf.toString('utf8', 0, readResult.bytesRead);
- } finally {
- await fh.close().catch(() => {});
- }
-}
-
/**
* Check if a worktree has any uncommitted changes. Returns true when the
* working tree is dirty (staged or unstaged changes exist). Used to gate
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index af5dc50500..4fbb27639a 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -10,13 +10,13 @@
* (#3450) — callers import from here directly.
*/
-import { readFile, writeFile, rename, readdir, rm } from 'fs/promises';
+import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents } from './cosEvents.js';
import { ServerError } from '../lib/errorHandler.js';
import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
-import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readFileTail, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { recordDomainUsage } from './domainUsage.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
import { loadAgentIndex, saveAgentIndex, getAgentDir } from './cosAgentIndex.js';
@@ -399,25 +399,85 @@ export async function getAgentRecord(agentId) {
return { ...rest, id: raw.id || raw.agentId || agentId, status: raw.status || 'completed' };
}
-export async function getAgent(agentId) {
+// Transcript read caps for `getAgent` (#3498). `output.txt` is append-only and
+// has no upper bound — a long TUI run writes tens of MB — so reading it whole
+// and mapping EVERY line to a `{ line, timestamp }` object spiked heap by
+// ~2x the file size per request. Both caps are load-bearing and neither
+// subsumes the other:
+// - the LINE cap bounds the object count (the allocation the issue is about)
+// - the BYTE cap bounds the string read, because a repaint-heavy TUI spool
+// can be one multi-MB "line" with no newlines at all, on which a
+// line-based tail is a no-op.
+export const AGENT_OUTPUT_TAIL_LINES = 1000;
+export const AGENT_OUTPUT_TAIL_BYTES = 512 * 1024;
+
+/**
+ * Tail an agent's `output.txt` into the `{ line, timestamp }` shape the UI
+ * renders, reading at most `maxBytes` from the end of the file and keeping at
+ * most `limit` lines.
+ *
+ * Deliberately tail-only: an `offset` from the head of the file would have to
+ * read everything before it, which is the exact cost this cap exists to avoid.
+ * The interesting end of an agent transcript is the end (that's where the
+ * failure and the summary are), so the trailing window is what callers want.
+ *
+ * @returns {Promise<{ lines: string[], truncated: boolean, totalBytes: number }|null>}
+ * null when the file is missing or unreadable. `totalBytes` is the
+ * size of the WHOLE transcript on disk, not of the window returned.
+ */
+async function readAgentTranscriptTail(outputFile, { limit, maxBytes }) {
+ // Stat separately from the tail read: the caller needs the FULL on-disk size
+ // for the truncation marker, and `readFileTail` only hands back the window.
+ const info = await stat(outputFile).catch(() => null);
+ if (!info) return null;
+ const text = await readFileTail(outputFile, maxBytes);
+ if (text === null) return null;
+ const clippedByBytes = info.size > maxBytes;
+ // The byte window can start mid-line (and mid-multibyte-character), so drop
+ // the leading fragment rather than surfacing a garbled partial line.
+ const split = text.split('\n');
+ const lines = (clippedByBytes ? split.slice(1) : split).filter(line => line.trim());
+ const clippedByLines = lines.length > limit;
+ return {
+ lines: clippedByLines ? lines.slice(-limit) : lines,
+ truncated: clippedByBytes || clippedByLines,
+ totalBytes: info.size
+ };
+}
+
+/**
+ * The agent record hydrated with the TAIL of its on-disk transcript.
+ *
+ * Callers that only need the record's fields should use `getAgentRecord` —
+ * this one still touches the filesystem. When the transcript is longer than
+ * the caps, the result carries `outputTruncated: true` so the UI can say the
+ * transcript was clipped instead of silently presenting a partial log as whole.
+ *
+ * @param {string} agentId
+ * @param {Object} [options]
+ * @param {number} [options.limit=AGENT_OUTPUT_TAIL_LINES] - Max transcript lines to return (from the tail)
+ * @param {number} [options.maxBytes=AGENT_OUTPUT_TAIL_BYTES] - Max bytes to read from the end of output.txt
+ */
+export async function getAgent(agentId, { limit = AGENT_OUTPUT_TAIL_LINES, maxBytes = AGENT_OUTPUT_TAIL_BYTES } = {}) {
let agent = await getAgentRecord(agentId);
if (!agent) return null;
// Completed agents live in date buckets; paused agents remain in the flat
- // agent dir but should still expose their preserved full transcript.
+ // agent dir but should still expose their preserved transcript.
if (agent.status === 'completed' || agent.status === 'paused') {
const dateStr = agent.status === 'completed' ? agent.completedAt?.slice(0, 10) : null;
const agentDir = dateStr ? getAgentDir(agentId, dateStr) : getAgentDir(agentId);
const repaired = await repairCodexTaskSummary(agentDir, agent);
if (repaired) agent = { ...agent, metadata: { ...agent.metadata, taskSummary: repaired } };
const outputFile = join(agentDir, 'output.txt');
- if (existsSync(outputFile)) {
- const fullOutput = await readFile(outputFile, 'utf-8');
- const lines = fullOutput.split('\n').filter(line => line.trim());
+ const tail = await readAgentTranscriptTail(outputFile, { limit, maxBytes });
+ if (tail) {
const timestamp = agent.completedAt || agent.pausedAt;
return {
...agent,
- output: lines.map(line => ({ line, timestamp }))
+ output: tail.lines.map(line => ({ line, timestamp })),
+ outputTruncated: tail.truncated,
+ outputTotalBytes: tail.totalBytes
};
}
}
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index a6ebec35fe..06868a6e68 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -46,7 +46,7 @@ vi.mock('fs/promises', async (importOriginal) => {
};
});
-import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent } from './cosAgentLifecycle.js';
+import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
import { saveState } from './cosState.js';
import { recordDomainUsage } from './domainUsage.js';
import { cosEvents } from './cosEvents.js';
@@ -82,6 +82,81 @@ describe('cosAgentLifecycle', () => {
{ line: 'full line one', timestamp: pausedAt },
{ line: 'full line two', timestamp: pausedAt }
]);
+ expect(agent.outputTruncated).toBe(false);
+ });
+
+ // #3498: output.txt is unbounded — a long TUI run writes tens of MB. Reading it
+ // whole and mapping EVERY line to an object spiked heap on a single request.
+ describe('transcript tail caps (#3498)', () => {
+ const writeCompleted = async (agentId, completedAt, contents) => {
+ mockCosState.state.agents[agentId] = { id: agentId, status: 'completed', completedAt, metadata: {}, output: [] };
+ const dir = join(mockCosState.agentsDir, completedAt.slice(0, 10), agentId);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'output.txt'), contents);
+ return dir;
+ };
+
+ it('returns only the tail lines and flags the transcript as truncated', async () => {
+ const completedAt = '2026-05-25T12:00:00.000Z';
+ const contents = Array.from({ length: 5000 }, (_, i) => `line ${i}`).join('\n');
+ await writeCompleted('agent-long', completedAt, contents);
+
+ const agent = await getAgent('agent-long', { limit: 10 });
+
+ expect(agent.output).toHaveLength(10);
+ expect(agent.output[0]).toEqual({ line: 'line 4990', timestamp: completedAt });
+ expect(agent.output[9]).toEqual({ line: 'line 4999', timestamp: completedAt });
+ expect(agent.outputTruncated).toBe(true);
+ expect(agent.outputTotalBytes).toBe(Buffer.byteLength(contents));
+ });
+
+ it('caps by BYTES too, so a newline-free TUI transcript cannot blow memory', async () => {
+ // A repainted TUI screen spools as effectively one enormous line, on which
+ // a line-based tail is a no-op — the byte cap is what bounds it.
+ const completedAt = '2026-05-26T12:00:00.000Z';
+ const contents = 'x'.repeat(200_000);
+ await writeCompleted('agent-oneline', completedAt, contents);
+
+ const agent = await getAgent('agent-oneline', { maxBytes: 1024 });
+
+ // The leading partial line is dropped, so a single over-cap line yields none.
+ expect(agent.output).toEqual([]);
+ expect(agent.outputTruncated).toBe(true);
+ expect(agent.outputTotalBytes).toBe(200_000);
+ });
+
+ it('drops the partial leading line the byte window starts mid-way through', async () => {
+ const completedAt = '2026-05-27T12:00:00.000Z';
+ const contents = `${'a'.repeat(50)}\nbbbb\ncccc\n`;
+ await writeCompleted('agent-partial', completedAt, contents);
+
+ const agent = await getAgent('agent-partial', { maxBytes: 20 });
+
+ expect(agent.output.map(o => o.line)).toEqual(['bbbb', 'cccc']);
+ expect(agent.outputTruncated).toBe(true);
+ });
+
+ it('applies the default caps when no options are passed', async () => {
+ const completedAt = '2026-05-28T12:00:00.000Z';
+ const contents = Array.from({ length: AGENT_OUTPUT_TAIL_LINES + 500 }, (_, i) => `line ${i}`).join('\n');
+ await writeCompleted('agent-default', completedAt, contents);
+
+ const agent = await getAgent('agent-default');
+
+ expect(agent.output).toHaveLength(AGENT_OUTPUT_TAIL_LINES);
+ expect(agent.outputTruncated).toBe(true);
+ });
+
+ it('leaves the record untouched when output.txt is missing', async () => {
+ const completedAt = '2026-05-29T12:00:00.000Z';
+ mockCosState.state.agents['agent-nofile'] = { id: 'agent-nofile', status: 'completed', completedAt, metadata: {}, output: [] };
+ await mkdir(join(mockCosState.agentsDir, '2026-05-29', 'agent-nofile'), { recursive: true });
+
+ const agent = await getAgent('agent-nofile');
+
+ expect(agent.output).toEqual([]);
+ expect(agent).not.toHaveProperty('outputTruncated');
+ });
});
it('persists post-completion metadata updates in the archived agent record', async () => {
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 70c81584ef..67038a5688 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -1,4 +1,4 @@
-import { open, readdir, readFile, stat } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { homedir } from 'os';
import { join } from 'path';
import { getAllProviders } from './providers.js';
@@ -8,6 +8,7 @@ import { isGrokCommand } from '../lib/grok.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
import { parseHumanReset } from '../lib/quotaReset.js';
+import { readFileTail } from '../lib/fileUtils.js';
import { getSettings } from './settings.js';
import { getImageGenQuota, IMAGE_GEN_FAMILY } from './imageGenQuota.js';
import { enabledCloudImageModes } from './imageGen/modes.js';
@@ -163,23 +164,10 @@ async function listCodexRolloutFiles(codexHome) {
return files;
}
-async function readFileTail(file, bytes) {
- const info = await stat(file);
- if (info.size <= bytes) return readFile(file, 'utf-8');
- const handle = await open(file, 'r');
- try {
- const buffer = Buffer.alloc(bytes);
- await handle.read(buffer, 0, bytes, info.size - bytes);
- return buffer.toString('utf-8');
- } finally {
- await handle.close();
- }
-}
-
async function fetchCodexQuota({ codexHome = codexHomeDir() } = {}) {
const files = await listCodexRolloutFiles(codexHome);
for (const file of files) {
- const tail = await readFileTail(file, CODEX_TAIL_BYTES).catch(() => null);
+ const tail = await readFileTail(file, CODEX_TAIL_BYTES);
if (!tail) continue;
const found = parseCodexRateLimits(tail);
if (found) return mapCodexQuota(found.rateLimits, found.timestamp);