The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): never replay a long session's history live after a daemon restart (#374)
Deeffae0c37a265
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex bacc4adb4..811ede74f 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -238,6 +238,7 @@ import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfileimport { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'import { deviceErrorText } from './lib/deviceErrors.js'import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'+import { transcriptIsFirstTurn } from './lib/firstTurnReplay.js'// Before ANY child is spawned: on Linux an absent locale makes tmux and ps mangle their output,// which silently costs the daemon every pane it would have discovered. See lib/childLocale.ts.ensureUtf8Locale()@@ -2138,7 +2139,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {*/const neverFoldedHistory = new Set<string>()/**- * Sessions whose first turn has already been replayed live by an attach.+ * Sessions whose first turn has already been replayed live by an attach, or whose transcript an attach+ * has already folded.** NOT the same question as `neverFoldedHistory` above, which is why they stay two sets: that one asks* "where should the watcher start reading?", this one asks "has this session's file already been@@ -2462,7 +2464,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// `reset` attach (claude fires `SessionStart` on compact, which resets) would fold the by-then// complete transcript and emit it live on top of everything the watcher had already streamed. That// is the same duplicate-turn class this whole change exists to remove.- if (replayLive) replayedFirstTurn.add(session.sessionId)+ // Any fold of a transcript with content counts too: the watcher now tails it from the end, so a later+ // replay could only send history out again as if it were live.+ if (replayLive || lines.length) replayedFirstTurn.add(session.sessionId)if (initialEvents.length) {emitSessionEvents(session.sessionId, initialEvents)console.log(`[agent] ${sid(session.agentId)} replayed the first turn its transcript already held · ${initialEvents.length} events`)@@ -3172,10 +3176,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {// so the birth-vs-`registeredAt` comparison stays, and comparing against `boundAt` instead — the// obvious-looking alternative, since `boundAt` is when this session was bound — does not work: the// transcript is created a moment BEFORE the hook binds it.- const bornAfterAgent = !meta.rebound && entry.boundAt !== null- && entry.boundAt - entry.registeredAt > 0- && !!entry.transcriptPath- && await statBirthMs(entry.transcriptPath) >= entry.registeredAt+ //+ // And only while the file is new (`transcriptIsFirstTurn`): a long session's transcript was born after+ // its agent too, and after a daemon restart its next SessionStart replayed the whole history live.+ const bornAfterAgent = transcriptIsFirstTurn(+ entry,+ entry.transcriptPath ? await statBirthMs(entry.transcriptPath) : 0,+ { rebound: !!meta.rebound, now: Date.now() },+ )const attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)if (!attached) {registry.unbindSession(entry.sessionId)diff --git a/cli/src/lib/firstTurnReplay.spec.ts b/cli/src/lib/firstTurnReplay.spec.tsnew file mode 100644index 000000000..00cd0a5fd--- /dev/null+++ b/cli/src/lib/firstTurnReplay.spec.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest'+import { FIRST_TURN_WINDOW_MS, transcriptIsFirstTurn } from './firstTurnReplay.js'++const registeredAt = Date.parse('2026-09-25T13:35:00Z')+const entry = { registeredAt, boundAt: registeredAt + 20_000, transcriptPath: '/t/rollout.jsonl' }+const birth = registeredAt + 18_000++describe('transcriptIsFirstTurn', () => {+ it('replays a transcript that appeared after its agent, moments ago', () => {+ expect(transcriptIsFirstTurn(entry, birth, { rebound: false, now: birth + 2_000 })).toBe(true)+ })++ it('never replays a long session again: a restart forgets the replay, the file stays old', () => {+ // The crash: two days later, a SessionStart after a daemon restart replayed 346 MB live.+ expect(transcriptIsFirstTurn(entry, birth, { rebound: false, now: birth + 2 * 86_400_000 })).toBe(false)+ expect(transcriptIsFirstTurn(entry, birth, { rebound: false, now: birth + FIRST_TURN_WINDOW_MS })).toBe(false)+ })++ it('keeps a first turn announced a few minutes after the file appeared', () => {+ expect(transcriptIsFirstTurn(entry, birth, { rebound: false, now: birth + FIRST_TURN_WINDOW_MS - 1 })).toBe(true)+ })++ it('folds a resumed transcript, older than its agent, as history', () => {+ expect(transcriptIsFirstTurn(entry, registeredAt - 81_500, { rebound: false, now: birth })).toBe(false)+ })++ it('folds when the session was rebound, unbound, has no file, or its birth is unreadable', () => {+ const now = birth + 1_000+ expect(transcriptIsFirstTurn(entry, birth, { rebound: true, now })).toBe(false)+ expect(transcriptIsFirstTurn({ ...entry, boundAt: null }, birth, { rebound: false, now })).toBe(false)+ expect(transcriptIsFirstTurn({ ...entry, boundAt: registeredAt }, birth, { rebound: false, now })).toBe(false)+ expect(transcriptIsFirstTurn({ ...entry, transcriptPath: null }, birth, { rebound: false, now })).toBe(false)+ expect(transcriptIsFirstTurn(entry, 0, { rebound: false, now })).toBe(false)+ })+})diff --git a/cli/src/lib/firstTurnReplay.ts b/cli/src/lib/firstTurnReplay.tsnew file mode 100644index 000000000..13c0cfedb--- /dev/null+++ b/cli/src/lib/firstTurnReplay.ts@@ -0,0 +1,41 @@+/**+ * When an attach may emit a transcript LIVE instead of folding it away as history.+ *+ * A session can be announced before its transcript exists, and the announcement that finally carries+ * the path then reports `isNew=false`. Folding that file as history would swallow the agent's first+ * turn, so a transcript born after its agent registered is replayed live, once (cli.ts+ * `attachSessionNow`).+ *+ * "Born after its agent" alone stays true for the whole life of an ordinary session: every fresh+ * session's transcript appears a few seconds after its agent registers. The only other guard against+ * a second replay was an in-memory set, empty after a daemon restart. So the first `SessionStart` a+ * long session fired after a restart (Claude compacting, Codex resuming) replayed its whole history+ * live. Measured on one machine: 3,553 events from a 346 MB Codex rollout overflowed the outbound+ * queue and exhausted the 4 GB heap. The daemon restarted, the next session did the same, and it+ * crashed again every minute or so.+ *+ * The first turn's announcement arrives while the file is new; a transcript that has existed for+ * longer than {@link FIRST_TURN_WINDOW_MS} is history, whatever the daemon remembers.+ */++/** How new a transcript must be for its content to count as the agent's first turn. */+export const FIRST_TURN_WINDOW_MS = 10 * 60_000++export interface FirstTurnCandidate {+ registeredAt: number+ boundAt: number | null+ transcriptPath?: string | null+}++/** Whether this announcement's transcript is the agent's first turn, to be replayed live. */+export function transcriptIsFirstTurn(+ entry: FirstTurnCandidate,+ /** When the transcript file was created, epoch ms; 0 when it could not be read. */+ birthMs: number,+ options: { rebound: boolean; now: number },+): boolean {+ if (options.rebound || entry.boundAt === null || !entry.transcriptPath) return false+ if (entry.boundAt - entry.registeredAt <= 0) return false+ if (birthMs < entry.registeredAt) return false+ return options.now - birthMs < FIRST_TURN_WINDOW_MS+}