From 98805a3f53d3324eba0fcda29a3171dc3f02d57e Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Thu, 12 Nov 2026 22:36:10 -0500 Subject: [PATCH 1/3] fix: close the hosted macOS agent-device connection on stop --- packages/stim-cli/src/__tests__/guide.test.ts | 2 ++ .../hosted-macos-client.integration.test.ts | 27 +++++++++++-------- .../src/device-host/agent-connection.ts | 10 +++---- .../stim-cli/src/device-host/hosted-macos.ts | 12 +++++---- packages/stim-cli/src/guide/macos.ts | 26 ++++++++++-------- packages/stim-cli/src/hosted-names.ts | 6 ++--- website/docs/macos.md | 2 +- 7 files changed, 48 insertions(+), 37 deletions(-) diff --git a/packages/stim-cli/src/__tests__/guide.test.ts b/packages/stim-cli/src/__tests__/guide.test.ts index 9259cc81df..2a90299ba0 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 7af3612cac..ee9255ec80 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 @@ -417,10 +417,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 +453,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); @@ -483,6 +487,7 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and 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 +518,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, }, }); @@ -526,11 +531,11 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and scenario === 'unavailable' ? [] : [ - ['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 +543,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(`could not clean up agent-device connection for ${session}: agent-device close failed`) : 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 e823ae4dca..cb795af8fa 100644 --- a/packages/stim-cli/src/device-host/agent-connection.ts +++ b/packages/stim-cli/src/device-host/agent-connection.ts @@ -16,11 +16,10 @@ function report(message: string): void { ambientWrite('stderr', `${phaseLine('device', message.replace(/\s+/g, ' '))}\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 the saved agent-device connection `session` if it uses `remoteConfig`. */ +export function closeAgentConnection(remoteConfig: string, session: string): void { const exec = getExecutor(); 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'); @@ -35,9 +34,8 @@ export function closeAgentConnection(remoteConfig: string, session?: string): vo }; 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 status = run(['connection', 'status', '--session', session]); + if (status?.connected !== true || status.session !== session || typeof status.remoteConfig !== 'string') return; const config = canonical(remoteConfig); if (config === null || canonical(status.remoteConfig) !== config) return; const failures: string[] = []; diff --git a/packages/stim-cli/src/device-host/hosted-macos.ts b/packages/stim-cli/src/device-host/hosted-macos.ts index ced5c1fa5a..e340b36b10 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 { @@ -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,8 @@ 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') + closeAgentConnection(placement.agent.remoteConfig, hostedAgentSessionName(root, 'macos', 'default')); 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 9ea1ca1656..1c47470f3c 100644 --- a/packages/stim-cli/src/guide/macos.ts +++ b/packages/stim-cli/src/guide/macos.ts @@ -459,16 +459,19 @@ 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 close and disconnect +that named session only when agent-device reports the same remote config. They +delete the file once the host confirms stop or revocation. If you used another +session name, including default from older Stim versions, run +agent-device disconnect --session before stim stop. Use the same +agent-device state directory you used to connect. A cleanup error is reported +without blocking 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 +492,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 d326c165ce..02f276b4dd 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 f6a1809b1a..95c0233bcb 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, run `agent-device disconnect --session ` before stopping. The installed guide covers driver setup, build inputs and placement. From 0ebe9903df9268124452b7975e17bebcc5608b77 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Thu, 12 Nov 2026 23:06:19 -0500 Subject: [PATCH 2/3] fix: check an explicitly named hosted macOS connection --- .../hosted-macos-client.integration.test.ts | 62 +++++++++++++++- .../src/device-host/agent-connection.ts | 73 ++++++++++--------- .../stim-cli/src/device-host/hosted-macos.ts | 9 ++- packages/stim-cli/src/guide/macos.ts | 16 ++-- website/docs/macos.md | 2 +- 5 files changed, 113 insertions(+), 49 deletions(-) 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 ee9255ec80..89fa3ae250 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 }); @@ -481,6 +483,62 @@ 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 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[args.indexOf('--session') + 1]; + 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', '--session', session, '--json']]), + ...(owned + ? [ + ['close', '--remote-config', config, '--session', session, '--json'], + ['disconnect', '--session', session, '--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) => { @@ -528,7 +586,7 @@ 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', '--session', session, '--json'], @@ -543,7 +601,7 @@ 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 - ? new RegExp(`could not clean up agent-device connection for ${session}: agent-device close failed`) + ? new RegExp(`agent-device disconnect --session '${session}'`) : cleansUp ? new RegExp(`closed agent-device connection for ${session}`) : /^$/, diff --git a/packages/stim-cli/src/device-host/agent-connection.ts b/packages/stim-cli/src/device-host/agent-connection.ts index cb795af8fa..4f54601e56 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,12 +13,15 @@ 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` 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, ...sessions: 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 run = (args: string[]) => { const remaining = deadline - Date.now(); @@ -32,38 +35,36 @@ export function closeAgentConnection(remoteConfig: string, session: string): voi 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', '--session', session]); - if (status?.connected !== true || status.session !== session || 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); - } + for (const session of new Set(sessions)) { + try { + const status = run(['connection', 'status', '--session', session]); + 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, '--session', session]); + } 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', '--session', session]); + } catch { + failed = true; + } + if (failed) { + report( + `could not clean up agent-device connection for ${quotedPath(session)}; run agent-device disconnect --session ${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 e340b36b10..4a505b4e3e 100644 --- a/packages/stim-cli/src/device-host/hosted-macos.ts +++ b/packages/stim-cli/src/device-host/hosted-macos.ts @@ -35,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, @@ -217,8 +217,11 @@ export async function stopHostedMacos( signal?: AbortSignal, ): Promise { signal?.throwIfAborted(); - if (placement.agent.driver === 'agent-device') - closeAgentConnection(placement.agent.remoteConfig, hostedAgentSessionName(root, 'macos', 'default')); + if (placement.agent.driver === 'agent-device') { + const session = ambientEnv().AGENT_DEVICE_SESSION?.trim(); + const standard = hostedAgentSessionName(root, 'macos', 'default'); + closeAgentConnection(placement.agent.remoteConfig, standard, ...(session ? [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 1c47470f3c..58c8e2ccf6 100644 --- a/packages/stim-cli/src/guide/macos.ts +++ b/packages/stim-cli/src/guide/macos.ts @@ -461,13 +461,15 @@ how a coding agent drives the app: { driver: "none", setting: or { driver: "agent-device", remoteConfig, command }. remoteConfig is a mode 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 close and disconnect -that named session only when agent-device reports the same remote config. They -delete the file once the host confirms stop or revocation. If you used another -session name, including default from older Stim versions, run -agent-device disconnect --session before stim stop. Use the same -agent-device state directory you used to connect. A cleanup error is reported -without blocking the hosted stop. +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 --session , using macos.host.bundleId diff --git a/website/docs/macos.md b/website/docs/macos.md index 95c0233bcb..c3900ad5e7 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. Keep the command's `--session` so `stim stop` can close that connection. If you chose another name, run `agent-device disconnect --session ` before stopping. 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. From c9ab2e562bc3920b3032facf1ec30952450f9dc1 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Thu, 12 Nov 2026 23:17:06 -0500 Subject: [PATCH 3/3] fix: keep literal agent-device session names on stop --- .../hosted-macos-client.integration.test.ts | 13 +++++++------ .../stim-cli/src/device-host/agent-connection.ts | 15 +++++++++------ packages/stim-cli/src/device-host/hosted-macos.ts | 4 ++-- 3 files changed, 18 insertions(+), 14 deletions(-) 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 89fa3ae250..247b8af903 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 @@ -490,7 +490,8 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and 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 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); @@ -500,7 +501,7 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and findExecutable: () => '/fake/agent-device', runFile: (_file: string, args: string[]) => { calls.push(args); - const name = args[args.indexOf('--session') + 1]; + 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({ @@ -518,18 +519,18 @@ describe.skipIf(process.platform !== 'darwin')('stim macos --remote (SwiftPM and const owned = scenario === 'custom' || scenario === 'same name'; expect(calls).toEqual([ ['connection', 'status', '--session', standard, '--json'], - ...(session === standard ? [] : [['connection', 'status', '--session', session, '--json']]), + ...(session === standard ? [] : [['connection', 'status', ...flags, '--json']]), ...(owned ? [ - ['close', '--remote-config', config, '--session', session, '--json'], - ['disconnect', '--session', session, '--json'], + ['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'" + ? "agent-device disconnect --session='--agent'\\''s desktop '" : owned ? `closed agent-device connection for ${standard}` : /^$/, diff --git a/packages/stim-cli/src/device-host/agent-connection.ts b/packages/stim-cli/src/device-host/agent-connection.ts index 4f54601e56..228d819c14 100644 --- a/packages/stim-cli/src/device-host/agent-connection.ts +++ b/packages/stim-cli/src/device-host/agent-connection.ts @@ -17,7 +17,7 @@ function report(message: string): void { } /** Closes each named agent-device connection that uses `remoteConfig`. */ -export function closeAgentConnection(remoteConfig: string, ...sessions: string[]): void { +export function closeAgentConnection(remoteConfig: string, standard: string, explicit?: string): void { const exec = getExecutor(); if (!exec.findExecutable('agent-device')) return; const config = canonical(remoteConfig); @@ -35,9 +35,11 @@ export function closeAgentConnection(remoteConfig: string, ...sessions: string[] if (result?.success !== true) throw new Error('agent-device did not confirm the command'); return result.data; }; - for (const session of new Set(sessions)) { + 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', '--session', session]); + 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 { @@ -46,7 +48,7 @@ export function closeAgentConnection(remoteConfig: string, ...sessions: string[] } let failed = false; try { - run(['close', '--remote-config', remoteConfig, '--session', session]); + run(['close', '--remote-config', remoteConfig, ...name]); } catch (error) { const reply = isJsonObject(error) && typeof error.status === 'number' && error.status !== 0 && error.signal === null @@ -55,13 +57,14 @@ export function closeAgentConnection(remoteConfig: string, ...sessions: string[] failed = !(reply?.success === false && isJsonObject(reply.error) && reply.error.code === 'SESSION_NOT_FOUND'); } try { - run(['disconnect', '--session', session]); + 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 --session ${quotedPath(session)} using the same agent-device state directory`, + `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}`); diff --git a/packages/stim-cli/src/device-host/hosted-macos.ts b/packages/stim-cli/src/device-host/hosted-macos.ts index 4a505b4e3e..4c811b3eec 100644 --- a/packages/stim-cli/src/device-host/hosted-macos.ts +++ b/packages/stim-cli/src/device-host/hosted-macos.ts @@ -218,9 +218,9 @@ export async function stopHostedMacos( ): Promise { signal?.throwIfAborted(); if (placement.agent.driver === 'agent-device') { - const session = ambientEnv().AGENT_DEVICE_SESSION?.trim(); + const session = ambientEnv().AGENT_DEVICE_SESSION; const standard = hostedAgentSessionName(root, 'macos', 'default'); - closeAgentConnection(placement.agent.remoteConfig, standard, ...(session ? [session] : [])); + closeAgentConnection(placement.agent.remoteConfig, standard, session); } let host: HostConnection | undefined; const cancel = () => host?.connection.close();