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: record stderr-only output, agree with the read path in stats, and name a failed detail fetch (#4540)
[._.]/ Adam Eivya0edf91754df
diff --git a/client/src/components/cos/tabs/RunEventsTab.jsx b/client/src/components/cos/tabs/RunEventsTab.jsxindex 5b5ab115c8..dae94020ce 100644--- a/client/src/components/cos/tabs/RunEventsTab.jsx+++ b/client/src/components/cos/tabs/RunEventsTab.jsx@@ -106,8 +106,11 @@ export default function RunEventsTab() {}let cancelled = false;setDetailLoading(true);+ // `null` is the same could-not-fetch sentinel the list uses. Falling back to+ // an empty diagnostic would render "this run has no events" — a statement+ // about the ledger — for what is actually a statement about the network.api.getRunEventDiagnostic(selectedId, { silent: true })- .catch(() => ({ projection: null, events: [] }))+ .catch(() => null).then((next) => {if (cancelled) return;setDetail(next);@@ -200,7 +203,10 @@ export default function RunEventsTab() {</p>)}{selectedId && detailLoading && <BrailleSpinner text="Replaying" />}- {selectedId && !detailLoading && <RunDiagnostic detail={detail} />}+ {selectedId && !detailLoading && detail === null && (+ <Banner tone="error">Could not load this run's events.</Banner>+ )}+ {selectedId && !detailLoading && detail !== null && <RunDiagnostic detail={detail} />}</div></div>)}diff --git a/client/src/components/cos/tabs/RunEventsTab.test.jsx b/client/src/components/cos/tabs/RunEventsTab.test.jsxindex 4405cfccc5..0813d46c07 100644--- a/client/src/components/cos/tabs/RunEventsTab.test.jsx+++ b/client/src/components/cos/tabs/RunEventsTab.test.jsx@@ -139,3 +139,28 @@ describe('summarizeEventData', () => {expect(summarizeEventData({ branch: null, category: 'pr-missing' })).toBe('category=pr-missing');});});++describe('RunEventsTab — a failed detail fetch is not an empty run', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getRunEventStats.mockResolvedValue(STATS);+ api.getRunEventProjections.mockResolvedValue([projection()]);+ });++ it('says the fetch failed rather than "this run has no events"', async () => {+ // One is a statement about the ledger, the other about the network. The+ // reassuring "may have aged out" copy would hide the second behind the first.+ api.getRunEventDiagnostic.mockRejectedValue(new Error('offline'));+ renderTab('/cos/run-events?run=run-a');++ expect(await screen.findByText(/Could not load this run's events/)).toBeInTheDocument();+ expect(screen.queryByText(/may have aged out/)).not.toBeInTheDocument();+ });++ it('still says "no events in the ledger" when the server genuinely has none', async () => {+ api.getRunEventDiagnostic.mockResolvedValue({ projection: null, events: [] });+ renderTab('/cos/run-events?run=run-a');++ expect(await screen.findByText(/may have aged out/)).toBeInTheDocument();+ });+});diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 5c65817df7..2debbdfd86 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -439,6 +439,30 @@ export async function spawnDirectly({// `run.output` for a run that has produced nothing — the exact case (a// provider that never spoke) the ledger is supposed to make visible.let firstOutputRecorded = false;+ /**+ * Record the run's first observed output, once (#4540) — never per chunk. A+ * per-chunk event would make the ledger a copy of the output it deliberately+ * redacts and would exhaust the retention bound in minutes. What the one event+ * buys is time-to-first-output: a run that stalled after speaking and a run+ * that never spoke at all are indistinguishable in the mutable record.+ *+ * Called from BOTH streams. Several providers say everything they have to say+ * on stderr (codex's whole progress feed is stderr), and that output lands in+ * the same transcript — a stdout-only recorder would file those runs as silent.+ * The explicit key keeps the append idempotent however the two callers race.+ */+ const recordFirstOutput = (source, chars) => {+ if (firstOutputRecorded) return;+ firstOutputRecorded = true;+ return appendRunEvent({+ kind: 'run.output',+ runId,+ agentId,+ taskId: task.id,+ eventId: `output:${agentId}:${runId || 'no-run'}:first`,+ data: { source, firstChunkChars: chars },+ });+ };const outputFile = join(agentDir, 'output.txt');const isStreamJson = cliConfig.streamFormat === 'stream-json';const streamParser = isStreamJson ? createStreamJsonParser() : null;@@ -528,23 +552,7 @@ export async function spawnDirectly({// Serialize the transcript body so two `data` events can't interleave their// awaits and reorder output.txt / the batched live tail.enqueueTranscriptWrite(async () => {- if (!firstOutputRecorded) {- firstOutputRecorded = true;- // Once per run, on the FIRST real byte (#4540) — never per chunk. A- // per-chunk event would make the ledger a copy of the output it- // deliberately redacts and would exhaust the retention bound in- // minutes. What this one event buys is time-to-first-output: a run- // that stalled after speaking and a run that never spoke at all are- // indistinguishable in the mutable record.- await appendRunEvent({- kind: 'run.output',- runId,- agentId,- taskId: task.id,- eventId: `output:${agentId}:${runId || 'no-run'}:first`,- data: { source: 'cli-stdout', firstChunkChars: text.length },- });- }+ await recordFirstOutput('cli-stdout', text.length);if (!hasStartedWorking) {hasStartedWorking = true;await updateAgent(agentId, { metadata: { phase: 'working' } });@@ -579,6 +587,7 @@ export async function spawnDirectly({// Synchronous fallback detection before the serialized write (see stdout).stopForImmediateFallbackSignal(`[stderr] ${text}`);enqueueTranscriptWrite(async () => {+ await recordFirstOutput('cli-stderr', text.length);// Codex stderr: show thinking + tool names, skip config dump and command outputif (codexStderrFormatter) {const lines = codexStderrFormatter.processChunk(text);diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 23a7524bd7..2c02e013d8 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -588,6 +588,24 @@ describe('stream error containment', () => {await spawnPromise.catch(() => {});});+ it('counts stderr-only output too — several providers say everything there', async () => {+ // codex's entire progress feed is stderr and lands in the same transcript.+ // A stdout-only recorder would file those runs as having produced nothing.+ appendRunEvent.mockClear();+ const spawnPromise = spawnDirectly(minimalArgs);+ await new Promise((r) => setTimeout(r, 10));++ fakeProcess.stderr.emit('data', Buffer.from('thinking...\n'));+ await new Promise((r) => setTimeout(r, 20));++ const outputs = appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.output');+ expect(outputs).toHaveLength(1);+ expect(outputs[0].data).toMatchObject({ source: 'cli-stderr' });++ fakeProcess.emit('close', 0);+ await spawnPromise.catch(() => {});+ });+it('records no run.output for a run that never produced any', async () => {// The 3s initialization timer flips the record to "working" with nothing// behind it, which is exactly the run this boundary must NOT vouch for.diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 6f2ca7967d..8c75c73fd8 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -878,6 +878,11 @@ export async function spawnViaRunner(agentId, task, opts) {agentId,taskId: task.id,eventId: `handoff:${agentId}:${runId || 'no-run'}:rejected`,+ // `accepted: false` mirrors what the finalize below already concludes. Note+ // that the runner spawn path cannot currently tell an explicit refusal from+ // an ambiguous transport failure (a lost acknowledgement for a spawn the+ // runner DID accept) — a pre-existing conflation this event inherits rather+ // than introduces. Tracked in #4615.data: { to: 'none', accepted: false, reason: message },});releaseAgentLane({ agentId, success: false, exitCode: 1, executionId, laneName, errorExecutionMessage: message });diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex 7470830954..c1828cdfa3 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -170,15 +170,17 @@ function expiryCutoff(now = Date.now()) {}/**- * Is this event still inside the age window?+ * Would a reader see this line — i.e. is it structurally sound AND still inside+ * the age window?*- * A line with no usable `at` is treated as NOT fresh. That is deliberate: `at`- * is required by the envelope schema, so a line without one is corrupt or- * truncated, the read path already drops it, and leaving it on disk would let- * unreadable bytes accumulate forever under a retention policy that can never- * date them. Pruning is the only thing that ever cleans them up.+ * One predicate, used by the read path, the stats, and the prune, so all three+ * agree by construction. A structurally invalid or undatable line counts as+ * NOT retained: the read path drops it either way, so counting it would make+ * the stats disagree with the endpoint they describe, and leaving it on disk+ * would let unreadable bytes accumulate forever under a retention policy that+ * can never date them. The prune is the only thing that ever cleans them up.*/-const isFresh = (event, cutoff) => typeof event?.at === 'string' && event.at > cutoff;+const isRetained = (event, cutoff) => isStoredRunEvent(event) && event.at > cutoff;/*** Rewrite both generations without their expired events, and drop the expired@@ -200,8 +202,8 @@ async function pruneExpired({ now = Date.now(), force = false } = {}) {readJSONLFile(ACTIVE_PATH)]);- const keptArchive = archive.filter((e) => isFresh(e, cutoff));- const keptActive = active.filter((e) => isFresh(e, cutoff));+ const keptArchive = archive.filter((e) => isRetained(e, cutoff));+ const keptActive = active.filter((e) => isRetained(e, cutoff));const dropped = (archive.length - keptArchive.length) + (active.length - keptActive.length);if (dropped === 0) return;@@ -307,8 +309,9 @@ export async function readRunEvents({ runId, agentId, taskId, kind, since, limit// A line that fails the STRUCTURAL check is a corrupt/truncated write, not// data — dropping it keeps one bad line from poisoning the whole projection.// The check deliberately admits kinds this build does not know (see- // `isStoredRunEvent`): a newer install's ledger must still read here.- let events = [...archive, ...active].filter((e) => isStoredRunEvent(e) && isFresh(e, cutoff));+ // `isStoredRunEvent`): a newer install's ledger must still read here. The+ // same predicate bounds the age, so a reader never sees an expired event.+ let events = [...archive, ...active].filter((e) => isRetained(e, cutoff));if (runId) events = events.filter((e) => e.runId === runId);if (agentId) events = events.filter((e) => e.agentId === agentId);@@ -368,11 +371,11 @@ export async function getRunEventLedgerStats() {readJSONLFile(ARCHIVE_PATH),readJSONLFile(ACTIVE_PATH)]);- // Counted the way a reader sees them (fresh only), so "stats say 40 events"- // and "the events endpoint returns 40" can never disagree.+ // Counted through the SAME predicate the read path uses, so "stats say 40+ // events" and "the events endpoint returns 40" can never disagree.const cutoff = expiryCutoff();- const freshArchive = archive.filter((e) => isFresh(e, cutoff));- const freshActive = active.filter((e) => isFresh(e, cutoff));+ const freshArchive = archive.filter((e) => isRetained(e, cutoff));+ const freshActive = active.filter((e) => isRetained(e, cutoff));const oldest = freshArchive[0]?.at ?? freshActive[0]?.at ?? null;return {activeEvents: freshActive.length,diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.jsindex 83c03daea8..626e82ed4f 100644--- a/server/services/agentRunEventLog.test.js+++ b/server/services/agentRunEventLog.test.js@@ -385,3 +385,18 @@ describe('retention — dedupe and the age bound agree (#4540)', () => {expect(await appendRunEvent({ ...event })).toMatchObject({ appended: true, duplicate: false });});});++describe('retention — one predicate for reads, stats, and the prune (#4540)', () => {+ it('does not count a corrupt line the read path refuses to return', async () => {+ // Otherwise "stats say 2 events" and "the events endpoint returns 1"+ // disagree, and the stats are the thing a reader consults to decide whether+ // a missing run aged out or was never recorded.+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', at: '2026-08-18T12:00:00.000Z' });+ writeFileSync(ACTIVE, `${readFileSync(ACTIVE, 'utf8')}{"eventId":"x","kind":"run.spawned","at":"2026-08-18T12:30:00.000Z"}\n`);+ restartServer();++ const stats = await getRunEventLedgerStats();+ expect(stats.activeEvents).toBe(1);+ expect(await readRunEvents()).toHaveLength(1);+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 8d114a378a..5d0cf074c8 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1213,6 +1213,7 @@ export async function spawnTuiAgent({agentId,taskId: task.id,eventId: `handoff:${agentId}:${runId || 'no-run'}:rejected`,+ // Same refusal-vs-lost-acknowledgement conflation as the CLI path (#4615).data: { to: 'none', accepted: false, kind: 'tui', reason: message },});}