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
2 changes: 2 additions & 0 deletions packages/stim-cli/src/__tests__/guide.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,8 @@ test('the macos guide covers the declared command flags and project settings', (
const agentActions = body.slice(body.indexOf('AGENT ACTIONS'));
expect(agentActions).toContain('agent-device open <bundleId>');
expect(agentActions).not.toContain('lsappinfo find');
expect(body).toContain('<bundleId> --remote-config <path> --session <name>');
expect(body).toContain('agent-device disconnect --session <your-name>');
});

test.each([iosCommand, androidCommand, macosCommand])(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ function credentials(state: 'approved' | 'pending' = 'approved', serverKey = FAK
}

beforeEach(() => {
vi.stubEnv('AGENT_DEVICE_SESSION', undefined);
dir = realpathSync(mkdtempSync(join(tmpdir(), 'stim-hosted-macos-')));
process.env.STIM_HOME = join(dir, 'home');
mkdirSync(process.env.STIM_HOME);
Expand Down Expand Up @@ -284,6 +285,7 @@ beforeEach(() => {
});

afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
resetExecutor();
rmSync(dir, { recursive: true, force: true });
Expand Down Expand Up @@ -417,10 +419,11 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and
expect(record?.host).toMatchObject({ machine: 'mini', appSlot: 3, bundleId: 'dev.fixture.app.hosted3' });
expect(macosAppState(readMacosRecord(root))?.state).toBe('running');
const config = agentRemoteConfig(root);
const session = `stim-default-macos-${sha256(Buffer.from(root)).slice(0, 8)}`;
expect(record?.host?.agent).toEqual({
driver: 'agent-device',
remoteConfig: config,
command: `agent-device <command> --remote-config ${config}`,
command: `agent-device <command> --remote-config ${config} --session ${session}`,
});
expect(statSync(config).mode & 0o777).toBe(0o600);
expect(JSON.parse(readFileSync(config, 'utf8'))).toEqual({
Expand Down Expand Up @@ -452,14 +455,17 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and
expect(existsSync(config)).toBe(true);
expect(host.methods).not.toContain('device-host.stop');
calls.push(commandArgs);
return JSON.stringify({ success: true, data: { connected: true, session: 'default', remoteConfig: config } });
if (commandArgs[0] === 'connection' && !commandArgs.includes('--session')) {
throw new Error('A leased remote connection needs its session named');
}
return JSON.stringify({ success: true, data: { connected: true, session, remoteConfig: config } });
},
});
await stopMacosApp(root);
expect(calls).toEqual([
['connection', 'status', '--json'],
['close', '--remote-config', config, '--session', 'default', '--json'],
['disconnect', '--session', 'default', '--json'],
['connection', 'status', '--session', session, '--json'],
['close', '--remote-config', config, '--session', session, '--json'],
['disconnect', '--session', session, '--json'],
]);
expect(host.methods).toContain('device-host.stop');
expect(existsSync(config)).toBe(false);
Expand All @@ -477,12 +483,70 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and
'canonical config',
'missing config',
];
test.each(['custom', 'wrong config', 'wrong session', 'same name'])(
'stop checks an explicit session without selecting another workspace: %s',
async (scenario) => {
host.grant = GRANT;
await runMacos(testContext(), root, () => {}, 'mini');
const config = agentRemoteConfig(root);
const standard = `stim-default-macos-${sha256(Buffer.from(root)).slice(0, 8)}`;
const session = scenario === 'same name' ? standard : "--agent's desktop ";
const flags = session === standard ? ['--session', standard] : [`--session=${session}`];
const otherConfig = join(dir, 'other-config.json');
writeFileSync(otherConfig, '{}');
vi.stubEnv('AGENT_DEVICE_SESSION', session);
const calls: string[][] = [];
setExecutor({
...getExecutor(),
findExecutable: () => '/fake/agent-device',
runFile: (_file: string, args: string[]) => {
calls.push(args);
const name = args.find((arg) => arg.startsWith('--session='))?.slice('--session='.length) ?? standard;
if (args[0] === 'disconnect' && scenario === 'custom')
throw new Error('should not leak secret-from-agent-device');
return JSON.stringify({
success: true,
data: {
connected: name === session,
session: scenario === 'wrong session' ? standard : name,
remoteConfig: scenario === 'wrong config' ? otherConfig : config,
},
});
},
});
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
await stopMacosApp(root);
const owned = scenario === 'custom' || scenario === 'same name';
expect(calls).toEqual([
['connection', 'status', '--session', standard, '--json'],
...(session === standard ? [] : [['connection', 'status', ...flags, '--json']]),
...(owned
? [
['close', '--remote-config', config, ...flags, '--json'],
['disconnect', ...flags, '--json'],
]
: []),
]);
const output = stderr.mock.calls.map(([line]) => line).join('');
expect(output).toMatch(
scenario === 'custom'
? "agent-device disconnect --session='--agent'\\''s desktop '"
: owned
? `closed agent-device connection for ${standard}`
: /^$/,
);
expect(output).not.toContain('secret-from-agent-device');
expect(host.methods).toContain('device-host.stop');
},
);

test.each(hostedAgentConnectionCleanupScenarios)(
'stop cleans up only its own agent connection, best effort: %s',
async (scenario) => {
host.grant = GRANT;
await runMacos(testContext(), root, () => {}, 'mini');
const config = agentRemoteConfig(root);
const session = `stim-default-macos-${sha256(Buffer.from(root)).slice(0, 8)}`;
const otherConfig = join(dir, 'other-config.json');
if (scenario === 'canonical config') symlinkSync(config, otherConfig);
else writeFileSync(otherConfig, '{}');
Expand Down Expand Up @@ -513,7 +577,7 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and
success: true,
data: {
connected: scenario !== 'disconnected',
session: 'named-session',
session,
remoteConfig: ['different config', 'canonical config'].includes(scenario) ? otherConfig : config,
},
});
Expand All @@ -523,24 +587,24 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and
try {
await stopMacosApp(root);
expect(calls).toEqual(
scenario === 'unavailable'
scenario === 'unavailable' || scenario === 'missing config'
? []
: [
['connection', 'status', '--json'],
['connection', 'status', '--session', session, '--json'],
...(cleansUp
? [
['close', '--remote-config', config, '--session', 'named-session', '--json'],
['disconnect', '--session', 'named-session', '--json'],
['close', '--remote-config', config, '--session', session, '--json'],
['disconnect', '--session', session, '--json'],
]
: []),
],
);
expect(stderr).toHaveBeenCalledTimes(cleansUp ? 1 : 0);
expect(stderr.mock.calls.map(([line]) => line).join('')).toMatch(
closeFails
? /could not clean up agent-device connection for named-session: agent-device close failed/
? new RegExp(`agent-device disconnect --session '${session}'`)
: cleansUp
? /closed agent-device connection for named-session/
? new RegExp(`closed agent-device connection for ${session}`)
: /^$/,
);
expect(host.methods).toContain('device-host.stop');
Expand Down
78 changes: 40 additions & 38 deletions packages/stim-cli/src/device-host/agent-connection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ambientWrite } from '@stim-cli/core';
import { isJsonObject, parseNdjsonLine } from '@stim-cli/core/state';
import { realpathSync } from 'node:fs';
import { phaseLine } from '../command-output.ts';
import { phaseLine, quotedPath } from '../command-output.ts';
import { getExecutor } from '../exec.ts';

function canonical(path: string): string | null {
Expand All @@ -13,14 +13,16 @@ function canonical(path: string): string | null {
}

function report(message: string): void {
ambientWrite('stderr', `${phaseLine('device', message.replace(/\s+/g, ' '))}\n`);
ambientWrite('stderr', `${phaseLine('device', message)}\n`);
}

/** Closes the saved agent-device connection `session` (agent-device's `default` when omitted) if it uses `remoteConfig`. */
export function closeAgentConnection(remoteConfig: string, session?: string): void {
/** Closes each named agent-device connection that uses `remoteConfig`. */
export function closeAgentConnection(remoteConfig: string, standard: string, explicit?: string): void {
const exec = getExecutor();
if (!exec.findExecutable('agent-device')) return;
const config = canonical(remoteConfig);
if (config === null) return;
const deadline = Date.now() + 30_000;
const sessionArgs = session === undefined ? [] : ['--session', session];
const run = (args: string[]) => {
const remaining = deadline - Date.now();
if (remaining <= 0) throw new Error('agent-device cleanup timed out');
Expand All @@ -33,39 +35,39 @@ export function closeAgentConnection(remoteConfig: string, session?: string): vo
if (result?.success !== true) throw new Error('agent-device did not confirm the command');
return result.data;
};
try {
if (!exec.findExecutable('agent-device')) return;
const status = run(['connection', 'status', ...sessionArgs]);
if (status?.connected !== true || typeof status.session !== 'string' || typeof status.remoteConfig !== 'string')
return;
const config = canonical(remoteConfig);
if (config === null || canonical(status.remoteConfig) !== config) return;
const failures: string[] = [];
for (const args of [
['close', '--remote-config', remoteConfig, '--session', status.session],
['disconnect', '--session', status.session],
]) {
try {
run(args);
} catch (error) {
const reply =
args[0] === 'close' &&
isJsonObject(error) &&
typeof error.status === 'number' &&
error.status !== 0 &&
error.signal === null
? parseNdjsonLine(error.stdout)
: null;
if (reply?.success === false && isJsonObject(reply.error) && reply.error.code === 'SESSION_NOT_FOUND') continue;
failures.push((error as Error).message);
}
const sessions = explicit?.trim() && explicit !== standard ? [standard, explicit] : [standard];
for (const session of sessions) {
const name = session === standard ? ['--session', session] : [`--session=${session}`];
try {
const status = run(['connection', 'status', ...name]);
if (status?.connected !== true || status.session !== session || typeof status.remoteConfig !== 'string') continue;
if (canonical(status.remoteConfig) !== config) continue;
} catch {
report(`could not check agent-device connection for ${quotedPath(session)}`);
continue;
}
let failed = false;
try {
run(['close', '--remote-config', remoteConfig, ...name]);
} catch (error) {
const reply =
isJsonObject(error) && typeof error.status === 'number' && error.status !== 0 && error.signal === null
? parseNdjsonLine(error.stdout)
: null;
failed = !(reply?.success === false && isJsonObject(reply.error) && reply.error.code === 'SESSION_NOT_FOUND');
}
try {
run(['disconnect', ...name]);
} catch {
failed = true;
}
if (failed) {
const option = session === standard ? '--session ' : '--session=';
report(
`could not clean up agent-device connection for ${quotedPath(session)}; run agent-device disconnect ${option}${quotedPath(session)} using the same agent-device state directory`,
);
} else {
report(`closed agent-device connection for ${session}`);
}
report(
failures.length
? `could not clean up agent-device connection for ${status.session}: ${failures.join('; ')}`
: `closed agent-device connection for ${status.session}`,
);
} catch (error) {
report(`could not clean up agent-device connection: ${(error as Error).message}`);
}
}
17 changes: 11 additions & 6 deletions packages/stim-cli/src/device-host/hosted-macos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { macosDir } from '../macos/state.ts';
import { type BuildHandoff } from '../offload/client.ts';
import { agentAccess, removeAgentAccess } from './hosted-agent.ts';
import { phaseLine } from '../command-output.ts';
import { hostedAgentSessionName } from '../hosted-names.ts';
import { closeAgentConnection } from './agent-connection.ts';
import { pullHostedMacosLogs } from './hosted-logs.ts';
import {
Expand All @@ -34,7 +35,7 @@ import {
} from './hosted-client.ts';
import { cancellableSleep } from '../cancellation.ts';
import { runCancellationSignal } from '../engine/native-run.ts';
import { ambientContext, ambientWrite } from '@stim-cli/core';
import { ambientContext, ambientEnv, ambientWrite } from '@stim-cli/core';
export {
connectHost,
probeHostedSession as probeHostedMacos,
Expand Down Expand Up @@ -199,11 +200,11 @@ export async function placeHostedMacos(
if (JSON.stringify(appliedArguments) !== JSON.stringify(requestedArguments))
note(`${host.machine} did not apply macos.arguments. Update stim-server on that host.`);
if (typeof delivery.notice === 'string') note(delivery.notice);
const agent = await agentAccess(agentRemoteConfig(root), host.credential, delivery.agent, note);
if (agent.driver === 'agent-device' && 'command' in agent)
agent.command += ` --session ${hostedAgentSessionName(root, 'macos', 'default')}`;
return {
placement: {
...placement,
agent: await agentAccess(agentRemoteConfig(root), host.credential, delivery.agent, note),
},
placement: { ...placement, agent },
launched: delivery.launched === true ? true : 'unverified',
arguments: appliedArguments,
};
Expand All @@ -216,7 +217,11 @@ export async function stopHostedMacos(
signal?: AbortSignal,
): Promise<void> {
signal?.throwIfAborted();
if (placement.agent.driver === 'agent-device') closeAgentConnection(placement.agent.remoteConfig);
if (placement.agent.driver === 'agent-device') {
const session = ambientEnv().AGENT_DEVICE_SESSION;
const standard = hostedAgentSessionName(root, 'macos', 'default');
closeAgentConnection(placement.agent.remoteConfig, standard, session);
}
let host: HostConnection | undefined;
const cancel = () => host?.connection.close();
signal?.addEventListener('abort', cancel, { once: true });
Expand Down
28 changes: 17 additions & 11 deletions packages/stim-cli/src/guide/macos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,16 +459,21 @@ While a placement is recorded, gc treats the workspace as in use. agent says
how a coding agent drives the app: { driver: "none", setting:
"hosting.agentDriver" } until the hosting Mac's owner sets that setting there,
or { driver: "agent-device", remoteConfig, command }. remoteConfig is a mode
0600 file in the workspace directory that holds the credential; run the command
it names and never print the file. stop, worktree remove and gc first run
agent-device close and disconnect for the connection that agent-device reports
as connected to that remote config (the default or active session), then delete
the file, so the next hosted workspace needs no manual disconnect. Any other
connection, including one under another session name, stays untouched, and a
failure or a missing agent-device is reported without blocking the stop. When
the hosted session ends, stim-server removes its agent-device session
0600 file in the workspace directory that holds the credential. Use the
command Stim prints with its workspace-specific --session and --remote-config.
Never print the config file. stop, worktree remove and gc check the printed
session name and any AGENT_DEVICE_SESSION in their environment. They close
and disconnect only names that agent-device reports using this remote config.
Use the same agent-device state directory you used to connect. If you used
another name, including default from older Stim versions, set
AGENT_DEVICE_SESSION=<your-name> when stopping, or run
agent-device disconnect --session <your-name> yourself. Stim deletes the config
file when the host confirms stop or revocation. A local cleanup error does not
block the hosted stop.
When the hosted session ends, stim-server removes its agent-device session
directories under its own state directory. Start with agent-device open
<bundleId> --remote-config <path>, using macos.host.bundleId; the lease allows
<bundleId> --remote-config <path> --session <name>, using macos.host.bundleId
and the name in the reported command. The lease allows
open, close, snapshot, wait, find, get, is, click, fill, press, type, focus,
scroll, screenshot and batch on that app only. The agent-device on this Mac must
know the macos-app lease backend. A request outside that command list, or a
Expand All @@ -489,8 +494,9 @@ script such as mini-desktop.sh use these instead:
build stim macos --remote <mac>
launch the same command; the host launches it under the
session's own home
shot <out.png> agent-device screenshot --remote-config <path>
click, key, type agent-device click, press or type --remote-config <path>
shot <out.png> agent-device screenshot <out.png> with the reported
--remote-config and --session
click, key, type agent-device click, press or type with the same flags
rclick unavailable: secondary click is not supported
quit stim stop (verified stop; the host frees the slot
and removes the app's defaults)
Expand Down
6 changes: 3 additions & 3 deletions packages/stim-cli/src/hosted-names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { workspaceId } from '@stim-cli/core';
import type { HostedAgentAccess } from '@stim-cli/core/state';

/**
* The agent-device session `stim agent-device` uses for a hosted device when the agent names none. agent-device keeps
* one saved remote connection per name for the whole machine, so the name carries the workspace id.
* The default agent-device session for a hosted device or app. agent-device keeps one saved remote connection per
* name for the whole machine, so the name carries the workspace id.
*/
export function hostedAgentSessionName(root: string, platform: 'ios' | 'android', slot: string): string {
export function hostedAgentSessionName(root: string, platform: 'ios' | 'android' | 'macos', slot: string): string {
return `stim-${slot}-${platform}-${workspaceId(root).slice(0, 8)}`;
}

Expand Down
Loading
Loading