Skip to content

perf(serve): clone the supervisor's code copy in one step on macOS - #31303

Merged
Jinwoo-H merged 4 commits into
mainfrom
jinwoo/serve-supervisor-snapshot-clone
Oct 21, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
jinwoo/serve-supervisor-snapshot-clone

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​139 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​137
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​52 $\color{#cf222e}{\Huge{\mathbf{−}}}$​24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​28

ELI5

orca serve --supervise keeps a private copy of Orca's command-line code outside the app, so an update can't change it mid-run. On a Mac, making that copy took 10 to 35 seconds, because it copied about 6,000 files one at a time. This PR makes it one whole-folder clone, the same way Orca already copies its terminal helper app. It now takes about 1.5 seconds.

What Changed

  • Before: buildSnapshot (serve-supervisor-relocation.ts) copied app.asar.unpacked and Resources/node_modules with Node's fs.cp in clone mode, which clones file by file. That took:

    • 10 to 15 s in the foreground;
    • about 35 s under the service's default launchd scheduling class.

    The copy runs every time a supervised service starts.

  • After: on macOS the copy is a single /bin/cp -cR per folder, an APFS clone of the whole tree. If that fails it falls back to /bin/cp -R. That took:

    • about 1.5 s in the foreground;
    • 19 to 30 s at background I/O priority on a busy machine, against 65 to 139 s before.

    Linux keeps fs.cp, which reflinks there, so the AppImage path is unchanged. Windows never relocates.

  • Shared helper: the clone-with-fallback now lives in src/main/macos-tree-clone.ts (cloneMacTree). It throws when both attempts fail and runs cp with no time limit, because a large tree at background I/O priority can outlast the 30 s default that other commands get. The terminal helper copy in macos-daemon-bundle.ts, which already used this exact approach, now calls it directly in place of its own copyBundle. It is still bounded by its deadline signal, and its failure log now names the folder ("Could not copy Orca Terminal Host.app").

Why

The terminal helper copy already proved this approach. Reusing it keeps one implementation and avoids hand-rolling a clone. Alternatives considered:

  • Tuning fs.cp: its cost is per-file work, not missing clone support; a plain byte copy measured 14.5 s.
  • Raising the service's launchd priority: that would change every service's scheduling, and it would still leave the copy file by file.

This matters more once #31200 lands. After an update, the supervisor re-runs itself from the new app and makes this copy again, so the copy adds directly to how long the server is down after an update.

Linked Issue

Related to #31022 (the update-time cost of the fix in #31200).

Visual Proof

N/A: no UI change. Timings are in Testing.

Testing

  • I manually tested these changes locally

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

  • macos-tree-clone.test.ts:

    • clones a real tree on APFS in one step, replacing an existing destination instead of nesting into it;
    • falls back to a plain copy over a cleared destination, with no time limit and the caller's signal;
    • throws when both attempts fail.
  • serve-supervisor-relocation.test.ts: "copies contents, symlinks and executable bits verbatim" runs on every platform except Windows, so it exercises cp on macOS and fs.cp on Linux. It covers relative, absolute, dangling and directory symlinks, file modes, and no nesting into an existing destination.

  • On the real packaged Resources tree (6,379 entries), the old and new methods produced byte-identical snapshots, with identical file modes.

  • Benchmark of the full relocation:

    Run Old (fs.cp) New (cp -cR)
    Foreground 10.1 to 15.6 s 1.4 to 1.9 s
    Background I/O 65 to 139 s 19 to 30 s
  • Gates: tc:cli, tc:node, oxlint, oxfmt and the changed-code quality gate are clean. src/cli/runtime and src/main/daemon pass, apart from two tests that also fail on main and one load flake that passes when run alone.

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

  • Platforms: the change runs on macOS only. Linux and AppImage relocation are unchanged, and Windows has no --supervise.
  • File modes: cp -R without -p applies the umask to file modes, whereas fs.cp kept modes exactly. This only differs for group- or world-writable files, and the packaged tree has none: the comparison was identical.
  • Logging: a failed snapshot copy logs only which folder failed, not cp's error output.

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)
  • 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)

orca serve --supervise copies the app's unpacked code and node_modules out
of the app before re-running itself from the copy. Node's fs.cp clones those
~6,000 files one at a time, which took 8-15 s in the foreground and around
35 s under the service manager's throttled I/O. One /bin/cp -cR per tree
does the same copy in about 1.5 s.

The clone-then-plain-copy fallback the terminal host copy already used now
lives in src/shared/macos-tree-clone.ts, and both copies call it. Linux keeps
fs.cp with reflink cloning, and Windows does not support --supervise.

Claude-Session: serve-snapshot-clone
@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 80c1d1f7-6d22-41c1-8880-664f807363d9
📥 Commits

Reviewing files that changed from the base of the PR and between 7614b5c and c3eba41.

📒 Files selected for processing: 2
  • config/electron-builder.config.cjs
  • config/scripts/electron-vite-output-contract.test.ts

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

📝 Walkthrough

Adds cloneMacTree, which clears the destination and tries APFS clone-recursive copying before recursive copying. Supervisor relocation uses this helper on macOS and retains recursive reflink copying on other platforms. Daemon bundle staging also uses the helper. Build validation and packaging include the new entry. Tests cover copied files, permissions, symlinks, destination replacement, fallback behavior, and copy failures.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to c3eba

The reviewed change has no established merge-blocking risk.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 11 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: improving macOS supervisor code-copy performance through cloning.
Description check Passed The description is detailed and covers the change, rationale, testing, platform impact, performance results, and checklist. The linked issue is identified as related rather than using the template's "…
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.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, platform impact, performance results, and checklist. The linked issue is identified as related rather than using the template's "Fixes #" format, and the full repository command checklist remains unchecked, but these are non-critical because the description provides test evidence and states that CI gates are clean.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • 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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cb25d989-04a1-4a02-9f26-8d4702462c0c
📥 Commits

Reviewing files that changed from the base of the PR and between ecee346 and ae76d1b.

📒 Files selected for processing: 5
  • src/cli/runtime/serve-supervisor-relocation.test.ts
  • src/cli/runtime/serve-supervisor-relocation.ts
  • src/main/daemon/macos-daemon-bundle.ts
  • src/shared/macos-tree-clone.test.ts
  • src/shared/macos-tree-clone.ts

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

Comment thread src/shared/macos-tree-clone.ts Outdated
Comment on lines +18 to +31
options: MacTreeCloneOptions = {}
): Promise<boolean> {
const rm = options.rm ?? nodeRm
// APFS clone first; a failed clone can leave a partial tree on other filesystems.
// Clearing also keeps `cp -R` from nesting `source` inside an existing `destination`.
for (const args of [['-cR'], ['-R']]) {
await rm(destination, { recursive: true, force: true })
const result = await runProcess({
program: '/bin/cp',
args: [...args, source, destination],
maxOutputBytes: 8192,
signal: options.signal
})
if (result.code === 0 && !result.timedOut) {

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg --files | rg '(^|/)(process-host|run-process|process\.ts)(/|\.|$)' | head -90
rg -n 'export .*runProcess|async function runProcess|function runProcess|spawnError|spawn error' packages src/shared | head -90
sed -n '65,115p' src/cli/runtime/serve-supervisor-relocation.ts
sed -n '55,90p' src/main/daemon/macos-daemon-bundle.ts

Repository: stablyai/orca

Length of output: 6569


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- run-process implementation ---'
nl -ba src/packages/process-host/src/run-process.ts | sed -n '1,280p'
printf '%s\n' '--- process spec and package exports ---'
nl -ba src/packages/process-host/src/process-spec.ts | sed -n '1,220p'
printf '%s\n' '--- runProcess references and error-related tests ---'
rg -n -F --glob '*.ts' -e 'runProcess' -e 'spawn' -e 'error' \
  src/packages/process-host/src/run-process.test.ts \
  src/packages/process-host/src/run-process-bytes.test.ts \
  src/packages/process-host/src/run-process-termination-failure.test.ts | head -220
printf '%s\n' '--- launch-error tests ---'
rg -n -C 8 -i --glob '*.test.ts' \
  -e 'spawn error' -e 'spawnerror' -e 'does not exist' -e 'ENOENT' \
  -e 'invalid executable' -e 'cannot spawn' src/packages/process-host/src || test "$?" -eq 1
printf '%s\n' '--- clone helper and callers ---'
nl -ba src/shared/macos-tree-clone.ts | sed -n '1,180p'
nl -ba src/cli/runtime/serve-supervisor-relocation.ts | sed -n '65,125p'
nl -ba src/main/daemon/macos-daemon-bundle.ts | sed -n '45,105p'
printf '%s\n' '--- package entrypoint/export bindings ---'
cat src/packages/process-host/package.json
rg -n -F --glob '*.ts' -e 'from "./run-process"' -e "from './run-process'" -e 'run-process' src/packages/process-host/src | head -100

Repository: stablyai/orca

Length of output: 35026


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- run-process implementation ---'
nl -ba src/packages/process-host/src/run-process.ts | sed -n '1,280p'
printf '%s\n' '--- process spec and package exports ---'
nl -ba src/packages/process-host/src/process-spec.ts | sed -n '1,220p'
printf '%s\n' '--- runProcess references and error-related tests ---'
rg -n -F --glob '*.ts' -e 'runProcess' -e 'spawn' -e 'error' src/packages/process-host/src/run-process.test.ts src/packages/process-host/src/run-process-bytes.test.ts src/packages/process-host/src/run-process-termination-failure.test.ts | head -220
printf '%s\n' '--- launch-error tests ---'
rg -n -C 8 -i --glob '*.test.ts' -e 'spawn error' -e 'spawnerror' -e 'does not exist' -e 'ENOENT' -e 'invalid executable' -e 'cannot spawn' src/packages/process-host/src || test "$?" -eq 1
printf '%s\n' '--- clone helper and callers ---'
nl -ba src/shared/macos-tree-clone.ts | sed -n '1,180p'
nl -ba src/cli/runtime/serve-supervisor-relocation.ts | sed -n '65,125p'
nl -ba src/main/daemon/macos-daemon-bundle.ts | sed -n '45,105p'
printf '%s\n' '--- package entrypoint/export bindings ---'
cat src/packages/process-host/package.json
rg -n -F --glob '*.ts' -e 'from "./run-process"' -e "from './run-process'" -e 'run-process' src/packages/process-host/src | head -100

Repository: stablyai/orca

Length of output: 35026


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- remaining runProcess event handling ---'
nl -ba src/packages/process-host/src/run-process.ts | sed -n '277,390p'
printf '%s\n' '--- launch failure test block ---'
nl -ba src/packages/process-host/src/run-process.test.ts | sed -n '255,305p'

Repository: stablyai/orca

Length of output: 6866


Catch launch errors before the -R fallback.

@orca/process-host rejects when /bin/cp cannot start. cloneMacTree does not catch that rejection, so the -cR attempt exits the loop before -R. A transient launch error can therefore fail a copyable tree even when the plain copy could succeed.

Suggested fix
-    const result = await runProcess({
-      program: '/bin/cp',
-      args: [...args, source, destination],
-      maxOutputBytes: 8192,
-      signal: options.signal
-    })
-    if (result.code === 0 && !result.timedOut) {
-      return true
+    try {
+      const result = await runProcess({
+        program: '/bin/cp',
+        args: [...args, source, destination],
+        maxOutputBytes: 8192,
+        signal: options.signal
+      })
+      if (result.code === 0 && !result.timedOut) {
+        return true
+      }
+    } catch {
+      continue
     }

…w on failure

The shared cp helper ran under runProcess's 30 s default time limit, which the old fs.cp copy never had. At background I/O priority a large tree can outlast it, so the supervisor would quietly give up and run from the app itself. The helper now runs cp with no limit; the terminal helper copy stays bounded by its deadline signal.

The helper moves to src/main beside the asar-safe rm and uses it directly, so it no longer takes an rm option. It throws instead of returning a boolean, so copyBundle is gone. The relocation reads process.platform instead of a platform dependency, and its copy test now runs on every platform but Windows.

Claude-Session: serve-snapshot-clone
…ads it

The serve supervisor's relocation code in the CLI now imports the macOS
tree copy module from the main-process sources. The CLI is compiled file by
file, but the later main-process build replaces out/main and keeps only the
files it is told to build as entries, so the packaged CLI failed at load
with "Cannot find module '../../main/macos-tree-clone'" on every platform,
and the CLI runtime verifier rejected the build.

Register the module as a CLI main entry, like the other main modules the
CLI imports, and unpack it from the app archive. Its asar-safe removal
dependency is bundled into a shared main chunk, which is already unpacked.
The build output contract test now covers both.

Claude-Session: serve-snapshot-clone
The compiled CLI layout keeps out/main/macos-tree-clone.js requiring
./asar-transparent-fs directly, and that file was still packed, so the
packaged CLI failed to load (caught by packaged-cli-assets in CI). The
bundled build only passed because the main build inlines it into an
unpacked chunk.

Claude-Session: serve-snapshot-clone
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Timed desktop Update & Restart runs on macOS: a registered orca serve --supervise service under a LaunchAgent, parked during the install, then the real installer swap. Builds are CI-signed with a throwaway identity, and the runs were back to back under the same machine load.

Update target Swap to serving again
#31200 only (file-by-file code copy) 19 s
#31200 + #31303 (one clone per folder) 8 s and 9 s
main, for reference (no re-launch, permissions broken) 14 s

After every run with #31200 the supervisor kept its PID, ran the installed app, and the terminal opened before the update was still alive.

On a busier machine earlier, the #31200-only path took 56–65 s, almost all of it the code copy. The two PRs together bring post-update downtime back to main's level or better.

@Jinwoo-H
Jinwoo-H merged commit 4e483ae into main Oct 21, 2026
49 checks passed
@Jinwoo-H
Jinwoo-H deleted the jinwoo/serve-supervisor-snapshot-clone branch October 21, 2026 02:02
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