Skip to content

Make the structured turn lifecycle row durable so completed durations survive - #19695

Merged
brennanb2025 merged 25 commits into
mainfrom
brennanb2025/native-chat-turn-lifecycle-durable
Sep 10, 2026
Merged

brennanb2025 merged 25 commits into
mainfrom
brennanb2025/native-chat-turn-lifecycle-durable

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 42 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3084 $\color{#cf222e}{\Huge{\mathbf{−}}}$​124 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2960
Prod 81 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1880 $\color{#cf222e}{\Huge{\mathbf{−}}}$​496 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1384

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:

State Meaning Shows
running the provider started the turn a live counter
completed the provider reported it finished the duration
interrupted you stopped it, or the host watched the agent exit the duration
unverifiable the host lost the agent without seeing it end no duration

That 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 running forever 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:

  • Older client, newer host. A client that predates the turn record would paint it as a stray text bubble, so the host serves those clients the previous shape, carrying the same timing. This is negotiated by capability and is marked transitional — it goes away once no supported release needs it.
  • Newer journal, older host. Only rows that carry a turn record use the new schema version; everything else stays on the old one. An older build refuses to interpret a version it does not know and opens the session read-only rather than truncating it. Nothing is lost, and it recovers on the next upgrade.
  • Older journal, newer host. Old rows are upgraded on read, and one shared reader understands both the old and new shape, so existing chats keep working untouched. Turns that finished on the old build have no record to recover, so they stay without a duration.
  • Future item kinds. Clients now ignore item kinds they do not recognise instead of rendering them as text, so the next addition of this sort needs no compatibility shim at all.

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 v3 turn row retains durationMs: 3296; actual old-client history and initial subscription snapshots publish the compatible status body, while modern clients receive turn.

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 commit 653e2f150a. Since then: main merged in, the CI failures that merge caused fixed, and two files split back under the 300-line cap (head 3149caaa17, CI green).

  • Node, web, CLI and mobile typechecks passed sequentially with --composite false after 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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Known gaps, deliberately left:

  • Turns that finished on an older build have no record to recover, so they never gain a duration. Turns started after the update are durable.
  • A turn/completed without a status maps to completed.
  • Rolling back after this ships makes affected sessions read-only on the old build until the next upgrade. Nothing is lost; this was verified at the parser level, not against a real old binary.
  • The compatibility shim for older clients is transitional and should be deleted once no supported release lacks the capability.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… 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.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/native-chat-turn-lifecycle-durable branch from 5c71a85 to ff55fcc Compare September 9, 2026 07:07

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — AgentJournalTurnLifecycleState grows interrupted/unverifiable; the row opens running with startedAt and settles to a terminal state with completedAt (or no end for unverifiable).
  • Host-clock endpoints — both providers stamp startedAt/completedAt on the execution host's clock at provider-event receipt, before the deferred sink; the running row's journal observedAt is pinned to startedAt.
  • Codex turn boundaries — CodexJournalTurnBoundaries replaces inline start/complete, settlement writes items (guarded by primaryThreadId) 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 result frames are stamped at receipt; aborted results settle interrupted.
  • Host recovery verdicts — observed exit revises running rows to interrupted; probe-only/cold-acquire death is unverifiable (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)).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This 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 a898e

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.68% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 74 functions across 60 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 iss… Provide a valid linked issue reference in the Linked Issue section, using the required Fixes #<issue-number> format, or update the repository requirement if issue linking is not applicable.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: making structured turn lifecycle rows durable so completed durations persist.
Full details: Description check

Explanation

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 Fixes # format.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.tsx
  • mobile/src/session/MobileNativeChatView.tsx
  • mobile/src/session/mobile-native-chat-controller-contract.ts
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-input-lease.test.ts
  • mobile/src/session/use-mobile-native-chat-input-lease.ts
  • mobile/src/session/use-mobile-native-chat-turn-disclosure.test.tsx
  • mobile/src/session/use-mobile-native-chat-turn-disclosure.ts
  • mobile/src/session/use-mobile-native-chat-turn-status.ts
  • mobile/src/session/use-mobile-structured-agent-session.ts
  • mobile/src/session/use-mobile-structured-agent-session.turn-timing.test.tsx
  • mobile/src/session/use-mobile-structured-agent-turn-timing.test.tsx
  • mobile/src/session/use-mobile-structured-agent-turn-timing.ts
  • src/main/claude/claude-structured-journal-translation-turn-timing.test.ts
  • src/main/claude/claude-structured-journal-translation.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-session-acquisition.ts
  • src/main/claude/claude-structured-session-adapter.ts
  • src/main/claude/claude-structured-session-close.ts
  • src/main/claude/claude-structured-session-recovery.test.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/claude/claude-turn-lifecycle-item.ts
  • src/main/codex/codex-structured-journal-contracts.ts
  • src/main/codex/codex-structured-journal-settlement.ts
  • src/main/codex/codex-structured-journal-translation-restore.ts
  • src/main/codex/codex-structured-journal-translation-settlement.test.ts
  • src/main/codex/codex-structured-journal-translation-streams.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
  • src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-state.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-state.ts
  • src/main/codex/codex-structured-journal-translation-turns.ts
  • src/main/codex/codex-structured-journal-translation.test.ts
  • src/main/codex/codex-structured-journal-translation.ts
  • src/main/codex/codex-structured-notification-retry.test.ts
  • src/main/codex/codex-structured-notification-retry.ts
  • src/main/codex/codex-structured-provider-events.ts
  • src/main/codex/codex-structured-session-acquire.ts
  • src/main/codex/codex-structured-session-adapter-lifecycle.test.ts
  • src/main/codex/codex-structured-session-adapter.ts
  • src/main/codex/codex-structured-session-cancel.test.ts
  • src/main/codex/codex-structured-session-state.ts
  • src/main/codex/codex-structured-thread-facts.ts
  • src/main/codex/codex-structured-turn-cancellation.ts
  • src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-wedged-profile-migration.test.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-journal-body.test.ts
  • src/main/native-chat/agent-session-wire/structured-rewind-journal-body.ts
  • src/main/runtime/orchestration/structured-mailbox-pointer-host.ts
  • src/main/runtime/structured-agent-session-integration.test.ts
  • src/renderer/src/components/native-chat/NativeChatMessageList.tsx
  • src/renderer/src/components/native-chat/NativeChatMessageList.turn-timing.test.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
  • src/renderer/src/components/native-chat/use-native-chat-turn-status.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-session.ts
  • src/renderer/src/components/native-chat/use-structured-agent-turn-timing.test.tsx
  • src/renderer/src/components/native-chat/use-structured-agent-turn-timing.ts
  • src/shared/agent-session-journal-schemas.test.ts
  • src/shared/agent-session-journal-schemas.ts
  • src/shared/agent-session-journal-types.ts
  • src/shared/native-chat-turn-status.ts
  • src/shared/structured-agent-session-turn-timing.test.ts
  • src/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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta. Approval is held only because the prior minor suggestion — the structuredAgentTurnLocalStartedAt lag-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 — codexTurnLifecycleBody now emits Codex turn completed for every non-running state, and claudeTurnLifecycleItem emits Claude turn completed when 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`.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Restore the startedAt assertion.

The partial matcher checks only turnId and state. It does not verify the host-recorded startedAt value. Use a controlled clock and assert the expected timestamp, or at minimum assert that startedAt is present and numeric.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2aadf75e-3c3c-48a7-9fe4-77a96a2db86e

📥 Commits

Reviewing files that changed from the base of the PR and between 9a1af94 and b256cb5.

📒 Files selected for processing (2)
  • src/main/codex/codex-structured-journal-translation-settlement.test.ts
  • src/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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review completed at b256cb5a69ffb2e21e3a0416fb4654911087cbdd after rebasing onto main. START and END readiness checks and the same-model review loop returned clean. The review fixed terminal lifecycle fallback text so older clients replay “turn completed” instead of “is working,” and updated two stale test expectations (9a1af944cf, b256cb5a69).

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:

  • Node, web, CLI, and mobile TypeScript checks passed sequentially; changed-file lint, quality, and formatting passed.
  • All 22 changed desktop suites were exercised: 221/223 initially passed; after correcting the two expectations, both affected suites passed 37/37. All four changed mobile suites passed, 11/11.
  • A real Codex response retained Worked for 7s before renderer reload, after reload, and after a full application process restart. Read-only journal comparison confirmed unchanged endpoints, 7,172 ms apart.
  • Native iOS displayed the same restarted desktop turn and retained its duration when toggling details.

Desktop evidence

Before reload:
Completed turn before reload

After renderer reload:
Completed turn after renderer reload

After full app restart:
Completed turn after app restart

Native iOS evidence

Completed turn:
Native completed turn

Details expanded:
Native details expanded

The 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.

Merge Sim added 2 commits September 9, 2026 01:00
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta. Approval is held only because the prior minor suggestion — the structuredAgentTurnLocalStartedAt lag-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 agentTurnLifecycleText helper in src/shared/agent-turn-lifecycle-text.ts maps all four states to distinct copy (completed → "turn completed", interrupted → "turn interrupted", unverifiable → "turn outcome unverifiable"), and both codexTurnLifecycleBody and claudeTurnLifecycleItem now call it instead of the hardcoded running/completed ternary.
  • Test expectation alignment — the settlement and turn-lifecycle fixtures now assert Codex turn interrupted for 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Each behavior keeps one test; duplicated harnesses and restated cases go.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 58348614-1705-4d52-be15-d977a76a5ced

📥 Commits

Reviewing files that changed from the base of the PR and between 6b4b547 and a898e0a.

📒 Files selected for processing (7)
  • mobile/src/session/use-mobile-structured-agent-turn-timing.test.tsx
  • src/main/claude/claude-structured-journal-translation-turn-timing.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx
  • src/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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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.ts was removed; its "replays a backpressured turn boundary with its original receipt time" case was folded into codex-structured-journal-translation-turn-lifecycle.test.ts.
  • Deleted the mobile session-level turn-timing suite — use-mobile-structured-agent-session.turn-timing.test.tsx was removed; the settled-duration + live-anchor behavior remains covered by use-mobile-structured-agent-turn-timing.test.tsx, and the session hook only spreads useMobileStructuredAgentTurnTiming over turnId/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/cancelled mapping now also asserts tombstones is 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?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 — AgentJournalTurnLifecycle gains userItemId (provider key of the opening user item) and durationMs (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 userItemId via codexTurnUserItemId (thread + turn + CODEX_USER_MESSAGE_ORDINAL) and reads turn.durationMs from readCodexTurnDurationMs; Claude uses the user-echo key and result.duration_ms through claudeTurnEndForResult.
  • History restore — historicalTurnLifecycle now carries userItemId and durationMs for pre-change turns, and the shared tests assert both.
  • Client resolution — selectStructuredAgentTurnTimings resolves a keyed row to its user item through the submission alias (or the direct item id), preferring durationMs over the host interval in completedStructuredAgentTurnSeconds, 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`.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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; the status + turnLifecycle carrier is now legacy, still read from older hosts/journals but never written.
  • Shared dual-shape reader — readAgentJournalTurn / agentJournalTurnBody / legacyAgentJournalTurnStatusBody in src/shared/agent-session-turn-record.ts decode both shapes, and every host-side reader plus the desktop/mobile selectors were migrated to it.
  • Per-row schema v3 — journalRowSchemaVersion stamps only rows carrying a turn item at v3; every other row stays v2.
  • Capability-gated downgrade — AGENT_SESSION_TURN_ITEM_CAPABILITY gates the new item; projectTurnItemHistory / projectTurnItemEvent rewrite turn items to the legacy status form at the history / subscribe boundary for clients that do not advertise it (desktop IPC and mobile both do).
  • Unknown-kind projection — the shared projection now renders turn records and unknown kinds as nothing instead of a text bubble, so later kinds need no gate.
  • Recovery key fix — settledLifecycle now carries userItemId forward, 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())`.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@greptile-apps

greptile-apps Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Too many files changed for review (123 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta — approval remains held by the two prior open findings (the epoch-row v3 rollback inconsistency and the structuredAgentTurnLocalStartedAt lag 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 exitObservedAt through the lease release so deathEvidence.observedAt records the exit receipt time instead of the (possibly delayed) release time; the later loaded settlement retry derives the turn's completedAt from that receipt.
  • Retained turn attribution for loaded chat history — mergeSubmissions now keeps any submission whose user-message item is still loaded, even after it falls out of the 256-recent window, so old turns resolve userItemId to their user bubble through the submission alias rather than falling back to journal order.
  • New tests — a settlement-retry case asserting completedAt stays 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ One minor suggestion inline — the two new commits are otherwise sound. The two prior open findings (the epoch-row v3 rollback inconsistency and the structuredAgentTurnLocalStartedAt lag no-op) remain untouched.

Reviewed changes

Two commits landed since the prior Pullfrog review (c6caab5):

  • Preserved the Codex exit receipt across close retries — CodexSession gains exitObservedAt (first observation wins via ??=), handleCodexSessionExit stamps it onto the ended event as observedAt, and both the translator's settledTurnLifecycle and host-recovery's settleUnexpectedStructuredAgentSessionExit now prefer event.observedAt over now, so a backpressured settlement retried much later still writes the turn's completedAt from the original receipt.
  • Registered a completed-turn-duration reliability gate — agent-session.completed-turn-duration in config/reliability-gates.jsonc pins the seven test files that prove duration/attribution survival with value-based oracles.
  • New/updated tests — a codex-requested-close-turn-timing suite drives a real backpressure rejection then stale-generation and final close retries to assert completedAt: 2_000, and the unexpected-exit retry test is parameterized over observedAt (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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread config/reliability-gates.jsonc Resolved
Merge Sim added 2 commits September 9, 2026 22:09
… 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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-duration gate's stale assertionRefs entry), which this commit does not touch.

Reviewed changes

  • Host-clock publication for the live counter — the host now stamps hostNow once per published frame (AgentSessionSubscribers) and on history pages, 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. The structuredAgentTurnLocalStartedAt lag no-op is gone: with a host clock the anchor subtracts real elapsed, and the observedAt - startedAt term survives only as the older-host fallback.
  • Rewind turn-row retention — mergeRetainedTurnRows / isRetainedTurnRow splice the host's turn rows back around the provider spine through both the Codex preflight and the final provider list, and recoverStructuredRewind excludes 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 — publishNewEpoch now writes v: 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 — reduceStructuredAgentSession gains a receivedAt parameter and a hostClock field; backgroundTaskStatesEqual is extracted to a shared module and emptyAgentSessionBatch replaces 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Completed turn before renderer reload · 653e2f150a

Before renderer reload

After renderer reload

After renderer reload

After full app restart with the same profile

After full app restart

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Second review loop is complete at 653e2f150a83d78bf8e695b3c5795c7e329ad5f5.

  • Functional correctness: independent source review returned clean after fixes for exit-receipt inflation during retries, lost attribution in loaded history, and local duration estimates overriding an explicitly unknown host result (including legacy rows without a start). Retained turns now survive rewind, and coalesced sends preserve the initiating prompt.
  • Architectural fit: the execution host owns a durable turn record and its timing; clients derive the completed label from that record. Unknown timing remains authoritative through the shared desktop/mobile consumer. This removes renderer lifetime as the persistence boundary without another timer, polling loop, or separate timing store.
  • Compatibility: canonical turn rows use journal v3 while epoch markers stay v2; clients lacking agent-session.turn-item.v1 receive the legacy status carrier. Older hosts refuse future journal versions safely rather than truncating them; this is read-only rollback behavior, not seamless downgrade editing.
  • Validation: START and END readiness audits plus independent review completed. Four sequential typechecks passed after the last source change; the final eight-file gate passed 58 tests in 4.65s. Consumer checks passed 64 shared/desktop and 54 mobile tests, with 31 targeted tests after the final upgrade fix; these runs overlap. Owned-file quality/hooks and the 119-gate manifest validator passed. The final commit only records gate evidence; tested source is 5acb404bf2.

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 v: 3, kind: turn, durationMs: 3296 after restart; actual authenticated old-capability history and initial subscription responses publish kind: status with that same duration, while modern-capability responses publish kind: turn. RPC render items have no row-version field; storage and publication were inspected separately.

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 orca emulator, but the screenshot provider had no visible Simulator window; mobile visual acceptance remains blocked. A disposable Linux SSH target authenticated and ran the relay, but Electron stalled in Keychain decryption before a remote turn completed; SSH visual acceptance remains blocked. Windows/Linux runtime, real old-host rollback, accumulated-history profiling and CI soak were not run; the reliability gate remains experimental.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — NativeChatSettledTurns now carries null per turn; an unverifiable (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 fold hasUnansweredStructuredAgentSessionDispatch in, 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/trimRetainedItems cap the reducer's live window at 1024 and force hasOlder when 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 3 commits September 10, 2026 11:20
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 to AgentSessionBackgroundTaskState.settledTasks, updating use-structured-agent-session.ts, NativeChatStructuredSession.tsx, and agent-session-background-task-state-equality.ts accordingly. These reconciles are correct.
  • Older-page anchor reconcile (#19845) — the reducer's older-page action now carries requestedCursor with a head.sequence > requested.sequence guard, 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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-unused agentSessionBackgroundTasksEqual import from the reducer (equality lives in the shared backgroundTaskStatesEqual module); repaired the retention test's older-page dispatches to carry requestedCursor: { epoch, sequence: Number.MAX_SAFE_INTEGER } instead of the removed requestedEpoch; consolidated a duplicate agent-session-journal-types import in use-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 null in settledTurns (the authoritative unknown-duration result outranks the client clock; the live counter renders from isWorking/workingStartedAt separately), and the expectation was updated to ['u2', null].
  • Split two files back under the line cap (3149caa) — the host's four mutation delegates moved to structured-agent-session-host-mutations.ts, and the refusal vocabulary moved to agent-session-wire-refusals.ts (re-exported from agent-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).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Both sides added a client capability to the same lists; each keeps its own.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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's AGENT_SESSION_TURN_ITEM_CAPABILITY in the desktop IPC clientCapabilities lists and in RUNTIME_CAPABILITIES.
  • Relocated attach-failure teardown — forgetStructuredAgentSession is imported/used from the new structured-agent-session-host-lifetime.ts (upstream refactor), reconciled in structured-agent-session-attach-orchestration.ts.
  • Shared type import — agent-session-wire.ts now imports the upstream AgentSessionBackgroundTaskState alongside 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.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 lists AGENT_SESSION_TURN_ITEM_CAPABILITY, so the CLI and every shared remote request/control/subscription transport name it in their handshake. Mobile already carried it in additionalCapabilities, so the Set deduplicates it with no net change.
  • Web renderer handshake — web-runtime-connection-frame-router.ts adds the capability to its e2ee_auth frame, so a browser-based client also opts into the typed turn record.
  • CLI transport test — websocket-transport.test.ts now expects the new capability in the emitted clientCapabilities.

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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.ts now includes AGENT_SESSION_TURN_ITEM_CAPABILITY in the e2ee_auth frame's expected clientCapabilities, matching the production list routeWebRuntimeConnectionFrame gained in e88c377 (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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 merged commit 2626e2e into main Sep 10, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant