Repository navigation
Stop a duplicate headless orca serve from crash-looping and exhausting AppImage FUSE mounts - #12212
Conversation
|
Warning Review limit reached
Next review available in: 5 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 17e6c0d0932da5a587b2346ee6e94ab66105b243 and 40eed26. 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughSingle-instance handling now forwards second-launch arguments and suppresses desktop activation for duplicate 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9832e5ed-05ff-4971-9290-1b9f4f0734cb
📒 Files selected for processing (5)
docs/reference/headless-linux-server.mdsrc/main/index.tssrc/main/startup/single-instance-lock-headless-exit.test.tssrc/main/startup/single-instance-lock.test.tssrc/main/startup/single-instance-lock.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
config/scripts/happy-dom-mutation-observer-retention.test.ts (1)
9-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExport the listener-reading logic instead of duplicating it in the test.
readListenerCallbacksre-implementsreadMutationListenersfromhappy-dom-mutation-observer-retention.ts, including the hardcoded'mutationListeners'string (Line 11) that also appears asMUTATION_LISTENERS_SYMBOL_DESCRIPTIONin the source file. If happy-dom's internal symbol name ever changes, only one of the two copies might get updated, and the test would then validate against a stale assumption instead of the real behavior it depends on.Export the symbol-reading helper (or at least the constant) from the source module and import it here.
♻️ Proposed refactor
-import { - installHappyDomMutationObserverRetention, - retainedMutationCallbackCount -} from './happy-dom-mutation-observer-retention' - -function readListenerCallbacks(target: Node): unknown[] { - const listenersSymbol = Object.getOwnPropertySymbols(target).find( - (candidate) => candidate.description === 'mutationListeners' - ) - const listeners = listenersSymbol - ? (target as unknown as Record<symbol, unknown>)[listenersSymbol] - : [] - if (!Array.isArray(listeners)) { - return [] - } - return listeners.map((listener: { callback?: { deref: () => unknown } }) => - listener.callback?.deref() - ) -} +import { + installHappyDomMutationObserverRetention, + readMutationListeners, + retainedMutationCallbackCount +} from './happy-dom-mutation-observer-retention' + +function readListenerCallbacks(target: Node): unknown[] { + return readMutationListeners(target).map((listener) => listener.callback?.deref()) +}
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 24dd260f-3fe9-4541-87ae-3542dbbe656b
📒 Files selected for processing (5)
config/scripts/happy-dom-mutation-observer-retention.test.tsconfig/scripts/happy-dom-mutation-observer-retention.tsconfig/vitest.config.tsdocs/reference/headless-linux-server.mdsrc/main/startup/single-instance-lock-headless-exit.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/startup/single-instance-lock-headless-exit.test.ts
- docs/reference/headless-linux-server.md
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/startup/single-instance-lock-exit.electron.test.ts (1)
12-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReduce this comment to one concise line.
Keep only the non-obvious reason for the real-process fixture. Move the incident history and platform details to the test description or linked issue.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8247ff0f-e41b-4f14-9957-aaac8ba13d55
📥 Commits
Reviewing files that changed from the base of the PR and between 6154a8d and f7f9d3a639ffccb22ba2f1244901ccaebf379544.
📒 Files selected for processing (2)
src/main/startup/single-instance-lock-exit.electron.test.tssrc/main/startup/single-instance-lock.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/startup/single-instance-lock.ts
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 20e1f2c7-9391-4076-9cf6-9a75fb637557
📥 Commits
Reviewing files that changed from the base of the PR and between f7f9d3a639ffccb22ba2f1244901ccaebf379544 and 17e6c0d0932da5a587b2346ee6e94ab66105b243.
📒 Files selected for processing (1)
src/main/startup/single-instance-lock-exit.electron.test.ts
Fix proof re-established from scratchThe previous Fix-proof section leaned on a triage file that was never committed. That is now replaced with evidence a reviewer can re-run. New: Against On this branch: Neighbouring suites: Also verified while re-checking: exit
|
Correction to my previous comment: the two-process lock race does not survive CIMy earlier comment claimed the new test staged a real duplicate-launch lock race with two Electron processes. It did on macOS. CI disproved it on Linux, and I have removed that part rather than leave a claim the runner contradicts.
Cause: Chromium's Linux
Fail/pass and mutation evidence are in the updated Fix proof section. Summary:
Against One thing my previous comment got right and is worth keeping: the exit-code chain to systemd is three processes deep and does hold — AppImage CLI redirect → CLI → Electron child exits |
|
CI is green on So the mechanism claim is no longer macOS-only reasoning: pre- |
…leaking AppImage mounts A second Orca launch that loses the single-instance lock called app.quit() before `ready`. That quit is deferred, so the doomed process kept booting into Chromium's Linux display initialization, failed with "Missing X server or $DISPLAY", and died with SIGSEGV. systemd read that as a crash and restarted it forever; each restart re-mounted the AppImage and left the squashfuse mount behind, until the host hit the 1000-mount FUSE ceiling and every later launch failed. The lock-losing launch now calls app.exit(3), which terminates synchronously before any display init. Exit code 3 is a stable "another process already owns this userData profile" contract, and the documented systemd unit uses RestartPreventExitStatus=3 plus a real StartLimitIntervalSec/StartLimitBurst window so a permanently failing launch can no longer retry unbounded. Second-instance argv is now forwarded to the owner, and a duplicate `orca serve` no longer asks the live headless server to open a desktop window. Desktop activation for ordinary launches and macOS dock re-activation is unchanged. Closes #11935
StartLimitIntervalSec=300/StartLimitBurst=5 rate-limits operator starts too, so after a crash-loop trips the burst systemd refuses a plain `systemctl start` for the rest of the window. The Upgrade and Roll back scripts run under `set -euo pipefail`, so that refusal aborted the rollback mid-flight and left the server down on the exact recovery path the doc prescribes. Both scripts (and their EXIT-trap recoveries) now run `systemctl reset-failed` first, the unit reference explains the interaction, and the crash-loop bullet points at it for manual starts. Co-authored-by: Orca <[email protected]>
…real Electron The committed coverage for #11935 was source-text greps, so nothing gated the mechanism the fix rests on: pre-`ready` `app.quit()` is deferred, which is why the lock-losing headless `orca serve` kept booting into Linux display init. This runs two real Electron processes against one disposable profile. The duplicate executes the lock-loss gate's own `app.*` statement, lifted out of `src/main/index.ts`, so reverting to `app.quit()` fails the test. It also feeds the owner's real forwarded argv through `shouldActivateDesktopForSecondInstance`. Also record why the activation predicate matches `--serve` and not the `serve` subcommand: an AppImage launched as `orca serve` exits at the CLI redirect before requesting the lock.
… profile Windows holds the profile's handles for a beat after SIGKILL, so an immediate rmSync can fail with EBUSY/EPERM. Co-authored-by: Orca <[email protected]>
Chromium reorders argv and the duplicate's argv is itself under test, so a trailing positional was the wrong channel for it. Co-authored-by: Orca <[email protected]>
The exit-contract cases assert on the duplicate's own already-terminated process, so they should not block on cross-process delivery. Co-authored-by: Orca <[email protected]>
… contract CI proved the two-process form cannot work on a display-less Linux runner: Chromium's ProcessSingleton needs the browser IO thread, which needs `ready`, which needs a display. The pre-`ready` owner looked stale and the duplicate took the lock (`expected [ 'DUPLICATE_WON_LOCK' ] to include 'DUPLICATE_LOST_LOCK'`). Lock acquisition and argv forwarding are already covered in single-instance-lock.test.ts. What only a real process can settle is what the loser does next, so that is all this file now runs -- display-independent. Co-authored-by: Orca <[email protected]>
|
Rebased onto Splitting it was deliberate: this PR carries a real availability trade-off (
|
e1de4bf to
40eed26
Compare
…esktop promotion (#12666) STA-1716 reported that a packaged `orca serve` could become the single-instance owner after the desktop app exits, leaving Dock/Finder unable to restore a window — and that forcing a reopen made the headless process hydrate a renderer that interrupted and DUPLICATED live agent sessions. Verification against main found every criterion already fixed (#8646 for desktop promotion and the fail-closed CLI, #12212 for duplicate serve activation, #12574 + #9729 for the resume/ownership guards). The genuine gap was criterion 6: the ticket's own automated regression never existed. An existing reliability gate asserted PTY identity survives promotion, but nothing asserted what the incident was actually about — how many agents the promoted renderer resumes. This adds that coverage: a unit/service-level journey that drives the real single-instance lock, activation gate, settle and focus paths, then runs the real resume logic against a store seeded as a renderer freshly mounted inside the serve process, asserting zero duplicate resumes. `settleServeDesktopActivation` moved from `index.ts` into its own module with identical semantics, so the test drives the real decision rather than re-implementing it — the earlier repro had to mirror that logic locally, which is the "test passes without running the scenario" failure mode. Proven to be a real oracle: breaking each guard individually turns it red, and reverting the pre-#12574 pane form reproduces the incident exactly (two duplicate `codex resume` tabs).
…g AppImage FUSE mounts (stablyai#12212) * fix(startup): stop a duplicate headless serve from crash-looping and leaking AppImage mounts A second Orca launch that loses the single-instance lock called app.quit() before `ready`. That quit is deferred, so the doomed process kept booting into Chromium's Linux display initialization, failed with "Missing X server or $DISPLAY", and died with SIGSEGV. systemd read that as a crash and restarted it forever; each restart re-mounted the AppImage and left the squashfuse mount behind, until the host hit the 1000-mount FUSE ceiling and every later launch failed. The lock-losing launch now calls app.exit(3), which terminates synchronously before any display init. Exit code 3 is a stable "another process already owns this userData profile" contract, and the documented systemd unit uses RestartPreventExitStatus=3 plus a real StartLimitIntervalSec/StartLimitBurst window so a permanently failing launch can no longer retry unbounded. Second-instance argv is now forwarded to the owner, and a duplicate `orca serve` no longer asks the live headless server to open a desktop window. Desktop activation for ordinary launches and macOS dock re-activation is unchanged. Closes stablyai#11935 * docs(headless): clear the start limit before the scripted service starts StartLimitIntervalSec=300/StartLimitBurst=5 rate-limits operator starts too, so after a crash-loop trips the burst systemd refuses a plain `systemctl start` for the rest of the window. The Upgrade and Roll back scripts run under `set -euo pipefail`, so that refusal aborted the rollback mid-flight and left the server down on the exact recovery path the doc prescribes. Both scripts (and their EXIT-trap recoveries) now run `systemctl reset-failed` first, the unit reference explains the interaction, and the crash-loop bullet points at it for manual starts. Co-authored-by: Orca <[email protected]> * test(startup): reproduce the stablyai#11935 duplicate-serve crash loop under real Electron The committed coverage for stablyai#11935 was source-text greps, so nothing gated the mechanism the fix rests on: pre-`ready` `app.quit()` is deferred, which is why the lock-losing headless `orca serve` kept booting into Linux display init. This runs two real Electron processes against one disposable profile. The duplicate executes the lock-loss gate's own `app.*` statement, lifted out of `src/main/index.ts`, so reverting to `app.quit()` fails the test. It also feeds the owner's real forwarded argv through `shouldActivateDesktopForSecondInstance`. Also record why the activation predicate matches `--serve` and not the `serve` subcommand: an AppImage launched as `orca serve` exits at the CLI redirect before requesting the lock. * test(startup): wait for the owner process to exit before removing its profile Windows holds the profile's handles for a beat after SIGKILL, so an immediate rmSync can fail with EBUSY/EPERM. Co-authored-by: Orca <[email protected]> * test(startup): pass the fixture marker path by env, not argv Chromium reorders argv and the duplicate's argv is itself under test, so a trailing positional was the wrong channel for it. Co-authored-by: Orca <[email protected]> * test(startup): only the activation case waits on the owner notification The exit-contract cases assert on the duplicate's own already-terminated process, so they should not block on cross-process delivery. Co-authored-by: Orca <[email protected]> * test(startup): drop the staged lock race, keep the real-Electron gate contract CI proved the two-process form cannot work on a display-less Linux runner: Chromium's ProcessSingleton needs the browser IO thread, which needs `ready`, which needs a display. The pre-`ready` owner looked stale and the duplicate took the lock (`expected [ 'DUPLICATE_WON_LOCK' ] to include 'DUPLICATE_LOST_LOCK'`). Lock acquisition and argv forwarding are already covered in single-instance-lock.test.ts. What only a real process can settle is what the loser does next, so that is all this file now runs -- display-independent. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
…esktop promotion (stablyai#12666) STA-1716 reported that a packaged `orca serve` could become the single-instance owner after the desktop app exits, leaving Dock/Finder unable to restore a window — and that forcing a reopen made the headless process hydrate a renderer that interrupted and DUPLICATED live agent sessions. Verification against main found every criterion already fixed (stablyai#8646 for desktop promotion and the fail-closed CLI, stablyai#12212 for duplicate serve activation, stablyai#12574 + stablyai#9729 for the resume/ownership guards). The genuine gap was criterion 6: the ticket's own automated regression never existed. An existing reliability gate asserted PTY identity survives promotion, but nothing asserted what the incident was actually about — how many agents the promoted renderer resumes. This adds that coverage: a unit/service-level journey that drives the real single-instance lock, activation gate, settle and focus paths, then runs the real resume logic against a store seeded as a renderer freshly mounted inside the serve process, asserting zero duplicate resumes. `settleServeDesktopActivation` moved from `index.ts` into its own module with identical semantics, so the test drives the real decision rather than re-implementing it — the earlier repro had to mirror that logic locally, which is the "test passes without running the scenario" failure mode. Proven to be a real oracle: breaking each guard individually turns it red, and reverting the pre-stablyai#12574 pane form reproduces the incident exactly (two duplicate `codex resume` tabs).
Summary
A second Orca launch that lost the single-instance lock called
app.quit()(src/main/index.ts:729on the base commitc9a37f58d8; the same gate issrc/main/index.ts:736after this change). Before Electron'sreadyevent that quit is deferred, not immediate — I verified this with a throwaway fixture against this repo's own Electron binary on macOS: the process printedLOCK_LOST, then went right on to printREACHED_READY. On a headless Linux server that continued boot walks straight into Chromium's Ozone/X11 initialization with no display, logsMissing X server or $DISPLAY, and dies withSIGSEGV.systemd reads
SIGSEGVas a crash, soRestart=on-failurerestarts it. The documented unit indocs/reference/headless-linux-server.mdhad noStartLimit*override, and systemd's defaults (10s window / 5 starts) can never trip atRestartSec=5, so the retry loop was effectively unbounded — 2,364 restarts on the reported host. Every restart re-mounted the AppImage under/tmp/.mount_orca-*, and the cgroup teardown SIGKILLed squashfuse before it could unmount, so mounts accumulated until the kernel's 1000-mount FUSE ceiling and every later AppImage launch failed withtoo many FUSE filesystems mounted.There was a second half to the same incident.
acquireSingleInstanceLock(src/main/startup/single-instance-lock.ts:38after this change;:29on the base commit) discarded the second launch's argv, sorequestDesktopActivation(src/main/index.ts:611) fired unconditionally. Electron delivers that notification from insiderequestSingleInstanceLock()on the loser — before any exit change can take effect — so each of those thousands of duplicateorca servelaunches also poked the live headless server intofocusExistingWindow()->openMainWindow(), i.e. repeatedly tried to build a GUI on a display-less box.What now happens:
src/main/index.ts:736callsapp.exit(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE). Pre-readyapp.exit(n)terminates synchronously (measured on macOS: no code after it runs, process exit code isn), so Linux display init is never reached and there is noSIGSEGV. This is the same pattern already shipping atsrc/main/index.ts:416(Windows-only packaged-CLI entry redirect —getPackagedCliEntryArgsreturnsnulloffwin32) and:424(Linux AppImage CLI redirect).SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE = 3(src/main/startup/single-instance-lock.ts:11) is a stable "another process already owns this userData profile" contract. The documentedorca-serve.service(both variants in the doc) now carriesRestartPreventExitStatus=3so systemd stops instead of retrying a launch that cannot succeed, plusStartLimitIntervalSec=300/StartLimitBurst=5so any other repeated startup failure is capped.acquireSingleInstanceLockforwards the second-instance argv, andshouldActivateDesktopForSecondInstance(src/main/startup/single-instance-lock.ts:16) suppresses desktop activation when that argv contains--serve(the flag the CLI shim pushes onto the Electron child atsrc/cli/runtime/launch.ts:93). Ordinary desktop second launches and macOS dock/Finder re-activation are unchanged.Scope against #11935. Closes #11935's crash-loop and mount-exhaustion path — items 1, 2 and 4 of the issue's Expected behavior list (deterministic lock-loss exit with no desktop activation or missing-X crash; a stable non-retryable service contract; a bounded documented retry policy). Two items are not fully delivered here:
src/main/startup/single-instance-lock-exit.electron.test.tscovers the part that matters and is portable — the lock loser's termination under the real Electron binary — but a live two-process lock race cannot be staged on a display-less runner, and the mount count needs a packaged AppImage on a real Linux host. See Fix proof for the CI evidence.ELI5
Orca only lets one copy run per profile. When a second copy showed up, it politely said "please shut down when you get a chance" — but it kept starting up in the meantime, and on a server with no screen that startup crashed hard. The server's watchdog saw a crash and started it again, forever, and every attempt left a bit of junk behind until the machine ran out of room and nothing could start at all. Now the second copy stops right away with a specific "someone else already has this" code, and the watchdog is told that particular code means "don't bother retrying". A duplicate server startup also no longer nags the real server to open a window on a machine that has no screen.
Fix proof
The earlier version of this section cited a triage repro that was never committed. That evidence is gone; everything below is reproducible from this branch.
src/main/startup/single-instance-lock-exit.electron.test.tsruns the lock-loss gate's ownapp.*statement, lifted verbatim out ofsrc/main/index.ts, under the real Electron binary beforeready. A revert toapp.quit()is what fails the test, not a hand-written model of it.It also reproduces the broken behavior in a second case rather than only asserting the fixed one, so a future Electron that made pre-
readyquit()synchronous fails loudly instead of silently making the fix redundant.Fails against
origin/main's sourcegit checkout c9a37f58d8 -- src/main/index.ts src/main/startup/single-instance-lock.ts docs/reference/headless-linux-server.md, then:The runtime failure is the decisive one — with
main's statement in the gate, the doomed launch really does keep running:CONTINUED_INTO_STARTUPis the bug: onmainthe lock loser walks past the gate into the rest ofsrc/main/index.ts, which on a display-less Linux host is Ozone/X11 init,Missing X server or $DISPLAY, andSIGSEGV— the signal death systemd counts as a failure and retries.Passes on this branch
The runtime file alone, five consecutive runs, to check it is not flaky:
2 passed (2)each time, 428–476 ms.Mutation-tested, so the assertions are not decorative
app.exit(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE)→app.exit(0)AssertionError: expected +0 to be 3app.exit(…)→app.quit()(i.e.origin/main)expected [ 'LOCK_LOST', …(2) ] to deeply equal [ 'LOCK_LOST' ]shouldActivateDesktopForSecondInstance→return trueAssertionError: expected true to be falsemutationListenersRENAMEDexpected +0 to be 1athappy-dom-mutation-observer-retention.test.ts:35Exit
3really does reach systemdRestartPreventExitStatus=3only works if the code survives the whole documented chain, which is three processes deep. It does:orca-linux.AppImage serve→maybeRedirectAppImageCliLaunch(src/main/index.ts:418) →spawnSync(CLI)→serveOrcaAppspawns the Electron child with--serve(src/cli/runtime/launch.ts:93) → child exits3→superviseForegroundServereturnsresult.code(src/cli/runtime/serve-update-supervisor.ts:82, reached becausehandoffPathis macOS-bundle-only soreadinessisnot-expected) →process.exitCode = exitCode(src/cli/handlers/core.ts:135) →app.exit(result.status)(src/main/index.ts:424). systemd's MainPID exits3, and no other Orca path in the serve process uses exit code3.macOS dock/Finder re-activation is unaffected:
createMacAppActivationHandlercallsrequestActivation()with no arguments (src/main/window/macos-app-activation.ts:11), soargvdefaults to[]andshouldActivateDesktopForSecondInstance([])istrue.What is deliberately not in the runtime test
A live two-process lock race. It was tried and CI disproved it: Chromium's Linux
ProcessSingletononly answers a second process once the browser IO thread is up, which needsready, which needs a display. On the display-less CI runner the pre-readyowner is treated as stale and the duplicate takes the lock:Lock acquisition and argv forwarding are covered by
single-instance-lock.test.ts; what only a real process can settle is what the loser does next, and that is what the runtime file pins. The reasoning is recorded in the file header so nobody re-attempts it.Still not proved here. Item 3 of the issue (a failed duplicate AppImage launch leaves no FUSE mount behind) and the mount-count half of item 5 need a packaged AppImage on a real Linux host; the repo has no harness for that and it cannot be validated from macOS. The clean in-band exit is a strong reason to expect the mount leak to stop — squashfuse is no longer SIGKILLed during cgroup teardown — but that is inference, not measurement.
Out of scope but required: happy-dom MutationObserver retention
Commit
6154a8d10ain this PR is unrelated to #11935. It addsconfig/scripts/happy-dom-mutation-observer-retention.ts(+81 lines) and its test (+72 lines), and wires the former intoconfig/vitest.config.tsas a repo-widesetupFilesentry that monkeypatchesMutationObserver.prototype.observe/disconnectfor every test file in the suite (4,000+ files). happy-dom holds each observer's internal callback in aWeakRef, so a GC pause under parallel load silently kills a still-connected observer; that flaked this PR's CI shard, and the patch was the way to get the shard green.It could reasonably be split into its own PR, and a reviewer should feel free to ask for that. Reviewing it here means reviewing a suite-wide test-harness change alongside a main-process startup fix. Its own suite:
Caveat, also recorded as a review note below: the second of those two tests does not actually exercise GC —
globalThis.gcis undefined under this vitest config (no--expose-gcinexecArgv), so thecollectGarbageblock is skipped and the case degrades to "happy-dom delivers two mutation batches".No regressions
npx vitest run --config config/vitest.config.ts src/main/startup/ src/cli/runtime/serve-signal-exit-diagnostic.test.ts src/cli/runtime/launch.test.ts src/main/runtime/runtime-rpc.test.ts config/scripts/happy-dom-mutation-observer-retention.test.tsThe pre-existing
src/main/startup/baseline, with the new runtime file excluded, is26 passed (26)files /182 passed (182)tests; the new file adds 3.That covers the whole
src/main/startup/directory (includingserve-desktop-activation-wiring.test.ts, which pins the literalacquireSingleInstanceLock(app, requestDesktopActivation)call text this change deliberately keeps byte-identical, anddesktop-startup-ordering.test.ts, which has ninereadFileSyncsource anchors into the editedsrc/main/index.ts), plus the CLI exit-code passthrough suites the exit contract depends on.Lint over every changed source file (docs excluded), both clean:
Trade-offs
3instead of0. Invisible to GUI users (LaunchServices and the Windows shell ignore non-zero launcher exits, and the crash dialog people saw was a signal-death artifact, not an exit-code one). But an operator script that treated exit0from a secondorca serveas "started" will now see a failure code. That is the more correct answer, not a silent success.RestartPreventExitStatus=3is a real availability trade. A unit started while another owner holds the profile now stays down and reportsfailedinstead of silently retrying. That is deliberate — retrying genuinely cannot help — but Chromium'sProcessSingletoncan occasionally report a false "already running" from a staleSingletonLockwhose recorded pid was reused, and under this directive that means downtime until someone intervenes. A new troubleshooting bullet indocs/reference/headless-linux-server.mdspells out the escape:systemctl reset-failed(required onceStartLimitBurstis tripped) plus removing the staleSingletonLock/SingletonSocket, and how to release already-leaked mounts withfindmnt+fusermount -uzwithout touching the live instance's mount.StartLimitBurst=5/StartLimitIntervalSec=300also caps benign flapping. With the existingRestartSec=5, the unit gets roughly 25 seconds of self-healing runway before systemd downs it permanently for the rest of the 5-minute window. systemd cannot tell a permanent fault from a transient one; a genuinely transient startup failure (slow network mount, late dependency) that would previously have healed on retry six now needssystemctl reset-failed. The scripted upgrade/rollback paths in the doc were updated to callreset-failedbefore everysystemctl startfor exactly this reason.orca serveagainst a machine already running Orca no longer raises the desktop window. It exits3with the existing explanatory stderr line. Correct for a headless-server command, but a visible change for anyone who was incidentally usingorca serveas a "show me the app" command; a plain launch is the supported path for that and is unchanged.orca serveinstances against one profile, asserting exit3, owner continuity, and an unchangedfindmnt -rn -t fuse.orca-linux.AppImagecount) is not included — this is item 5 of the issue's expected behavior. The repo has no packaged-AppImage e2e harness to hang it on, and it cannot be validated from macOS, so committing an unverified job would have shipped a red or flaky gate. The load-bearing assumption it would close is that the JS main script runs before the X11/Ozone connection on Linux; the only evidence for that today is the reported journal ordering (Orca's[single-instance]line precedesMissing X server or $DISPLAY). That ordering is consistent with the issue report, but is worth confirming on a real Linux host.Cross-platform
All verification in this PR was performed on macOS — the unit suites, the lint runs, and the
app.exit()timing fixture. Nothing here was executed on Linux or Windows, which matters because Linux is the platform the bug was reported on. The Linux and Windows statements below are reasoned from the source and from the issue's journal, not measured.app.exit(3)pre-readywas measured directly on this repo's Electron on macOS — synchronous termination, no subsequent code runs, process exit code3. Dock/Finder re-activation is untouched:createMacAppActivationHandler(src/main/index.ts:619) is passedrequestDesktopActivationand calls it with no arguments (src/main/window/macos-app-activation.ts:11), which defaultsargvto[]and therefore still activates. TheORCA_BYPASS_SINGLE_INSTANCE_LOCK=1diagnostic escape hatch still forceshasSingleInstanceLock = true, so it never reaches the new exit.pnpm devis unaffected —shouldSkipSingleInstanceLockforceshasSingleInstanceLock = truefor dev, non-serve runs unlessORCA_E2E_ENFORCE_SINGLE_INSTANCE_LOCK=1.app.exit()pattern already ships on the Windows-only path atsrc/main/index.ts:416. The second-instance argv on Windows includes the exe path, butargv.includes('--serve')matches an exact flag token (and--serve-json,--serve-port, … are distinct tokens that do not match), so drive letters, casing, and\separators are irrelevant. No path is constructed or compared, so nopath.joinconcern. Not committing the triage repro'sspawnSync('node_modules/.bin/electron')cases avoids a hazard that would have hard-errored for anyone running the unit suite on Windows.main.csstokens do not apply.3instead of segfaulting into an unbounded restart loop, and the argv-aware activation stops a supervisor-spawned duplicate from pushing that display-less host intoopenMainWindow().initDataPath()(src/main/index.ts:747), before the store loads, and before any worktree, folder-workspace, repo, or provider concept is resolved. No Git command is added or changed, so the 2.25 baseline,GitCapabilityCache, and the leading-cglobal-option rule are not engaged. No GitHub/GitLab-specific code is touched.Performance
Strictly less work on the failure path and effectively none on the app's success path.
src/main/index.tsmodule body plus full Electron platform init before dying. Now it terminates atsrc/main/index.ts:736. Projected against the reported host's numbers (not measured here), that is 2,364 doomed Electron boots and 999 leaked squashfuse mounts that no longer happen.argv.includes('--serve')— an array scan over a handful of strings — persecond-instanceevent. That event only fires on a duplicate launch, never on any hot path. It also removes work: a duplicateorca serveno longer triggersopenMainWindow(), so no BrowserWindow creation, no renderer boot, no IPC storm on a headless server.setupFilesentry now loads one small module and patches twoMutationObserverprototype methods in every test file's environment. The observed cost is small —setup 372msacross the 29 files in the run above, ~13ms per file — but it is paid by the entire suite, not just this change.Security
No change to the security surface.
ipcMain.handleregistrations sit inside theif (hasSingleInstanceLock)block or later in the module; the change only makes the lock-losing process stop before reaching them, which is strictly safer — it can no longer register handlers or run startup against a profile another process owns.fusermount -uz/umount -lguidance is explicitly scoped to mounts with no live owner.--serve.initDataPath(), so no token, pairing material, ororca-runtime.jsonis read or written on this path. The fix in fact reduces the window in which a lock-losing process could clobber the owner's discovery files.SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE,shouldActivateDesktopForSecondInstance) are pure, main-process-only, and take no untrusted input beyond Electron's ownsecond-instanceargv, which is already trusted to the same degree as the process's ownprocess.argv.MutationObserver.prototypeand holds callbacks in aWeakMapkeyed by observer. It lives inconfig/scripts/and is loaded only byconfig/vitest.config.ts, so it never ships in the app bundle.AI Review Report
Reviewed by independent subagents in a loop until clean, across two hostile lenses — correctness/regressions and cross-platform + remote + performance.
Non-blocking notes (5), recorded for transparency (notes 2 and 4 are the same out-of-scope finding raised independently by both lenses; it is now disclosed in its own section above):
config/scripts/happy-dom-mutation-observer-retention.test.ts— the second test, keeps delivering records after the weak callback would have been collected, never exercises the behavior it names.globalThis.gcis undefined under this vitest config (config/vitest.config.tssetsexecArgv: ['--no-experimental-webstorage'], with no--expose-gc), so thecollectGarbageblock is skipped entirely and the test degrades to "happy-dom delivers two mutation batches", which happy-dom does unpatched. Verified by reading the config; the first test in that file does pin the real behavior.config/scripts/happy-dom-mutation-observer-retention.ts— commit6154a8d10a(test(env): keep happy-dom MutationObserver callbacks alive across GC) is unrelated to [Bug]: duplicate headless orca serve crash-loop leaks AppImage FUSE mounts until mount_max #11935. It adds 153 lines of new global test infrastructure and wires it intoconfig/vitest.config.tsas a repo-widesetupFilesentry that monkeypatchesMutationObserver.prototype.observe/disconnectfor every test file in the suite. Nothing in the startup/single-instance fix needs it. (Now disclosed in the body; still arguably a separate PR.)src/main/startup/single-instance-lock-headless-exit.test.ts— resolved. At review time all five tests there were source/doc text greps, so the mechanism the fix rests on (pre-readyapp.exit(n)terminating before the rest of startup runs) had no automated gate.src/main/startup/single-instance-lock-exit.electron.test.tsnow gates it against the real Electron binary, resolving the electron path throughcreateRequire(import.meta.url)('electron')rather than the extension-lessnode_modules/.bin/electronshim, so it is Windows-safe; and it discriminates fixed from broken by whether the statements after the gate run, which is display-independent and therefore valid on the headless Linux CI runner.config/scripts/happy-dom-mutation-observer-retention.ts— same finding as note 2 from the cross-platform lens: an unrelated global test-harness change (two new files plus a suite-widesetupFilesentry patchingMutationObserver.prototypefor every one of the repo's 4,000+ test files) is bundled into a main-process startup fix, and at review time the PR body never mentioned it in any section.docs/reference/headless-linux-server.md—StartLimitIntervalSec=300+StartLimitBurst=5combined with the existingRestartSec=5gives the unit only ~25 seconds of self-healing runway before it is permanently downed, while the surrounding prose (line 182) says the cap applies to "any other permanent startup fault". systemd cannot distinguish permanent from transient; the limiter trips on the 5th start regardless of cause. Captured as an explicit trade-off above.Made with Orca 🐋