Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
ef409da
feat(close): stop a virtual device the session's own open booted
thymikee Nov 13, 2026
defd523
refactor(session): record the open boot through a named store transition
thymikee Nov 13, 2026
1618384
docs(close): describe the boot-owning stop as the default
thymikee Nov 14, 2026
f085091
docs(help): keep the close boot rule inside the compact workflow card
thymikee Nov 14, 2026
2b5d105
test(skills): track the plain-close finish line in the skill contracts
thymikee Nov 14, 2026
f686dda
fix(close): resolve the denied implicit stop before finalizing
thymikee Nov 14, 2026
5ded0a5
refactor(policy): keep the capability predicate inside its module
thymikee Nov 14, 2026
8f47cfd
fix(lifecycle): bind close boot ownership to the prepared device
thymikee Nov 14, 2026
8dd819b
chore(gates): retain scoped close guidance and declare atomic device …
thymikee Nov 14, 2026
6a94ad9
docs(lifecycle): keep close guidance within context budgets
thymikee Nov 14, 2026
978c30b
fix(close): bind shutdown policy and clarify provider shutdown
thymikee Nov 14, 2026
876ad43
test(close): cover policy input at lifecycle owner
thymikee Nov 14, 2026
8a4368a
docs(close): distinguish implicit and provider shutdown
thymikee Nov 14, 2026
51c0146
fix(close): preserve suite warnings and current session refs
thymikee Nov 14, 2026
20c2d71
docs(close): name open as the boot owner in help
thymikee Nov 15, 2026
ae5780c
fix(close): require current claim for implicit shutdown
thymikee Nov 15, 2026
6eeb91b
fix(replay): preserve warnings from successful native actions
thymikee Nov 15, 2026
fc84771
docs(close): clarify ownership and shutdown results
thymikee Nov 15, 2026
d59576d
test(close): give replay cleanup its owned device claim
thymikee Nov 15, 2026
93b40d7
fix(replay): load warning reader when actions execute
thymikee Nov 15, 2026
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
7 changes: 7 additions & 0 deletions .changeset/close-stops-its-own-boot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'agent-device': minor
---

Plain `close` now stops the local simulator or emulator that its own session `open` booted, so a session leaves the device as it found it. A device that was already running when the session opened keeps running, and physical and provider-owned devices are never stopped this way. The stop is reported in `data.shutdown`, the same field `close --shutdown` reports.

This is a default change. `close --shutdown` keeps its meaning and still stops a device the session did not boot. A daemon policy that denies `device-shutdown` blocks both stops: there, `close --shutdown` fails with `UNAUTHORIZED` and `error.details.reason: DAEMON_POLICY_DENIED`, and a plain `close` succeeds and says in `warnings` that it left the device running. A close that stops a device no longer keeps that simulator's iOS runner warm for the next `open`.
3 changes: 3 additions & 0 deletions docs/adr/0029-daemon-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Status

Accepted (2026-09-29). Amended (2026-11-04): `devices.allow` admits web session devices like app devices (ADR 0037).
Amended (2026-11-14): plain close skips a denied implicit stop of a local simulator or emulator that this session's `open` booted (#4162).

## Rules at a glance

Expand All @@ -21,6 +22,8 @@ Accepted (2026-09-29). Amended (2026-11-04): `devices.allow` admits web session
- **Capability gate:** the device-shutdown host capability refuses shutdown from every command.
The only exception permits Apple readiness to roll back a Simulator boot started and then canceled by the same request.
That Simulator was not previously running.
A plain close of a local simulator or emulator booted by this session's `open` skips the denied implicit stop, succeeds, and reports the kept local device.
A `close --shutdown` the caller asked for fails like any other denied request.
4. Denials use `UNAUTHORIZED`, `details.reason: 'DAEMON_POLICY_DENIED'`, `retriable: false`, a hint, and the policy digest.
They include `rule`: `command`, `device`, `capability`, or `lease`.
They never expose the policy's host path.
Expand Down
4 changes: 3 additions & 1 deletion docs/agents/device-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ A failed command can look like a fast success. Before you record the time of a c

Use one session for each purpose. For more isolation, use a separate `--state-dir` under `/private/tmp`.
Close each session that you opened manually, including failed attempts, with its original session, platform, UDID, and state directory.
If your session booted a local simulator or emulator, add `--shutdown`, unless the user asks to keep it running.
If this session's `open` booted a local simulator or emulator, use plain `close`.
If daemon policy denies `device-shutdown`, inspect the warning.
If a local device was already running, leave it running unless the user requests shutdown.

For `DEVICE_IN_USE`:

Expand Down
10 changes: 10 additions & 0 deletions packages/client/src/__tests__/index-apps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,3 +462,13 @@ test('apps.installFromSource forwards GitHub Actions artifact sources unchanged'
artifactId: 1234567890,
});
});

test.each(['apps', 'sessions'] as const)('%s.close preserves response warnings', async (api) => {
const setup = createClientTransport(async (req) => {
assert.equal(req.command, 'close');
return { ok: true, data: { session: 'qa', warnings: ['Device remains running.', 42] } };
});
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
const result = await client[api].close({ session: 'qa' });
assert.deepEqual(result.warnings, ['Device remains running.']);
});
4 changes: 4 additions & 0 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,12 @@ export function createAgentDeviceClient(
const session = resolveRequestSession(options);
try {
const data = await executeCommand<Record<string, unknown>>('close', options);
const warnings = readResponseWarnings(data);
return {
session,
shutdown: normalizeTargetShutdownResult(data.shutdown),
provider: asOptionalRecord(data.provider),
...(warnings.length > 0 ? { warnings } : {}),
savedScript: readOptionalString(data, 'savedScript'),
identifiers: { session },
};
Expand Down Expand Up @@ -375,10 +377,12 @@ export function createAgentDeviceClient(
close: async (options: AppCloseOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('close', options);
const warnings = readResponseWarnings(data);
return {
session,
closedApp: options.app,
shutdown: normalizeTargetShutdownResult(data.shutdown),
...(warnings.length > 0 ? { warnings } : {}),
savedScript: readOptionalString(data, 'savedScript'),
identifiers: { session },
};
Expand Down
15 changes: 15 additions & 0 deletions packages/command-output/src/output/result-serialization.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import {
serializeCloseResult,
serializeInstallFromSourceResult,
serializeOpenResult,
serializeSessionListEntry,
Expand Down Expand Up @@ -237,3 +238,17 @@ test('serializeInstallFromSourceResult uses install-family package naming', () =
message: 'Installed: Demo',
});
});

test('serializeCloseResult preserves warnings and omits an empty warning channel', () => {
const result = { session: 'qa', identifiers: { session: 'qa' } };
assert.deepEqual(serializeCloseResult({ ...result, warnings: ['Device remains running.'] }), {
session: 'qa',
message: 'Closed: qa',
warnings: ['Device remains running.'],
});
assert.deepEqual(serializeCloseResult({ ...result, warnings: [] }), {
session: 'qa',
message: 'Closed: qa',
});
assert.deepEqual(serializeCloseResult(result), { session: 'qa', message: 'Closed: qa' });
});
1 change: 1 addition & 0 deletions packages/command-output/src/output/result-serialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export function serializeCloseResult(
return {
session: result.session,
...(result.shutdown ? { shutdown: result.shutdown } : {}),
...(result.warnings?.length ? { warnings: result.warnings } : {}),
...('provider' in result && result.provider ? { provider: result.provider } : {}),
...successText(
[
Expand Down
6 changes: 4 additions & 2 deletions packages/command-surface/src/management/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,12 @@ const openCommandMetadata = defineFieldCommandMetadata(

const closeCommandMetadata = defineFieldCommandMetadata(
'close',
'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.',
"Close the named app, or close the active session app when app is omitted. When this session's open booted a local simulator or emulator, close stops it too, leaving the device as the session found it; a device that was already running keeps running. Pass shutdown to explicitly stop a local simulator or emulator regardless of boot ownership. A daemon whose policy denies device-shutdown skips the implicit stop on plain close, which succeeds with a warning that the local device stays running. Explicit close with shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.",
{
app: stringField('Optional app to close.'),
shutdown: booleanField('Shutdown the session/device where supported.'),
shutdown: booleanField(
'Shutdown the session/device where supported, even one this session did not boot.',
),
saveScript: jsonSchemaField<boolean | string>({
oneOf: [booleanSchema(), stringSchema()],
}),
Expand Down
5 changes: 5 additions & 0 deletions packages/contracts/src/client-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ export type AppCloseResult = {
session: string;
closedApp?: string;
shutdown?: TargetShutdownResult;
/**
* #4162: disclosure carried on the close response, e.g. the policy-refused stop of a device
* this session's own open booted. The close still succeeded; the warning says what stayed up.
*/
warnings?: string[];
Comment thread
thymikee marked this conversation as resolved.
Resolved
/**
* #1258: absolute path of the committed session/healed script when this close
* published one (`close --save-script`, or a repair-armed session's finalize)
Expand Down
5 changes: 5 additions & 0 deletions packages/contracts/src/client-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ export type SessionCloseResult = {
session: string;
shutdown?: TargetShutdownResult;
provider?: CloudProviderSessionResult;
/**
* #4162: disclosure carried on the close response, e.g. the policy-refused stop of a device
* this session's own open booted. The close still succeeded; the warning says what stayed up.
*/
warnings?: string[];
/**
* #1258: absolute path of the committed session/healed script when this close
* published one (`close --save-script`, or a repair-armed session's finalize)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import {
export function lifecycleOperationsSpy(
overrides: Partial<ApplicationLifecycleRuntimeOperations> = {},
) {
// The returned handle is always the spy the loader installs, so a suite reads its calls whichever
// way it built the case. A supplied implementation becomes that spy's behaviour.
const finalizeApplicationClose = vi.fn<
ApplicationLifecycleRuntimeOperations['finalizeApplicationClose']
>(async () => ({}));
>(overrides.finalizeApplicationClose ?? (async () => ({})));
const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) =>
Object.freeze({
...(await applicationLifecycleRuntimeFixture(device, signal, shutdownTarget)),
Expand Down
25 changes: 23 additions & 2 deletions packages/daemon/src/core/__tests__/daemon-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,17 @@ function makeHandler(
inventory?: readonly DeviceInfo[];
providerInventory?: readonly DeviceInfo[];
leaseRegistry?: LeaseRegistry;
bootedByOpen?: true;
} = {},
) {
const sessionStore = makeSessionStore('agent-device-daemon-policy-');
sessionStore.publish('default', makeIosSession('default', { appBundleId: 'com.example.app' }));
sessionStore.publish(
'default',
makeIosSession('default', {
appBundleId: 'com.example.app',
bootedByOpen: options.bootedByOpen,
}),
);
const bind = vi.fn(lifecycleDeviceRuntimeGateway.bind);
const inspectFacts = vi.fn(lifecycleDeviceRuntimeGateway.inspectFacts);
const handler = createRequestHandler({
Expand All @@ -81,7 +88,7 @@ function makeHandler(
hostDiagnostics: hostDiagnosticsFixture(),
daemonPolicy,
});
return { handler, bind, inspectFacts };
return { handler, bind, inspectFacts, sessionStore };
}

function request(command: string, extra: Partial<DaemonRequest> = {}): DaemonRequest {
Expand Down Expand Up @@ -491,3 +498,17 @@ test('a policy that allows one web session device admits that session only, neve
expectPolicyDenied(await handler(openWeb(denied)), 'device');
}
});

test('plain close uses the loaded policy dependency and releases a boot-owned session without shutdown', async () => {
const { handler, sessionStore } = makeHandler(
policy({ capabilities: { deny: ['device-shutdown'] } }),
{ bootedByOpen: true },
);
const response = await handler(request('close'));
expect(response).toMatchObject({
ok: true,
data: { warnings: [expect.stringContaining('device-shutdown')] },
});
if (response.ok) expect(response.data?.shutdown).toBeUndefined();
expect(sessionStore.get('default')).toBeUndefined();
});
9 changes: 8 additions & 1 deletion packages/daemon/src/core/daemon-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,18 @@ export function assertDaemonPolicyAdmitsDevice(policy: DaemonPolicy, device: Dev
});
}

export function isDaemonPolicyCapabilityDenied(
policy: DaemonPolicy,
capability: DaemonPolicyCapability,
): boolean {
return policy.deniedCapabilities.has(capability);
}

export function assertDaemonPolicyAllowsCapability(
policy: DaemonPolicy,
capability: DaemonPolicyCapability,
): void {
if (!policy.deniedCapabilities.has(capability)) return;
if (!isDaemonPolicyCapabilityDenied(policy, capability)) return;
throw policyDenied(policy, 'capability', `This daemon's policy denies ${capability}.`, {
capability,
});
Expand Down
8 changes: 8 additions & 0 deletions packages/daemon/src/core/session-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,14 @@ export type SessionState = {
ownerStartTime: string | null;
};
device: DeviceInfo;
/**
* #4162: this session's `open` booted the local simulator or emulator it now holds, so a plain
* `close` stops it and leaves the device as the session found it. Recorded only when device
* selection reports the boot (`selection.bootOccurred`), which never happens for a provider or
* physical target, nor for a device that was already running. The open-state publisher sets it
* through `SessionStore.updateOpenDevice`; changing device identity clears it. Close only reads it.
*/
bootedByOpen?: true;
createdAt: number;
surface?: SessionSurface;
appBundleId?: string;
Expand Down
17 changes: 16 additions & 1 deletion packages/daemon/src/core/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value';
import path from 'node:path';
import fs from 'node:fs';
import { AppError } from '@agent-device/kernel/errors';
import { devicesOverlap } from '@agent-device/kernel/device';
import {
devicesOverlap,
deviceIdentity,
sameDeviceIdentity,
type DeviceInfo,
} from '@agent-device/kernel/device';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import type { SessionRef, SessionRuntimeHints, SessionState } from './session-state.ts';
import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts';
Expand Down Expand Up @@ -409,6 +414,16 @@ export class SessionStore {
session.lastActivityAtMs = atMs;
}

/** Carries boot ownership across reopens of the same device, never onto a replacement. */
updateOpenDevice(ref: SessionRef, device: DeviceInfo, bootOccurred: boolean): void {
const current = this.requireCurrent(ref);
const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device));
this.update(ref, {
device,
bootedByOpen: bootOccurred || (retainsBoot && current.bootedByOpen) ? true : undefined,
});
}

/**
* Marks a session kept after unconfirmed close effects or a relaunch that failed or was canceled
* after dispatch, so daemon idle reap no longer waits on it. A successful reopen clears the mark;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ import {
} from '../../__tests__/support/test-device-runtime-gateway.ts';
// Readiness is package-owned; hold the open at the fixture's platform-neutral readiness gate.
import { awaitFixtureReadiness } from '../../__tests__/support/application-lifecycle-runtime-fixture.ts';
import { parseDaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file';
import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts';
import { readResponseWarnings } from '@agent-device/kernel/success-text';
import { toReplayTestAttemptOutcome } from '@agent-device/replay-port/session-test-outcome';

const mockResolveTargetDevice = vi.mocked(getResolveTargetDeviceMock());
const mockAwaitFixtureReadiness = vi.mocked(awaitFixtureReadiness);
Expand All @@ -60,6 +64,54 @@ beforeEach(() => {
mockAwaitFixtureReadiness.mockResolvedValue(undefined);
});

test.each([false, true])(
'same-session replay close preserves denied-stop warnings (later failure: %s)',
async (laterFailure) => {
const root = mkdtempForTestSync('agent-device-replay-close-policy-');
const replayPath = path.join(root, 'close.ad');
fs.writeFileSync(replayPath, laterFailure ? 'close\napp-switcher\n' : 'close\n');
const sessionStore = makeSessionStore('agent-device-replay-close-policy-');
sessionStore.publish(
'default',
makeIosSession('default', { bootedByOpen: true, appBundleId: 'com.example.app' }),
);
const cleanup = platformResourceCleanupFixture();
const handler = createRequestHandler({
host: createTestHostEnvironment(),
createCommandSurface: testCreateCommandSurface,
logPath: path.join(root, 'daemon.log'),
token: 'test-token',
sessionStore,
leaseRegistry: new LeaseRegistry(),
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
deviceInventoryGateways: createTestDeviceInventoryGateways(),
platformResourceCleanup: cleanup,
daemonPolicy: parseDaemonPolicy(
{ version: 1, capabilities: { deny: ['device-shutdown'] } },
path.join(root, 'policy.json'),
),
trackDownloadableArtifact: () => 'artifact-id',
});
const response = await handler({
token: 'test-token',
session: 'default',
command: 'replay',
positionals: [replayPath],
meta: { cwd: root, requestId: 'replay-close-policy', sessionExplicit: true },
});
expect(response.ok).toBe(!laterFailure);
const warnings = readResponseWarnings(response.ok ? response.data : response.error.details);
expect(warnings).toEqual([
"This session's open booted this device and close would stop it, but this daemon's policy denies device-shutdown. The device is still running.",
]);
expect(toReplayTestAttemptOutcome(response).warnings).toEqual(warnings);
expect(cleanup.retainExecutionHostAfterClose).toHaveBeenCalledWith(
expect.objectContaining({ shutdownRequested: false }),
);
expect(sessionStore.listRefs()).toHaveLength(0);
},
);

test('replay runs active-session actions inside the parent request provider scope', async () => {
const root = mkdtempForTestSync('agent-device-replay-scope-');
const replayPath = path.join(root, 'flow.ad');
Expand Down
8 changes: 7 additions & 1 deletion packages/daemon/src/server/request-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,10 @@ import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-
import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts';
import type { DaemonPlatformServices } from '../core/platform-services.ts';
import type { DaemonProviderCredentials } from '@agent-device/daemon-contracts/provider-credentials';
import { restrictDeviceInventoryToDaemonPolicy } from '../core/daemon-policy.ts';
import {
restrictDeviceInventoryToDaemonPolicy,
isDaemonPolicyCapabilityDenied,
} from '../core/daemon-policy.ts';
import type { DaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file';

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -194,6 +197,8 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn {
daemonPolicy,
} = deps;
const { sessionStore, leaseRegistry } = deps;
const deviceShutdownDenied =
daemonPolicy !== undefined && isDaemonPolicyCapabilityDenied(daemonPolicy, 'device-shutdown');
const deviceInventoryGateways = daemonPolicy
? restrictDeviceInventoryToDaemonPolicy(deps.deviceInventoryGateways, daemonPolicy)
: deps.deviceInventoryGateways;
Expand Down Expand Up @@ -414,6 +419,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn {
androidObservation,
createCommandSurface,
platformResourceCleanup,
deviceShutdownDenied,
bindDevice: lockedScope.bindDevice,
platformServices: lockedScope.platformServices,
inspectFacts: lockedScope.inspectFacts,
Expand Down
Loading
Loading