orca icon indicating copy to clipboard operation
orca copied to clipboard

Run WSL file watching in a managed Linux host

Open Jinwoo-H opened this issue 4 months ago • 1 comments

Fixes #7792.

Summary

  • replace the per-root scripting bridge with a versioned Orca-managed Linux watcher host
  • run one native host per WSL distro and multiplex all active worktree roots over a JSON-line protocol
  • package a checksum-pinned Linux runtime plus x64 and arm64 native watcher addons in Windows builds, so WSL watching requires no distro-installed Python, Node, or watcher utility
  • keep fully recursive snapshots only as a compatibility fallback for unsupported architectures/libc environments
  • make recovery WSL-lifecycle-aware: a deliberate distro shutdown stays shut down, while an already-running distro gets bounded watcher restart

Root cause

The original WSL watcher periodically scanned metadata and limited find to two levels. A nested file such as docs/deep/README.md never entered a snapshot, so an external edit could not emit fs:changed and an open rich Markdown editor stayed stale.

Removing the depth cap fixed correctness but not the architecture. On a representative 362 MB WSL repository, one recursive scan took 1.17 seconds and returned about 2.6 MB; the old loop ran every two seconds. WSL was still the only local filesystem path that continuously rescanned and transferred the tree while idle.

Design

The steady-state watcher now runs beside the filesystem inside the distro:

  • The Windows installer carries a compressed, pinned Node 24.15.0 runtime and native watcher addon for Linux x64 and arm64.
  • On first use in a distro, Orca installs the matching slice under ~/.local/share/orca/wsl-watcher/<bundle-version>/<arch> with an atomic, concurrency-safe install, runtime self-check, and third-party licenses.
  • A single host process owns every active root in that distro, applies nested high-churn exclusions at the native watcher, and sends only event deltas back to the main process.
  • The host has subscription/startup timeouts, bounded protocol buffers, a native-delivery canary, interruption overflows, and clean last-subscriber teardown.
  • If the host exits, Orca checks wsl.exe --list --running --quiet, which does not start the distro. It waits while the distro is stopped and resumes native watching after WSL is running again.
  • Glibc x64/arm64 distros use the managed native path. Unsupported environments retain the fully recursive five-second scan fallback.
  • SSH watching and non-WSL local watching keep their existing implementations.

The Windows-only resource is 62,272,424 bytes compressed and is excluded from app.asar, avoiding a duplicate copy. macOS and Linux packages do not receive this resource.

Reproduction and validation

  • Reproduced the original nested Markdown failure on Ubuntu WSL.
  • The opt-in live WSL test performs a fresh managed-runtime install, verifies no idle batches for 2.5 seconds, observes a three-level-deep external edit within the two-second native-only gate, and verifies a nested node_modules edit produces no event batch.
  • Built an unpacked Windows app and confirmed its external resources/wsl-watcher manifest, x64/arm64 runtime slices, and absence from app.asar.
  • Launched that packaged app on an isolated profile, added a real WSL Git repository, and opened docs/deep/README.md in the rich editor. A Linux-side write changed the visible heading from Before to After from managed WSL within 900 ms without close, refresh, or reopen; Explorer modified markers updated at the same time.
  • Process inspection confirmed the packaged app used the versioned managed runtime, not the distro's installed Node. Closing the app removed the Linux host process.
  • Audited Windows/Linux and SSH boundaries. Windows-only preparation is gated in the pack hook, host paths use explicit WSL conversion, arguments avoid a Windows host shell, and remote watcher selection is unchanged.

Checks

  • 96 focused watcher/external-editor/package tests passed; 3 opt-in/real-environment tests skipped in the normal run
  • live Ubuntu WSL integration test passed
  • full node/CLI/web pnpm run typecheck passed
  • changed-file oxlint and pre-commit lint/format hooks passed
  • pnpm run check:reliability-gates passed
  • pnpm run check:max-lines-ratchet passed
  • production pnpm run build:electron-vite passed
  • Windows unpacked packaging passed with local executable signing/editing disabled; the production config itself is unchanged
  • git diff --check passed

Full pnpm run lint still reaches the unrelated existing src/main/ipc/notification-authorization-status.ts:71 switch-exhaustiveness error for a missing undefined case. All changed files and the remaining lint gates pass.

Jinwoo-H avatar Jul 09 '26 20:07 Jinwoo-H

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds managed native and snapshot WSL watcher engines with shared host IPC, snapshot parsing, event diffing, restart handling, and overflow tracking. Adds WSL runtime installation, caching, immutable publication, lease management, and packaging preparation. Updates Electron build configuration and adds the watcher host build entry. Expands unit, runtime, configuration, and optional live integration tests for startup, fallback, event delivery, shared subscriptions, restart, resource safety, and cleanup behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.15% 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 The changes address #7792 by replacing stale WSL polling with a managed Linux watcher host and verifying external edits reload open Markdown files.
Out of Scope Changes check ✅ Passed The broad build, runtime, protocol, and test changes all support the WSL watcher overhaul and do not appear unrelated to the stated fix.
Title check ✅ Passed The title is concise and clearly summarizes the main change: moving WSL file watching into a managed Linux host.
Description check ✅ Passed The description is detailed and covers summary, cause, design, validation, and review, but it omits screenshots, security audit, and notes sections.

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[bot] avatar Jul 09 '26 20:07 coderabbitai[bot]

Review + live-test report (Windows 11 + real WSL Ubuntu)

Deep review of this branch plus hands-on testing on a Windows machine with WSL. Verified working end-to-end, and pushed 22bf88db3 with fixes for the confirmed issues found during review.

Verified live

  • The fix itself: dev app with a \wsl.localhost\Ubuntu\... repo — markdown preview updates within ~2s of an in-WSL edit; new files appear in the Explorer with correct git status decorations (this was the stale-markdown bug).
  • Lifecycle: one shared host per distro; host killed inside WSL self-recovers; last unsubscribe exits the host; zero orphan processes after app exit.
  • Fresh install: concurrent watchers on a wiped runtime install exactly one version, no transfer leftovers.
  • Stopped distro: via a disposable imported distro — the restart loop never wakes a terminated distro, and the watcher recovers autonomously on distro restart.
  • Fallback: GNU + portable (BusyBox-style) snapshot scripts produce parseable frames live, including filenames with spaces.
  • Perf: 30k-file tree — startup, deep-event latency (<2.5s), and 90s idle CPU (incl. safety rescans) all within bounds.
  • Supply chain: pinned Node 24.15.0 tarball hashes match nodejs.org SHASUMS exactly (x64 + arm64).

Fixed in 22bf88db3 (all live-reproduced or code-confirmed)

  1. Unreadable subtree killed the watcher entirely — a chmod 000/root-owned dir (common with docker artifacts) failed the native engine's initial scan with io-error AND aborted the set -efu snapshot script, so createWslWatcher rejected and the root was cached unwatchable until app restart (regression vs main's 2>/dev/null || true). Now: scans treat EACCES/EPERM as invisible (like ENOENT) and the script degrades to a partial frame. Re-tested live: native engine subscribes and delivers events past the unreadable dir.
  2. Canary temp-dir leak — Windows-side hard kills never run the host's exit handler; 47 orphaned /tmp/orca-wsl-watcher-* dirs accumulated in one day of testing. Now: pid-in-name + dead-owner sweep at host start (verified live: next host start reclaims prior dirs).
  3. Broken bundle retried forever — a present-but-corrupt bundle (missing/corrupt manifest.json) threw a plain error, classified transient → native reprobe every 30s indefinitely. The message-string branch in isPermanentWslNativeFailure checked text that no code ever throws. Now: bundle read errors wrap in WslWatcherCompatibilityError (permanent); dead branch removed.
  4. UTF-16 list decoding — wsl.exe --list output was utf8-decoded (execFile default), so decodeWslListOutput's utf16le branch was dead code; parsing worked only because NUL-stripping cancels UTF-16 interleaving for ASCII names. Non-ASCII distro names would never match → isWslDistroRunning false forever → watcher never recovers after an engine stop. Now: encoding: 'buffer'.

Known follow-ups (not blocking, documented for later)

  • Trees >100k entries (post-ignores) permanently fail the native initial scan (DEFAULT_MAX_SCAN_ENTRIES) and fall to 5s polling plus a full 100k-entry rescan every 30s reprobe, forever. Consider classifying entry-limit as permanent-per-session or raising the cap.
  • Attach performs two back-to-back full recursive scans (baseline + immediate checkpoint) — the journal machinery could make it one.
  • Topology-reason restarts pin at 500ms with no backoff; sustained dir churn outside the ignore list causes restart/overflow thrash.
  • Dev builds never run prepare:wsl-watcher, so pnpm dev silently uses the snapshot fallback unless prepared manually.
  • Reuse: toWslUncPath duplicates wsl.ts toWindowsWslPath; the running-distro parser duplicates normalizeWslListOutput (without its docker-desktop filter); host-client NDJSON framing duplicates daemon/ndjson.ts; the canary is a near-copy of the parcel-watcher-process one.
  • Pre-existing (unchanged by this PR): \wsl$\...-registered worktrees get events emitted under \wsl.localhost\, so prefix matching never fires — worth normalizing the provider at repo-add.

Gap to note: CI skips the Windows package job, so the electron-builder staging path (beforeBuild lease → extraResources) has unit-test coverage only — worth one real packaged Windows build before release.

Jinwoo-H avatar Jul 10 '26 08:07 Jinwoo-H

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-07-10T08:49:33Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

OrcaWin avatar Oct 27 '26 09:10 OrcaWin