Skip to content

perf(editor): stop hidden panels duplicating remote reloads - #13634

Merged
nwparker merged 5 commits into
mainfrom
nwparker/perf-hidden-editor-external-reloads
Aug 11, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/perf-hidden-editor-external-reloads

Conversation

@nwparker

@nwparker nwparker commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Stops clean hidden editor panels from fetching external file changes immediately; they invalidate their cache and reload lazily when revealed.
  • Keeps dirty drafts and app-level conflict tracking intact while generation checks prevent stale file or diff reads from restoring invalidated content.
  • Shares one fresh read across source and Markdown-preview mirrors for the same external event.
  • Gates hidden initial, retry, Git-status, file-nonce, and diff-nonce reads, and invalidates inactive cached Changes diffs.
  • Routes Cmd/Ctrl+S to the focused main or floating editor by file ID so same-file mirrors save once.

A synthetic SSH-style external event with ten retained panels dropped from 10 content RPCs (one useful owner read plus nine hidden reads) to 1: a 90% reduction.

ELI5

Previously, every editor tab kept asking the remote host for a fresh copy when a file changed, even if nine of ten tabs were tucked away. Now the visible tab fetches once, hidden tabs place a bookmark saying 'refresh me when opened,' and matching source/preview views reuse the same delivery.

flowchart LR
  W[External file event] --> V{Visible owner?}
  V -- Yes --> R[One generation-scoped read]
  V -- Hidden and clean --> I[Invalidate local cache]
  V -- Dirty --> D[Preserve draft and conflict state]
  I --> O[Reveal panel]
  O --> L[Lazy reload]
  R --> M[Source and preview reuse one promise]
Loading

Screenshots

No visual change.

Testing

  • pnpm lint (only pre-existing WorktreeJumpPalette exhaustive-deps warnings)
  • pnpm run typecheck
  • pnpm run check:code-quality:changed (zero new findings)
  • pnpm run check:react-doctor:changed (0 issues after the CI follow-up)
  • Focused regression suite: 11 files / 135 tests passed
  • pnpm test: 4,598 files / 49,277 tests passed; its only local harness failure was the unrelated default cross-version selector choosing legacy v799, which lacks src/main
  • Cross-version harness rerun with ORCA_CROSS_VERSION_BASELINE_REF=v1.4.178: 4/4 passed
  • pnpm run build:electron-vite
  • pnpm build (targeted Electron Vite build passed; full native packaging build not run locally)
  • Formatting, file-scoped lint, max-lines ratchet, and git diff --check
  • Added regression coverage for visibility, stale reads, retries, nonces, Git status, mirrored saves, floating routing, and folder/SSH routing

Red before / green after

Before the fix, 4 of 5 new regression tests failed. One synthetic SSH-style change caused 10 reads, and unrelated visible and hidden panels also handled the save request.

After the fix, all 135 focused tests pass. Source and preview share one actual readRuntimeFileContent, and ten retained panels produce one RPC instead of ten (10→1, 90% fewer). The same-commit visibility regression also fails at two reads with passive ref synchronization and passes at one with commit-time synchronization.

AI Review Report

The review checked visibility authority, cache generations, in-flight races, listener/timer cleanup, source/preview ownership, floating-panel routing, SSH/folder/runtime-host behavior, and macOS/Linux/Windows shortcut handling.

The review and first CI pass flagged four issues that were fixed before handoff:

  • Same-file split mirrors could issue duplicate saves.
  • Canceling a hidden retry timer could consume retry budget.
  • Inactive cached Changes diffs could stay stale after an external edit.
  • Render-time ref writes could leak values from a discarded React render; refs now synchronize during commit.

Cross-platform review confirmed the save shortcut chooses Meta on macOS and Ctrl on Linux/Windows, with no new path, shell, label, or Electron platform assumptions. The final repository review found no blocking correctness issue.

Security Audit

No dependency, command execution, shell, secret, credential, or remote-wire changes were introduced. The change adds no IPC channel or opcode and keeps existing external-path authorization and runtime ownership boundaries in place. File IDs scope renderer save requests without weakening path validation. Dirty drafts and conflict state remain preserved.

The deferred client-local authorization edge noted below can cause an extra read only; it does not bypass authorization or change content ownership.

Notes

  • No remote-wire change: mixed-version clients and hosts continue using the existing payloads and opcodes.
  • SSH, folder workspaces, and runtime-host paths register synchronously and are covered.
  • Deferred P3: dedupe can miss client-local external/live-tail files when asynchronous authorization for mirrored panels resolves on separate turns. Ordinary SSH/folder/runtime-host traffic is unaffected.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 7 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 30e8822d-ca36-452e-847c-f7f5a55b4595

📥 Commits

Reviewing files that changed from the base of the PR and between 7671320 and a633b95.

📒 Files selected for processing (5)
  • src/renderer/src/components/editor/editor-cmd-save-target.test.ts
  • src/renderer/src/components/editor/editor-cmd-save-target.ts
  • src/renderer/src/components/editor/editor-panel-content-types.ts
  • src/renderer/src/components/editor/useEditorPanelContentState.ts
  • src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx
📝 Walkthrough

Walkthrough

The editor now uses shared save-target helpers and typed command-save events. Save requests target the active editor or the owning floating editor, including Markdown preview source files. Editor panels receive visibility and save-ownership state. Hidden panels defer file and diff reads, invalidate stale content, and reload when shown. External changes use event generations to coordinate reloads. Retry attempts are recorded only after valid delayed retries. Tests cover save routing, visibility, invalidation, floating panels, and retry behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.35% 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 and concisely describes the primary performance change: preventing hidden editor panels from duplicating remote reloads.
Description check ✅ Passed The description includes all required sections, detailed testing results, AI review findings, cross-platform checks, security audit coverage, and noted follow-up work.
✨ 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/editor/useEditorPanelContentState.ts (1)

141-158: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider scoping the retry-budget reset to explicit reload intent.

invalidateFileContent deletes fileLoadRetryAttemptsRef.current[fileId] for every invalidated file. The external-change handler calls invalidateContent for all matching hidden or inactive tabs. A tab that is currently exhausting its owner-not-ready budget therefore gets a fresh budget from an unrelated watcher event on the same path. The budget only matters for a visible tab, so the practical effect is bounded, but the reset is broader than the nonce-driven reload intent that needs it.

If you want the reset only for explicit reload requests, add a flag:

♻️ Optional scoping of the retry reset
-  const invalidateFileContent = useCallback((fileIds: string[]): void => {
+  const invalidateFileContent = useCallback((fileIds: string[], resetRetries = true): void => {
     const uniqueIds = new Set(fileIds)
     for (const fileId of uniqueIds) {
       fileReadGenerationRef.current[fileId] = ++fileReadGenerationCounterRef.current
-      delete fileLoadRetryAttemptsRef.current[fileId]
+      if (resetRetries) {
+        delete fileLoadRetryAttemptsRef.current[fileId]
+      }
     }
src/renderer/src/components/editor/useEditorPanelExternalContentEvents.test.tsx (1)

36-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the parameter-object cast so signature drift fails the build.

as Parameters<typeof useEditorPanelExternalContentEvents>[0] suppresses type checking for the whole options object. If a parameter is renamed, removed, or added to UseEditorPanelExternalContentEventsParams, this test still compiles and can assert against stale wiring. Type the individual mocks instead, and pass the object without a cast.

♻️ Proposed typed wiring
+type HookParams = Parameters<typeof useEditorPanelExternalContentEvents>[0]
+
 function ExternalContentProbe({ activeFileId, calls, isVisible, openFiles }: ProbeProps): null {
@@
   useEditorPanelExternalContentEvents({
     activeContentFileIdRef,
     editorViewModeRef,
-    invalidateContent: calls.invalidate,
-    invalidateDiffContent: calls.invalidateDiff,
+    invalidateContent: calls.invalidate as HookParams['invalidateContent'],
+    invalidateDiffContent: calls.invalidateDiff as HookParams['invalidateDiffContent'],
     isVisibleRef,
-    loadDiffContent: calls.loadDiff,
-    loadFileContent: calls.loadFile,
+    loadDiffContent: calls.loadDiff as HookParams['loadDiffContent'],
+    loadFileContent: calls.loadFile as HookParams['loadFileContent'],
     openFilesRef,
     setDiffContents,
     setFileContents
-  } as Parameters<typeof useEditorPanelExternalContentEvents>[0])
+  })
   return null
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c27909c1-90dc-405f-9fc3-6acdef80eb49

📥 Commits

Reviewing files that changed from the base of the PR and between 56b6d84 and b58e992.

📒 Files selected for processing (20)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/editor/EditorPanel.tsx
  • src/renderer/src/components/editor/editor-autosave.ts
  • src/renderer/src/components/editor/editor-cmd-save-target.test.ts
  • src/renderer/src/components/editor/editor-cmd-save-target.ts
  • src/renderer/src/components/editor/editor-save-target.ts
  • src/renderer/src/components/editor/useEditorCmdSaveRequest.test.tsx
  • src/renderer/src/components/editor/useEditorCmdSaveRequest.ts
  • src/renderer/src/components/editor/useEditorPanelContentState.ts
  • src/renderer/src/components/editor/useEditorPanelExternalContentEvents.test.tsx
  • src/renderer/src/components/editor/useEditorPanelExternalContentEvents.ts
  • src/renderer/src/components/editor/useEditorPanelFileLoadRetry.test.tsx
  • src/renderer/src/components/editor/useEditorPanelFileLoadRetry.ts
  • src/renderer/src/components/editor/useEditorPanelSave.ts
  • src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx
  • src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx
  • src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx
  • src/renderer/src/components/tab-group/TabGroupPanel.tsx
  • src/renderer/src/components/tab-group/TabGroupSplitLayout.test.ts
  • src/renderer/src/components/tab-group/TabGroupSplitLayout.tsx

Comment on lines +141 to +153
beforeEach(() => {
snapshots.clear()
mocks.getRuntimeGitDiff.mockReset()
mocks.readRuntimeFileContent.mockReset()
mocks.getState.mockReset()
mocks.getState.mockReturnValue({
settings: null,
openFiles: [],
setLastKnownDiskSignature: vi.fn()
})
container = document.body.appendChild(document.createElement('div'))
root = createRoot(container)
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find Vitest setup files and any global IS_REACT_ACT_ENVIRONMENT assignment.
set -euo pipefail

fd -e ts -e mts -e js -e mjs --iglob '*vitest*' --iglob '*vite.config*' . | head -50
rg -n 'setupFiles|globalSetup' --glob '*vite*config*' --glob '*vitest*' .
rg -n 'IS_REACT_ACT_ENVIRONMENT' -g '!**/node_modules/**' .

Repository: stablyai/orca

Length of output: 331


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' 'Candidate Vitest/Vite files:'
fd --type f \( -e ts -e mts -e js -e mjs \) . | rg '(^|/)([^/]*(vitest|vite\.config)[^/]*)$' | head -50

printf '%s\n' 'Setup configuration references:'
rg -n 'setupFiles|globalSetup' --glob '*vite*config*' --glob '*vitest*' . || true

printf '%s\n' 'Act-environment assignments:'
rg -n 'IS_REACT_ACT_ENVIRONMENT' -g '!**/node_modules/**' . || true

Repository: stablyai/orca

Length of output: 485


🏁 Script executed:

#!/bin/bash
set +e

printf '%s\n' 'Candidate Vitest/Vite files:'
fd --type f . 2>/dev/null | rg '(^|/)([^/]*(vitest|vite\.config)[^/]*)$' | head -50

printf '%s\n' 'Setup configuration references:'
rg -n 'setupFiles|globalSetup' --glob '*vite*config*' --glob '*vitest*' . || true

printf '%s\n' 'Act-environment assignments:'
rg -n 'IS_REACT_ACT_ENVIRONMENT' -g '!**/node_modules/**' . || true

Repository: stablyai/orca

Length of output: 12215


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' 'Vitest configuration:'
cat -n config/vitest.config.ts | sed -n '1,140p'

printf '%s\n' 'Renderer test scripts and config references:'
rg -n -C 3 'vitest|config/vitest|electron\.vite|src/renderer' package.json config electron.vite.config.ts 2>/dev/null | head -160

printf '%s\n' 'Target and sibling flag context:'
for f in \
  src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx \
  src/renderer/src/components/editor/useEditorPanelExternalContentEvents.test.tsx
do
  printf '\n--- %s ---\n' "$f"
  rg -n -C 5 'IS_REACT_ACT_ENVIRONMENT|beforeEach|afterEach|act\(' "$f" | head -180
done

Repository: stablyai/orca

Length of output: 23106


Set IS_REACT_ACT_ENVIRONMENT before creating the root. No shared renderer setup assigns this flag. Add globalThis.IS_REACT_ACT_ENVIRONMENT = true in beforeEach, as in the sibling test.

- Mark invalidated file content stale instead of dropping it so a reveal swaps
  bytes in place; the read-generation fence already blocks stale write-backs.
- Skip the lazy read when the newest read for the tab is still outstanding, so
  a worktree flip-flop cannot double-fetch.
- Stop claiming Cmd/Ctrl+S outside the workspace view, where no mounted panel
  owns the request and the keystroke was silently swallowed.
@nwparker
nwparker merged commit baeb1b3 into main Aug 11, 2026
44 checks passed
nwparker added a commit that referenced this pull request Aug 11, 2026
…13777)

Mark invalidated diff content stale instead of dropping it, mirroring the file-content treatment from #13634. The diff read-generation fence (diffReadGenerationRef) already rejects a superseded read's write-back, so retaining the bytes and swapping them on arrival is safe and keeps every RPC saving -- it just stops the loading placeholder flashing on each reveal.

The git-status reload effect now treats a stale entry like a missing one so the lazy-load effect stays the single fetcher for it.

Co-authored-by: Orca <[email protected]>
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
…#13634)

* perf(editor): park hidden external reloads

* fix(editor): sync content refs after commit

* fix(editor): close post-commit ref window

* test(editor): cover commit-time visibility

* fix(editor): keep invalidated content visible and stop redundant reads

- Mark invalidated file content stale instead of dropping it so a reveal swaps
  bytes in place; the read-generation fence already blocks stale write-backs.
- Skip the lazy read when the newest read for the tab is still outstanding, so
  a worktree flip-flop cannot double-fetch.
- Stop claiming Cmd/Ctrl+S outside the workspace view, where no mounted panel
  owns the request and the keystroke was silently swallowed.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#13777)

Mark invalidated diff content stale instead of dropping it, mirroring the file-content treatment from stablyai#13634. The diff read-generation fence (diffReadGenerationRef) already rejects a superseded read's write-back, so retaining the bytes and swapping them on arrival is safe and keeps every RPC saving -- it just stops the loading placeholder flashing on each reveal.

The git-status reload effect now treats a stale entry like a missing one so the lazy-load effect stays the single fetcher for it.

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