Repository navigation
perf(editor): stop hidden panels duplicating remote reloads - #13634
Conversation
|
Warning Review limit reached
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 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 configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/renderer/src/components/editor/useEditorPanelContentState.ts (1)
141-158: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConsider scoping the retry-budget reset to explicit reload intent.
invalidateFileContentdeletesfileLoadRetryAttemptsRef.current[fileId]for every invalidated file. The external-change handler callsinvalidateContentfor 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 winRemove 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 toUseEditorPanelExternalContentEventsParams, 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
📒 Files selected for processing (20)
src/renderer/src/components/Terminal.tsxsrc/renderer/src/components/editor/EditorPanel.tsxsrc/renderer/src/components/editor/editor-autosave.tssrc/renderer/src/components/editor/editor-cmd-save-target.test.tssrc/renderer/src/components/editor/editor-cmd-save-target.tssrc/renderer/src/components/editor/editor-save-target.tssrc/renderer/src/components/editor/useEditorCmdSaveRequest.test.tsxsrc/renderer/src/components/editor/useEditorCmdSaveRequest.tssrc/renderer/src/components/editor/useEditorPanelContentState.tssrc/renderer/src/components/editor/useEditorPanelExternalContentEvents.test.tsxsrc/renderer/src/components/editor/useEditorPanelExternalContentEvents.tssrc/renderer/src/components/editor/useEditorPanelFileLoadRetry.test.tsxsrc/renderer/src/components/editor/useEditorPanelFileLoadRetry.tssrc/renderer/src/components/editor/useEditorPanelSave.tssrc/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsxsrc/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsxsrc/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsxsrc/renderer/src/components/tab-group/TabGroupPanel.tsxsrc/renderer/src/components/tab-group/TabGroupSplitLayout.test.tssrc/renderer/src/components/tab-group/TabGroupSplitLayout.tsx
| 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) | ||
| }) |
There was a problem hiding this comment.
📐 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/**' . || trueRepository: 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/**' . || trueRepository: 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
doneRepository: 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.
…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]>
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`).
…#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.
…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]>
…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`).
Summary
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]Screenshots
No visual change.
Testing
pnpm lint(only pre-existingWorktreeJumpPaletteexhaustive-deps warnings)pnpm run typecheckpnpm run check:code-quality:changed(zero new findings)pnpm run check:react-doctor:changed(0 issues after the CI follow-up)pnpm test: 4,598 files / 49,277 tests passed; its only local harness failure was the unrelated default cross-version selector choosing legacyv799, which lackssrc/mainORCA_CROSS_VERSION_BASELINE_REF=v1.4.178: 4/4 passedpnpm run build:electron-vitepnpm build(targeted Electron Vite build passed; full native packaging build not run locally)git diff --checkRed 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:
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