Skip to content

Fix completed native chat turn duration - #19627

Closed
brennanb2025 wants to merge 6 commits into
mainfrom
brennanb2025/native-chat-completed-turn-duration
Closed

brennanb2025 wants to merge 6 commits into
mainfrom
brennanb2025/native-chat-completed-turn-duration

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​815 $\color{#cf222e}{\Huge{\mathbf{−}}}$​52 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​763
Prod 39 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​716 $\color{#cf222e}{\Huge{\mathbf{−}}}$​148 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​568

Completed structured-chat turns now keep their execution duration after reopening: a turn that finished in 3m 7s still shows Worked for 3m 7s the next morning.

The execution host records turn endpoints in optional journal metadata associated with the durable user message. Snapshots, replay, late provider corrections, cancellation deferral, and retained turns after rewind preserve that evidence. Desktop and mobile calculate completed labels from the persisted interval. Existing working-row tombstones and older-client cancellation and liveness behavior remain intact.

Provider timestamps take precedence. Missing live timestamps use host receipt time captured once before buffering; historical restore never supplies the current time. Missing, invalid, reversed or incompatible-clock intervals show no numeric duration. Mixed provider and host evidence requires matching live acquisition proof.

Validation includes real provider translation → deferred event sink → SQLite close/reopen → shared projection → rendered message list, covering next-morning 3m 7s with an empty renderer cache and a second optimistic turn. Final timing/lifecycle suites passed 67 tests, the clock-merge suite passed 12 tests, and the mobile view suite passed 13 tests. Additional isolated adapter, cancellation, settlement, sink, rewind and reopen suites passed 91 tests. Node, web, CLI and mobile typechecks passed; formatting and lint passed. Two additional lifecycle size-boundary regressions passed, proving timing metadata is included when splitting durable batches. Real Codex Electron turns retained their 4s and 2s durations after renderer reload, full app restart and idle; screenshots and validation limits are attached. The final test-only follow-up passed 155 targeted tests and strengthens persisted mobile disclosure and reconnect identity assertions. GitHub Actions CI passed, including all eight test shards, mobile verification, wire compatibility and Linux/Windows packaging.

@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 completedAt plumbing is inert as shipped: it is wired into the legacy NativeChatResolvedView path — which renders NativeChatMessageList with showTurnStatus={false} and therefore discards the value — while the structured-session surface that actually draws the Worked for row is untouched. The reported bug is not yet fixed.

Reviewed changes

  • Shared reducer, hook, and message-list contract — reduceNativeChatTurnTiming now accepts an optional completedAt and settles a completed turn against completedAt ?? now instead of the render-time clock; useNativeChatTurnStatus and NativeChatMessageList thread the prop through.
  • Desktop wiring attempt — NativeChatResolvedView passes sessionWithPending.transcriptLifecycle.timestamp as completedAt when the lifecycle is completed.
  • Incident doc + regression test — NATIVE_CHAT_DURATION_FIX.md documents the incident, plan, and validation matrix; a deterministic reducer test pins (start 1s, completion 4.507s, viewed at 99s → 3s).

⚠️ The surface that renders Worked for is not wired

NativeChatStructuredSession (mode === 'structured') renders NativeChatMessageList with showTurnStatus enabled and workingStartedAt={null} — this is the path that displays the Worked for row the incident screenshot shows, and it still passes no completedAt. Its session object is a hand-built NativeChatLiveSession shape with no transcriptLifecycle, so there is no completion timestamp available to supply yet. The only live behavior change in this PR is the pure-reducer semantics, with no production caller passing a non-null completedAt.

Technical details
# Wire completedAt into the structured-session path (or re-scope the PR)

## Affected sites
- src/renderer/src/components/native-chat/NativeChatResolvedView.tsx:398 — completedAt prop is discarded (showTurnStatus={false}).
- src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx:193 — renders the Worked-for row, passes workingStartedAt={null} and no completedAt.
- src/shared/native-chat-types.ts:167 — NativeChatTurnLifecycle carries turnId + provider timestamp, currently ignored.

## Required outcome
- The turn that renders "Worked for" settles from an authoritative completion timestamp, not Date.now().
- The completed start/end pair is delivered from the execution host (or projected) rather than fabricated by the renderer.

## Open questions for the human
- Is structured-session persistence (retaining completed start/end in the journal/snapshot) planned as a separate PR? If so, this PR should be re-scoped or retitled as reducer groundwork rather than a fix.

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

Comment thread src/shared/native-chat-turn-status.ts Resolved
@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 075169ea-6ce6-44d9-b2f4-c63e0a2c5712

📥 Commits

Reviewing files that changed from the base of the PR and between a70d5d7 and 793d9cb.

📒 Files selected for processing (2)
  • mobile/src/session/use-mobile-native-chat-turn-disclosure.test.tsx
  • src/main/runtime/structured-agent-session-integration.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The change adds durable turn-timing metadata for Claude and Codex sessions. Provider and host timestamps flow through notification handling, journal persistence, reducer state, message projection, and native-chat status rendering. Completed durations now use explicit completion evidence or persisted journal endpoints. Tests cover invalid timestamps, retries, replay, late corrections, rewinds, mobile rendering, and end-to-end duration persistence.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 793d9

The change persists completed-turn durations across replay and reopening, but a desktop status configuration may suppress the new duration and some timing updates may cause unnecessary message-list churn. Resolve these behaviors before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.96% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 54 functions across 52 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the implementation, motivation, validation, and known gaps, but it does not follow the required template. It omits the required ELI5, What Changed, Why, Linked Issue, Visual P… Complete the required template sections. Add a linked issue after Fixes #, provide visual proof or write N/A with a reason, document testing and platform coverage, complete the required checkboxes, address AI disclosure and review field…
✅ 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 summarizes the main change: completed native chat turn durations now persist and display correctly.
Full details: Description check

Explanation

The description explains the implementation, motivation, validation, and known gaps, but it does not follow the required template. It omits the required ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. It also does not provide the required issue link or explicit checklist status.

Resolution

Complete the required template sections. Add a linked issue after Fixes #, provide visual proof or write N/A with a reason, document testing and platform coverage, complete the required checkboxes, address AI disclosure and review fields, and include the agent skill upstream boundary statement.

  • Fix all pre-merge checks with AI
✨ 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: 882240b2-c43b-46a3-856d-8d6b9eb9ff79

📥 Commits

Reviewing files that changed from the base of the PR and between 4f0e380 and eaf2828.

📒 Files selected for processing (6)
  • NATIVE_CHAT_DURATION_FIX.md
  • src/renderer/src/components/native-chat/NativeChatMessageList.tsx
  • src/renderer/src/components/native-chat/NativeChatResolvedView.tsx
  • src/renderer/src/components/native-chat/use-native-chat-turn-status.ts
  • src/shared/native-chat-turn-status.test.ts
  • src/shared/native-chat-turn-status.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Comment thread NATIVE_CHAT_DURATION_FIX.md Resolved
Comment on lines +398 to +402
completedAt={
sessionWithPending.transcriptLifecycle?.state === 'completed'
? sessionWithPending.transcriptLifecycle.timestamp
: null
}

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 | 🟠 Major | ⚡ Quick win

Enable the timing consumer on this path.

NativeChatMessageList forwards completedAt only when showTurnStatus is true, but this call sets showTurnStatus={false} on Line 403. The added value is therefore replaced with null, and this list does not render NativeChatWorkingStatus. The desktop path cannot use this completion timestamp. Enable the timing path here or pass the timestamp to the actual desktop duration renderer.

Comment thread src/shared/native-chat-turn-status.ts Resolved

@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 fallback change in this delta removes the render-time settle, but since no production surface passes a real completedAt, completed turns now display no duration — and on mobile the Worked for N disclosure row disappears entirely. See the inline comment on the reducer gate.

Reviewed changes

  • Reducer settle now requires completion evidence — reduceNativeChatTurnTiming no longer falls back to now; a completed turn without completedAt is retained instead of settling.
  • Test updates — the "settles ... when work stops" case became "does not settle a completed duration without completion evidence", plus a new completion-evidence case, and completedAt threaded through the re-key tests.
  • Structured persistence attempt reverted — 1a22dc8156 ("Persist structured turn duration endpoints") and its revert 41afda986c net to zero, so the structured path remains unwired.
  • Incident doc removed — NATIVE_CHAT_DURATION_FIX.md was deleted in 7dc6ca2027.

⚠️ The fix is suppressed rather than delivered

No path in this PR can render a correct completed duration. The one structural attempt to pipe authoritative endpoints through the structured journal/projection/session (1a22dc8156) was reverted, and the desktop legacy wiring is still discarded behind showTurnStatus={false}. The reported "15h" bug is now masked only because completed durations no longer render at all — the correct "3m 7s" is still unattainable, and (per the inline comment) the mobile surface regresses in the process. If persistence is a separate follow-up, this PR reads as reducer groundwork rather than the fix its title claims.

ℹ️ Nitpicks

  • The PR description still points at NATIVE_CHAT_DURATION_FIX.md for the follow-up, but that file was deleted in 7dc6ca2027.

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

Comment thread src/shared/native-chat-turn-status.ts Resolved

@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: e0815642-6f41-4918-88b9-9189f48cc577

📥 Commits

Reviewing files that changed from the base of the PR and between eaf2828 and 41afda9.

📒 Files selected for processing (2)
  • src/shared/native-chat-turn-status.test.ts
  • src/shared/native-chat-turn-status.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment thread src/shared/native-chat-turn-status.ts Resolved
@brennanb2025

brennanb2025 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Desktop Electron QA by OpenCode Muse Spark 1.3 Free, using an isolated background app and hidden CDP. The first three screenshots show real structured Codex turns on 2c3e3e9008; full app restart, journal replay, and idle checks ran on final HEAD a70d5d7e9a. The intervening production change corrects lifecycle batch-size accounting and has two passing boundary regressions. Setup used a disposable repo/worktree and the rendered Settings and composer.

  • Turn 1 completed live: Worked for 4s (response TURN-OK)
    turn-completed-4s
  • Full renderer reload (empty cache, journal rehydrate): still Worked for 4s
    turn-reloaded-4s
  • Second turn completed Worked for 2s; first turn still Worked for 4s (next-turn identity preserved)
    turn-two-identity
  • App killed + relaunched on final source: journal replay renders 4s + 2s unchanged
    final-head-replay
  • ~3 min idle: still 4s / 2s, no idle inflation; 0 console errors throughout
    final-idle-stable

Gaps: no 15h-scale idle run; live Working-for counting and aborted-turn label not exercised live (unit-covered); mobile validation incomplete per coordinator directive (cancelled capture, no retry). Full private report retained in QA evidence dir.

@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

  • Persisted turn timing through the journal — the execution host now records completed-turn start/end endpoints (AgentJournalTurnTiming) on durable journal rows and threads them through the codex and claude translators into the snapshot projection.
  • Source/clock provenance — each endpoint carries source (provider vs host) and an acquisition clock; a completed duration renders only when both endpoints share a source, or when mixed evidence shares a provable live acquisition.
  • Completed-duration rendering from persisted state — the desktop and mobile hooks wrap status derivation in selectPersistedNativeChatTurnStatuses, so completed turns render Worked for N from message.turnTiming instead of the renderer clock.
  • Regression coverage — end-to-end journal translation → deferred sink → SQLite close/reopen → projection → rendered message list, plus reducer, settlement, batch-partition, cancellation, and clock-merge suites pin the next-morning 3m 7s case and the invalid/reversed/mixed-clock rejections.

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/native-chat/agent-session-journal/journal-row-builders.ts (1)

126-138: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Share the lifecycle mutation row-shaping helper.

The two mappings currently serialize the same fields; only revision differs. Extract a helper that accepts mutation and revision, then use it in both paths. This prevents future field changes from making the partitioner’s byte estimate differ from the row the builder checks.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: a1bab56e-677d-4b87-9467-9aa58a012ffb

📥 Commits

Reviewing files that changed from the base of the PR and between 41afda9 and a70d5d7.

📒 Files selected for processing (48)
  • mobile/src/session/MobileNativeChatView.test.ts
  • mobile/src/session/use-mobile-native-chat-turn-status.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-session-acquisition.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/claude/claude-structured-turn-timing.ts
  • src/main/codex/codex-structured-journal-items.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-turns.ts
  • src/main/codex/codex-structured-journal-translation.ts
  • src/main/codex/codex-structured-notification-retry.ts
  • src/main/codex/codex-structured-notification-timing.test.ts
  • src/main/codex/codex-structured-provider-events.ts
  • src/main/codex/codex-structured-session-acquire.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-turn-cancellation.ts
  • src/main/codex/codex-structured-turn-timing.test.ts
  • src/main/codex/codex-structured-turn-timing.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts
  • src/main/native-chat/agent-session-journal/journal-item-appender.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-batch-partition.test.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-batch-partition.ts
  • src/main/native-chat/agent-session-journal/journal-reducer.ts
  • src/main/native-chat/agent-session-journal/journal-row-builders.ts
  • src/main/native-chat/agent-session-journal/journal-row-schema.ts
  • src/main/native-chat/agent-session-journal/journal-store-contracts.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-journal/journal-turn-timing.test.ts
  • src/main/native-chat/agent-session-journal/journal-turn-timing.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-estimate.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
  • src/renderer/src/components/native-chat/NativeChatMessageList.test.tsx
  • src/renderer/src/components/native-chat/use-native-chat-turn-status.ts
  • src/shared/agent-session-journal-schemas.ts
  • src/shared/agent-session-journal-types.ts
  • src/shared/agent-session-turn-timing.test.ts
  • src/shared/agent-session-turn-timing.ts
  • src/shared/native-chat-turn-status.test.ts
  • src/shared/native-chat-turn-status.ts
  • src/shared/native-chat-types.ts
  • src/shared/structured-agent-session-projection.ts
  • src/shared/structured-agent-session-reducer.test.ts
  • src/shared/structured-agent-session-reducer.ts
  • tests/e2e/native-chat-turn-timing.unit.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/native-chat-turn-status.test.ts
  • src/shared/native-chat-turn-status.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +42 to +47
const touchTiming = (value: unknown): void => {
const key = readAgentJournalTurnTiming(value)?.userItemId
if (key) {
touchedItemIds.add(input.canonicalItemId?.(key) ?? aliases.get(key) ?? key)
}
}

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

Do not report timing-referenced item ids as removed.

touchTiming adds the timing userItemId to touchedItemIds, and line 83 turns every touched id that is not live into a removedItemIds entry. Timing endpoints can arrive before the user item exists; journal-turn-timing.ts line 10 documents that case and stores such timings in pendingTurnTimings. Until the dispatch is accepted, no alias exists, so the provider key does not resolve to a live item.

Two effects follow. The batch emits a removal instruction for an item that was never removed. The non-empty removedItemIds also defeats the journalUnchanged fast path in reduceStructuredAgentSession (src/shared/structured-agent-session-reducer.ts lines 237-261), so the reducer rebuilds items and returns a new state object for a batch with no real change.

Add the timing-derived id only when it resolves to a live item.

🐛 Proposed fix
+  const live = liveItemsById(input.snapshot.items)
   const touchTiming = (value: unknown): void => {
     const key = readAgentJournalTurnTiming(value)?.userItemId
-    if (key) {
-      touchedItemIds.add(input.canonicalItemId?.(key) ?? aliases.get(key) ?? key)
+    if (!key) {
+      return
+    }
+    const itemId = input.canonicalItemId?.(key) ?? aliases.get(key) ?? key
+    // A timing endpoint can precede its user item; an absent item is not a removal.
+    if (live.has(itemId)) {
+      touchedItemIds.add(itemId)
     }
   }

Then reuse that binding instead of the later declaration:

-  const live = liveItemsById(input.snapshot.items)
   const items = [...touchedItemIds]

@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

  • Persisted-duration mobile disclosure tests — use-mobile-native-chat-turn-disclosure.test.tsx now drives completed messages with turnTiming (start 1s → end 6s) and pins workedSeconds to 5 across a next-morning re-render, re-scopes the 128-expansion cap to replayed turns, and adds two cases: activity disclosure under a persisted turn, and no fabricated duration when a live turn stops without endpoints.
  • Reconnect timing integration assertions — structured-agent-session-integration.test.ts verifies that a client dropped mid-turn and reconnected by cursor receives the completion republish on the same user item: a host-sourced end endpoint whose clock matches the start endpoint, an advancing turnTimingSequence, unchanged content, and a projection surfacing that timing on the single user message.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review/fix loop completed at 793d9cbf48. Independent reviews using the same model and reasoning effort found no remaining proven in-scope issues; readiness checks ran at the start and end.

Completed durations now come from execution-owned endpoints persisted with the journal and delivered on reopen/reconnect. The fixes preserve turn identity, cancellation observations, late timing corrections, and lifecycle batch-size accounting. The final follow-up strengthens mobile disclosure and reconnect tests without changing production code.

Validation: 155 targeted tests passed in the final follow-up, alongside the earlier real SQLite reopen/render and batch-boundary regressions. Node, web, CLI and mobile typechecks and applicable lint/format checks passed. GitHub Actions CI is green, including all eight test shards, mobile verification, cross-version wire compatibility and Linux/Windows packaging.

Electron screenshots and manual QA were produced by OpenCode Muse Spark 1.3 Free: real Codex turns retained 4s and 2s after reload, full app restart and idle. The final test-only commit leaves that validated production code unchanged.

Remaining validation gaps: mobile visual QA was cancelled; real Claude UI, overnight manual idle, platform/SSH/relay failure scenarios and mixed-version manual deployment checks and release-scale performance were not exercised. Older turns without trustworthy endpoints remain non-numeric, with mobile activity available through Tools. No merge performed.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Superseded by #19695, which keeps the turn lifecycle row durable instead of attaching timing to the user message. Closing this one.

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