diff --git a/packages/stim-cli/src/__tests__/hosted-macos-worker.test.ts b/packages/stim-cli/src/__tests__/hosted-macos-worker.test.ts index 34562ba6df..64d7c80ceb 100644 --- a/packages/stim-cli/src/__tests__/hosted-macos-worker.test.ts +++ b/packages/stim-cli/src/__tests__/hosted-macos-worker.test.ts @@ -33,6 +33,7 @@ const native = vi.hoisted(() => ({ pressure: vi.fn<() => string | null>(), identity: vi.fn<(record: unknown) => string>(), stop: vi.fn<(root: string) => Promise>(), + stopApps: vi.fn<(area: string) => Promise>(), })); vi.mock('../exec.ts', () => ({ getExecutor: () => ({ runFile: native.runFile, runFileQuiet: native.quiet, spawn: native.spawn }), @@ -46,7 +47,10 @@ vi.mock('../process-identity.ts', async (original) => ({ ...(await original()), inspectProcessIdentity: (record: unknown) => native.identity(record), })); -vi.mock('../macos/stop.ts', () => ({ stopMacosAppHeld: (root: string) => native.stop(root) })); +vi.mock('../macos/stop.ts', () => ({ + stopMacosAppHeld: (root: string) => native.stop(root), + stopHostedBundleInstances: (area: string) => native.stopApps(area), +})); let root: string; let home: string; @@ -336,6 +340,35 @@ test('stop retains app data and preferences when process shutdown cannot be veri expect(existsSync(join(home, '..', 'blobs'))).toBe(true); }); +test('stop ends copies of the session bundles before deleting them, and keeps them when one will not stop', async () => { + receipt(); + await runHostedMacosApp('install', request, { attempt: 'app' }); + native.stopApps.mockClear(); + native.stopApps.mockRejectedValueOnce(new Error('Copy did not exit')); + expect(await runHostedMacosApp('stop', request)).toMatchObject({ state: 'unknown', notice: 'Copy did not exit' }); + expect(existsSync(join(area, 'App.app'))).toBe(true); + expect(existsSync(join(home, 'app-home'))).toBe(true); + native.stopApps.mockImplementationOnce(() => { + expect(existsSync(join(area, 'App.app'))).toBe(true); + return Promise.resolve(); + }); + expect(await runHostedMacosApp('stop', request)).toMatchObject({ state: 'stopped' }); + expect(native.stopApps).toHaveBeenLastCalledWith(realpathSync(root)); + expect(existsSync(join(area, 'App.app'))).toBe(false); +}); + +test('installing a replacement ends copies of earlier attempts before it launches', async () => { + receipt(); + const launchesWhenStopped: number[] = []; + native.stopApps.mockImplementation(() => { + launchesWhenStopped.push(native.spawn.mock.calls.length); + return Promise.resolve(); + }); + expect(await runHostedMacosApp('install', request, { attempt: 'app' })).toMatchObject({ state: 'installed' }); + expect(launchesWhenStopped).toEqual([0]); + expect(native.spawn).toHaveBeenCalledTimes(1); +}); + test('a preference plist removal failure leaves stop unresolved and app data intact', async () => { receipt(); await runHostedMacosApp('install', request, { attempt: 'app' }); diff --git a/packages/stim-cli/src/__tests__/macos.test.ts b/packages/stim-cli/src/__tests__/macos.test.ts index 1eb46540c8..31dc315aea 100644 --- a/packages/stim-cli/src/__tests__/macos.test.ts +++ b/packages/stim-cli/src/__tests__/macos.test.ts @@ -250,8 +250,8 @@ test('bundle instances are the executables of app bundles directly in the worksp }); describe.skipIf(process.platform !== 'darwin')('unrecorded copies of the owned bundle', () => { - function bundleCopy(script: string): ChildProcess { - const executable = join(macosDir(root), 'Sample.app', 'Contents', 'MacOS', 'Sample'); + function bundleCopy(script: string, directory = macosDir(root)): ChildProcess { + const executable = join(directory, 'Sample.app', 'Contents', 'MacOS', 'Sample'); mkdirSync(join(executable, '..'), { recursive: true }); if (!existsSync(executable)) copyFileSync(process.execPath, executable, constants.COPYFILE_FICLONE); const child = getExecutor().spawn( @@ -309,6 +309,18 @@ describe.skipIf(process.platform !== 'darwin')('unrecorded copies of the owned b expect(workspaceInUse(root)).toEqual([]); }, 20_000); + test('a hosted session stop ends a LaunchServices copy of an earlier attempt and spares other processes', async () => { + const attempts = join(dir, 'session', 'apps'); + const earlier = await started(bundleCopy("process.on('SIGTERM', () => {})", join(attempts, 'earlier'))); + const current = await started(bundleCopy('', join(attempts, 'current'))); + mkdirSync(join(attempts, 'earlier.lock')); + const bystander = await ownedProcess(); + await stopping.stopHostedBundleInstances(realpathSync(join(dir, 'session'))); + expect(inspectProcessIdentity(earlier)).toBe('gone'); + expect(inspectProcessIdentity(current)).toBe('gone'); + expect(inspectProcessIdentity(bystander)).toBe('same'); + }, 20_000); + test('workspace removal stops an unrecorded copy before emptying the workspace', async () => { const copy = await started(bundleCopy('')); writeWorkspaceState(root, { macos: record() }); diff --git a/packages/stim-cli/src/device-host/macos.ts b/packages/stim-cli/src/device-host/macos.ts index 983753418e..47f318e493 100644 --- a/packages/stim-cli/src/device-host/macos.ts +++ b/packages/stim-cli/src/device-host/macos.ts @@ -28,7 +28,7 @@ import { import { getExecutor } from '../exec.ts'; import { readHostMemoryPressure } from '../host-memory.ts'; import { macosProcess, requiredMacosRecord } from '../macos/state.ts'; -import { stopMacosAppHeld } from '../macos/stop.ts'; +import { stopHostedBundleInstances, stopMacosAppHeld } from '../macos/stop.ts'; import { waitForMacosRegistration } from '../macos/registration.ts'; import { spawnEntry } from '../spawn-entry.ts'; import { ensureWorkspaceStorage } from '../workspace/paths.ts'; @@ -128,11 +128,12 @@ export async function runHostedMacosApp( if (device.appSlot !== request.appSlot) throw new Error('The hosted macOS app slot changed.'); assertHostedDeviceLedger(home, `macos-${device.appSlot}`, 'macos'); const runRoot = join(realpathSync(home), 'macos-app'); + const area = realpathSync(join(home, '..')); if (mode === 'stop') { if (requiredMacosRecord(runRoot)) await stopMacosAppHeld(runRoot); + await stopHostedBundleInstances(area); const bundleId = preferenceIdentity(home, device.appSlot); if (bundleId) removePreferences(bundleId); - const area = realpathSync(join(home, '..')); assertInside(area, home); removeAppData(realpathSync(home), join(home, 'app-home')); const apps = join(home, '..', 'apps'); @@ -188,6 +189,7 @@ export async function runHostedMacosApp( } exec.runFile('codesign', ['--force', '--sign', '-', bundle], options); if (requiredMacosRecord(runRoot)) await stopMacosAppHeld(runRoot); + await stopHostedBundleInstances(area); const previousId = preferenceIdentity(home, device.appSlot); if (previousId && previousId !== bundleId) removePreferences(previousId); mkdirSync(runRoot, { recursive: true, mode: 0o700 }); diff --git a/packages/stim-cli/src/guide/macos.ts b/packages/stim-cli/src/guide/macos.ts index 8234ee3133..4c897f3cfa 100644 --- a/packages/stim-cli/src/guide/macos.ts +++ b/packages/stim-cli/src/guide/macos.ts @@ -64,7 +64,10 @@ owned app, including copies opened through LaunchServices (open, agent-device open). stim macos, stim stop, stim worktree remove and stim gc --delete stop all of them: SIGTERM, up to 5 s, then SIGKILL, and success only once each has exited. When an app cannot be verified or does not exit, stop reports -STIM_MACOS_OWNER_UNVERIFIED or a failure, and removal keeps the workspace. +STIM_MACOS_OWNER_UNVERIFIED or a failure, and removal keeps the workspace. For +a hosted session the same rule covers every app bundle the session received, so +stop and a replacement launch also end a copy that LaunchServices started from +an earlier attempt. Local stim macos starts the app in the background without activating it or changing focus: it sets STIM_BACKGROUND_LAUNCH=1 in the app's environment, which Stim Desktop honors, including for reopen events from open -g. An app that diff --git a/packages/stim-cli/src/macos/instances.ts b/packages/stim-cli/src/macos/instances.ts index 90bafb8926..68f2022b2d 100644 --- a/packages/stim-cli/src/macos/instances.ts +++ b/packages/stim-cli/src/macos/instances.ts @@ -1,5 +1,6 @@ -import { existsSync, realpathSync } from 'node:fs'; -import type { MacosProcess } from '@stim-cli/core/state'; +import { existsSync, lstatSync, readdirSync, realpathSync } from 'node:fs'; +import { join } from 'node:path'; +import { hostedAppAttempt, type MacosProcess } from '@stim-cli/core/state'; import { getExecutor } from '../exec.ts'; import { inspectProcessIdentity, processStartMicros, captureProcessToken } from '../process-identity.ts'; import { macosDir } from './state.ts'; @@ -85,10 +86,28 @@ function failedBundleListing(record: MacosProcess, error: unknown): string | nul return open; } +/** The attempt directories under a hosted session's `apps`, each of which holds one `App.app`. */ +export function hostedBundleDirs(area: string): string[] { + const apps = join(area, 'apps'); + if (process.platform !== 'darwin' || !existsSync(apps)) return []; + if (realpathSync(apps) !== apps) throw new Error('Hosted app data resolves outside its private area.'); + return readdirSync(apps) + .filter((attempt) => hostedAppAttempt(attempt)) + .map((attempt) => join(apps, attempt)) + .filter((dir) => lstatSync(dir, { throwIfNoEntry: false })?.isDirectory()); +} + /** Verifies owned bundle instances without blocking on process and executable probes. */ -export async function runningBundleInstancesAsync(root: string, operation?: StimContext): Promise { +export function runningBundleInstancesAsync(root: string, operation?: StimContext): Promise { + return runningInstancesInAsync(bundleDirs(root), operation); +} + +/** Verifies the running copies of app bundles directly inside `dirs`. */ +export async function runningInstancesInAsync( + dirs: readonly string[], + operation?: StimContext, +): Promise { operation?.signal.throwIfAborted(); - const dirs = bundleDirs(root); if (!dirs.length) return []; const listing = await runOperationFile(operation, getExecutor(), 'ps', ['-axww', '-o', 'pid=,comm='], { cwd: operation?.cwd, diff --git a/packages/stim-cli/src/macos/stop.ts b/packages/stim-cli/src/macos/stop.ts index f5dcbfecfd..605a056bdc 100644 --- a/packages/stim-cli/src/macos/stop.ts +++ b/packages/stim-cli/src/macos/stop.ts @@ -4,7 +4,7 @@ import { inspectProcessIdentity, waitForProcessExit } from '../process-identity. import { withWorkspaceProcessLock } from '../engine/workspace-process-lock.ts'; import { workspaceDir } from '../workspace/paths.ts'; import { withWorkspaceStateLockAsync, writeWorkspaceState } from '../workspace/workspace-state.ts'; -import { runningBundleInstancesAsync } from './instances.ts'; +import { hostedBundleDirs, runningBundleInstancesAsync, runningInstancesInAsync } from './instances.ts'; import { macosRuntimeClaim, requiredMacosRecord } from './state.ts'; import { readClaimSet } from '../ownership-claim.ts'; import type { StimContext } from '@stim-cli/core'; @@ -56,6 +56,11 @@ export async function stopBundleInstances(root: string, operation?: StimContext) return instances.length > 0; } +/** Stops every running copy of a hosted session's app bundles, including copies LaunchServices started from an earlier attempt. */ +export async function stopHostedBundleInstances(area: string, operation?: StimContext): Promise { + await stopProcesses(await runningInstancesInAsync(hostedBundleDirs(area), operation), undefined, operation); +} + export async function stopMacosAppHeld(root: string, operation?: StimContext): Promise { operation?.signal.throwIfAborted(); const record = requiredMacosRecord(root); diff --git a/website/docs/macos.md b/website/docs/macos.md index 2e290d7b11..daa442348b 100644 --- a/website/docs/macos.md +++ b/website/docs/macos.md @@ -83,7 +83,9 @@ LaunchServices with `open` or `agent-device open`. `stim macos`, `stim stop`, `stim worktree remove` and `stim gc --delete` stop all of them: SIGTERM, up to 5 seconds, then SIGKILL. Stop reports success only after each copy has exited; when one cannot be verified or does not exit, it reports the failure and removal -keeps the workspace. It does not start Metro. Local `stim macos` starts the app in +keeps the workspace. For a hosted session the same rule covers every app bundle the +session received, so stop and a replacement launch also end a copy that LaunchServices +started from an earlier attempt. It does not start Metro. Local `stim macos` starts the app in the background without activating it or changing focus: it sets `STIM_BACKGROUND_LAUNCH=1` in the app's environment, which Stim Desktop honors, including for reopen events from `open -g`. An app that activates itself at launch or on reopen still takes focus. Hosted launches