Repository navigation
fix: stop every running copy of a hosted macOS session's app bundles - #4456
Conversation
janicduplessis
left a comment
There was a problem hiding this comment.
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>, andmaterializeHostedAppputsApp.appthere, sohostedBundleDirs(area)covers every attempt dir that holds a bundle.- Install: the sweep runs after
materializeHostedAppand 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,runHostedMacosAppreportsunknown, and nothing is deleted. That matches the fail-closed rule. Identity comes frombundleRecord/inspectProcessIdentityand thelsoftxt check, the same path as the local stop. SIGTERM, 5 s, SIGKILL is reused. - Off darwin
hostedBundleDirsreturns[], and the worker tests mockstop.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 (theApp.appexists 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):
packages/stim-cli/src/macos/instances.ts:90-102(hostedBundleDirs) takes every entry of<area>/appsand callsrealpathSyncon it. That directory also holds<attempt>.lockand<attempt>.lock.claimsentries, whichwithDirLockcreates and removes inchangeHostedAppandofferHostedApp(packages/server/src/hosted-app.ts:54,83). Any of them that disappears betweenreaddirSyncandrealpathSyncthrows 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 reportunknownwith an ENOENT notice. A dangling symlink or removed entry has the same effect. Filter the entries withhostedAppAttempt(@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.- Same function: the realpath of an entry is added to the match list without a containment check against
area. If anapps/<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 callsassertInside(area, directory), but only after the sweep and only in stop. Skip any resolved directory that is not insidearea. 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
left a comment
There was a problem hiding this comment.
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:
areaisrealpathSync(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.materializeHostedAppbuilds the bundle atjoin(home, '..', 'apps', attempt), the same lexical parent, so the bundle is under<area>/apps/<attempt>.hostedBundleDirs(macos/instances.ts:90-98) requiresappsto be a non-symlink (realpathSync(apps) === apps, valid becauseareais already a realpath), keeps only names that passhostedAppAttempt(this drops<attempt>.lockand.lock.claims), and keeps only entries whoselstatis a directory (a symlink is not). It no longer callsrealpathSyncon entries, so a symlinked attempt cannot widen the match list.throwIfNoEntry: falsecovers an entry removed betweenreaddirSyncandlstat, so the earlier ENOENT concern in install is gone.- The match itself is a second guard:
runningInstancesInAsyncrequires both thepspath and anlsof -d txtpath 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, withapps/linksymlinked to it, giveshostedBundleDirs=[]; a copy launched through the symlink path is not matched even ifapps/linkis 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 puttingrealpathSyncback on entries. - Install: the only new throw is
appsbeing a symlink, which fails closed asunknownbefore any launch (stop does the same before deleting, and the existingassertInsidewould 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):
- 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
realpathSyncregression above: inmacos.test.tsmakeapps/linkeda symlink to a directory holding a runningSample.appcopy started from its real path, callstopHostedBundleInstances, and expect that copy to besameafterwards. It fails against the previous commit (I confirmed the realpath variant matches that pid in the probe). mkdirSync(join(attempts, 'earlier.lock'))in the new test cannot fail: an empty directory in the list matches nothing, so removing thehostedAppAttemptfilter 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.
|
Human review: process stopping and ownership decisions in this PR, for a post-merge check.
|
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 callstopMacosAppHeld(<home>/macos-app), which stops the recorded supervisor and app and then scans for running copies, but only under the workspacemacos/directory (macosDir(root)). A copy that LaunchServices started from an earlier attempt's bundle, for example throughagent-device open <bundleId>, runs fromapps/<attempt>/App.appand is outside that scan.stim stopthen reported success, deleted the bundle under the running process, and left the copy running (#4127: pid 70192 under attempt9ecccf52, 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'sapps/<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 thepsandlsofverification ofrunningBundleInstancesAsync, now parameterized by directories (runningInstancesInAsync). The hosted worker calls it after stopping the recorded app, instopbefore preferences and bundles are removed, and ininstallbefore the replacement launches. A copy that will not stop leaves the sessionunknownand 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
openinstead 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 asapps/earlier/Sample.appandapps/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 reportsunknownwhen 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,knipclean;pnpm test: 437 files, 10954 tests passed, 30 skipped.stim macos --remote-build janics-mac-mini --remote janics-mac-mini,stim stopand 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