Skip to content

Stop a duplicate headless orca serve from crash-looping and exhausting AppImage FUSE mounts - #12212

Merged
nwparker merged 7 commits into
mainfrom
nwparker/bugbash-11935
Aug 4, 2026
Merged

nwparker merged 7 commits into
mainfrom
nwparker/bugbash-11935

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A second Orca launch that lost the single-instance lock called app.quit() (src/main/index.ts:729 on the base commit c9a37f58d8; the same gate is src/main/index.ts:736 after this change). Before Electron's ready event that quit is deferred, not immediate — I verified this with a throwaway fixture against this repo's own Electron binary on macOS: the process printed LOCK_LOST, then went right on to print REACHED_READY. On a headless Linux server that continued boot walks straight into Chromium's Ozone/X11 initialization with no display, logs Missing X server or $DISPLAY, and dies with SIGSEGV.

systemd reads SIGSEGV as a crash, so Restart=on-failure restarts it. The documented unit in docs/reference/headless-linux-server.md had no StartLimit* override, and systemd's defaults (10s window / 5 starts) can never trip at RestartSec=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 with too many FUSE filesystems mounted.

There was a second half to the same incident. acquireSingleInstanceLock (src/main/startup/single-instance-lock.ts:38 after this change; :29 on the base commit) discarded the second launch's argv, so requestDesktopActivation (src/main/index.ts:611) fired unconditionally. Electron delivers that notification from inside requestSingleInstanceLock() on the loser — before any exit change can take effect — so each of those thousands of duplicate orca serve launches also poked the live headless server into focusExistingWindow() -> openMainWindow(), i.e. repeatedly tried to build a GUI on a display-less box.

What now happens:

  • src/main/index.ts:736 calls app.exit(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE). Pre-ready app.exit(n) terminates synchronously (measured on macOS: no code after it runs, process exit code is n), so Linux display init is never reached and there is no SIGSEGV. This is the same pattern already shipping at src/main/index.ts:416 (Windows-only packaged-CLI entry redirect — getPackagedCliEntryArgs returns null off win32) 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 documented orca-serve.service (both variants in the doc) now carries RestartPreventExitStatus=3 so systemd stops instead of retrying a launch that cannot succeed, plus StartLimitIntervalSec=300 / StartLimitBurst=5 so any other repeated startup failure is capped.
  • acquireSingleInstanceLock forwards the second-instance argv, and shouldActivateDesktopForSecondInstance (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 at src/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:

  • Item 3 ("a failed duplicate AppImage launch leaves no FUSE mount behind") should follow from a clean in-band exit instead of a SIGKILL during cgroup teardown, but that is a Linux-runtime consequence and is not verified in this PR.
  • Item 5 (a regression that launches two packaged headless instances against one disposable profile and asserts the second exit, first-instance continuity, and mount count) is not delivered as written. src/main/startup/single-instance-lock-exit.electron.test.ts covers 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.ts runs the lock-loss gate's own app.* statement, lifted verbatim out of src/main/index.ts, under the real Electron binary before ready. A revert to app.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-ready quit() synchronous fails loudly instead of silently making the fix redundant.

Fails against origin/main's source

git checkout c9a37f58d8 -- src/main/index.ts src/main/startup/single-instance-lock.ts docs/reference/headless-linux-server.md, then:

npx vitest run --config config/vitest.config.ts \
  src/main/startup/single-instance-lock-exit.electron.test.ts \
  src/main/startup/single-instance-lock-headless-exit.test.ts \
  src/main/startup/single-instance-lock.test.ts

 ❯ src/main/startup/single-instance-lock-headless-exit.test.ts (5 tests | 4 failed) 9ms
     × exits the lock-losing launch immediately instead of scheduling a graceful quit 5ms
     × keeps a duplicate serve launch from promoting the live server to a desktop window 1ms
     × makes every documented serve unit treat a duplicate owner as terminal 1ms
     × clears the start limit before every scripted start, which a tripped burst would refuse 1ms
 ❯ src/main/startup/single-instance-lock.test.ts (11 tests | 4 failed) 7ms
     × forwards the second launch argv so the owner can decide whether to activate 3ms
     × ignores a duplicate serve launch but still activates for a desktop launch 0ms
     × fails open when no argv is available 0ms
     × stays 3 because the documented systemd unit keys RestartPreventExitStatus off it 1ms
 ❯ src/main/startup/single-instance-lock-exit.electron.test.ts (2 tests | 1 failed) 383ms
     × stops the duplicate launch before any further startup runs, with the already-running code 213ms

 Test Files  3 failed (3)
      Tests  9 failed | 9 passed (18)

The runtime failure is the decisive one — with main's statement in the gate, the doomed launch really does keep running:

AssertionError: expected [ 'LOCK_LOST', …(2) ] to deeply equal [ 'LOCK_LOST' ]

+   "CONTINUED_INTO_STARTUP",
+   "REACHED_TAIL",

CONTINUED_INTO_STARTUP is the bug: on main the lock loser walks past the gate into the rest of src/main/index.ts, which on a display-less Linux host is Ozone/X11 init, Missing X server or $DISPLAY, and SIGSEGV — the signal death systemd counts as a failure and retries.

Passes on this branch

 Test Files  3 passed (3)
      Tests  18 passed (18)
   Duration  503ms

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

Mutation Result
app.exit(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE) → app.exit(0) AssertionError: expected +0 to be 3
app.exit(…) → app.quit() (i.e. origin/main) expected [ 'LOCK_LOST', …(2) ] to deeply equal [ 'LOCK_LOST' ]
shouldActivateDesktopForSecondInstance → return true AssertionError: expected true to be false
happy-dom symbol description → mutationListenersRENAMED expected +0 to be 1 at happy-dom-mutation-observer-retention.test.ts:35

Exit 3 really does reach systemd

RestartPreventExitStatus=3 only 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) → serveOrcaApp spawns the Electron child with --serve (src/cli/runtime/launch.ts:93) → child exits 3 → superviseForegroundServe returns result.code (src/cli/runtime/serve-update-supervisor.ts:82, reached because handoffPath is macOS-bundle-only so readiness is not-expected) → process.exitCode = exitCode (src/cli/handlers/core.ts:135) → app.exit(result.status) (src/main/index.ts:424). systemd's MainPID exits 3, and no other Orca path in the serve process uses exit code 3.

macOS dock/Finder re-activation is unaffected: createMacAppActivationHandler calls requestActivation() with no arguments (src/main/window/macos-app-activation.ts:11), so argv defaults to [] and shouldActivateDesktopForSecondInstance([]) is true.

What is deliberately not in the runtime test

A live two-process lock race. It was tried and CI disproved it: Chromium's Linux ProcessSingleton only answers a second process once the browser IO thread is up, which needs ready, which needs a display. On the display-less CI runner the pre-ready owner is treated as stale and the duplicate takes the lock:

AssertionError: expected [ 'DUPLICATE_WON_LOCK' ] to include 'DUPLICATE_LOST_LOCK'
Error: Timed out waiting for the owner to receive the second-instance notification

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 6154a8d10a in this PR is unrelated to #11935. It adds config/scripts/happy-dom-mutation-observer-retention.ts (+81 lines) and its test (+72 lines), and wires the former into config/vitest.config.ts as a repo-wide setupFiles entry that monkeypatches MutationObserver.prototype.observe/disconnect for every test file in the suite (4,000+ files). happy-dom holds each observer's internal callback in a WeakRef, 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:

npx vitest run --config config/vitest.config.ts config/scripts/happy-dom-mutation-observer-retention.test.ts

 Test Files  1 passed (1)
      Tests  2 passed (2)
   Duration  241ms (transform 27ms, setup 25ms, import 17ms, tests 3ms, environment 114ms)

Caveat, also recorded as a review note below: the second of those two tests does not actually exercise GC — globalThis.gc is undefined under this vitest config (no --expose-gc in execArgv), so the collectGarbage block 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.ts

 RUN  v4.1.5

 Test Files  31 passed (31)
      Tests  283 passed (283)
   Duration  10.37s (transform 9.17s, setup 1.07s, import 9.96s, tests 12.80s, environment 215ms)

The pre-existing src/main/startup/ baseline, with the new runtime file excluded, is 26 passed (26) files / 182 passed (182) tests; the new file adds 3.

That covers the whole src/main/startup/ directory (including serve-desktop-activation-wiring.test.ts, which pins the literal acquireSingleInstanceLock(app, requestDesktopActivation) call text this change deliberately keeps byte-identical, and desktop-startup-ordering.test.ts, which has nine readFileSync source anchors into the edited src/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:

npx oxlint src/main/index.ts src/main/startup/single-instance-lock.ts \
  src/main/startup/single-instance-lock.test.ts \
  src/main/startup/single-instance-lock-headless-exit.test.ts \
  config/scripts/happy-dom-mutation-observer-retention.ts \
  config/scripts/happy-dom-mutation-observer-retention.test.ts config/vitest.config.ts
PLAIN_EXIT=0
npx oxlint --config config/oxlint-code-quality-native-plugins.json <same files> --deny-warnings
QUALITY_EXIT=0

Trade-offs

  • A duplicate launch now exits 3 instead of 0. 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 exit 0 from a second orca serve as "started" will now see a failure code. That is the more correct answer, not a silent success.
  • RestartPreventExitStatus=3 is a real availability trade. A unit started while another owner holds the profile now stays down and reports failed instead of silently retrying. That is deliberate — retrying genuinely cannot help — but Chromium's ProcessSingleton can occasionally report a false "already running" from a stale SingletonLock whose recorded pid was reused, and under this directive that means downtime until someone intervenes. A new troubleshooting bullet in docs/reference/headless-linux-server.md spells out the escape: systemctl reset-failed (required once StartLimitBurst is tripped) plus removing the stale SingletonLock/SingletonSocket, and how to release already-leaked mounts with findmnt + fusermount -uz without touching the live instance's mount.
  • StartLimitBurst=5 / StartLimitIntervalSec=300 also caps benign flapping. With the existing RestartSec=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 needs systemctl reset-failed. The scripted upgrade/rollback paths in the doc were updated to call reset-failed before every systemctl start for exactly this reason.
  • orca serve against a machine already running Orca no longer raises the desktop window. It exits 3 with the existing explanatory stderr line. Correct for a headless-server command, but a visible change for anyone who was incidentally using orca serve as a "show me the app" command; a plain launch is the supported path for that and is unchanged.
  • Deployed units keep their unbounded retry until re-copied. The doc change only helps hosts whose unit files are refreshed. The code fix alone should still stop the mount leak on existing hosts, because a clean non-zero exit lets the AppImage runtime unmount in-band instead of leaving squashfuse to be SIGKILLed during cgroup teardown — but that specific claim is Linux-only and is not verified in this PR (see below).
  • What this PR does not prove. The Linux packaged-AppImage end-to-end scenario (two headless orca serve instances against one profile, asserting exit 3, owner continuity, and an unchanged findmnt -rn -t fuse.orca-linux.AppImage count) 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 precedes Missing 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.

  • macOS: app.exit(3) pre-ready was measured directly on this repo's Electron on macOS — synchronous termination, no subsequent code runs, process exit code 3. Dock/Finder re-activation is untouched: createMacAppActivationHandler (src/main/index.ts:619) is passed requestDesktopActivation and calls it with no arguments (src/main/window/macos-app-activation.ts:11), which defaults argv to [] and therefore still activates. The ORCA_BYPASS_SINGLE_INSTANCE_LOCK=1 diagnostic escape hatch still forces hasSingleInstanceLock = true, so it never reaches the new exit.
  • Linux: the target platform, and the one not exercised here. By construction the lock loser now dies before display init instead of segfaulting. pnpm dev is unaffected — shouldSkipSingleInstanceLock forces hasSingleInstanceLock = true for dev, non-serve runs unless ORCA_E2E_ENFORCE_SINGLE_INSTANCE_LOCK=1.
  • Windows: same synchronous exit; the identical app.exit() pattern already ships on the Windows-only path at src/main/index.ts:416. The second-instance argv on Windows includes the exe path, but argv.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 no path.join concern. Not committing the triage repro's spawnSync('node_modules/.bin/electron') cases avoids a hazard that would have hard-errored for anyone running the unit suite on Windows.
  • No keyboard shortcuts, accelerators, or shortcut labels are involved, and there is no renderer surface, so STYLEGUIDE / main.css tokens do not apply.
  • SSH-remote: strictly improved and never assumes local execution. A headless box reached over SSH is exactly the reported deployment; a duplicate-owner launch there now fails fast with a legible journal line and exit 3 instead of segfaulting into an unbounded restart loop, and the argv-aware activation stops a supervisor-spawned duplicate from pushing that display-less host into openMainWindow().
  • Folder workspaces (non-git): not applicable. All of this runs in main-process startup before 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 -c global-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.

  • Lock loser: previously evaluated the entire remainder of the src/main/index.ts module body plus full Electron platform init before dying. Now it terminates at src/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.
  • Lock winner: one added argv.includes('--serve') — an array scan over a handful of strings — per second-instance event. That event only fires on a duplicate launch, never on any hot path. It also removes work: a duplicate orca serve no longer triggers openMainWindow(), so no BrowserWindow creation, no renderer boot, no IPC storm on a headless server.
  • Successful startup: unchanged. No polling, no timers, no renders, no new IPC channels, no new dependency, no new process, no added latency.
  • Test suite: slightly slower, not faster. The triage repro's Electron-fixture cases were never committed, so nothing is being removed from the suite; and the out-of-scope setupFiles entry now loads one small module and patches two MutationObserver prototype methods in every test file's environment. The observed cost is small — setup 372ms across 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.

  • IPC: no new or modified channels. All ipcMain.handle registrations sit inside the if (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.
  • Command execution: none added in product code. The only new commands are in operator documentation, and the fusermount -uz / umount -l guidance is explicitly scoped to mounts with no live owner.
  • Path handling: no path is constructed, joined, or compared. The argv check is an exact-token match on --serve.
  • Auth surface: unchanged. This runs before initDataPath(), so no token, pairing material, or orca-runtime.json is 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.
  • New exports (SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE, shouldActivateDesktopForSecondInstance) are pure, main-process-only, and take no untrusted input beyond Electron's own second-instance argv, which is already trusted to the same degree as the process's own process.argv.
  • Test-only prototype patch: the happy-dom change mutates MutationObserver.prototype and holds callbacks in a WeakMap keyed by observer. It lives in config/scripts/ and is loaded only by config/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.

  • Review loop count: 1 round(s)
  • Final verdict: CLEAN
  • The final round returned zero blocker/major findings from both lenses.

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

  1. 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.gc is undefined under this vitest config (config/vitest.config.ts sets execArgv: ['--no-experimental-webstorage'], with no --expose-gc), so the collectGarbage block 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.
  2. config/scripts/happy-dom-mutation-observer-retention.ts — commit 6154a8d10a (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 into config/vitest.config.ts as a repo-wide setupFiles entry that monkeypatches MutationObserver.prototype.observe/disconnect for 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.)
  3. 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-ready app.exit(n) terminating before the rest of startup runs) had no automated gate. src/main/startup/single-instance-lock-exit.electron.test.ts now gates it against the real Electron binary, resolving the electron path through createRequire(import.meta.url)('electron') rather than the extension-less node_modules/.bin/electron shim, 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.
  4. 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-wide setupFiles entry patching MutationObserver.prototype for 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.
  5. docs/reference/headless-linux-server.md — StartLimitIntervalSec=300 + StartLimitBurst=5 combined with the existing RestartSec=5 gives 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 🐋

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 564a441b-0761-4ae4-b015-8732b3006a07

📥 Commits

Reviewing files that changed from the base of the PR and between 17e6c0d0932da5a587b2346ee6e94ab66105b243 and 40eed26.

📒 Files selected for processing (4)
  • docs/reference/headless-linux-server.md
  • src/main/index.ts
  • src/main/startup/single-instance-lock-exit.electron.test.ts
  • src/main/startup/single-instance-lock-headless-exit.test.ts
📝 Walkthrough

Walkthrough

Single-instance handling now forwards second-launch arguments and suppresses desktop activation for duplicate orca serve launches. Lock-loss handling exits immediately with status 3. Systemd service examples now limit restart attempts and prevent restarts after status 3, while managed Xvfb remains restartable. Documentation adds troubleshooting guidance for profile locks, stale Chromium locks, restart limits, and orphaned AppImage mounts. Tests cover these behaviors and documented service settings.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes preventing duplicate headless launches from crash-looping and exhausting AppImage FUSE mounts.
Description check ✅ Passed The description thoroughly covers the change, testing, risks, security, cross-platform impact, trade-offs, and known verification limits.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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: Pro Plus

Run ID: 9832e5ed-05ff-4971-9290-1b9f4f0734cb

📥 Commits

Reviewing files that changed from the base of the PR and between c9a37f5 and 183ad3f.

📒 Files selected for processing (5)
  • docs/reference/headless-linux-server.md
  • src/main/index.ts
  • src/main/startup/single-instance-lock-headless-exit.test.ts
  • src/main/startup/single-instance-lock.test.ts
  • src/main/startup/single-instance-lock.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
config/scripts/happy-dom-mutation-observer-retention.test.ts (1)

9-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Export the listener-reading logic instead of duplicating it in the test.

readListenerCallbacks re-implements readMutationListeners from happy-dom-mutation-observer-retention.ts, including the hardcoded 'mutationListeners' string (Line 11) that also appears as MUTATION_LISTENERS_SYMBOL_DESCRIPTION in 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

📥 Commits

Reviewing files that changed from the base of the PR and between 183ad3f and 6154a8d.

📒 Files selected for processing (5)
  • config/scripts/happy-dom-mutation-observer-retention.test.ts
  • config/scripts/happy-dom-mutation-observer-retention.ts
  • config/vitest.config.ts
  • docs/reference/headless-linux-server.md
  • src/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/startup/single-instance-lock-exit.electron.test.ts (1)

12-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce 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.ts
  • src/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

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

@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Fix proof re-established from scratch

The 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: src/main/startup/single-instance-lock-exit.electron.test.ts (3 tests) reproduces the reported failure with two real Electron processes against one disposable profile — the only configuration the bug exists in, since the crash loop is a property of the loser of a genuine lock race. The duplicate executes the lock-loss gate's own app.* statement, lifted verbatim out of src/main/index.ts, so a revert to app.quit() is what fails the test.

Against origin/main's copy of the changed source (git checkout c9a37f58d8 -- src/main/index.ts src/main/startup/single-instance-lock.ts docs/reference/headless-linux-server.md):

 ❯ src/main/startup/single-instance-lock-headless-exit.test.ts (5 tests | 4 failed) 7ms
 ❯ src/main/startup/single-instance-lock.test.ts (11 tests | 4 failed) 7ms
 ❯ src/main/startup/single-instance-lock-exit.electron.test.ts (3 tests | 2 failed) 700ms
     × exits the duplicate before any further startup runs, leaving the owner untouched 232ms
     × hands the owner a real argv that suppresses desktop activation only for serve 144ms

AssertionError: expected [ 'DUPLICATE_LOST_LOCK', …(1) ] to not include 'DUPLICATE_CONTINUED_INTO_STARTUP'

 Test Files  3 failed (3)
      Tests  10 failed | 9 passed (19)

On this branch: Test Files 3 passed (3) / Tests 18 passed (18), and the runtime file alone passes 5/5 consecutive runs in 766–833 ms.

Neighbouring suites: src/main/startup/ + src/cli/runtime/launch.test.ts + serve-signal-exit-diagnostic.test.ts + runtime-rpc.test.ts + the happy-dom suite → 31 files / 283 tests passed. The pre-existing src/main/startup/ baseline is 26 files / 182 tests; this adds 3.

Also verified while re-checking: exit 3 really does reach systemd

RestartPreventExitStatus=3 only 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) → serveOrcaApp spawns the Electron child with --serve (src/cli/runtime/launch.ts:93) → child exits 3 → superviseForegroundServe returns result.code (src/cli/runtime/serve-update-supervisor.ts:82, reached because handoffPath is macOS-bundle-only so readiness is not-expected) → process.exitCode = exitCode (src/cli/handlers/core.ts:135) → app.exit(result.status) (src/main/index.ts:424). systemd's MainPID exits 3.

macOS dock/Finder re-activation is unaffected: createMacAppActivationHandler calls requestActivation() with no arguments (src/main/window/macos-app-activation.ts:11), so argv defaults to [] and shouldActivateDesktopForSecondInstance([]) is true.

Still not proved

Issue item 3 (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. All verification here ran on macOS; CI will exercise the new runtime test on ubuntu-latest.


On the bundled happy-dom change

6154a8d10a (config/scripts/happy-dom-mutation-observer-retention.ts + its test + a repo-wide setupFiles entry) is unrelated to #11935 and I recommend splitting it into its own PR, landing that first, and rebasing this one on it.

It is a real fix for a real, pre-existing, repo-wide flake — the shard failure it was written for is:

FAIL src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx > releases a latched readiness once the terminal attaches
AssertionError: expected 'unavailable' to be 'ready'

and that file already carries hand-written workarounds for the same cause (// A fixed 9-flip budget flakes when CI load drops MutationObserver). That is exactly why it should not ride along here:

  1. It changes MutationObserver.prototype for all 4,021 test files (423 of which run under happy-dom); this PR changes one startup gate. Different blast radius, different reviewer expertise.
  2. It benefits every open PR. Coupled to this one, it lands only when a startup fix with a genuine availability trade-off (RestartPreventExitStatus=3 keeps a unit down instead of retrying) clears review.
  3. If this PR ever has to be reverted for that trade-off, the revert silently reintroduces the flake repo-wide.
  4. A suite-wide prototype patch is precisely the change you want isolated in git bisect history.

The known weakness also deserves its own review rather than being buried here: the second test in happy-dom-mutation-observer-retention.test.ts never exercises GC, because globalThis.gc is undefined under this vitest config (execArgv: ['--no-experimental-webstorage'], no --expose-gc), so the case degrades to "happy-dom delivers two mutation batches".

CodeRabbit nitpick: export readMutationListeners and reuse it in the test

Declining. The duplicated 'mutationListeners' literal in the test is an independent oracle — the test reads happy-dom's internals directly rather than through the module under test, so expect(callbacks.length).toBe(1) still means something if the module's own lookup breaks. Importing the module's helper would make both sides agree by construction. The two assertions cover different failure modes; keeping them independent is the point.

@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my previous comment: the two-process lock race does not survive CI

My 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.

tests node 24 8/16 and tests node 26 8/16 on de162369a7:

 ❯ src/main/startup/single-instance-lock-exit.electron.test.ts (3 tests | 3 failed) 90477ms
AssertionError: expected [ 'DUPLICATE_WON_LOCK' ] to include 'DUPLICATE_LOST_LOCK'
Error: Timed out waiting for the owner to receive the second-instance notification
Error: Hook timed out in 60000ms.

Cause: Chromium's Linux ProcessSingleton only answers a second process once the browser IO thread is up, which requires ready, which requires a display. On a display-less runner the pre-ready owner looks stale, so the duplicate takes the lock and no second-instance is ever delivered. The race is not stageable there, and it is not worth an xvfb dependency in the unit suite to make it so.

e1de4bf075 keeps the part that is both portable and load-bearing: the lock loser's own app.* statement, lifted verbatim out of src/main/index.ts, executed under the real Electron binary before ready. Lock acquisition and argv forwarding stay covered by single-instance-lock.test.ts. The reasoning is recorded in the test file header so nobody re-attempts the race.

Fail/pass and mutation evidence are in the updated Fix proof section. Summary:

Mutation Result
app.exit(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE) → app.exit(0) expected +0 to be 3
app.exit(…) → app.quit() (i.e. origin/main) expected [ 'LOCK_LOST', …(2) ] to deeply equal [ 'LOCK_LOST' ]
shouldActivateDesktopForSecondInstance → return true expected true to be false
happy-dom symbol description → mutationListenersRENAMED expected +0 to be 1

Against origin/main's source the three suites give Tests 9 failed | 9 passed (18); on this branch Tests 18 passed (18), and the runtime file alone passes five consecutive runs in 428–476 ms.

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 3 → superviseForegroundServe returns result.code → process.exitCode → app.exit(result.status). No other path in the serve process uses exit code 3.

@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

CI is green on e1de4bf075: 41 jobs success, 1 skipped (e2e, conditional). The new runtime test ran and passed on the display-less ubuntu-latest runner on both Node versions, which is the platform the bug was reported on:

tests node 24 8/16:  ✓ src/main/startup/single-instance-lock-exit.electron.test.ts (2 tests) 390ms
                     Test Files  261 passed | 1 skipped (262)
tests node 26 8/16:  ✓ src/main/startup/single-instance-lock-exit.electron.test.ts (2 tests) 774ms
                     Tests  2517 passed | 5 skipped (2522)

So the mechanism claim is no longer macOS-only reasoning: pre-ready app.exit(3) terminating before the rest of startup runs is now verified on Linux by CI itself. What remains unverified is only the packaged-AppImage FUSE mount count on a real Linux host (issue item 3 and the mount half of item 5).

nwparker and others added 7 commits August 3, 2026 23:18
…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]>
@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main now that the unrelated happy-dom test-environment fix has landed on its own as #12438 (merged). git rebase detected that commit as already applied upstream and dropped it, so this PR is now scoped purely to the #11935 startup fix — no config/vitest.config.ts or happy-dom-* changes remain in the diff.

Splitting it was deliberate: this PR carries a real availability trade-off (RestartPreventExitStatus=3 intentionally leaves a unit failed rather than retrying), and if it were ever reverted for that reason, the revert would have silently reintroduced a repo-wide test flake affecting every open PR.

src/main/startup/ after the rebase: Test Files 27 passed (27) · Tests 184 passed (184).

@nwparker
nwparker force-pushed the nwparker/bugbash-11935 branch from e1de4bf to 40eed26 Compare August 4, 2026 06:19
@nwparker
nwparker merged commit d8e5944 into main Aug 4, 2026
42 checks passed
@nwparker
nwparker deleted the nwparker/bugbash-11935 branch August 4, 2026 06:34
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
…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).
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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).
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.

[Bug]: duplicate headless orca serve crash-loop leaks AppImage FUSE mounts until mount_max

1 participant