Skip to content

Stop the app freezing while Windows stages the terminal daemon runtime - #51222

Merged
brennanb2025 merged 22 commits into
mainfrom
brennanb2025/daemon-staging-async-runtime
Nov 28, 2026
Merged

brennanb2025 merged 22 commits into
mainfrom
brennanb2025/daemon-staging-async-runtime

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

On Windows, Orca copies the terminal daemon's runtime out of the install folder so that app updates can't kill running terminals. That copy used to run on Orca's main thread, so the whole app froze while it ran. In our packaged test launches that was 1.4–3.9 s on the first launch after an update, and about 110 ms on later fresh daemon launches. Now the copy runs in the background, and the app stays responsive.

Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​470 $\color{#cf222e}{\Huge{\mathbf{−}}}$​51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​419
Prod 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​941 $\color{#cf222e}{\Huge{\mathbf{−}}}$​357 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​584

What Changed

  • Before: every fresh daemon launch on packaged Windows fingerprinted and copied the runtime (about 1.8k files, 275 MiB) with synchronous file calls on Electron main. That happens after a daemon protocol bump or an update that needs a new daemon.
  • After: fingerprinting, copying, verifying and deleting old copies use async file calls, capped at 2 file operations in flight. The daemon still launches only after the staged copy is complete and verified, and it is published by an atomic rename of a staging folder.
  • Mechanism:
    • Bounded walk: one breadth-first walk lists folders with readdir and stat, never opendir or fs.cp. It copies with copyFile and deletes with unlink/rmdir, never following links out of the folder. It replaces the temporary sync walk Fix a Windows crash when a folder can't be opened #51332 added to daemon-host-manifest.ts.
    • Cold launch (no copy exists yet for this version): the source code is not hashed up front, because there is nothing to compare against. The copy hashes each code file's bytes as it writes them and builds the marker from those hashes.
      • Each code file's metadata (inode, size, timestamps) is recorded when the file is read and checked again after the copy. A file replaced mid-copy, such as by an update, rejects the copy, so a build can't mix two versions.
    • When a copy already exists: the sources are hashed and compared, as before. The copy's code bytes must match, and it is re-verified against its marker before use.
    • Failures: after the first error, no new work starts, and in-flight work finishes before the staging folder is cleaned up. The staging rename retries briefly while Windows scanners hold a newly written file; it reuses the existing async retry, moved from the plugin installer to src/main/filesystem/windows-rename-retry.ts.
    • Cleanup: deleting abandoned and superseded copies is async and doesn't delay the launch. Overlapping cleanup calls share one walk. Read-only files (kept from a read-only install) are cleared and removed, as rmSync did.
  • Module moves: prune, pinned-version collection, inventory roots and the observed-build memo moved into their own modules, to keep files under the line limit.
  • copyPath (Fix a Windows crash when a folder can't be opened #51332) is a general serial fs.cp replacement. This walk is separate because it bounds concurrency, hashes while copying and deletes without following links.
  • macOS and Linux are unchanged. They already stage off main through a /bin/cp subprocess and AppImage extraction.

Why

A blocked main thread freezes every window, including typing in terminals, for the whole copy. Async fs keeps the existing staging, verification and fallback design, so no new process or worker bundle is needed. The 2-operation cap keeps staging from taking over libuv's thread pool while the rest of startup is loading.

Linked Issue

N/A: internal performance work; no public issue.

Visual Proof

N/A: this changes no UI. The visible effect is that the app no longer freezes during the first daemon launch after an update. The numbers are under Testing.

Testing

  • Packaged app on Windows with Defender real-time protection on: 8 alternating cold-launch pairs of a base build and this PR, plus 4 base-only control launches, with the same 3-project workload.

    Cold launch Base This PR
    Main's longest block while staging 1.6–2.4 s 175–298 ms
    First window (ready-to-show), paired difference — −285 to +171 ms (base vs base: median 258 ms, up to 564 ms)
    Workspace list shown, both-clean pairs — 1.7–1.8 s earlier
    Daemon ready, from daemon init (median of pair differences) — +0.9 s
    • First window is within the base-vs-base spread, so the difference is noise. The pre-window startup steps match pair by pair.
    • The workspace list shows earlier because the sync copy no longer blocks main while the renderer loads.
  • Packaged-app scenarios (all passed):

    • Cold launch: the daemon runs from a complete, marked copy, never from staging.
    • Warm launch: the existing copy is reused with no recopy.
    • Restart: with a surviving daemon, the terminal session continues.
    • Under ~50% CPU load: staging completes and the terminal works.
    • Crash mid-copy: an app killed with 1,544 of 1,833 files copied leaves a staging folder that the next launch deletes, then makes a fresh complete copy.
  • Standalone benchmark (fresh process per run, packaged install as source): main's longest block drops from 0.7–1.3 s cold and ~110 ms warm to 12–53 ms.

  • Fleet perf gate (~1,900 workspaces, Linux, where this path returns immediately): idle and streaming metrics are unchanged.

  • New tests:

    • A changed code file is rejected, whether it changes after fingerprinting or mid-copy on a cold launch.
    • A cold copy is reused rather than recopied.
    • Deletes never follow links out of the folder.
    • Missing source folders are rejected or skipped as appropriate.
    • The stop-on-failure pool settles in-flight work before rejecting.
    • Fix a Windows crash when a folder can't be opened #51332's manifest test runs against the async API.
  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the test anti-patterns

Performance

This removes a 1.4–3.9 s freeze of the main thread on the first daemon launch after an update on Windows, and a ~110 ms freeze on later fresh daemon launches. The work per launch is the same or less: a cold launch no longer hashes the sources before copying. It never grows with workspaces, terminals or history, and staging holds at most 2 file operations in flight. Off packaged Windows the function returns immediately, as before.

Risk

Level: Medium

  • Trade-off: on the first launch after an update or daemon protocol bump, the first terminal is ready a median 0.9 s later. Paired launches ranged from −0.5 to +3.2 s, and the two +3.2 s pairs ran while the machine was busy with other work.
    • The cause is the capped async copy sharing I/O with the rest of startup, instead of freezing the app for 1.4–3.9 s.
    • First window and workspace loading are not slower; the workspace list shows earlier.
    • Warm launches don't copy and are unaffected.
  • Riskiest part: deciding whether a staged copy is complete and current. If that went wrong, the daemon would fall back to the install-folder runtime, as it already does on any staging failure. The cost is that terminals could again be killed by an update.
  • Safeguards:
    • A partial, mixed-version or unverified copy is never published.
    • A crash mid-copy leaves a staging folder that a later launch removes once the writer's pid has exited.
  • Known limits, unchanged by this PR:
    • The synchronous daemon-host lookup the Antigravity hook path uses at startup still runs on main.
    • A copy keeps running if the app quits during startup; the next launch removes its staging folder.
    • Coordinating publish, launch and prune across processes is tracked as a follow-up.
  • Back out: a plain revert.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

  • Platforms: Windows only. macOS and Linux are unchanged.
  • Remote, SSH and mobile: not affected. Staging runs only for the local packaged Windows daemon.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

brennanb2025 added a commit that referenced this pull request Nov 28, 2026
… walk

cpSync with a filter walks folders with opendirSync, which goes through
the same Windows open that can report a failure as success and crash.
On Windows only, the filtered folder copies now use a small sync walk
(readdirSync, mkdirSync, copyFileSync) with the same filter and
dereferenced links; executeManifest keeps its shape. #51222 replaces
this walk with its async walker.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Heads-up from #51332 (Windows opendir crash fix): on Windows, executeManifest in daemon-host-manifest.ts now copies filtered folders with a small sync readdir walk (copyFilteredTreeSync) instead of a filtered cpSync, which uses opendirSync. This PR replaces that path with its async walker, so when rebasing drop copyFilteredTreeSync and its test (daemon-host-manifest.test.ts) along with the old cpSync call.

brennanb2025 added a commit that referenced this pull request Nov 28, 2026
* fix(fs): open folders with readdir on Windows everywhere in main and shared

On Windows, opendir can report a failed open (a missing folder, for
example) as success with no handle, and building the handle then writes
through null and crashes the process (#50875, #50997). The PATH scanner
already avoids it (#51158); every other main/shared caller still used
opendir or opendirSync.

openDirectory/openDirectorySync in src/shared/open-directory.ts return
the real Dir on macOS and Linux and a readdir-backed handle on Windows.
All callers go through it, and a test fails on any new direct opendir in
src/main or src/shared.

* docs(fs): note Windows lists the folder in full in the worktree removal check

* chore(ratchets): carry the moved opendirSync allowances to open-directory

* fix(fs): drop the Windows listing on close; test refuses opendir on Windows

* test(fs): type the opendir guards without casts

* fix(fs): copy folder trees with readdir on Windows instead of fs.cp's opendir walk

fs.cp opens every source folder with opendir, so a folder that can be
stat'd but not listed, or one removed mid-copy, can hit the same Windows
crash. copyPath (src/shared/copy-path.ts) keeps fs.cp on macOS/Linux and
for files and links; on Windows it walks folders with readdir. The ban
test now also rejects a direct fs.cp in src/main and src/shared.

* fix(fs): stop a local name shadowing copyPath; match fs.cp's default force

* fix(fs): copy files inline in the Windows tree walk and keep fs.cp's into-self checks

Per-file fs.cp repeated a stat of every destination ancestor; files are
now copied the way fs.cp's onFile does (overwrite unless force is false,
mode and optional timestamps). Links still go to fs.cp, now with
recursive false so they can never re-enter its opendir walk. The root
check now also walks destination ancestors by identity, catching a
destination reached through a junction into the source.

* fix(daemon): copy filtered Windows daemon-host folders with a readdir walk

cpSync with a filter walks folders with opendirSync, which goes through
the same Windows open that can report a failure as success and crash.
On Windows only, the filtered folder copies now use a small sync walk
(readdirSync, mkdirSync, copyFileSync) with the same filter and
dereferenced links; executeManifest keeps its shape. #51222 replaces
this walk with its async walker.

* test(fs): read the opendir baseline from the real module so the test also runs on Windows

* test(fs): capture the real opendir in the mock; carry the daemon staging walk's sync allowance

* fix(fs): yield to the event loop every 32 entries of a Windows listing, as Dir's buffered reads do
… temporary sync walk with the async tree walk
@brennanb2025
brennanb2025 marked this pull request as ready for review November 28, 2026 06:23
@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

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

No actionable comments were generated in the recent review.

Walkthrough

Windows daemon-host inventory, manifest copying, relocation, and pruning now use asynchronous filesystem operations. The changes add bounded-concurrency helpers, code-hash and source-signature checks, pinned-version evidence collection, and symlink-safe tree removal. The launcher awaits host materialization. Plugin installation and daemon-host publishing now use a shared Windows rename retry helper.

Merge Risk: Low · previous review 3cb54

This change moves Windows daemon-runtime staging off the main thread, so the app should no longer freeze during staging. Two narrow races carry over from earlier review: a source update during a cold copy, and pruning racing with a newly started version. Both need concurrent same-user activity, and the worst outcome is a recopy or a failed launch that recovers on the next one. The first launch after an update starts the daemon about 0.9 s later; this is a deliberate trade-off.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main user-visible goal: the app stops freezing while Windows stages the terminal daemon runtime. The changeset moves daemon-host staging, copying, hashing and cleanup off Electron'…
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.
Description check Passed The description follows the repository template closely. It covers ELI5, What Changed, Why, Visual Proof (N/A with reason), Testing with measured results, Performance, and Risk with level, safeguards,…
Full details: Title check

Explanation

The title names the main user-visible goal: the app stops freezing while Windows stages the terminal daemon runtime. The changeset moves daemon-host staging, copying, hashing and cleanup off Electron's main thread to async file calls, so the title matches the primary change. It does not mention the mechanism, but it is specific and accurate.

Full details: Description check

Explanation

The description follows the repository template closely. It covers ELI5, What Changed, Why, Visual Proof (N/A with reason), Testing with measured results, Performance, and Risk with level, safeguards, and back-out plan. The Linked Issue section says N/A for internal work, but the template states an issue should always exist, and it marks the issue as required for outside contributors. The author is internal, so this is a minor gap. The AI Disclosure and Review sections are empty. The AI Disclosure section is optional for StablyAI team members. The Review section is empty and the template does not state its content. The final lint, typecheck, test, and build checklist item is unchecked, and the PR notes CI may cover it. The Testing section reports results but the packaged-app measurements are not reproducible from the description alone. These gaps are non-critical, so the description is mostly complete.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 20899e80-76b2-4000-9490-46f8dd25c513
Commits

Reviewing files that changed from the base of the PR and between 9bba289 and 3cb54ff.

Files selected for processing: 3

  • src/main/daemon/executable-host/windows/daemon-host-inventory-roots.ts
  • src/main/daemon/executable-host/windows/daemon-host-relocation.ts
  • src/main/daemon/executable-host/windows/testing/daemon-host-relocation.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

@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: 4

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9317f8b4-0856-4200-a474-2c0dc58b5819
Commits

Reviewing files that changed from the base of the PR and between 4048b2e and e2c4ee2.

Files selected for processing: 21

  • config/main-blocking-helper-baseline.txt
  • config/main-sync-fs-baseline.txt
  • src/main/daemon/executable-host/windows/daemon-host-build-inventory.ts
  • src/main/daemon/executable-host/windows/daemon-host-file-hash-cache.ts
  • src/main/daemon/executable-host/windows/daemon-host-inventory-roots.ts
  • src/main/daemon/executable-host/windows/daemon-host-manifest.test.ts
  • src/main/daemon/executable-host/windows/daemon-host-manifest.ts
  • src/main/daemon/executable-host/windows/daemon-host-observed-builds.ts
  • src/main/daemon/executable-host/windows/daemon-host-pinned-versions.ts
  • src/main/daemon/executable-host/windows/daemon-host-prune.ts
  • src/main/daemon/executable-host/windows/daemon-host-reclaim.ts
  • src/main/daemon/executable-host/windows/daemon-host-relocation.ts
  • src/main/daemon/executable-host/windows/daemon-host-tree-walk.ts
  • src/main/daemon/executable-host/windows/testing/daemon-host-relocation.test.ts
  • src/main/daemon/launch/daemon-out-of-process-launcher.ts
  • src/main/daemon/providers/lifecycle/daemon-provider-init.ts
  • src/main/filesystem/windows-rename-retry.ts
  • src/main/plugins/installation/plugin-atomic-file-write.ts
  • src/main/plugins/installation/plugin-install-staging.ts
  • src/shared/concurrency/map-with-concurrency.test.ts
  • src/shared/concurrency/map-with-concurrency.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

…added mid-copy, re-check dirs before descending in removal, skip file-symlink test on Windows

@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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 13f26838-4810-488c-8420-8b45db09ad2f
Commits

Reviewing files that changed from the base of the PR and between e2c4ee2 and e23e179.

Files selected for processing: 4

  • src/main/daemon/executable-host/windows/daemon-host-manifest.ts
  • src/main/daemon/executable-host/windows/daemon-host-prune.ts
  • src/main/daemon/executable-host/windows/daemon-host-tree-walk.ts
  • src/main/daemon/executable-host/windows/testing/daemon-host-relocation.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8b1cbf31-6809-4fcb-8fcb-bf07a25f77fc
Commits

Reviewing files that changed from the base of the PR and between e23e179 and d73503e.

Files selected for processing: 2

  • src/main/daemon/executable-host/windows/daemon-host-manifest.ts
  • src/main/daemon/executable-host/windows/testing/daemon-host-relocation.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6b2b0047-6689-45fd-b0e9-bc0e1db83de0
Commits

Reviewing files that changed from the base of the PR and between d73503e and 9bba289.

Files selected for processing: 3

  • src/main/daemon/executable-host/windows/daemon-host-inventory-roots.ts
  • src/main/daemon/executable-host/windows/daemon-host-relocation.ts
  • src/main/daemon/executable-host/windows/testing/daemon-host-relocation.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

…he visit prune runs

The one-shot prune after the terminal-startup wait checked the active worktree
against the startup scan, which predates a worktree created during that wait,
and cleared the selection; the new worktree then never mounted a terminal.
Treat a worktree the listing still shows as live, as the default-tab guard
in the same prune already does.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf-scan: 8de25fe

P1 — The measured cold first-terminal slowdown remains unresolved. The launcher now awaits async staging before spawning the daemon. Staging enumerates the complete accepted tree before copying, with two filesystem operations in flight.

The saved packaged Windows comparison measured:

  • First-terminal readiness 897 ms later at the paired median, slower in 7/8 pairs.
  • Clean median pre-copy time: 103 → 674 ms; copy time: 1,299 → 1,864 ms.
  • Main blocking improved substantially, and workspace hydration finished earlier.

This affects each cold profile/build miss or rematerialization. At both 750 and 7,500 worktrees, the population remains one packaged runtime per affected launch—approximately 1,800–2,200 files and the supplied 275 MiB—not one copy per worktree.

These measurements compare 3bf671279172cd3355d886701dd25ea5645e9cac against 5f27429c3c6, not the requested exact base/head. HEAD retains the relevant staging sequence and concurrency limit. Later functional QA does not remeasure this latency. The resolving check is an alternating packaged Windows base/HEAD comparison through terminal readiness, with identical seeded profiles, Defender settings, and competing startup work.

Coverage: reviewed 4048b2ec577653d166130fe706b9fad94198401d..8de25fefedba88b64aef4d4d7124fb4ad309a732, including both required surfaces, callers, publication, removal, and failure cleanup. Checkout remained unchanged.

Let F/D be accepted packaged files/directories, C fingerprinted files, B retained builds, V superseded versions, P protocol PID records, and W/H/A worktrees, visit entries, and default-tab guards.

Work Trigger, population, and bound Paying thread
Source admission Fresh launch after adoption fails; packaged Electron Windows only. Fixed manifest roots, required files, export targets, and path budget. Main orchestration; async filesystem I/O
Cold staging Build miss; enumerate F/D, create destinations, copy F files. One shared materialization promise; two active file workers. Retained listing O(F+D); up to two complete code-file buffers. Filesystem I/O through libuv; hashing and collection construction on main
Warm inventory/reuse Fresh daemon launch with existing builds; source traversal plus matching destination verification. Unchanged hashes reuse stat signatures. Async stats/reads; streaming SHA-256 callbacks on main
Copy validation/publication C source-signature rechecks, code-directory membership validation, optional-root checks, staged export validation, marker write, rename. Directory membership CPU is O(Dcode×(F+D)). Async filesystem I/O; comparisons, sorting, JSON, and hashing on main
Build selection Each lookup reads B markers and sorts candidates; worst-case marker work O(B×C). Async materialization still uses synchronous marker selection. Electron main
Rename retry Publication lock failure; at most six attempts and five delays totaling 750 ms. Async I/O and finite main timer callbacks
Failed-copy cleanup Stop admission, settle active workers, then traverse and delete staging. Two active file operations; reverse-order directory removal. Async filesystem I/O; main orchestration
Superseded-version cleanup Provider initialization; versions processed sequentially, with up to V×P fresh PID-record checks before deletion. Live/unverifiable ownership vetoes removal. Async I/O; parsing and PID signal probes on main
Abandoned-staging cleanup Fresh launch/provider initialization; overlapping callers share one prune promise. Positive writer-exit evidence required. Async I/O; PID probes on main
Plugin publication Existing atomic writes/installations call the extracted rename helper. Retry policy and temporary-file cleanup are unchanged. Unchanged async I/O
Startup visit prune Two production startup call sites per completed hydration sequence; existing O(W+H+A) work. The change adds at most one existing-set lookup per call, at both W=750 and W=7,500. Renderer main

The renderer change preserves one legitimately selected worktree already present in the listing. It adds no collection traversal, subscription, persistence field, or resource owner. The updater still returns the original state when its patch is empty.

Six scan questions:

Question Disposition
Work before skip gates Reviewed. Platform, packaging, adoption, required-input, fingerprint, and path-budget gates remain. Cold staging skips preliminary hashing but validates copied bytes and source stability.
Ownership multiplication Reviewed. Materialization and both prune owners coalesce overlapping callers and clear their promises on settlement. No per-row or per-terminal staging owner was added.
Thread/storage cost Reviewed. Bulk copy/removal I/O moves off main; hashing, JSON, sorting, marker reads, and PID probes still execute there. No SQLite path is introduced. First-terminal latency is the finding above.
Growth/progress Reviewed structurally. Workers stop admission on failure and drain before rejection. Cleanup advances through the remaining tree. Package-directory cross-scans remain shape-dependent and unmeasured.
Execution host Windows gates, Defender retry handling, native-package filters, and deletion behavior inspected. Saved packaged Windows evidence reviewed; no exact-head Windows execution performed. Remote, macOS, and Linux relocation admission is unchanged.
Obsolete work/cleanup Reviewed. No cancellation reaches an active copy; one app-owned copy may finish after startup abort. The existing aborted-init path releases its late daemon lease. Crash recovery retains PID-based staging reclamation.

Touched regression classes:

Class Disposition
Startup/first usable progress P1 above.
Sync filesystem work on main Bulk staging/removal improved; synchronous marker selection and hook-runtime inventory remain pre-existing.
Re-reading unchanged input Stat-keyed hash reuse preserved; verified cold copies seed source hashes.
Unbounded fan-out/queues Source-proven two-worker admission per operation, with failure draining; no per-file promise fan-out. Separate maintenance owners can overlap.
Hot-path rescans Renderer adds one O(1) lookup. Copy validation introduces O(Dcode×(F+D)) directory cross-scans; package-shape impact was not measured.
No-op store identities Existing original-state return preserved; retaining a valid selection avoids the erroneous publication.
Expensive work past gates No platform/adoption gate removed. New validation gates reject incomplete or changing sources. Keeping a listed selection permits its intended existing consumers to continue.
Fixed polling/new idle wakeups Added steady-idle wakeups: 0/s on main, renderer, and daemon by source inspection. Rename timers terminate after bounded retries.
Per-entity retention/hidden owners Promise references clear. Background cleanup serves durability/reclamation. Hash-cache and current-version build retention already lacked eviction before this span.
Eager startup imports Added local mechanism modules and Node built-ins; no new SDK, subprocess, watcher, or recurring service.

Pre-existing amplification remains: each synchronous hook-runtime lookup scans source inventory and retained markers; retained build/hash-cache populations grow with same-version replacement history. These are not introduced by this span.

Validation was source inspection and review of saved evidence. Existing test assertions were inspected, not executed. Fresh gated verification did not complete in this restricted checkout. No exact-head timing, CPU, heap, or idle measurement is claimed; later Windows functional QA covers cold launch, warm reuse, pruning, and crash recovery, not resolution of the measured latency regression.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop status: 8de25fe

Problem: on packaged Windows, every fresh terminal-daemon launch first copies the daemon runtime (about 1.8k–2.2k files, 275 MiB) out of the install folder. That work, fingerprinting plus copying, ran with synchronous file calls on Electron's main thread and froze every window. After an update it froze for 0.7–8 s cold, and for about 110 ms warm.

Change: staging now uses async, bounded file I/O, with at most 2 operations in flight. The daemon still starts only after the copy is complete, verified and atomically renamed into place.

Verified:

  • Packaged Windows (Defender on, base vs this PR, 8 alternating cold-launch pairs plus 4 base-only controls):
    • Main's longest block while staging: 1.6–2.4 s → 175–298 ms.
    • First window: within base-vs-base noise.
    • Workspace list: shows 1.7–1.8 s earlier.
    • First terminal: a median 0.9 s later (pairs −0.5 to +3.2 s; the two +3.2 s pairs ran on a busy machine).
  • Standalone bench (on e23e179): main's longest block 711–8,913 ms → 11–19 ms cold, and 109–121 ms → 11–12 ms warm.
  • Packaged Windows QA on b224bd9 (the staging code as shipped), all passed:
    • Cold launch: the daemon runs from a complete, marked copy.
    • Pruning: an old version folder is deleted.
    • Crash mid-copy: the copy was killed with 1,796 of 2,160 files done. The next launch recovered with a fresh complete copy and removed the dead staging folder.
  • Earlier head (434b5bf), also passed:
    • Warm launch: reuses the existing copy with no recopy.
    • Restart: with a surviving daemon, a running ping -t session continued.
  • Fleet perf gate (~1,900 workspaces): every metric ok; the gate reports INCOMPLETE only because its store-notify probe is missing in both builds.
  • CI: green on 8de25fe, including the packaged Windows serve-switch check and the daemon-host and opendir/fs.cp ban tests.

Found and fixed during final CI (8de25fe):

  • The failure: the packaged Windows serve-switch check failed intermittently, with a new worktree never opening and no terminal.
  • The cause: a startup race in the app. A worktree created while terminal startup was still waiting lost its selection when a one-time cleanup ran at the end of that wait. That cleanup checked against a worktree list taken before the create.
    • The race already existed.
    • Before this PR, the frozen main thread kept the window near zero.
    • With staging off main, the window lasts as long as the copy (about 11 s on a CI runner).
  • The fix: the cleanup now keeps a worktree the current list still shows, the rule it already used for default tabs.
  • Before the fix: 5 of 16 plain runs failed this way, and the same check on main passed 8 of 8.
  • After the fix: 10 of 10 passed, including 4 runs where the worktree was created before the daemon started.
  • Load runs: the two runs under synthetic CPU and disk load failed only the test's heartbeat-timing checks, which fail the same way on main.

Reviews:

  • Two independent review passes, with every finding fixed.
  • The blinded regression audit is SAFE at the final head (8de25fe merged onto main 7bf63e7).
  • Every CodeRabbit thread is resolved.
  • The fresh perf-scan on 8de25fe is blocked only on the first-terminal trade-off above, which is waived below. It found no new idle wakeups, and every operation is bounded.

Deferred (known limits, not introduced here):

  • The synchronous daemon-host lookup used by the Antigravity hook path still runs on main, but after a cold copy it reads no code.
  • A copy continues if the app quits during startup; the next launch cleans it up.
  • Cross-process coordination of publish, launch and prune is STA-19485.

Perf trade-off (waived):

  • Gain: no 1.6–2.4 s main-thread freeze during staging.
  • Cost: a cold first terminal after a Windows build update arrives about 0.9 s later at the median.

Perf waiver (Brennan): "Waive it, I'll merge" (the +897 ms cold first terminal after a Windows build update, traded for no 1.6–2.4 s main freeze). #51222 (comment)

QA screenshots

  • Cold launch at the final head: a fresh install staged the runtime and opened a working terminal.
    Cold launch: terminal running from the relocated runtime
  • Warm launch: the existing copy was reused with no recopy.
    Warm launch reusing the copy
  • Restart: a running ping -t session survived an app restart.
    Restart with a surviving daemon

@brennanb2025
brennanb2025 merged commit fe0e302 into main Nov 28, 2026
69 checks passed
0xff26b9a8 pushed a commit to 0xff26b9a8/orca that referenced this pull request Nov 28, 2026
* fix(fs): open folders with readdir on Windows everywhere in main and shared

On Windows, opendir can report a failed open (a missing folder, for
example) as success with no handle, and building the handle then writes
through null and crashes the process (stablyai#50875, stablyai#50997). The PATH scanner
already avoids it (stablyai#51158); every other main/shared caller still used
opendir or opendirSync.

openDirectory/openDirectorySync in src/shared/open-directory.ts return
the real Dir on macOS and Linux and a readdir-backed handle on Windows.
All callers go through it, and a test fails on any new direct opendir in
src/main or src/shared.

* docs(fs): note Windows lists the folder in full in the worktree removal check

* chore(ratchets): carry the moved opendirSync allowances to open-directory

* fix(fs): drop the Windows listing on close; test refuses opendir on Windows

* test(fs): type the opendir guards without casts

* fix(fs): copy folder trees with readdir on Windows instead of fs.cp's opendir walk

fs.cp opens every source folder with opendir, so a folder that can be
stat'd but not listed, or one removed mid-copy, can hit the same Windows
crash. copyPath (src/shared/copy-path.ts) keeps fs.cp on macOS/Linux and
for files and links; on Windows it walks folders with readdir. The ban
test now also rejects a direct fs.cp in src/main and src/shared.

* fix(fs): stop a local name shadowing copyPath; match fs.cp's default force

* fix(fs): copy files inline in the Windows tree walk and keep fs.cp's into-self checks

Per-file fs.cp repeated a stat of every destination ancestor; files are
now copied the way fs.cp's onFile does (overwrite unless force is false,
mode and optional timestamps). Links still go to fs.cp, now with
recursive false so they can never re-enter its opendir walk. The root
check now also walks destination ancestors by identity, catching a
destination reached through a junction into the source.

* fix(daemon): copy filtered Windows daemon-host folders with a readdir walk

cpSync with a filter walks folders with opendirSync, which goes through
the same Windows open that can report a failure as success and crash.
On Windows only, the filtered folder copies now use a small sync walk
(readdirSync, mkdirSync, copyFileSync) with the same filter and
dereferenced links; executeManifest keeps its shape. stablyai#51222 replaces
this walk with its async walker.

* test(fs): read the opendir baseline from the real module so the test also runs on Windows

* test(fs): capture the real opendir in the mock; carry the daemon staging walk's sync allowance

* fix(fs): yield to the event loop every 32 entries of a Windows listing, as Dir's buffered reads do

(cherry picked from commit b807f1f)
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