diff --git a/packages/stim-cli/src/__tests__/guide.test.ts b/packages/stim-cli/src/__tests__/guide.test.ts index 9259cc81d..2a90299ba 100644 --- a/packages/stim-cli/src/__tests__/guide.test.ts +++ b/packages/stim-cli/src/__tests__/guide.test.ts @@ -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 '); expect(agentActions).not.toContain('lsappinfo find'); + expect(body).toContain(' --remote-config --session '); + expect(body).toContain('agent-device disconnect --session '); }); test.each([iosCommand, androidCommand, macosCommand])( diff --git a/packages/stim-cli/src/__tests__/hosted-macos-client.integration.test.ts b/packages/stim-cli/src/__tests__/hosted-macos-client.integration.test.ts index 7af3612ca..247b8af90 100644 --- a/packages/stim-cli/src/__tests__/hosted-macos-client.integration.test.ts +++ b/packages/stim-cli/src/__tests__/hosted-macos-client.integration.test.ts @@ -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); @@ -284,6 +285,7 @@ beforeEach(() => { }); afterEach(() => { + vi.unstubAllEnvs(); vi.restoreAllMocks(); resetExecutor(); rmSync(dir, { recursive: true, force: true }); @@ -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 --remote-config ${config}`, + command: `agent-device --remote-config ${config} --session ${session}`, }); expect(statSync(config).mode & 0o777).toBe(0o600); expect(JSON.parse(readFileSync(config, 'utf8'))).toEqual({ @@ -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); @@ -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, '{}'); @@ -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, }, }); @@ -523,14 +587,14 @@ 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'], ] : []), ], @@ -538,9 +602,9 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and 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'); diff --git a/packages/stim-cli/src/device-host/agent-connection.ts b/packages/stim-cli/src/device-host/agent-connection.ts index e823ae4dc..228d819c1 100644 --- a/packages/stim-cli/src/device-host/agent-connection.ts +++ b/packages/stim-cli/src/device-host/agent-connection.ts @@ -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 { @@ -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'); @@ -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}`); } } diff --git a/packages/stim-cli/src/device-host/hosted-macos.ts b/packages/stim-cli/src/device-host/hosted-macos.ts index ced5c1fa5..4c811b3ee 100644 --- a/packages/stim-cli/src/device-host/hosted-macos.ts +++ b/packages/stim-cli/src/device-host/hosted-macos.ts @@ -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 { @@ -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, @@ -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, }; @@ -216,7 +217,11 @@ export async function stopHostedMacos( signal?: AbortSignal, ): Promise { 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 }); diff --git a/packages/stim-cli/src/guide/macos.ts b/packages/stim-cli/src/guide/macos.ts index 9ea1ca165..58c8e2ccf 100644 --- a/packages/stim-cli/src/guide/macos.ts +++ b/packages/stim-cli/src/guide/macos.ts @@ -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= when stopping, or run +agent-device disconnect --session 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 - --remote-config , using macos.host.bundleId; the lease allows + --remote-config --session , 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 @@ -489,8 +494,9 @@ script such as mini-desktop.sh use these instead: build stim macos --remote launch the same command; the host launches it under the session's own home - shot agent-device screenshot --remote-config - click, key, type agent-device click, press or type --remote-config + shot agent-device screenshot 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) diff --git a/packages/stim-cli/src/hosted-names.ts b/packages/stim-cli/src/hosted-names.ts index d326c165c..02f276b4d 100644 --- a/packages/stim-cli/src/hosted-names.ts +++ b/packages/stim-cli/src/hosted-names.ts @@ -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)}`; } diff --git a/website/docs/macos.md b/website/docs/macos.md index f6a1809b1..c3900ad5e 100644 --- a/website/docs/macos.md +++ b/website/docs/macos.md @@ -187,7 +187,7 @@ stim stop`} Use `macos.remote` for a default. A named Mac is strict and never launches locally. Use `remote-only` to allow any eligible worker and prevent a local launch. Stop the session before switching hosts. If stop cannot reach the host, retry when it is available. -The workspace shows the hosted window in Desktop. The host needs capture and control permissions. To drive it with an agent, configure `hosting.agentDriver` on the host and use the app-scoped command in `macos.host.agent` from the JSON output. The installed guide covers driver setup, build inputs and placement. +The workspace shows the hosted window in Desktop. The host needs capture and control permissions. To drive it with an agent, configure `hosting.agentDriver` on the host and use the app-scoped command in `macos.host.agent` from the JSON output. Keep the command's `--session` so `stim stop` can close that connection. If you chose another name, pass it in `AGENT_DEVICE_SESSION` when stopping, or run `agent-device disconnect --session ` yourself. Use the same agent-device state directory you connected with. The installed guide covers driver setup, build inputs and placement.