Skip to content

fix: stop every running copy of a hosted macOS session's app bundles - #4456

Merged
janicduplessis merged 2 commits into
mainfrom
fix/4127-hosted-macos-stop-apps-dir
Oct 26, 2026
Merged

janicduplessis merged 2 commits into
mainfrom
fix/4127-hosted-macos-stop-apps-dir

Conversation

@janicduplessis

Copy link
Copy Markdown
Collaborator

Description

A hosted macOS session keeps each delivered app attempt under <session>/apps/<attempt>/App.app, and every attempt carries the same hosted bundle id (<id>.hosted<slot>). The hosted worker's stop and install call stopMacosAppHeld(<home>/macos-app), which stops the recorded supervisor and app and then scans for running copies, but only under the workspace macos/ directory (macosDir(root)). A copy that LaunchServices started from an earlier attempt's bundle, for example through agent-device open <bundleId>, runs from apps/<attempt>/App.app and is outside that scan. stim stop then reported success, deleted the bundle under the running process, and left the copy running (#4127: pid 70192 under attempt 9ecccf52, ignoring SIGTERM). A later session reusing the slot shares its bundle id, so it can resolve to the stale copy.

Solution

stopHostedBundleInstances(area) stops every identity-verified process whose executable is an app bundle inside one of the session's apps/<attempt> directories, with the same SIGTERM, 5 s, SIGKILL sequence and the same refusal on an unverifiable process (STIM_MACOS_OWNER_UNVERIFIED) as the local path. It reuses the ps and lsof verification of runningBundleInstancesAsync, now parameterized by directories (runningInstancesInAsync). The hosted worker calls it after stopping the recorded app, in stop before preferences and bundles are removed, and in install before the replacement launches. A copy that will not stop leaves the session unknown and the bundles in place.

Not changed: superseded attempt bundles still stay registered with LaunchServices until the session stops. agent-device 0.21.31 attaches to a running app on open instead of launching a duplicate (callstack/agent-device#3707), which covers the replacement case; this PR covers the leftover process.

Test plan

  • pnpm test packages/stim-cli/src/__tests__/macos.test.ts -t "hosted session stop" runs real processes: copies of Node placed as apps/earlier/Sample.app and apps/current/Sample.app, one ignoring SIGTERM, plus a bystander. Both copies end (the stubborn one by SIGKILL) and the bystander survives.
  • hosted-macos-worker.test.ts: stop calls the new function while the bundle still exists, keeps bundles and app data and reports unknown when a copy will not exit; install stops copies before spawning the launch. Both fail with the two calls removed.
  • pnpm run format:check, lint, build, typecheck, knip clean; pnpm test: 437 files, 10954 tests passed, 30 skipped.
  • Not verified on janics-mac-mini: the hosted worker code runs from the mini's installed stim-server, so this change needs a release to reach it. On 2026-10-26 (Stim 1.27.0 client), stim macos --remote-build janics-mac-mini --remote janics-mac-mini, stim stop and a relaunch gave a drivable window (37 AX nodes) each time, so the symptom reported in the later comment on Hosted macOS: stop leaves a LaunchServices copy from an earlier app attempt running #4127 did not reproduce there. The stale-copy path itself was not exercised on the mini.

Refs #4127

@janicduplessis janicduplessis added type: bug Breaks documented or expected behavior priority: P2 Normal; default when unsure area: cli packages/stim-cli, including its README and guide area: server packages/server labels Oct 26, 2026

@janicduplessis janicduplessis left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fresh review of the issue, the diff, the tests and the guide text. hosted-macos-worker.test.ts and macos.test.ts pass in the PR worktree (136 tests).

Checked and fine:

  • area (realpathSync(<home>/..)) is the session's device-host area. hostedAppArea(session, attempt, home) is <home>/../apps/<attempt>, and materializeHostedApp puts App.app there, so hostedBundleDirs(area) covers every attempt dir that holds a bundle.
  • Install: the sweep runs after materializeHostedApp and before the supervisor spawn, so the new attempt is not yet running. Only a copy of the same attempt id (a retry) or of an earlier attempt can match, and all of those belong to this session's private area. Nothing outside the session is in scope.
  • Stop ordering: sweep, then removePreferences, then app-data and bundle removal. An unverifiable or non-exiting process throws before any deletion, runHostedMacosApp reports unknown, and nothing is deleted. That matches the fail-closed rule. Identity comes from bundleRecord/inspectProcessIdentity and the lsof txt check, the same path as the local stop. SIGTERM, 5 s, SIGKILL is reused.
  • Off darwin hostedBundleDirs returns [], and the worker tests mock stop.ts.
  • Tests: the real-process test needs SIGKILL escalation (earlier copy ignores SIGTERM), covers both attempt dirs, and asserts a bystander stays same. The worker tests fail if the install call is removed (launch count) or if stop deletes before sweeping (the App.app exists check at call time). Both name the requirement in #4127. ASCII is clean, and the new comments are doc comments on exported functions.

Actionable (small):

  1. packages/stim-cli/src/macos/instances.ts:90-102 (hostedBundleDirs) takes every entry of <area>/apps and calls realpathSync on it. That directory also holds <attempt>.lock and <attempt>.lock.claims entries, which withDirLock creates and removes in changeHostedApp and offerHostedApp (packages/server/src/hosted-app.ts:54,83). Any of them that disappears between readdirSync and realpathSync throws ENOENT. In stop this matches the existing delete loop, but in install it is a new failure path: an offer or chunk for another attempt arriving during an install makes the install report unknown with an ENOENT notice. A dangling symlink or removed entry has the same effect. Filter the entries with hostedAppAttempt (@stim-cli/core/state, /^[a-zA-Z0-9_-]{1,128}$/), which drops the lock and claims entries. That also removes the need to tolerate odd entries.
  2. Same function: the realpath of an entry is added to the match list without a containment check against area. If an apps/<x> entry were a symlink to another directory, for example /Applications, the sweep would signal verified processes running bundles from there. The existing delete loop calls assertInside(area, directory), but only after the sweep and only in stop. Skip any resolved directory that is not inside area. This needs a prior write into the private area, so it is a defense-in-depth fix, not an exploit path.

Not blocking: the added website paragraph in website/docs/macos.md is spliced into the middle of the line that continues with "It does not start Metro. Local stim macos...". It reads fine but now says "hosted session" before the Metro sentence. Moving it after the Metro sentence would be cleaner.

Process: this diff stops processes by ownership decision in a hosted session (macos.ts:131-135, 192; stop.ts:59-62; instances.ts:89-102). Once the two items above are fixed and checked again, it needs review: ai-approved plus review: needs-human and a Human review: comment. I have added no labels because there are actionable findings.

@janicduplessis janicduplessis left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fresh re-review of 0de1018 (the "sweep only real attempt directories" commit). No actionable findings. macos.test.ts (the new case) and hosted-macos-worker.test.ts (31 tests) pass in the PR worktree; format:check, lint and knip are clean; build and native process inspection are green, the test jobs were still pending when I looked.

Containment fix, checked:

  • area is realpathSync(join(home, '..')) (device-host/macos.ts:131), computed once before the stop/install branch, so both call sites (stop at 134, install at 192) receive a realpath. materializeHostedApp builds the bundle at join(home, '..', 'apps', attempt), the same lexical parent, so the bundle is under <area>/apps/<attempt>.
  • hostedBundleDirs (macos/instances.ts:90-98) requires apps to be a non-symlink (realpathSync(apps) === apps, valid because area is already a realpath), keeps only names that pass hostedAppAttempt (this drops <attempt>.lock and .lock.claims), and keeps only entries whose lstat is a directory (a symlink is not). It no longer calls realpathSync on entries, so a symlinked attempt cannot widen the match list. throwIfNoEntry: false covers an entry removed between readdirSync and lstat, so the earlier ENOENT concern in install is gone.
  • The match itself is a second guard: runningInstancesInAsync requires both the ps path and an lsof -d txt path to be under <area>/apps/<attempt>/X.app/Contents/MacOS/Y. I ran a probe against the PR code: a bundle copy running from a directory outside the area, with apps/link symlinked to it, gives hostedBundleDirs = []; a copy launched through the symlink path is not matched even if apps/link is passed as a dir (lsof reports the real path); only passing the realpath of the symlink target matches it. So the one regression that would reopen the hole is putting realpathSync back on entries.
  • Install: the only new throw is apps being a symlink, which fails closed as unknown before any launch (stop does the same before deleting, and the existing assertInside would refuse that layout anyway). A lock entry or removed entry can no longer fail an install.
  • Stop/install ordering, the identity check (bundleRecord, inspectProcessIdentity) and the SIGTERM, 5 s, SIGKILL path are the existing ones, reused unchanged. Off darwin it returns [].

Tests (non-blocking, both optional):

  1. A dedicated symlink test is not required for safety, since the lstat filter and the lsof real-path check each independently keep the outside process out. It is cheap and is the only test that would catch the realpathSync regression above: in macos.test.ts make apps/linked a symlink to a directory holding a running Sample.app copy started from its real path, call stopHostedBundleInstances, and expect that copy to be same afterwards. It fails against the previous commit (I confirmed the realpath variant matches that pid in the probe).
  2. mkdirSync(join(attempts, 'earlier.lock')) in the new test cannot fail: an empty directory in the list matches nothing, so removing the hostedAppAttempt filter would not change the result. Either drop the line or make it carry a bundle copy that must survive, which would then exercise the filter.

Docs nit (carried from the first review, not blocking): in website/docs/macos.md the hosted paragraph is still spliced before "It does not start Metro", so that sentence now reads as if it were about hosted sessions.

CLAUDE.md rules: ASCII source, doc comments only on exported functions, guide and website updated for the user-facing behavior, tests assert observable process results with real processes at the macOS seam. This stops processes by ownership decision, so it gets review: needs-human for a post-merge look.

@janicduplessis janicduplessis added review: ai-approved A fresh AI review found nothing left to fix review: needs-human Holds merge until a maintainer reviews the lines named in the Human review: comment labels Oct 26, 2026
@janicduplessis

Copy link
Copy Markdown
Collaborator Author

Human review: process stopping and ownership decisions in this PR, for a post-merge check.

  • packages/stim-cli/src/device-host/macos.ts:131-134 and :192 (the realpath'd session area and the two sweep call sites in stop and install)
  • packages/stim-cli/src/macos/stop.ts:59-62 (stopHostedBundleInstances)
  • packages/stim-cli/src/macos/instances.ts:89-98 (hostedBundleDirs: real attempt directories only, apps must not be a symlink) and :105-139 (runningInstancesInAsync: ps path plus lsof real-path check before any signal)

@janicduplessis
janicduplessis added this pull request to the merge queue Oct 26, 2026
Merged via the queue into main with commit 0d5153f Oct 26, 2026
32 of 37 checks passed
@janicduplessis
janicduplessis deleted the fix/4127-hosted-macos-stop-apps-dir branch October 26, 2026 05:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli packages/stim-cli, including its README and guide area: server packages/server priority: P2 Normal; default when unsure review: ai-approved A fresh AI review found nothing left to fix review: needs-human Holds merge until a maintainer reviews the lines named in the Human review: comment type: bug Breaks documented or expected behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant