Skip to content

perf(native-chat): suspend hidden transcript streams - #13622

Merged
nwparker merged 4 commits into
mainfrom
nwparker/perf-suspend-hidden-native-chat
Aug 11, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/perf-suspend-hidden-native-chat

Conversation

@nwparker

@nwparker nwparker commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This is a focused performance follow-up to #13525.

  • Suspend Native Chat transcript reads, subscriptions, retry timers, and pagination while the pane or owning worktree is hidden.
  • Keep the committed transcript, read phase, lifecycle status, and scroll/UI state mounted for an instant return.
  • On reveal, start exactly one fresh read and one fresh stream; fence late work from the prior source generation.
  • Clear retained transcript data when a hidden view changes owner, session, or path so stale content cannot bleed across sources.

ELI5

Each visible chat keeps a live call open to the transcript's host. Hiding the tab used to leave that call—and the host's file watcher and once-a-second safety check—running. Orca now hangs up while keeping the last conversation on screen, then makes one fresh call when the tab returns. Any old callers that finish late are ignored.

Lifecycle

flowchart LR
  V[Visible Native Chat] --> F[Fresh read + stream]
  F --> T{Transcript transport}
  T -->|Local or direct SSH| I[Desktop IPC subscription]
  T -->|Paired web| W[Paired-runtime child stream]
  T -->|Runtime-owned desktop| D[Dedicated environment stream]
  I --> L[Desktop-side watcher or resolve poll]
  W --> H[Runtime-host watcher or resolve poll]
  D --> H
  L --> R[fs.watch + 1 s reconciliation]
  H --> R

  Z[Hidden] --> X[Fence late reads, pages, and frames]
  X --> C[Cancel retry + close stream]
  C --> Q[Dispose watcher or abort resolve poll]
  Z --> K[Keep committed transcript and UI state]
  K -->|Reveal| F
  F --> A[Fresh authoritative snapshot]
Loading

Direct SSH uses the desktop-local IPC path, so hiding releases the desktop-side watcher or resolve poll; this does not claim teardown of a watcher on the SSH host.

Quantitative proof

  • Initially hidden: 0 reads and 0 subscriptions.
  • Visible → hidden: 1 unsubscribe; advancing the fake clock by 60,000 ms produces 0 retry reads.
  • Invoking the old callback with 1,000 stale appended frames after hide causes +0 Probe renders and no committed-message mutation.
  • Reveal adds exactly 1 fresh read and 1 fresh subscription; the old stream stays closed and its late snapshot cannot win.
  • A stale pagination race cannot overwrite the reveal seed: 3 total reads (initial, old page, reveal seed), with only the fresh generation accepted.
  • Installed host subscriptions release their native watcher, one-second reconciliation scheduler, retry/debounce state, parser state, and watcher census entry. Pending setup releases its resolve-poll timer and abort controller.

The 1,000-frame result measures transcript-frame-induced hook renders by directly invoking a stale callback; it is not a claim of zero renders or zero store subscriptions for the entire retained Native Chat tree.

Reliability contract

While a retained transcript generation is disabled, it starts no transcript read or stream; any prior stream and scheduled retry are closed, and late frame/read/page results cannot mutate committed state. The first re-enable starts exactly one read and one stream, whose authoritative snapshot replaces retained data.

A controlled transport-spy/deferred harness counts reads, subscriptions, unsubscriptions, and Probe renders while resolving old reads, frames, deferred teardown handles, and pagination out of order. The focused regression fails on hidden I/O, a duplicate reveal stream, post-hide retry, stale overwrite, or transcript-frame-induced hidden render.

This is contract-level lifecycle/race coverage across transports, not a live SSH or paired-host end-to-end benchmark. The deterministic lifecycle suite is the focused oracle; no dedicated reliability-manifest entry was added.

Transport and compatibility

  • Local desktop teardown removes the renderer IPC listener and unsubscribes pending or installed desktop-side transcript setup.
  • Paired web sends the keyed unsubscribe and closes its child stream; runtime cleanup then aborts pending setup or disposes the installed host watcher.
  • Runtime-owned desktop cancels reconnect work and closes its dedicated environment stream; connection cleanup disposes host setup/watchers.
  • Synchronous teardown and late/deferred stream acquisition use the same normalized cleanup path.
  • Already-started reads are not aborted. After hide they may run until their existing timeout (up to 15 seconds remotely), but their results are ignored.
  • Retained Zustand selectors remain mounted, so this does not claim zero total hidden renders or subscriptions.
  • No wire format, IPC/RPC shape, persistence, path, shell, mobile, or visual behavior changed.
  • Folder workspaces, local worktrees, direct SSH, paired web, runtime-owned desktop, and mixed client/host versions retain their existing transport contracts.

Validation

Scope Result
Focused renderer lifecycle matrix 4 files, 54 tests passed
Broader Native Chat matrix 96 files, 939 tests passed
Host teardown matrix 5 files, 69 tests passed
Exact-claim audit rerun 4 files, 36 tests passed
Initial exact-tip independent review suite 5 files, 57 tests passed
Final exact-tip delta review 4 focused files, 38 tests passed; React Doctor 0 issues
Changed-code quality review 0 findings across 8 files
Max-lines and reliability gates Ratchet passed; all 73 manifest gates passed
Lint pnpm lint passed; only pre-existing WorktreeJumpPalette.tsx warnings
Desktop build Full pnpm build:desktop passed, including typecheck, relay targets, CLI, Electron/Vite, and web projection

Exact-tip AI review at 459689b655bfef18fa21d043dcdb5360992662c9: clean, with no P0/P1/P2 findings.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review 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

Native chat views now receive renderer visibility and enable retained-session transcript I/O only while visible. The live-session hook retains committed messages while hidden, cancels streams and retries, rejects stale reads and pagination results, and resumes with a fresh source generation. Retry scheduling, stream teardown, and message assembly moved into dedicated helpers. Shared view prop types were added. Tests cover visibility, lifecycle, teardown, retries, transcript changes, and pagination races.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 identifies the main change: suspending hidden Native Chat transcript streams for performance.
Description check ✅ Passed The description is detailed and covers the change, lifecycle, validation, compatibility, and lack of visual changes, but it omits several template headings.
✨ 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: 1

🧹 Nitpick comments (2)
src/renderer/src/components/native-chat/use-native-chat-live-session-visibility.test.ts (2)

322-324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the subscription limit after a source change.

The test verifies only readSession after the source changes. subscribe has a separate limit argument. Add an assertion for transport.subscribe.mock.calls[2]?.[0]?.limit so the test detects a stale paged stream subscription.


341-342: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the public status recovers.

The test verifies readPhase and messages after the read resolves. It does not verify that status leaves 'error'. Add an assertion for the public status so this test detects an error UI that remains after the seeded read succeeds.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ccb200a7-ed6c-4688-87e7-d7fc26606957

📥 Commits

Reviewing files that changed from the base of the PR and between 459689b and c191ed64a3ba6d0b79f7ea8b5d36ba8dc2d31f77.

📒 Files selected for processing (6)
  • src/renderer/src/components/native-chat/use-native-chat-live-session-visibility.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.ts
  • src/renderer/src/components/native-chat/use-native-chat-retained-session.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-retained-session.ts
  • src/shared/native-chat-transcript-retention.test.ts
  • src/shared/native-chat-transcript-retention.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/native-chat/use-native-chat-live-session.ts

Comment on lines 43 to +51
if (messages === session.messages && readPhase === session.readPhase) {
return session
}
return {
...session,
messages,
readPhase,
...(sessionMatchesIdentity ? {} : { status: 'loading' as const, error: undefined })
if (!sessionMatchesIdentity) {
return { ...session, messages, readPhase, status: 'loading', error: undefined }
}
// Retained history beats the full-pane error: a reveal-time read/stream failure is usually transient.
if (session.status === 'error' && messages.length > 0) {
return { ...session, messages, readPhase, status: 'ready', error: undefined }

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

Handle retained errors before the identity fast path.

If an error session reuses the captured message array, line 43 returns the original status: 'error' session. The error suppression at line 50 then does not run. Move the error branch before the reference-equality return. Add a test where the error session uses the captured message array.

Proposed fix
-  if (messages === session.messages && readPhase === session.readPhase) {
-    return session
-  }
   if (!sessionMatchesIdentity) {
     return { ...session, messages, readPhase, status: 'loading', error: undefined }
   }
-  // Retained history beats the full-pane error: a reveal-time read/stream failure is usually transient.
   if (session.status === 'error' && messages.length > 0) {
     return { ...session, messages, readPhase, status: 'ready', error: undefined }
   }
+  if (messages === session.messages && readPhase === session.readPhase) {
+    return session
+  }
📝 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
if (messages === session.messages && readPhase === session.readPhase) {
return session
}
return {
...session,
messages,
readPhase,
...(sessionMatchesIdentity ? {} : { status: 'loading' as const, error: undefined })
if (!sessionMatchesIdentity) {
return { ...session, messages, readPhase, status: 'loading', error: undefined }
}
// Retained history beats the full-pane error: a reveal-time read/stream failure is usually transient.
if (session.status === 'error' && messages.length > 0) {
return { ...session, messages, readPhase, status: 'ready', error: undefined }
if (!sessionMatchesIdentity) {
return { ...session, messages, readPhase, status: 'loading', error: undefined }
}
if (session.status === 'error' && messages.length > 0) {
return { ...session, messages, readPhase, status: 'ready', error: undefined }
}
if (messages === session.messages && readPhase === session.readPhase) {
return session
}

@nwparker
nwparker force-pushed the nwparker/perf-suspend-hidden-native-chat branch from 63b1dc5 to f54ac09 Compare August 11, 2026 08:06
nwparker and others added 4 commits August 11, 2026 01:14
- An error snapshot frame no longer latches frameArrived, so the in-flight
  read can still seed the pane instead of leaving it on the error surface.
- Retained history is shown over a full-pane read error for the same source.
- The paged read window survives a hide/reveal; only a source change resets it.

Co-authored-by: Orca <[email protected]>
The shared retention type no longer takes `loading`, so mobile's call was an
excess-property error that broke the mobile typecheck job. Dropping it also
lets mobile inherit the desktop behavior: a stream error or dropped client
keeps the last transcript instead of swapping it for the error empty state.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-suspend-hidden-native-chat branch from f54ac09 to 1b0c588 Compare August 11, 2026 08:14
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker nwparker closed this Aug 11, 2026
@nwparker nwparker reopened this Aug 11, 2026
@nwparker
nwparker merged commit b3965f3 into main Aug 11, 2026
89 of 91 checks passed
nwparker added a commit that referenced this pull request Aug 11, 2026
The stream-gating hook (#13608) and the subscription parking installer
(#13621) each reimplemented `isWindowVisible() || isDocumentVisibilityProvenStale()`
plus its visibilitychange + stale-recovery subscription, and each carried
its own 500ms park delay that agreed only by coincidence.

Extract both into `lib/window-park-visibility.ts` and leave the two
consumers as thin wrappers: `useWindowStreamVisible` feeds the snapshot
and subscribe into `useSyncExternalStore`, the parking installer calls
them imperatively. The subscribe now always uses the defensive
`typeof document` guard the parking side already had, and registers
stale recovery before the visibilitychange listener so the stale latch
is cleared before the callback reads it.

Both park delays now derive from one `WINDOW_HIDE_PARK_GRACE_MS`: they
debounce the same signal against the same user behaviour (a quick
app-switch round trip). The parking side's 8x reveal-side backoff stays
where it is - that models its own resume cost, not the grace window.

Renderer-authoritative gating (#13622 native chat, #13634 editor panels)
is deliberately left alone; it keys off Zustand routing state, not OS
visibility.

Also switch the active-runtime ref writes in web-session-tabs-sync to
`useLayoutEffect` so no resume event can land between paint and the
passive flush, and correct the stale comment above them - the install
effect reads neither ref (both readers are gated on `isVisibilityResume`).
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* perf(native-chat): suspend hidden transcript streams

* fix(native-chat): keep assembly renders pure

* fix(native-chat): keep a transient error from stranding a revealed chat

- An error snapshot frame no longer latches frameArrived, so the in-flight
  read can still seed the pane instead of leaving it on the error surface.
- Retained history is shown over a full-pane read error for the same source.
- The paged read window survives a hide/reveal; only a source change resets it.

Co-authored-by: Orca <[email protected]>

* fix(mobile): match the trimmed native-chat retention signature

The shared retention type no longer takes `loading`, so mobile's call was an
excess-property error that broke the mobile typecheck job. Dropping it also
lets mobile inherit the desktop behavior: a stream error or dropped client
keeps the last transcript instead of swapping it for the error empty state.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#13778)

The stream-gating hook (stablyai#13608) and the subscription parking installer
(stablyai#13621) each reimplemented `isWindowVisible() || isDocumentVisibilityProvenStale()`
plus its visibilitychange + stale-recovery subscription, and each carried
its own 500ms park delay that agreed only by coincidence.

Extract both into `lib/window-park-visibility.ts` and leave the two
consumers as thin wrappers: `useWindowStreamVisible` feeds the snapshot
and subscribe into `useSyncExternalStore`, the parking installer calls
them imperatively. The subscribe now always uses the defensive
`typeof document` guard the parking side already had, and registers
stale recovery before the visibilitychange listener so the stale latch
is cleared before the callback reads it.

Both park delays now derive from one `WINDOW_HIDE_PARK_GRACE_MS`: they
debounce the same signal against the same user behaviour (a quick
app-switch round trip). The parking side's 8x reveal-side backoff stays
where it is - that models its own resume cost, not the grace window.

Renderer-authoritative gating (stablyai#13622 native chat, stablyai#13634 editor panels)
is deliberately left alone; it keys off Zustand routing state, not OS
visibility.

Also switch the active-runtime ref writes in web-session-tabs-sync to
`useLayoutEffect` so no resume event can land between paint and the
passive flush, and correct the stale comment above them - the install
effect reads neither ref (both readers are gated on `isVisibilityResume`).
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