Skip to content

fix(editor): make lazy-chunk recovery actually reload instead of being silently vetoed - #11929

Merged
nwparker merged 5 commits into
mainfrom
fix/crash-c-misc-react
Aug 2, 2026
Merged

nwparker merged 5 commits into
mainfrom
fix/crash-c-misc-react

Conversation

@nwparker

@nwparker nwparker commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes production crash report b860def2-cad3-4ef9-b055-016c360f5864, where lazy-chunk recovery requested a renderer reload but a dirty editor tab silently vetoed it. The editor could then remain stuck in the same document while treating recovery as already exhausted.

This PR:

  • routes lazy-chunk reloads through Orca's existing restart-preparation sequence: back up dirty editor buffers, checkpoint the renderer session, arm the intentional-restart bypass, then reload;
  • stores the requesting document's identity in the session guard, so Orca can distinguish a reload that landed from one that was vetoed;
  • bounds a refused reload to 10 seconds, clears stale guards/listeners/timers, and caps retries per document to prevent loops;
  • preserves the original reportable error when recovery did not actually happen;
  • contains a proven post-reload lazy-chunk failure in the rich-markdown pane without filing a duplicate crash report, while retaining diagnostic breadcrumbs and a chunk-specific reloadKey;
  • moves restart preparation into src/shared so preload and renderer recovery use one implementation.

Production diagnostics support the root cause: a lazy_chunk_reload breadcrumb was recorded, but no renderer bootstrap followed; periodic renderer activity continued in the same document until the crash report was created 44 minutes later.

ELI5

Orca loads parts of its UI in small files. After an update, an already-open window can ask for an old file that no longer exists. Reloading the window normally fixes that.

The bug was that Orca wrote “reload attempted” on a sticky note and then asked to reload. If any editor tab had unsaved changes, Orca blocked the reload to protect the work—but the sticky note remained. Orca then believed the reload had happened even though it was still the same window, so the editor could stay broken.

Now Orca first backs up unsaved edits and saves the session, then reloads. The sticky note also identifies which copy of the window wrote it: if the same copy is still reading it, the reload did not happen. Orca clears the stale note and surfaces the real error instead of pretending recovery succeeded.

Screenshots

No visual change. Existing fallback UI and copy are unchanged.

Testing

  • pnpm lint — local focused lint and CI static analysis passed
  • pnpm typecheck — node, CLI, and web TypeScript projects passed locally
  • pnpm test — 33 focused tests passed locally; the full Node 24 and Node 26 CI matrices passed
  • pnpm build — Linux and Windows CI package jobs passed
  • Added or updated high-quality regression tests

Focused coverage includes:

  • dirty editor tabs no longer veto recovery after hot-exit backup;
  • failed backup/checkpoint refuses the reload without losing work;
  • landed, vetoed, timed-out, and host-thrown reload requests clean up correctly;
  • same-document guards stay reportable while prior-document guards remain loop-safe;
  • concurrent lazy failures cannot re-arm an in-flight reload;
  • rich-markdown lazy failures render the existing fallback and deduplicate breadcrumbs;
  • preload updater/unload relays are tested behaviorally rather than through source-text matching.

npm run check:max-lines-ratchet also passes with no new bypasses.

AI Review Report

Reviewed the full lazy-load, restart-preparation, unload-veto, persistence, and boundary-reporting paths.

The review found and fixed one cleanup bug: if the host threw while requesting location.reload(), the in-flight flag, session guard, restart latch, timer, and unload listener could remain armed. The request now cancels those resources in finally, records a request-failed outcome, and preserves the original chunk error. A regression test covers this path.

The review also replaced brittle source-text preload tests with behavioral tests and made dirty-tab test cleanup failure-safe.

Concurrency, stale session state, blocked storage, partial checkpoint completion, repeated vetoes, breadcrumb loss, and ordinary non-chunk errors were checked. Cross-platform review covered macOS, Linux, Windows, Electron's will-prevent-unload, and the paired-web fallback where that Electron signal is unavailable. No shortcut, path, shell, Git, SSH-host, or folder-workspace assumptions are introduced; the behavior is renderer-local and workspace-type agnostic.

Security Audit

No new command execution, filesystem paths, credentials, auth, dependencies, or provider APIs are introduced. The only IPC behavior touched is the existing typed updater status/unload relay.

The intentional unload bypass remains fail-closed: it is armed only after dirty buffers are backed up and the synchronous renderer checkpoint succeeds. If either step fails, Orca aborts recovery and keeps the current document and unsaved work intact. Reload attempts remain session-guarded and per-document capped.

Verdict

Valid and should be merged. The production evidence matches the vetoed-reload failure mode, the fix reuses Orca's established restart safety contract, and the failure/concurrency paths now have strong regression coverage. The main trade-off is intentional: after a reload is proven to have landed, a persistent lazy-chunk failure produces a contained pane fallback and breadcrumb rather than another crash report, matching RecoverableRenderErrorBoundary's existing policy.

Notes

This closes only b860def2-cad3-4ef9-b055-016c360f5864. The two unrelated useConfirmationDialog must be used inside ConfirmationDialogProvider development-session reports from the original crash cluster are not changed here.

nwparker and others added 2 commits August 1, 2026 02:39
RichMarkdownErrorBoundary reported every caught error as a react-error-boundary
crash, including the LazyChunkLoadError sentinel that lazy-with-retry throws
after it has already exhausted its retries and its one guarded reload. That
sentinel means "the chunk hash changed under a running window" (an app update),
which is deliberate graceful degradation, not a crash.

RecoverableRenderErrorBoundary already skips reporting it (#6206); this boundary
was never updated. Crash b860def2 is exactly that path: a lazy_chunk_reload
breadcrumb ("Unexpected token ':'") fires first, then the post-reload attempt
surfaces LazyChunkLoadError and files a report.

The fallback UI is unchanged, so the pane stays usable and offers retry.
…ash reports

- lazy-with-retry: reload guard stores the requesting document's identity, so a
  vetoed reload() no longer reads as "recovery ran" (crash b860def2)
- lazy-with-retry: bound the post-reload suspension so a vetoed navigation
  surfaces the real error instead of hanging the pane on a spinner
- RichMarkdownErrorBoundary: contain the LazyChunkLoadError sentinel without a
  crash report, but record a lazy_chunk_boundary_degraded breadcrumb
- EditorContent: name the rich markdown chunk at the lazy call site

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

coderabbitai Bot commented Aug 1, 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: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

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: 513a1582-d5eb-4bba-a905-d56d97f63115

📥 Commits

Reviewing files that changed from the base of the PR and between 8e50300 and 33acb49.

📒 Files selected for processing (3)
  • src/preload/index.ts
  • src/preload/renderer-restart-wiring.test.ts
  • src/preload/renderer-restart-wiring.ts
📝 Walkthrough

Walkthrough

Lazy retry recovery now tracks document-specific reload state instead of a boolean marker. Reload attempts that do not navigate receive bounded handling before the original error returns. Confirmed post-reload dynamic-import failures retain specialized error handling. Shared restart wiring now relays updater and unload-prevention events. The rich-markdown editor provides an explicit reload key. Its error boundary records deduplicated breadcrumbs for lazy chunk failures and preserves crash reporting for ordinary render errors. Tests cover these recovery, restart, and reporting paths.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% 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 describes the main fix: ensuring lazy-chunk recovery reloads instead of being silently vetoed.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes sections with relevant details.
✨ 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.

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a production crash where a dirty editor tab silently vetoed a lazy-chunk recovery reload, leaving the sessionStorage guard set as if the reload had landed. The fix routes lazy-chunk recovery reloads through the restart-preparation sequence and stores a document-identity token in the guard so a surviving document can detect that its own reload was refused.

  • lazy-with-retry.ts: replaces bare window.location.reload() with requestLazyChunkRecoveryReload, writes a per-document token to the guard, caps reload attempts at 2, clears the guard in finally for all survived-document paths.
  • lazy-chunk-recovery-reload.ts (new): implements the restart-prepared reload with a 10-second grace window, proper cleanup, and ORCA_APP_RESTART_ABORTED_EVENT dispatch in finally.
  • renderer-restart-preparation.ts moved to src/shared/; RichMarkdownErrorBoundary gains a LazyChunkLoadError containment path that records a deduplicated breadcrumb instead of a crash report.

Confidence Score: 5/5

Safe to merge; the change is narrowly scoped to lazy-chunk recovery and uses well-established restart-preparation machinery.

All four refusal outcomes are covered by focused regression tests. The document-identity token correctly distinguishes a vetoed reload from a landed one. The restart latch and session guard are cleaned up in finally blocks on every survived-document path. The per-document retry cap and concurrent in-flight guard prevent reload loops.

Files Needing Attention: No files require special attention. The most complex logic is in lazy-with-retry.ts and lazy-chunk-recovery-reload.ts, both of which have thorough behavioral test coverage added in this PR.

Important Files Changed

Filename Overview
src/renderer/src/lib/lazy-with-retry.ts Core change: replaces bare window.location.reload() with restart-prepared reload, adds per-document identity token to sessionStorage guard, introduces per-document retry cap (2), and surfaces the original error after any refused reload.
src/renderer/src/lib/lazy-chunk-recovery-reload.ts New module orchestrating the restart-prepared reload with correct RESTART_ABORTED dispatch in finally for all survived-document paths and 10s veto grace window with proper cleanup.
src/shared/renderer-restart-preparation.ts Renamed from src/preload/ to src/shared/ with only import path updates; no logic changes.
src/renderer/src/components/editor/RichMarkdownErrorBoundary.tsx Adds LazyChunkLoadError containment: records a deduplicated breadcrumb instead of a crash report when a post-reload chunk failure is caught.
src/preload/renderer-restart-wiring.ts New preload-layer module extracting IPC relay wiring and updater-install orchestration from index.ts to enable behavioral tests.
src/preload/index.ts Import paths updated and inline logic delegated to registerRendererRestartIpcRelays and prepareAndInvokeUpdaterInstall; no behavioral change.
src/renderer/src/lib/lazy-with-retry.test.ts Substantially expanded with behavioral harness covering landed reload, refused checkpoint, host-thrown reload, veto signal, per-document cap, and in-flight sibling-chunk guard.
src/shared/renderer-restart-preparation.test.ts Renamed alongside source; brittle source-text inspection tests removed and replaced with behavioral equivalents.

Reviews (3): Last reviewed commit: "test(preload): exercise restart IPC regi..." | Re-trigger Greptile

// Only a token left by a *different* document proves the reload landed; a token
// matching this document means the reload was requested and vetoed.
const LANDED_RELOAD_GUARD_VALUE = 'doc-before-the-reload'
const VETOED_RELOAD_GUARD_VALUE = (): string => String(performance.timeOrigin)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 VETOED_RELOAD_GUARD_VALUE diverges from currentDocumentReloadToken() logic

VETOED_RELOAD_GUARD_VALUE is defined as (): string => String(performance.timeOrigin), which omits the Number.isFinite(timeOrigin) && timeOrigin > 0 guard that currentDocumentReloadToken() applies before choosing String(timeOrigin). If performance.timeOrigin is 0 in a future test environment, the test stores '0' in sessionStorage while currentDocumentReloadToken() returns FALLBACK_RELOAD_TOKEN; '0' !== FALLBACK_RELOAD_TOKEN maps to 'reload-landed' instead of 'reload-not-landed', causing the vetoed-reload test to throw LazyChunkLoadError instead of the raw error. The same pattern appears in lazy-with-retry.test.ts line 169. The tests would fail loudly (not silently) in that environment, but the failure mode would be confusing rather than self-explanatory. Importing and re-using currentDocumentReloadToken in the tests (or exposing it as a test-only helper) would keep the guard logic in one place.

Comment thread src/renderer/src/lib/lazy-with-retry.ts Resolved
…-restart path

Crash b860def2's recovery reload was requested and never landed: Terminal's
beforeunload handler preventDefault()s while any editor tab is dirty and Electron
cancels the navigation with no dialog, so chunk recovery could never run in the
common case. Take the updater's path instead — hot-exit backup, one synchronous
session checkpoint, restart latch — then reload.

- Reject on ORCA_RENDERER_UNLOAD_PREVENTED_EVENT instead of a blind, never-cleared
  10s timer; keep the timer only as a backstop.
- Record a lazy_chunk_reload_vetoed breadcrumb in the same tick as the report it
  now files, so the 30-entry ring cannot evict the evidence.
- Drop this document's own stale guard after a refused reload (capped in memory)
  so saving the blocking tab does not forfeit recovery for the session.
- Carry reloadKey on LazyChunkLoadError and the degraded breadcrumb.
- Move renderer-restart-preparation to src/shared: it is now a renderer/preload
  contract, and the composite web project cannot import preload runtime code.

Co-authored-by: Orca <[email protected]>
@nwparker nwparker changed the title fix(editor): prove the lazy-chunk reload landed before suppressing crash reports fix(editor): make lazy-chunk recovery actually reload instead of being silently vetoed Aug 1, 2026

@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 (3)
src/renderer/src/lib/lazy-with-retry.test.ts (1)

428-447: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Register the harness cleanup so a failed assertion cannot leak listeners.

Each test calls harness.cleanup() as its last statement. If an earlier assertion fails, the beforeunload listener, the hot-exit listener, and the registerUpdaterBeforeUnloadBypass registration stay attached. The bypass also leaves the module-level intentionalAppRestartInProgress flag armed. Later tests in this file then fail for the wrong reason. Register the cleanup with onTestFinished inside installDirtyEditorTab, or track the harness and clean it in afterEach.

♻️ Proposed refactor
+  let activeHarness: Harness | undefined
+
   beforeEach(() => {
     vi.useFakeTimers()
     window.sessionStorage.clear()
     resetLazyChunkReloadRequestsForTest()
   })
 
   afterEach(() => {
+    activeHarness?.cleanup()
+    activeHarness = undefined
     vi.restoreAllMocks()
     vi.useRealTimers()
     delete (window as unknown as { api?: unknown }).api
     window.sessionStorage.clear()
   })

Then set activeHarness = harness before return harness in installDirtyEditorTab and drop the trailing harness.cleanup() calls.

src/preload/renderer-restart-wiring.test.ts (2)

6-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Replace the source-text assertions with a behavioral test.

This test asserts the source text of src/preload/index.ts, including exact whitespace and return await ordering in the regex at Lines 32-34. A formatter change, an added log line, or a rename breaks the test without any behavior change. The test also cannot prove that the relay runs, because it never executes the wiring. Import the preload wiring with a mocked electron.ipcRenderer, emit updater:status and window:unload-prevented, then assert the dispatched renderer events and the abort() call on a rejected quitAndInstall.

The shared behavior is already testable: createUpdaterQuitAbortRelay and prepareRendererForAppRestart have direct unit tests in src/shared/renderer-restart-preparation.test.ts. Only the IPC-to-event relay needs a preload-level test.


1-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Build the path from separate segments and anchor it to the test file.

process.cwd() assumes the Vitest process runs from the repository root. 'src/preload/index.ts' also embeds a POSIX separator inside one join segment. Resolve the path relative to this test file instead, and pass each segment to join.

As per coding guidelines: "use platform-aware ... path utilities such as path.join instead of hardcoded separators".

♻️ Proposed refactor
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
 import { describe, expect, it } from 'vitest'
 
 describe('preload restart wiring', () => {
-  const source = readFileSync(join(process.cwd(), 'src/preload/index.ts'), 'utf8')
+  const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'index.ts'), 'utf8')

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 481ba2b4-cf2f-44ce-a991-b83e8edde13f

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfe9f2 and f5f2a32.

📒 Files selected for processing (10)
  • src/preload/index.ts
  • src/preload/renderer-restart-wiring.test.ts
  • src/renderer/src/components/editor/EditorContent.tsx
  • src/renderer/src/components/editor/RichMarkdownErrorBoundary.lazy-chunk.test.tsx
  • src/renderer/src/components/editor/RichMarkdownErrorBoundary.tsx
  • src/renderer/src/lib/lazy-chunk-recovery-reload.ts
  • src/renderer/src/lib/lazy-with-retry.test.ts
  • src/renderer/src/lib/lazy-with-retry.ts
  • src/shared/renderer-restart-preparation.test.ts
  • src/shared/renderer-restart-preparation.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/editor/EditorContent.tsx
  • src/renderer/src/components/editor/RichMarkdownErrorBoundary.tsx

Comment thread src/renderer/src/lib/lazy-with-retry.ts Resolved
@nwparker
nwparker merged commit 3f8654c into main Aug 2, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…g silently vetoed (stablyai#11929)

* fix(editor): stop filing crash reports for expected lazy-chunk swaps

RichMarkdownErrorBoundary reported every caught error as a react-error-boundary
crash, including the LazyChunkLoadError sentinel that lazy-with-retry throws
after it has already exhausted its retries and its one guarded reload. That
sentinel means "the chunk hash changed under a running window" (an app update),
which is deliberate graceful degradation, not a crash.

RecoverableRenderErrorBoundary already skips reporting it (stablyai#6206); this boundary
was never updated. Crash b860def2 is exactly that path: a lazy_chunk_reload
breadcrumb ("Unexpected token ':'") fires first, then the post-reload attempt
surfaces LazyChunkLoadError and files a report.

The fallback UI is unchanged, so the pane stays usable and offers retry.

* fix(editor): prove the lazy-chunk reload landed before suppressing crash reports

- lazy-with-retry: reload guard stores the requesting document's identity, so a
  vetoed reload() no longer reads as "recovery ran" (crash b860def2)
- lazy-with-retry: bound the post-reload suspension so a vetoed navigation
  surfaces the real error instead of hanging the pane on a spinner
- RichMarkdownErrorBoundary: contain the LazyChunkLoadError sentinel without a
  crash report, but record a lazy_chunk_boundary_degraded breadcrumb
- EditorContent: name the rich markdown chunk at the lazy call site

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

* fix(editor): route lazy-chunk recovery reload through the intentional-restart path

Crash b860def2's recovery reload was requested and never landed: Terminal's
beforeunload handler preventDefault()s while any editor tab is dirty and Electron
cancels the navigation with no dialog, so chunk recovery could never run in the
common case. Take the updater's path instead — hot-exit backup, one synchronous
session checkpoint, restart latch — then reload.

- Reject on ORCA_RENDERER_UNLOAD_PREVENTED_EVENT instead of a blind, never-cleared
  10s timer; keep the timer only as a backstop.
- Record a lazy_chunk_reload_vetoed breadcrumb in the same tick as the report it
  now files, so the 30-entry ring cannot evict the evidence.
- Drop this document's own stale guard after a refused reload (capped in memory)
  so saving the blocking tab does not forfeit recovery for the session.
- Carry reloadKey on LazyChunkLoadError and the degraded breadcrumb.
- Move renderer-restart-preparation to src/shared: it is now a renderer/preload
  contract, and the composite web project cannot import preload runtime code.

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

* fix(editor): clean up failed lazy chunk reload requests

* test(preload): exercise restart IPC registrations

---------

Co-authored-by: Orca <[email protected]>
@brennanb2025 brennanb2025 mentioned this pull request Nov 16, 2026
11 tasks done
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