Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion packages/stim-cli/src/__tests__/hosted-macos-worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>>(),
stopApps: vi.fn<(area: string) => Promise<void>>(),
}));
vi.mock('../exec.ts', () => ({
getExecutor: () => ({ runFile: native.runFile, runFileQuiet: native.quiet, spawn: native.spawn }),
Expand All @@ -46,7 +47,10 @@ vi.mock('../process-identity.ts', async (original) => ({
...(await original<typeof import('../process-identity.ts')>()),
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;
Expand Down Expand Up @@ -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' });
Expand Down
16 changes: 14 additions & 2 deletions packages/stim-cli/src/__tests__/macos.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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() });
Expand Down
6 changes: 4 additions & 2 deletions packages/stim-cli/src/device-host/macos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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 });
Expand Down
5 changes: 4 additions & 1 deletion packages/stim-cli/src/guide/macos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 23 additions & 4 deletions packages/stim-cli/src/macos/instances.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<MacosProcess[]> {
export function runningBundleInstancesAsync(root: string, operation?: StimContext): Promise<MacosProcess[]> {
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<MacosProcess[]> {
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,
Expand Down
7 changes: 6 additions & 1 deletion packages/stim-cli/src/macos/stop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<void> {
await stopProcesses(await runningInstancesInAsync(hostedBundleDirs(area), operation), undefined, operation);
}

export async function stopMacosAppHeld(root: string, operation?: StimContext): Promise<boolean> {
operation?.signal.throwIfAborted();
const record = requiredMacosRecord(root);
Expand Down
4 changes: 3 additions & 1 deletion website/docs/macos.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading