Repository navigation
Make the structured turn lifecycle row durable so completed durations survive - #19695
Conversation
… survive A structured-chat turn used to end by tombstoning its running lifecycle item, which threw away the only durable record of when the turn ended. Completed "Worked for" labels therefore depended on the renderer having observed the turn finish, and vanished on reopen. The lifecycle item is now revised in place, never tombstoned: - running, with startedAt, at the provider's turn start - completed or interrupted, with completedAt, at the provider's terminal frame, a user stop, or a child exit the host observed - unverifiable, with no end, when a cold acquire finds a running row from a generation whose exit nobody observed Both timestamps are the execution host's clock at receipt, captured before the deferred sink, so the completed value is identical on every client and needs no client clock. Codex history restore uses the provider's own second-granular endpoints for turns that predate this change. Desktop and mobile read settled durations off the journal through one shared selector, and anchor the live counter on the host start with the client's local receipt so a skewed client clock never leaks into the label. Locally observed durations remain the fallback for hosts that still tombstone. Timestamps live inside the existing turnLifecycle field, which old clients strip, and every working-state consumer keys on state === 'running', so no capability negotiation is needed.
5c71a85 to
ff55fcc
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
This PR makes the structured turn lifecycle row a durable, revised-in-place fact instead of a tombstoned transient, so "Worked for N" survives reload, restart, mobile, and remote hosts.
- Four-state lifecycle row —
AgentJournalTurnLifecycleStategrowsinterrupted/unverifiable; the row opensrunningwithstartedAtand settles to a terminal state withcompletedAt(or no end forunverifiable). - Host-clock endpoints — both providers stamp
startedAt/completedAton the execution host's clock at provider-event receipt, before the deferred sink; the running row's journalobservedAtis pinned tostartedAt. - Codex turn boundaries —
CodexJournalTurnBoundariesreplaces inline start/complete, settlement writes items (guarded byprimaryThreadId) instead of tombstones, history restore writes terminal rows from second-granular endpoints, and retry/cancellation deferral carry the original receipt time. - Claude receipt stamping — turn-start and
resultframes are stamped at receipt; aborted results settleinterrupted. - Host recovery verdicts — observed exit revises running rows to
interrupted; probe-only/cold-acquire death isunverifiable(no end), matching the SSH execution-boundary rule. - Client selectors — a shared selector joins each lifecycle row to the user message before it, host durations override local observation, and the live counter anchors on the client's local receipt of the running row.
I verified the load-bearing seams independently: the settled-turn key (item.itemId) matches the projected NativeChatMessage.id; activeStructuredAgentSessionTurnId/projectStructuredAgentSessionStatus still key on running only so the new terminal states project idle; lifecycle-batch mutation revisions always outrank the running row; the reducer orders by sequence (not observedAt) so pinning cannot reorder the timeline; and the wire change is backward compatible (non-strict zod strips startedAt/completedAt on old clients, state remains z.string().min(1)).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis change adds host-recorded turn timing and lifecycle states across Claude, Codex, shared journal types, mobile, and renderer surfaces. Running lifecycle rows are revised to completed, interrupted, or unverifiable states instead of being removed by tombstones. Receipt timestamps persist through retries and deferred notifications. Mobile and renderer hooks display host-settled durations and maintain stable local anchors for active turns. Mobile input-lock settling is centralized in a reusable hook. Tests cover provider translation, recovery, timing selectors, UI propagation, and input-lock behavior. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to This change persists turn lifecycle and duration data across clients and restarts, but a recovered backpressured Codex notification stream can remain paused and stop receiving future events. Resolve that availability regression and the remaining timing-test coverage concerns before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description covers the change, rationale, testing, visual proof, review notes, compatibility, and known gaps. However, the required linked issue entry is incomplete because it says no separate issue exists and does not use the required ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: f76dded1-cf9b-495f-b637-3a0d8e9e67d1
📥 Commits
Reviewing files that changed from the base of the PR and between 7197593 and 5c71a857fee0f8471f3e9106276c266fa112b9c4.
📒 Files selected for processing (73)
mobile/src/session/MobileNativeChatOverlay.tsxmobile/src/session/MobileNativeChatView.tsxmobile/src/session/mobile-native-chat-controller-contract.tsmobile/src/session/use-mobile-native-chat-controller.tsmobile/src/session/use-mobile-native-chat-input-lease.test.tsmobile/src/session/use-mobile-native-chat-input-lease.tsmobile/src/session/use-mobile-native-chat-turn-disclosure.test.tsxmobile/src/session/use-mobile-native-chat-turn-disclosure.tsmobile/src/session/use-mobile-native-chat-turn-status.tsmobile/src/session/use-mobile-structured-agent-session.tsmobile/src/session/use-mobile-structured-agent-session.turn-timing.test.tsxmobile/src/session/use-mobile-structured-agent-turn-timing.test.tsxmobile/src/session/use-mobile-structured-agent-turn-timing.tssrc/main/claude/claude-structured-journal-translation-turn-timing.test.tssrc/main/claude/claude-structured-journal-translation.test.tssrc/main/claude/claude-structured-journal-translation.tssrc/main/claude/claude-structured-session-acquisition.tssrc/main/claude/claude-structured-session-adapter.tssrc/main/claude/claude-structured-session-close.tssrc/main/claude/claude-structured-session-recovery.test.tssrc/main/claude/claude-structured-session-state.tssrc/main/claude/claude-turn-lifecycle-item.tssrc/main/codex/codex-structured-journal-contracts.tssrc/main/codex/codex-structured-journal-settlement.tssrc/main/codex/codex-structured-journal-translation-restore.tssrc/main/codex/codex-structured-journal-translation-settlement.test.tssrc/main/codex/codex-structured-journal-translation-streams.test.tssrc/main/codex/codex-structured-journal-translation-turn-boundaries.tssrc/main/codex/codex-structured-journal-translation-turn-lifecycle.test.tssrc/main/codex/codex-structured-journal-translation-turn-state.test.tssrc/main/codex/codex-structured-journal-translation-turn-state.tssrc/main/codex/codex-structured-journal-translation-turns.tssrc/main/codex/codex-structured-journal-translation.test.tssrc/main/codex/codex-structured-journal-translation.tssrc/main/codex/codex-structured-notification-retry.test.tssrc/main/codex/codex-structured-notification-retry.tssrc/main/codex/codex-structured-provider-events.tssrc/main/codex/codex-structured-session-acquire.tssrc/main/codex/codex-structured-session-adapter-lifecycle.test.tssrc/main/codex/codex-structured-session-adapter.tssrc/main/codex/codex-structured-session-cancel.test.tssrc/main/codex/codex-structured-session-state.tssrc/main/codex/codex-structured-thread-facts.tssrc/main/codex/codex-structured-turn-cancellation.tssrc/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.tssrc/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.tssrc/main/native-chat/agent-session-wire/structured-agent-session-wedged-profile-migration.test.tssrc/main/native-chat/agent-session-wire/structured-rewind-journal-body.test.tssrc/main/native-chat/agent-session-wire/structured-rewind-journal-body.tssrc/main/runtime/orchestration/structured-mailbox-pointer-host.tssrc/main/runtime/structured-agent-session-integration.test.tssrc/renderer/src/components/native-chat/NativeChatMessageList.tsxsrc/renderer/src/components/native-chat/NativeChatMessageList.turn-timing.test.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSession.tsxsrc/renderer/src/components/native-chat/use-native-chat-turn-status.tssrc/renderer/src/components/native-chat/use-structured-agent-session.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-session.tssrc/renderer/src/components/native-chat/use-structured-agent-turn-timing.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-turn-timing.tssrc/shared/agent-session-journal-schemas.test.tssrc/shared/agent-session-journal-schemas.tssrc/shared/agent-session-journal-types.tssrc/shared/native-chat-turn-status.tssrc/shared/structured-agent-session-turn-timing.test.tssrc/shared/structured-agent-session-turn-timing.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
|
|
||
| // A brief unlock that reverts inside the settle window never reaches the composer. | ||
| act(() => renderer?.update(createElement(Harness, { reason: null }))) | ||
| act(() => vi.advanceTimersByTime(300)) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert that the transient unlock remains locked.
During the 600 ms settle window, useSettledMobileNativeChatInputLock must keep settled as 'waiting'. Without this assertion, MobileNativeChatView can receive null and enable the composer for 300 ms, while the later 'disconnected' update still makes the final assertion pass.
act(() => renderer?.update(createElement(Harness, { reason: null })))
act(() => vi.advanceTimersByTime(300))
+ expect(settled).toBe('waiting')
act(() => renderer?.update(createElement(Harness, { reason: 'disconnected' })))📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| act(() => vi.advanceTimersByTime(300)) | |
| act(() => vi.advanceTimersByTime(300)) | |
| expect(settled).toBe('waiting') |
| expect(hook?.isWorking).toBe(true) | ||
| const anchor = hook!.workingStartedAt | ||
| // Client clock (50s) is nowhere near the host's (9,010s): only the 300ms append lag moves it. | ||
| expect(anchor).toBe(Date.now() - 300) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Allow automatic fake-time advancement in the anchor assertion.
shouldAdvanceTime: true advances mocked Date.now() in real time. The hook reads Date.now() while it stamps workingStartedAt, then line 145 reads it again. An automatic timer tick between these reads makes the exact equality fail.
Capture the clock once and assert a bounded range:
💚 Proposed fix
- expect(hook?.isWorking).toBe(true)
- const anchor = hook!.workingStartedAt
- // Client clock (50s) is nowhere near the host's (9,010s): only the 300ms append lag moves it.
- expect(anchor).toBe(Date.now() - 300)
+ expect(hook?.isWorking).toBe(true)
+ const stampedAt = Date.now()
+ const anchor = hook!.workingStartedAt
+ // Client clock (50s) is nowhere near the host's (9,010s): only the 300ms append lag moves it.
+ expect(anchor).toBeLessThanOrEqual(stampedAt - 300)
+ expect(anchor).toBeGreaterThan(stampedAt - 1_000)| @@ -154,7 +154,8 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda | |||
| reason: exit.error.message, | |||
| cause: 'unexpected-exit', | |||
| fence: exit.session.fence, | |||
| acquisitionGeneration: exit.session.acquisitionGeneration | |||
| acquisitionGeneration: exit.session.acquisitionGeneration, | |||
| observedAt: this.deps.now?.() ?? Date.now() | |||
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Capture the unexpected-exit timestamp when the exit is received.
handleExit starts connection.close(), and settleUnexpectedExit awaits persistSessionHandle() before it reads observedAt. Delayed cleanup therefore records settlement time instead of provider-exit receipt time. Store the timestamp on ClaudeSessionExit in handleExit and use it in settleUnexpectedExit.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The branch was rebased from 5c71a85 to ff55fcc (six upstream commits landed on main in between). I diffed the two heads' formatted diffs content-for-content: the PR's additions and deletions are byte-identical — the only deltas are line-number shifts in NativeChatMessageList.tsx (its base context grew by four lines), and the hunks reapplied cleanly.
There is no new behavioral surface to review. The minor observation from the prior review (the structuredAgentTurnLocalStartedAt lag subtraction being a no-op given the pinned running-row observedAt) still stands and is unaffected by the rebase.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval is held only because the prior minor suggestion — the
structuredAgentTurnLocalStartedAtlag-subtraction no-op under the pinned producers — is still open and untouched by these commits.
Reviewed changes
Since the prior Pullfrog review (ff55fcc), the lifecycle row's status text was corrected so a durable, settled row no longer reads "working":
- Settled turn status copy —
codexTurnLifecycleBodynow emitsCodex turn completedfor every non-runningstate, andclaudeTurnLifecycleItememitsClaude turn completedwhen an end is present, replacing the… is working…text the tombstone model never had to worry about. - Test expectation alignment — the settlement and translation fixtures now expect the settled copy instead of
… is working….
I verified the change end to end: the lifecycle row's text is never rendered (the projection returns null for turnLifecycle items and selectStructuredAgentTurnActivity skips them), so this is journal-metadata hygiene with no user-visible behavior change.
ℹ️ Settled text only names the completed state
codexTurnLifecycleBody labels every non-running state — including interrupted and unverifiable — as Codex turn completed, and Claude's end covers interrupted the same way. The host-recovery path (runningTurnLifecycleRevisions) additionally spreads the original running row, so rows it settles to interrupted/unverifiable still carry … is working… — the exact stale copy this commit removes from the completion path. Neither matters today because the field isn't rendered, but the rows are now durable, so any future direct reader of the journal will see a misleading label.
Technical details
# Settled lifecycle text does not distinguish terminal states
## Affected sites
- src/main/codex/codex-structured-journal-translation-turns.ts:29 — `state === 'running' ? 'Codex is working…' : 'Codex turn completed'` labels `interrupted`/`unverifiable` as completed.
- src/main/claude/claude-turn-lifecycle-item.ts:53 — `end ? 'Claude turn completed' : …` labels `interrupted` ends as completed.
- src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.ts:50 — `{ ...item.body, turnLifecycle: settledLifecycle(...) }` preserves the running row's `… is working…` text on host-recovery settlements.
## Required outcome
- None required to merge: the `text` field is not rendered today.
## Open questions for the human (optional)
- Is the lifecycle `text` intended as a human-readable terminal-state label? If so, `interrupted`/`unverifiable` should read differently, and `runningTurnLifecycleRevisions` should update `text` alongside `turnLifecycle`.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/codex/codex-structured-journal-translation.test.ts (1)
721-721: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winRestore the
startedAtassertion.The partial matcher checks only
turnIdandstate. It does not verify the host-recordedstartedAtvalue. Use a controlled clock and assert the expected timestamp, or at minimum assert thatstartedAtis present and numeric.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 2aadf75e-3c3c-48a7-9fe4-77a96a2db86e
📒 Files selected for processing (2)
src/main/codex/codex-structured-journal-translation-settlement.test.tssrc/main/codex/codex-structured-journal-translation.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/codex/codex-structured-journal-translation-settlement.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
|
Review completed at The fix addresses the underlying loss: the execution host retains durable lifecycle endpoints and clients derive completed duration during replay. Review found no remaining actionable correctness, architecture, compatibility, or resource-lifecycle defect within scope. Validation:
Desktop evidenceNative iOS evidenceThe restart screenshots also retain an earlier provider-exit notice; the duration remains intact. This tool-free turn verifies disclosure state, not rich tool-detail content. Grok QA was attempted but blocked by its weekly usage limit; the coordinator completed actual Electron CDP QA and a separate reviewer inspected the saved evidence. An optional Gemini inspection was blocked at its folder trust prompt. Remaining coverage limits: Android, live Windows/Linux, network-failure and old-client/rollback matrices, live Claude/approval/interrupted flows, mobile-originated completion/mobile restart, and release-scale performance measurements were not exercised. Direct native SSH/WSL execution remains excluded by existing location gates. No merge performed. |
Routes both Codex turn notifications through the background-task roster before the lifecycle boundaries, and lets the provider-exit test expect the open turn's interrupted revision instead of a tombstone.
An interrupted or unverifiable turn must not read as completed for any consumer that renders status text raw. One shared helper builds the text for both providers from the lifecycle state.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval is held only because the prior minor suggestion — the
structuredAgentTurnLocalStartedAtlag-subtraction no-op under the pinned producers — remains open and untouched by these commits.
Reviewed changes
Since the prior Pullfrog review (b256cb5), the settled lifecycle row's status text was generalized to name each terminal state, and main was merged in.
- Terminal-state lifecycle text — a new
agentTurnLifecycleTexthelper insrc/shared/agent-turn-lifecycle-text.tsmaps all four states to distinct copy (completed→ "turn completed",interrupted→ "turn interrupted",unverifiable→ "turn outcome unverifiable"), and bothcodexTurnLifecycleBodyandclaudeTurnLifecycleItemnow call it instead of the hardcoded running/completed ternary. - Test expectation alignment — the settlement and turn-lifecycle fixtures now assert
Codex turn interruptedfor interrupted turns, so the new mapping is exercised exactly.
I verified the helper is exhaustive over AgentJournalTurnLifecycleState (a new state can't silently fall through to a default), and both producers pass a value that matches the helper's agent union.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Each behavior keeps one test; duplicated harnesses and restated cases go.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 58348614-1705-4d52-be15-d977a76a5ced
📒 Files selected for processing (7)
mobile/src/session/use-mobile-structured-agent-turn-timing.test.tsxsrc/main/claude/claude-structured-journal-translation-turn-timing.test.tssrc/main/codex/codex-structured-journal-translation-turn-lifecycle.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.tssrc/renderer/src/components/native-chat/use-structured-agent-session.test.tsxsrc/renderer/src/components/native-chat/use-structured-agent-turn-timing.test.tsx
💤 Files with no reviewable changes (1)
- src/main/claude/claude-structured-journal-translation-turn-timing.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| await vi.advanceTimersByTimeAsync(50) | ||
|
|
||
| expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) | ||
| expect(connection.resumeReading).not.toHaveBeenCalled() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Resume reading when the retry queue drains.
enqueue() pauses connection after the first backpressure result. The immediate retry then accepts the queued event and removes it, but createCodexStructuredNotificationRetry deletes its state without calling resumeReading(). The connection remains paused and later provider notifications cannot be read. Line 203 currently accepts this stalled state.
Resume the connection after deleting an empty retry state. Assert the resume in this test.
Proposed fix
if (state.events.length === 0) {
states.delete(sessionId)
+ state.connection.resumeReading?.()
}…red duration A lifecycle row now names the user item that opened the turn by its provider key, so clients attribute timing explicitly and fall back to journal order only for rows from older hosts. A provider-initiated turn with no prompt can no longer claim the previous prompt's duration. When the provider measures the turn itself (Codex turn.durationMs, Claude result.duration_ms) the terminal row records it and clients prefer it over the host interval, so a turn shows the same number live and after a history restore. Host receipt times remain the live-counter anchor and the fallback.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — one test-coverage observation below.
Reviewed changes
Since the prior Pullfrog review (6b4b547), this is a test-only dedup commit (a898e0a) that removes duplicate harnesses and restated cases without touching production code:
- Deleted the standalone retry-queue suite —
codex-structured-notification-retry.test.tswas removed; its "replays a backpressured turn boundary with its original receipt time" case was folded intocodex-structured-journal-translation-turn-lifecycle.test.ts. - Deleted the mobile session-level turn-timing suite —
use-mobile-structured-agent-session.turn-timing.test.tsxwas removed; the settled-duration + live-anchor behavior remains covered byuse-mobile-structured-agent-turn-timing.test.tsx, and the session hook only spreadsuseMobileStructuredAgentTurnTimingoverturnId/isWorking. - Consolidated duplicated cases — the claude turn-timing, codex turn-lifecycle, stale-turn-verdict, unexpected-exit, and renderer session/turn-timing suites each collapsed restated scenarios into one test, and several assertions were strengthened in passing (e.g. the
interrupted/failed/cancelledmapping now also assertstombstonesis empty and checks the reduced row shape).
ℹ️ The retry-queue FIFO-ordering test was dropped, not deduplicated
The removed codex-structured-notification-retry.test.ts contained a second test — "queues a later notification behind a pending one without inventing a receipt time" — that was not carried forward anywhere. It was the only test exercising handle()'s state.events.length > 0 branch (codex-structured-notification-retry.ts:144): a second notification arriving while one is already pending is enqueued behind it and never jumps ahead, so the replay loop always re-emits the head with the head's own observedAt. With that test gone, that FIFO/receipt-time-preservation invariant now has zero coverage. This mattered most when the receipt-time threading was new (older commits), and the surviving single-notification case still covers the basic backpressure/retry path, so nothing is broken — but the dedup's own premise ("each behavior keeps one test") left this one at zero.
Technical details
# Notification-retry queue FIFO ordering lost its only test
## Affected sites
- src/main/codex/codex-structured-notification-retry.ts:144 — the `enqueue`-behind-pending branch in `handle()` is now untested.
- src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts:181 — the surviving sibling covers a single backpressured notification only.
## Required outcome
- Restore a case asserting that a later notification enqueued while another is pending is replayed behind the head with the head's own `observedAt` (the deleted test's assertion on `[method, observedAt]`).
## Open questions for the human (optional)
- Was this intentional given the receipt-time threading is now settled, or an accidental drop during the fold?DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
The host-recovery settlement path drops the new userItemId, so an observed-exit interrupted row reverts to journal-order attribution and can claim a prompt it did not open.
Reviewed changes
Since the prior review (a898e0a), commit a133af6 adds two fields to the lifecycle row and threads them through producers and clients:
- Keyed lifecycle rows —
AgentJournalTurnLifecyclegainsuserItemId(provider key of the opening user item) anddurationMs(the provider's own measured turn duration); both are optional and non-strict, so old clients strip them and new clients fall back cleanly. - Producer stamping — Codex derives
userItemIdviacodexTurnUserItemId(thread + turn +CODEX_USER_MESSAGE_ORDINAL) and readsturn.durationMsfromreadCodexTurnDurationMs; Claude uses the user-echo key andresult.duration_msthroughclaudeTurnEndForResult. - History restore —
historicalTurnLifecyclenow carriesuserItemIdanddurationMsfor pre-change turns, and the shared tests assert both. - Client resolution —
selectStructuredAgentTurnTimingsresolves a keyed row to its user item through the submission alias (or the direct item id), preferringdurationMsover the host interval incompletedStructuredAgentTurnSeconds, with journal-order as the fallback for key-less rows from older hosts.
⚠️ userItemId is dropped when host recovery settles a running turn
runningTurnLifecycleRevisions (structured-agent-session-stale-turn-verdict.ts:50) revises a running row by calling settledLifecycle, which rebuilds the object from { turnId, state } plus startedAt/completedAt — it does not carry userItemId forward. That is used by two paths: settleStaleRunningTurnsOnAcquire (cold acquire → unverifiable, no duration) and unexpectedExitFallbackMutations (observed exit → interrupted, which does expose a duration). For an interrupted row settled from an observed exit, the client sees key === undefined and falls back to the nearest preceding user message in journal order — so a provider-initiated turn (which at turn/started was written with a userItemId that resolves to nothing) becomes attributed to the last prompt it happened to follow. That is exactly the misattribution this commit's keyed attribution was introduced to prevent, and it exists only on the recovery path because the running row was written with userItemId but the settle path discards it.
Technical details
# Recovery settlement must carry userItemId through
## Affected sites
- src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.ts:56 — `settledLifecycle` rebuilds the lifecycle without `userItemId`.
- src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.ts:50 — `runningTurnLifecycleRevisions` is the shared revise-in-place helper.
- src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.ts:226 — `interrupted` verdict path that exposes a duration to clients.
## Required outcome
- `settledLifecycle` should copy `userItemId` (and `durationMs`, when present) from the running `turnLifecycle` onto the settled one, mirroring what the Codex/Claude producers already write on terminal rows.
## Suggested approach (optional)
- In `settledLifecycle`, add `if (lifecycle.userItemId !== undefined) settled.userItemId = lifecycle.userItemId`, and the same for `durationMs`.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The turn record is now its own item kind rather than a status row carrying a lifecycle field: no text to misuse, and the fold matches the durable turn record other systems keep. Rows that carry it are stamped journal schema v3; every other row stays v2, so an older host keeps reading them and latches read-only at the first v3 row instead of truncating the epoch. Clients that predate the item would paint an unknown kind as a text bubble, so the host publishes the legacy status form to any client that does not advertise agent-session.turn-item.v1, through the same per-client seam background tasks use. The downgrade is transitional and goes once no supported release lacks the capability. The shared projection now renders unknown item kinds as nothing, so later kinds need no gate. One shared reader handles both forms for old journals and old hosts.
There was a problem hiding this comment.
Important
The epoch row itself is stamped v3, so a session created on this build latches an older host read-only at sequence 1 with an empty timeline — not "reading v2 rows up to the first turn" as the PR's own compatibility notes describe. That story only holds for sessions whose epoch predates this change.
Reviewed changes
Since the prior Pullfrog review (a133af6), commit 1d90b77 promotes the turn lifecycle from a status row into a first-class kind: 'turn' journal item:
- First-class turn item —
AgentJournalTurnItem({ kind: 'turn' } & AgentJournalTurnLifecycle) becomes the durable record; thestatus+turnLifecyclecarrier is now legacy, still read from older hosts/journals but never written. - Shared dual-shape reader —
readAgentJournalTurn/agentJournalTurnBody/legacyAgentJournalTurnStatusBodyinsrc/shared/agent-session-turn-record.tsdecode both shapes, and every host-side reader plus the desktop/mobile selectors were migrated to it. - Per-row schema v3 —
journalRowSchemaVersionstamps only rows carrying aturnitem at v3; every other row stays v2. - Capability-gated downgrade —
AGENT_SESSION_TURN_ITEM_CAPABILITYgates the new item;projectTurnItemHistory/projectTurnItemEventrewriteturnitems to the legacy status form at thehistory/subscribeboundary for clients that do not advertise it (desktop IPC and mobile both do). - Unknown-kind projection — the shared projection now renders
turnrecords and unknown kinds as nothing instead of a text bubble, so later kinds need no gate. - Recovery key fix —
settledLifecyclenow carriesuserItemIdforward, resolving the prior review's recovery misattribution concern.
I verified the load-bearing seams independently: the downgrade wraps exactly the two item-carrying methods (agentSession.history and agentSession.subscribe; subscribeStatus emits host-computed summaries, not raw items); the turn item schema is a non-strict z.object so older clients strip unknown fields and the kind discriminant keeps old journals admissible; and the userItemId fix in settledLifecycle matches what the producers already write on terminal rows.
⚠️ Epoch rows are written at v3, so an older host latches a new-build session empty at sequence 1
The design in agent-session-journal-types.ts and docs/reference/remote-wire-compatibility.md is that only rows carrying a turn item are stamped v3 and everything else stays v2, so an older host keeps reading v2 rows and latches read-only at the first v3 turn row. But publishNewEpoch hardcodes v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION — now 3 — rather than going through the body-aware journalRowBase. The epoch row is sequence 1 and is the first row replayJournal parses, so an older host sees v=3 > 2, sets readOnly and stops before folding any row: a session created (or forked) on this build renders empty on a rolled-back host instead of showing its pre-turn v2 content. Nothing is lost or compacted, but the documented rollback behavior is silently not what happens for the session-creation path, and the two epoch-writing paths (publishNewEpoch v3 vs replaceJournalEpoch's journalRowBase v2) now disagree.
Technical details
# Epoch rows are stamped v3, contradicting the "every other row stays v2" design
## Affected sites
- src/shared/agent-session-journal-types.ts:20 — `AGENT_SESSION_JOURNAL_SCHEMA_VERSION = 3`, the constant `publishNewEpoch` hardcodes.
- src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts:36 — `v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION` stamps a new epoch (e.g. `session_created`) at v3; this file is not in the diff, so the bump changed its behavior silently.
- src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts:48 — the other epoch path uses `journalRowBase(epoch, 1, …)` with no bodies, correctly staying v2.
- src/main/native-chat/agent-session-journal/journal-open.ts:72-87 — `parseJournalRow` returns `unreadable` for `v > 2`, and `replayJournal` breaks at the first such row; with a v3 epoch that is sequence 1, so zero rows are folded.
## Required outcome
- Non-turn rows — including the epoch row — must be written at v2 so an older host reads v2 rows and latches read-only at the first v3 `turn` row, not at the epoch. Either make `publishNewEpoch` use `journalRowBase` (matching `replaceJournalEpoch`), or update the design/doc to accept v3 epochs for new sessions.
## Suggested approach (optional)
- In `publishNewEpoch`, replace `v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION` with `...journalRowBase(input.epoch, 1, input.fence, input.now())`.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…hat-turn-lifecycle-durable
|
Too many files changed for review (123 files, 100 file limit). Bypass the limit by tagging |
There was a problem hiding this comment.
ℹ️ No new issues in this delta — approval remains held by the two prior open findings (the epoch-row v3 rollback inconsistency and the
structuredAgentTurnLocalStartedAtlag no-op), which these commits do not touch.
Reviewed changes
Two commits landed since the prior Pullfrog review (1d90b77):
- Preserved the observed turn end across settlement retries — the unexpected-exit path threads
exitObservedAtthrough the lease release sodeathEvidence.observedAtrecords the exit receipt time instead of the (possibly delayed) release time; the later loaded settlement retry derives the turn'scompletedAtfrom that receipt. - Retained turn attribution for loaded chat history —
mergeSubmissionsnow keeps any submission whose user-message item is still loaded, even after it falls out of the 256-recent window, so old turns resolveuserItemIdto their user bubble through the submission alias rather than falling back to journal order. - New tests — a settlement-retry case asserting
completedAtstays at the original receipt time across a retry, and a reducer retention suite covering budget overflow, the stream no-op fast path, and rewind alias cleanup.
I verified both seams independently: the reducer passes the exact item set that lands in state at every call site, so retained submissions never outlive their user item; and turnVerdictFromDeathEvidence reads deathEvidence.observedAt, which the first commit now pins to the exit receipt.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ One minor suggestion inline — the two new commits are otherwise sound. The two prior open findings (the epoch-row v3 rollback inconsistency and the
structuredAgentTurnLocalStartedAtlag no-op) remain untouched.
Reviewed changes
Two commits landed since the prior Pullfrog review (c6caab5):
- Preserved the Codex exit receipt across close retries —
CodexSessiongainsexitObservedAt(first observation wins via??=),handleCodexSessionExitstamps it onto theendedevent asobservedAt, and both the translator'ssettledTurnLifecycleand host-recovery'ssettleUnexpectedStructuredAgentSessionExitnow preferevent.observedAtovernow, so a backpressured settlement retried much later still writes the turn'scompletedAtfrom the original receipt. - Registered a completed-turn-duration reliability gate —
agent-session.completed-turn-durationinconfig/reliability-gates.jsoncpins the seven test files that prove duration/attribution survival with value-based oracles. - New/updated tests — a
codex-requested-close-turn-timingsuite drives a real backpressure rejection then stale-generation and final close retries to assertcompletedAt: 2_000, and the unexpected-exit retry test is parameterized overobservedAt(undefined/2_000).
I verified the Codex close path end to end: exitObservedAt is set before admission and survives both the early-return-on-rejected-close and the host-recovery settlementRetryRequired branches, so a retried close cannot re-stamp the receipt.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… from the real start Findings from an independent adversarial review of the typed turn record: - A Codex rewind adopted the provider's item list as the new epoch, and the provider never returns the host's own turn rows, so every duration before the rewind point vanished. The host's turn rows are now spliced back beside the item each followed, and recovery no longer expects the provider to prove rows it never owned. - The epoch row was stamped with the current schema version, so an older host latched read-only at row 1 of every new session, defeating the mixed version design. It carries no body and stays at v2; a stored-row test now reads SQLite directly, because the reader upcasts every row on read. - A send Codex folds into a running turn shares the opening prompt's provider key, and the alias map credited the duration to the later prompt. The earliest submission naming a key now wins. - The live counter anchored on first sight, so a client attaching mid-turn counted from zero. Published frames now carry the host's clock, the reducer keeps the last sample with its local receipt time, and both clients anchor on how long the host says the turn has run.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — the two prior substantive findings are now resolved. Approval remains held only by one outstanding minor inline thread from a prior review (the
agent-session.completed-turn-durationgate's staleassertionRefsentry), which this commit does not touch.
Reviewed changes
- Host-clock publication for the live counter — the host now stamps
hostNowonce per published frame (AgentSessionSubscribers) and onhistorypages, and the desktop/mobile reducers record it as{ hostNow, receivedAt }, so a client attaching mid-turn anchors its live counter on the real start instead of first sight. ThestructuredAgentTurnLocalStartedAtlag no-op is gone: with a host clock the anchor subtracts real elapsed, and theobservedAt - startedAtterm survives only as the older-host fallback. - Rewind turn-row retention —
mergeRetainedTurnRows/isRetainedTurnRowsplice the host's turn rows back around the provider spine through both the Codex preflight and the final provider list, andrecoverStructuredRewindexcludes turn rows from the provider proof, so pre-boundary durations survive a rewind instead of being dropped with the provider-only epoch. - Epoch row stamped v2 —
publishNewEpochnow writesv: journalRowSchemaVersion([])instead of the hardcoded schema version, resolving the rollback inconsistency; a new test pins stored rows as[epoch 2, message 2, turn 3]. - Coalesced-send attribution — the timing selector keeps the earliest submission per provider key, so a mid-turn send folded into the running turn under the same key attributes to the prompt that opened it.
- Reducer host-clock state —
reduceStructuredAgentSessiongains areceivedAtparameter and ahostClockfield;backgroundTaskStatesEqualis extracted to a shared module andemptyAgentSessionBatchreplaces the inline empty-batch literals.
I verified the load-bearing seams independently: the host clock is sampled once per frame and both clock terms stay single-clock (the anchor computes receivedAt - (hostNow - startedAt), which cancels client skew); the rewind merge is idempotent over repeated passes and never drops a turn row (they are host-owned and never part of the provider spine); and hostNow is an additive optional field on the stream-frame types, so old clients ignore it and new clients on old hosts fall back to first-sight, matching the existing backgroundTasks/activity pattern.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Second review loop is complete at
Electron proof: a real Codex turn on this exact head shows Worked for 3s before renderer reload, after reload, and after full app restart (new process, same profile). All three screenshots are attached. Its stored row remains Gaps: Grok QA was blocked by its weekly quota, so Codex performed the Electron arm. An explicit model/effort launch failed; configured-default Codex reviews completed, but exact deployment/effort parity is unverified. Native iOS pairing and chat navigation worked through QA also recorded a write refusal in a restored, never-submitted test chat; the fresh-chat flow passed, and no PR code cause was established for that separate observation. No merge performed. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior Pullfrog review (e2b3abe), five commits landed — one a main merge, the rest making the host's "no duration" word authoritative on every surface and closing out the last open nit:
- Made unknown durations authoritative —
NativeChatSettledTurnsnow carriesnullper turn; anunverifiable(or terminal-without-endpoint) row suppresses the locally observed "Worked for N" so the label is identical before and after reload, on desktop and mobile. - Unified
isWorking— desktop and mobile both foldhasUnansweredStructuredAgentSessionDispatchin, so a dispatched-but-unanswered send reads working while Claude's running row trails the send. - Recovered provider-exit submissions — the unexpected-exit path marks pending submissions
unknown/recovered, so a session whose provider exited without ack stops latching "working". - Bounded live items —
retainedItemLimit/trimRetainedItemscap the reducer's live window at 1024 and forcehasOlderwhen a trim drops rows. - Corrected the reliability-gate
assertionRefs— the stale pre-rename assertion string is fixed (the prior open thread).
I verified the load-bearing seams independently: a null settled entry deletes only the key it names from the locally-derived completedByTurn (the running turn's live counter is untouched, since it is rendered from isWorking/workingStartedAt, not the settled map); selectStructuredAgentTurnTimings emits null only for unverifiable rows without a start and skips untimed non-unverifiable rows, preserving the older-host local fallback; markPendingSubmissionsUnknown sets recovered: true, which hasUnansweredStructuredAgentSessionDispatch already excludes, and its double call across the retry path is idempotent; and the head-trim raises hasOlder without ever silently dropping attribution, since mergeSubmissions keys off the same trimmed items.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Main renamed the background-tasks view binding and grew its roster equality to compare settled tasks; the extracted comparator adopts that logic so the reducer keeps both it and the host-clock sample.
- A merged import list named the same module twice, which the native code quality plugin fails on. - A running turn is now reported by the host with no duration, so the settled map carries an explicit null for it; the hook test still expected the entry to be absent. - main gave the older-page action a cursor with a head-trim guard, so the retention test's epoch-only action no longer typechecks; it now passes an unbounded sequence, which is what the old shape meant. - The roster comparator moved into the extracted module, leaving its import unused in the reducer.
Merging main put both one effective line over 300, and the cap forbids a disable or a shave. The wire module's refusal vocabulary moves to its own file and is re-exported, so its consumers are untouched; the host's four thin mutation delegates move next to the functions they call.
There was a problem hiding this comment.
Caution
Merging origin/main (e27ca9b) left pnpm tc broken with four typecheck errors. The reconcile against two upstream native-chat changes — #19845 (renamed the reducer's older-page action from requestedEpoch to requestedCursor) and #19311 (moved task-list equality into the shared agentSessionBackgroundTasksEqual helper) — missed two spots, so CI typecheck now fails.
Reviewed changes
Since the prior review (653e2f1), a single commit landed: e27ca9b merges origin/main.
- Background-tasks strip reconcile (#19311) — adapted the branch to the reshaped
structuredSessionBackgroundTasksView(show/isMonitoring/tasks/settledTasks/supportsStop/supportsStopAll) and toAgentSessionBackgroundTaskState.settledTasks, updatinguse-structured-agent-session.ts,NativeChatStructuredSession.tsx, andagent-session-background-task-state-equality.tsaccordingly. These reconciles are correct. - Older-page anchor reconcile (#19845) — the reducer's
older-pageaction now carriesrequestedCursorwith ahead.sequence > requested.sequenceguard, and both the renderer read-owner and the mobile owner got bounded re-anchor/retry loops. Correct on the producer side.
🚨 Merge residue leaves an unused import in the reducer
structured-agent-session-reducer.ts imports agentSessionBackgroundTasksEqual but no longer calls it — the equality was moved out into backgroundTaskStatesEqual in agent-session-background-task-state-equality.ts, and the merge kept the import while dropping its inline use. tsc reports TS6133: 'agentSessionBackgroundTasksEqual' is declared but its value is never read, which fails pnpm tc.
Technical details
# Remove the unused `agentSessionBackgroundTasksEqual` import
## Affected sites
- src/shared/structured-agent-session-reducer.ts:7 — `agentSessionBackgroundTasksEqual` in the value import from `./agent-session-wire` is now unused after the equality extraction.
## Required outcome
- Drop `agentSessionBackgroundTasksEqual` from the reducer's import (it is still used by `agent-session-background-task-state-equality.ts`), so `pnpm tc` passes again.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Two commits landed since the prior review (e27ca9b), both addressing the merge issues I flagged (review 5170931157):
- Fixed the merge's CI failures (
2bfbae0) — dropped the now-unusedagentSessionBackgroundTasksEqualimport from the reducer (equality lives in the sharedbackgroundTaskStatesEqualmodule); repaired the retention test'solder-pagedispatches to carryrequestedCursor: { epoch, sequence: Number.MAX_SAFE_INTEGER }instead of the removedrequestedEpoch; consolidated a duplicateagent-session-journal-typesimport inuse-structured-agent-session.test.tsx. - Aligned a hook test with a running turn's explicit null — the running turn's row now maps to an explicit
nullinsettledTurns(the authoritative unknown-duration result outranks the client clock; the live counter renders fromisWorking/workingStartedAtseparately), and the expectation was updated to['u2', null]. - Split two files back under the line cap (
3149caa) — the host's four mutation delegates moved tostructured-agent-session-host-mutations.ts, and the refusal vocabulary moved toagent-session-wire-refusals.ts(re-exported fromagent-session-wire.ts). Both are pure moves.
I verified the fixes end to end: pnpm exec tsc on the node and web projects both report zero errors at 3149caa, the reducer import is now a plain import type, and the two extractions preserve the existing call sites (typecheck confirms no dangling references).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Both sides added a client capability to the same lists; each keeps its own.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior Pullfrog review (3149caa), a single merge of origin/main landed (451ce78), reconciling the branch against upstream #19705 ("show live background work and name each row by kind"):
- Advertised the upstream row-stop capability —
AGENT_SESSION_BACKGROUND_TASK_ROW_STOP_CAPABILITY(agent-session.background-task-row-stop.v1) now joins the PR'sAGENT_SESSION_TURN_ITEM_CAPABILITYin the desktop IPCclientCapabilitieslists and inRUNTIME_CAPABILITIES. - Relocated attach-failure teardown —
forgetStructuredAgentSessionis imported/used from the newstructured-agent-session-host-lifetime.ts(upstream refactor), reconciled instructured-agent-session-attach-orchestration.ts. - Shared type import —
agent-session-wire.tsnow imports the upstreamAgentSessionBackgroundTaskStatealongside its existing wire types.
I verified the reconcile end to end: both capability lists carry the two capabilities without duplication, every new import is used (no dangling or unused symbols), and pnpm tc:node, tc:web, and tc:cli all report zero errors at this head. No PR-authored behavior changed.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Local IPC and mobile advertised it; the remote and web transports did not, so a desktop paired to a remote host, the CLI, and web silently ran on the legacy carrier forever and the canonical row was never exercised there. The renderer that paints it is the same build on every transport.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
A single commit (e88c377) landed since the prior review (451ce78), completing the turn-item capability advertisement across the remaining client transports so the host serves the canonical turn record everywhere rather than the legacy status carrier.
- Shared remote-request transports —
remoteRuntimeClientCapabilities()now listsAGENT_SESSION_TURN_ITEM_CAPABILITY, so the CLI and every shared remote request/control/subscription transport name it in their handshake. Mobile already carried it inadditionalCapabilities, so theSetdeduplicates it with no net change. - Web renderer handshake —
web-runtime-connection-frame-router.tsadds the capability to itse2ee_authframe, so a browser-based client also opts into the typed turn record. - CLI transport test —
websocket-transport.test.tsnow expects the new capability in the emittedclientCapabilities.
I verified the load-bearing seam: every consumer of agentSession.history / agentSession.subscribe (desktop, web, and mobile) renders raw items through the shared projectStructuredItemToNativeChat, which projects both turn and unknown kinds to nothing — never a stray text bubble — and the CLI does not subscribe to raw agent-session items at all. So advertising the capability on these transports cannot surface a turn item any client mishandles, and the only behavioral consequence is that this-build clients receive the typed record instead of an unnecessary downgrade.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
A single commit (04dbd14) landed since the prior Pullfrog review (e88c377), closing the one test the capability advertisement missed.
- Web auth-frame test expectation —
web-runtime-client.test.tsnow includesAGENT_SESSION_TURN_ITEM_CAPABILITYin thee2ee_authframe's expectedclientCapabilities, matching the production listrouteWebRuntimeConnectionFramegained ine88c377(which had updated the CLI transport test but not this one).
I verified the changed test against its production counterpart: the assertion is an exact toEqual over the full capability list, and the two lists are now identical in both membership and position, so the web-renderer test tracks the handshake precisely and no other exact-list capability assertion is out of sync.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏









ELI5
A chat turn used to end by deleting the row that said "this turn is running". That row was the only place an end time could have lived, so nothing was ever written down. The "Worked for 3m 7s" you saw was just your window remembering what it had watched happen. Close the tab, reload, or restart, and the number was gone — not stale, gone, because it had never been recorded anywhere.
Now a turn is something Orca writes down. It is written when the turn starts, updated when it ends, and it stays there. The label reads that record, so it is the same number after a reload, after a restart, tomorrow morning, and on your phone.
What changed
A turn is now a record, not the gap between two events
The turn is a first-class journal entry that is revised in place and never deleted. It moves through four states, and the state says exactly what the machine that ran the work actually knows:
runningcompletedinterruptedunverifiableThat last state is the point of the design. The old code had no way to say "this turn ended but nobody saw it end", so a crash left a row that said
runningforever and the UI counted up to infinity. Now it is a state, and it deliberately shows nothing rather than a number nobody can stand behind.The machine that ran the work owns the clock
Both timestamps are taken by the execution host, at the moment the provider's event arrives, before anything is buffered. Nothing is measured by your window.
That matters because the number is now the same everywhere: your desktop, a second window, your phone over the relay, and a laptop whose clock is ten minutes off all read the same two host timestamps. When the provider reports its own measured duration, we prefer that over our own subtraction, so the number matches what the agent itself thinks it spent.
The live counter that ticks during a turn is anchored the same way. Published frames carry the host's current clock, so a client that opens a chat mid-turn counts from when the turn really started instead of from the moment it happened to connect.
Every record names the prompt it belongs to
Each turn record carries the id of the user message that opened it, resolved through the send's own identity. Previously we inferred it from position in the transcript. That inference breaks in a real case: the agent folds a message you send mid-turn into the turn already running, and both messages then share one provider identity — so the duration landed on the wrong bubble. Naming the prompt explicitly removes the guess.
Old and new versions keep working, in both directions
This is a persistence and wire change, so both skew directions are handled:
Why this is better
The bug is gone by construction, not patched over. The old failure was not a missing guard — it was that the end of a turn was modelled as an absence, and absence carries no information. Nothing you could add to the renderer would fix that. Giving the end time a durable home removes the failure mode itself, which is why the fix is in the record rather than in a timer.
It stops lying when it does not know. The host now distinguishes "ended, and here is when" from "lost it, and I never saw it end". The second case shows no duration. Previously that case was indistinguishable from a turn still running.
One definition, every surface. Desktop and mobile compute the label from the same record through the same shared reader, so they cannot drift. A third surface gets it for free.
It does not add a subsystem. Timing rides the journal that already exists, with its existing replay, revision and recovery machinery. There is no timer to keep alive, no polling loop, no second store to keep in sync, and no new lifetime to reason about.
It is a foundation, not a one-off. A durable, host-owned turn record with an honest unknown state is what a remote or SSH-hosted session needs anyway: when the host is a different machine, "I lost the agent and never saw it end" is the normal case, not an edge case.
Linked Issue
No separate issue exists. This supersedes #19627, which attached timing to the user message and needed a pending buffer, a separate sequence field, per-translator clock ids, a multi-clause validity gate and a hash in the settlement key — all of which existed only because the end of a turn was a deletion. None of that machinery survives here.
Visual Proof
At head
653e2f150a, a real completed Codex turn shows Worked for 3s before reload, after renderer reload, and after full app restart with the same profile. All three screenshots are attached. The persisted v3turnrow retainsdurationMs: 3296; actual old-client history and initial subscription snapshots publish the compatiblestatusbody, while modern clients receiveturn.Native iOS pairing and chat navigation succeeded, but the screenshot provider had no Simulator window; mobile visual acceptance remains blocked. SSH authentication and relay deployment succeeded in a disposable Linux target, but Electron stalled in Keychain decryption before the remote turn; that arm remains blocked. These earlier attempts are not final-head mobile/SSH passes.
Testing
Second review loop, macOS; reviewed source
5acb404bf2, evidence-only manifest commit653e2f150a. Since then: main merged in, the CI failures that merge caused fixed, and two files split back under the 300-line cap (head3149caaa17, CI green).Node, web, CLI and mobile typechecks passed sequentially with
--composite falseafter the final shared selector change.Final reliability gate: 58 tests across eight files passed in 4.65s. It covers exit-receipt retries, history attribution retention, provider lifecycle timing, old-client RPC projection, rendered settled duration, and authoritative unknown timing across reload.
Consumer-fix validation: 64 shared/desktop tests and 54 mobile tests passed. After the untimed upgrade case was fixed, 31 targeted shared/desktop tests and the six-case recovery regression passed; these overlapping runs are not summed as unique coverage.
Owned-file oxlint/oxfmt and commit hooks passed, including React Doctor; the reliability manifest validator passed for 119 gates. The gate remains experimental, with no CI soak or accumulated-history performance benchmark claimed.
START and END readiness audits and independent code review cover host ownership, retry/recovery, retained rewind history, schema rollback refusal, and mixed-version clients. Older broad-suite results belong to earlier heads and are supplementary only.
Automated tests added/updated
AI Disclosure
Codex agents reviewed, implemented fixes, and performed the replacement Electron QA. The explicit model/effort launch failed; configured-default Codex reviews completed, with exact deployment/effort parity unverified. Grok QA was blocked by its weekly quota.
Review
Second-loop independent source review and START/END readiness audits found no remaining proven in-scope issue after the retry, attribution and unknown-duration fixes. Completed duration uses host-owned persisted facts; local estimates cannot override an explicit unknown result. Windows/Linux runtime, real old-host rollback, accumulated-history profiling and CI soak remain unverified. A restored never-submitted test chat also refused writes during QA; no PR code cause was established, and the fresh-chat persistence flow passed.
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Known gaps, deliberately left:
turn/completedwithout a status maps tocompleted.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)