Skip to content
Merged
5 changes: 5 additions & 0 deletions .changeset/device-selector-session-claim-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'agent-device': patch
---

Refuse `require-owner` commands run under a session this daemon does not hold with `DEVICE_IN_USE` when another session of this daemon holds the device (without reading the host-global claim store). Enforce the in-memory holder guard in the request scope's device access before inspecting device facts or binding, covering every device-touching `require-owner` command. Give `test` the suite-orchestrator claim policy `none` so suite cleanup and recording can act through child case sessions without triggering false device contention. Preserve `NO_ACTIVE_SESSION` for sessionless requests without a device selector.
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ test('every command that deviates from require-owner is a reviewed, diffable set
'session',
'session_list',
'session_save_script',
'test',
'web',
],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ export const SESSION_OPERATION_COMMAND_DESCRIPTORS = [
},
{
name: 'test',
deviceClaimPolicy: 'require-owner',
deviceClaimPolicy: 'none',
Comment thread
twotnguyen marked this conversation as resolved.
Resolved
...(ownerFilesEnabled
? { ownerFiles: ['packages/command-surface/src/replay/index.ts'] as const }
: {}),
Expand Down
4 changes: 3 additions & 1 deletion packages/command-registry/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ export type CommandTimeoutPolicy = {
* - `observe` — device inventory/ownership projection; may report a
* claim, never mutates one.
* - `require-owner` — session-bound work; trusts the invariant `open`
* established and does NO claim-store I/O.
* established and does NO claim-store I/O. Refuses a
* foreign in-memory session holder when its own session
* is unheld.
* - `transient-exclusive` — sessionless device mutation; acquires a
* command-scoped claim before device operations reach
* the handler, refuses a foreign claim, and releases
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -736,3 +736,62 @@ test('a later request does not inherit a prior request device pin', async () =>
);
});
});

test('require-owner commands with device selector are refused when another session holds device (#4228)', async () => {
const device = { ...makeIosDevice('SIM-HELD-BY-FIRST'), appleOs: 'ios' as const };
process.env.AGENT_DEVICE_CLAIMS_DIR = root('issue-4228-claims-');
const { handler, runtime, sessionStore } = route(device);
expect(
(
await handler(
openRequest('first', { platform: 'ios' }, 'first-open', {}, ['com.example.app']),
)
).ok,
).toBe(true);

// 1. Session B open is refused with DEVICE_IN_USE
const openB = await handler(
openRequest('second', { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' }, 'second-open', {}, [
'com.example.app',
]),
);
expect(openB).toMatchObject({
ok: false,
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
});

runtime.bind.mockClear();
runtime.inspectFacts.mockClear();

// 2. Session B snapshot with selector must also be refused with DEVICE_IN_USE
const snapshotB = await handler({
token: 'test-token',
session: 'second',
command: 'snapshot',
positionals: [],
flags: { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' },
meta: { requestId: 'second-snapshot', sessionExplicit: true },
});
expect(sessionStore.get('second')).toBeUndefined();
expect(runtime.bind).not.toHaveBeenCalled();
expect(snapshotB).toMatchObject({
ok: false,
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
});

// 3. Session B clipboard write with selector (mutating handler family) must also be refused with DEVICE_IN_USE
const clipboardB = await handler({
token: 'test-token',
session: 'second',
command: 'clipboard',
positionals: ['write', 'pasted text'],
flags: { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' },
meta: { requestId: 'second-clipboard', sessionExplicit: true },
});
expect(sessionStore.get('second')).toBeUndefined();
expect(runtime.bind).not.toHaveBeenCalled();
expect(clipboardB).toMatchObject({
ok: false,
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,43 @@ test('fresh replay retains a dynamically selected device through finalization',
expect(externalRequestSettled).toBe(true);
});

test('test runs a one-case suite whose script leaves a session open, passes, and closes the session', async () => {
const root = mkdtempForTestSync('agent-device-replay-test-leak-');
const scriptPath = path.join(root, '01-case.ad');
fs.writeFileSync(scriptPath, 'context platform=ios\nopen "com.example.app"\n');
const sessionStore = makeSessionStore('agent-device-replay-test-leak-');

const handler = createRequestHandler({
host: createTestHostEnvironment(),
createCommandSurface: testCreateCommandSurface,
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
token: 'test-token',
sessionStore,
leaseRegistry: new LeaseRegistry(),
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
deviceInventoryGateways: createTestDeviceInventoryGateways(),
trackDownloadableArtifact: () => 'artifact-id',
});

const response = await handler({
token: 'test-token',
session: 'default',
command: 'test',
positionals: [root],
flags: { platform: 'ios' },
meta: { cwd: root, requestId: 'suite-unclosed-session' },
});

expect(response).toMatchObject({
ok: true,
data: expect.objectContaining({
passed: 1,
failed: 0,
}),
});
expect(sessionStore.listRefs()).toHaveLength(0);
});

function requestPlatformProvidersFake(): {
providers: RequestPlatformProviders;
contexts: PlatformProviderRequestContext[];
Expand Down
39 changes: 35 additions & 4 deletions packages/daemon/src/server/request-execution-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ import {
} from '../core/context.ts';
import { assertSessionSelectorMatches } from '../core/session-selector.ts';
import {
isImplicitSessionScopeConflict,
resolveCallerScopeRoot,
resolveEffectiveSessionName,
} from '../sessions/session-routing.ts';
import {
buildDeviceInUseBySessionError,
buildForeignWorkspaceSessionConflict,
} from '../core/session-recovery-hints.ts';
import { deriveWebSessionIdentity } from '../core/session-tenant-scope.ts';
import {
assertRequestLeaseAdmissionPreflight,
Expand All @@ -51,6 +56,7 @@ import {
} from './request-binding.ts';
import {
beginOpenDeviceWait,
findSessionHoldingDevice,
readOpenWaitBudgetMs,
} from '../sessions/open-device-contention-wait.ts';
import {
Expand Down Expand Up @@ -336,6 +342,7 @@ export async function createRequestExecutionScope(params: {
platformRequestScope: params.platformRequestScope,
daemonPolicy: params.daemonPolicy,
claimRecoveryGateway: params.claimRecoveryGateway,
sessionStore,
});

let bindingCleanup: Promise<void> | undefined;
Expand Down Expand Up @@ -567,13 +574,15 @@ function createRequestDeviceAccess(params: {
platformRequestScope: PlatformRequestScope;
daemonPolicy: DaemonPolicy | undefined;
claimRecoveryGateway: ClaimRecoveryGatewayFactory;
sessionStore: SessionStore;
}): {
claimAdmission: DeviceClaimAdmission;
runtimeBindings: RequestRuntimeBindings;
} {
const { deviceRuntimeGateway, platformRequestScope, daemonPolicy } = params;
const claimPolicy = resolveCommandDeviceClaimPolicy(params.command);
const claimAdmission = createDeviceClaimAdmission({
policy: resolveCommandDeviceClaimPolicy(params.command),
policy: claimPolicy,
command: params.command,
session: params.sessionName,
workspace: params.workspace,
Expand All @@ -598,9 +607,31 @@ function createRequestDeviceAccess(params: {
scope: platformRequestScope,
dispatchLedger: params.dispatchLedger,
admitDeviceClaim: claimAdmission.admit,
admitDevice: daemonPolicy
? (device) => assertDaemonPolicyAdmitsDevice(daemonPolicy, device)
: undefined,
admitDevice:
daemonPolicy || claimPolicy === 'require-owner'
? (device) => {
if (daemonPolicy) {
assertDaemonPolicyAdmitsDevice(daemonPolicy, device);
}
if (claimPolicy === 'require-owner' && !params.sessionStore.get(params.sessionName)) {
Comment thread
twotnguyen marked this conversation as resolved.
Resolved
const inUse = findSessionHoldingDevice(
params.sessionStore,
device.id,
params.sessionName,
);
if (inUse) {
const refusal = isImplicitSessionScopeConflict(params.req, inUse.session)
? buildForeignWorkspaceSessionConflict(inUse, device)
: buildDeviceInUseBySessionError(inUse, device);
throw new AppError(
refusal.error.code,
refusal.error.message,
refusal.error.details,
);
}
}
}
: undefined,
}),
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function beginOpenDeviceWait(params: {

/** The other session holding `deviceId`, or `undefined` when nothing stands between this open and
* the device — including when this open's own session is what holds it. */
function findSessionHoldingDevice(
export function findSessionHoldingDevice(
sessionStore: SessionStore,
deviceId: string,
sessionName: string,
Expand Down