Skip to content

Commit 27d87b1

Browse files
twotnguyenthymikeeclaude
authored
fix(daemon): enforce device claim for commands with explicit selector (#4270)
* fix(daemon): enforce device claim for commands with explicit selector * fix(daemon): preserve noActiveSessionError for unselected queries and verify pre-admission * refactor(daemon): enforce require-owner in-memory claim guard in request device access * fix(command-registry): set test device claim policy to none (#4228) * refactor(daemon): consolidate device conflict resolution helper (#4228) * fix(daemon): correct type imports and formatting for device conflict resolution * refactor(daemon): unexport internal findSessionHoldingDevice to satisfy fallow dead code audit * test(daemon): expect a fresh session to be refused on a held device Two fresh named sessions no longer share one device: the second waits for the holder's request, then gets DEVICE_IN_USE (#4228). Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Michał Pierzchała <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent c7df72a commit 27d87b1

11 files changed

Lines changed: 196 additions & 70 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'agent-device': patch
3+
---
4+
5+
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.

‎packages/command-registry/src/__tests__/registry-device-claim-policy.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ test('every command that deviates from require-owner is a reviewed, diffable set
7676
'session',
7777
'session_list',
7878
'session_save_script',
79+
'test',
7980
'web',
8081
],
8182
});

‎packages/command-registry/src/descriptors/session-operations.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ export const SESSION_OPERATION_COMMAND_DESCRIPTORS = [
183183
},
184184
{
185185
name: 'test',
186-
deviceClaimPolicy: 'require-owner',
186+
deviceClaimPolicy: 'none',
187187
...(ownerFilesEnabled
188188
? { ownerFiles: ['packages/command-surface/src/replay/index.ts'] as const }
189189
: {}),

‎packages/command-registry/src/types.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,9 @@ export type CommandTimeoutPolicy = {
8888
* - `observe` — device inventory/ownership projection; may report a
8989
* claim, never mutates one.
9090
* - `require-owner` — session-bound work; trusts the invariant `open`
91-
* established and does NO claim-store I/O.
91+
* established and does NO claim-store I/O. Refuses a
92+
* foreign in-memory session holder when its own session
93+
* is unheld.
9294
* - `transient-exclusive` — sessionless device mutation; acquires a
9395
* command-scoped claim before device operations reach
9496
* the handler, refuses a foreign claim, and releases

‎packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,3 +736,62 @@ test('a later request does not inherit a prior request device pin', async () =>
736736
);
737737
});
738738
});
739+
740+
test('require-owner commands with device selector are refused when another session holds device (#4228)', async () => {
741+
const device = { ...makeIosDevice('SIM-HELD-BY-FIRST'), appleOs: 'ios' as const };
742+
process.env.AGENT_DEVICE_CLAIMS_DIR = root('issue-4228-claims-');
743+
const { handler, runtime, sessionStore } = route(device);
744+
expect(
745+
(
746+
await handler(
747+
openRequest('first', { platform: 'ios' }, 'first-open', {}, ['com.example.app']),
748+
)
749+
).ok,
750+
).toBe(true);
751+
752+
// 1. Session B open is refused with DEVICE_IN_USE
753+
const openB = await handler(
754+
openRequest('second', { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' }, 'second-open', {}, [
755+
'com.example.app',
756+
]),
757+
);
758+
expect(openB).toMatchObject({
759+
ok: false,
760+
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
761+
});
762+
763+
runtime.bind.mockClear();
764+
runtime.inspectFacts.mockClear();
765+
766+
// 2. Session B snapshot with selector must also be refused with DEVICE_IN_USE
767+
const snapshotB = await handler({
768+
token: 'test-token',
769+
session: 'second',
770+
command: 'snapshot',
771+
positionals: [],
772+
flags: { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' },
773+
meta: { requestId: 'second-snapshot', sessionExplicit: true },
774+
});
775+
expect(sessionStore.get('second')).toBeUndefined();
776+
expect(runtime.bind).not.toHaveBeenCalled();
777+
expect(snapshotB).toMatchObject({
778+
ok: false,
779+
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
780+
});
781+
782+
// 3. Session B clipboard write with selector (mutating handler family) must also be refused with DEVICE_IN_USE
783+
const clipboardB = await handler({
784+
token: 'test-token',
785+
session: 'second',
786+
command: 'clipboard',
787+
positionals: ['write', 'pasted text'],
788+
flags: { platform: 'ios', udid: 'SIM-HELD-BY-FIRST' },
789+
meta: { requestId: 'second-clipboard', sessionExplicit: true },
790+
});
791+
expect(sessionStore.get('second')).toBeUndefined();
792+
expect(runtime.bind).not.toHaveBeenCalled();
793+
expect(clipboardB).toMatchObject({
794+
ok: false,
795+
error: { code: 'DEVICE_IN_USE', message: 'Device is already in use by session "first".' },
796+
});
797+
});

‎packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts‎

Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ test('direct daemon requests cannot bypass reject lock policy for existing sessi
161161
}
162162
});
163163

164-
test('fresh named sessions with matching explicit serial bind and serialize on the selected device', async () => {
164+
test('a fresh named session with a matching explicit serial waits for the holder, then is refused', async () => {
165165
const sessionStore = makeSessionStore('agent-device-router-lock-');
166166
const dispatchGate = installGatedDispatch();
167167

@@ -218,23 +218,22 @@ test('fresh named sessions with matching explicit serial bind and serialize on t
218218

219219
dispatchGate.releaseNext();
220220

221-
await vi.waitFor(() => {
222-
expect(dispatchGate.order).toEqual([
223-
'start-snapshot-emulator-5554',
224-
'end-snapshot-emulator-5554',
225-
'start-snapshot-emulator-5554',
226-
]);
227-
});
228-
229-
dispatchGate.releaseNext();
230-
231221
const [firstResponse, secondResponse] = await Promise.all([first, second]);
232222

233223
expect(firstResponse.ok).toBe(true);
234-
expect(secondResponse.ok).toBe(true);
235-
expect(dispatchGate.getMaxActive()).toBe(1);
224+
expect(secondResponse).toMatchObject({
225+
ok: false,
226+
error: {
227+
code: 'DEVICE_IN_USE',
228+
details: { session: 'qa-android-a', deviceId: 'emulator-5554' },
229+
},
230+
});
231+
expect(dispatchGate.order).toEqual([
232+
'start-snapshot-emulator-5554',
233+
'end-snapshot-emulator-5554',
234+
]);
236235
expect(sessionStore.get('qa-android-a')?.device.id).toBe('emulator-5554');
237-
expect(sessionStore.get('qa-android-b')?.device.id).toBe('emulator-5554');
236+
expect(sessionStore.get('qa-android-b')).toBeUndefined();
238237
});
239238

240239
test('fresh named sessions with the same name serialize first binding before rejecting another device', async () => {
@@ -316,7 +315,7 @@ test('fresh named sessions with the same name serialize first binding before rej
316315
expect(sessionStore.get('qa-android')?.device.id).toBe('emulator-5554');
317316
});
318317

319-
test('fresh named sessions with only lock platform default serialize on the selected device', async () => {
318+
test('a fresh named session with only a lock platform default waits for the holder, then is refused', async () => {
320319
const sessionStore = makeSessionStore('agent-device-router-lock-');
321320
const dispatchGate = installGatedDispatch();
322321

@@ -369,23 +368,22 @@ test('fresh named sessions with only lock platform default serialize on the sele
369368

370369
dispatchGate.releaseNext();
371370

372-
await vi.waitFor(() => {
373-
expect(dispatchGate.order).toEqual([
374-
'start-snapshot-emulator-5554',
375-
'end-snapshot-emulator-5554',
376-
'start-snapshot-emulator-5554',
377-
]);
378-
});
379-
380-
dispatchGate.releaseNext();
381-
382371
const [firstResponse, secondResponse] = await Promise.all([first, second]);
383372

384373
expect(firstResponse.ok).toBe(true);
385-
expect(secondResponse.ok).toBe(true);
386-
expect(dispatchGate.getMaxActive()).toBe(1);
374+
expect(secondResponse).toMatchObject({
375+
ok: false,
376+
error: {
377+
code: 'DEVICE_IN_USE',
378+
details: { session: 'qa-default-a', deviceId: 'emulator-5554' },
379+
},
380+
});
381+
expect(dispatchGate.order).toEqual([
382+
'start-snapshot-emulator-5554',
383+
'end-snapshot-emulator-5554',
384+
]);
387385
expect(sessionStore.get('qa-default-a')?.device.id).toBe('emulator-5554');
388-
expect(sessionStore.get('qa-default-b')?.device.id).toBe('emulator-5554');
386+
expect(sessionStore.get('qa-default-b')).toBeUndefined();
389387
});
390388

391389
test('fresh named sessions reject incompatible selector combinations before binding', async () => {

‎packages/daemon/src/server/__tests__/request-router-record-runtime-lock.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ vi.mock('../../core/device/device-ready.ts', () => ({
3737
ensureDeviceReady: vi.fn(async () => {}),
3838
}));
3939

40-
test('fresh default-device recording starts serialize before durable admission', async () => {
40+
test('a fresh session record start waits for the holder, then is refused before binding', async () => {
4141
let releaseFirstStart: () => void = () => {};
4242
const firstStartBlocked = new Promise<void>((resolve) => {
4343
releaseFirstStart = resolve;
@@ -68,8 +68,9 @@ test('fresh default-device recording starts serialize before durable admission',
6868
await expect(first).resolves.toMatchObject({ ok: true, data: { recording: 'started' } });
6969
await expect(second).resolves.toMatchObject({
7070
ok: false,
71-
error: { code: 'COMMAND_FAILED', details: { reason: 'cleanup-unconfirmed' } },
71+
error: { code: 'DEVICE_IN_USE', details: { session: 'session-a', deviceId: DEVICE.id } },
7272
});
73+
expect(runtime.bind).toHaveBeenCalledOnce();
7374
expect(runtime.start).toHaveBeenCalledOnce();
7475
});
7576

‎packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,43 @@ test('fresh replay retains a dynamically selected device through finalization',
257257
expect(externalRequestSettled).toBe(true);
258258
});
259259

260+
test('test runs a one-case suite whose script leaves a session open, passes, and closes the session', async () => {
261+
const root = mkdtempForTestSync('agent-device-replay-test-leak-');
262+
const scriptPath = path.join(root, '01-case.ad');
263+
fs.writeFileSync(scriptPath, 'context platform=ios\nopen "com.example.app"\n');
264+
const sessionStore = makeSessionStore('agent-device-replay-test-leak-');
265+
266+
const handler = createRequestHandler({
267+
host: createTestHostEnvironment(),
268+
createCommandSurface: testCreateCommandSurface,
269+
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
270+
token: 'test-token',
271+
sessionStore,
272+
leaseRegistry: new LeaseRegistry(),
273+
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
274+
deviceInventoryGateways: createTestDeviceInventoryGateways(),
275+
trackDownloadableArtifact: () => 'artifact-id',
276+
});
277+
278+
const response = await handler({
279+
token: 'test-token',
280+
session: 'default',
281+
command: 'test',
282+
positionals: [root],
283+
flags: { platform: 'ios' },
284+
meta: { cwd: root, requestId: 'suite-unclosed-session' },
285+
});
286+
287+
expect(response).toMatchObject({
288+
ok: true,
289+
data: expect.objectContaining({
290+
passed: 1,
291+
failed: 0,
292+
}),
293+
});
294+
expect(sessionStore.listRefs()).toHaveLength(0);
295+
});
296+
260297
function requestPlatformProvidersFake(): {
261298
providers: RequestPlatformProviders;
262299
contexts: PlatformProviderRequestContext[];

‎packages/daemon/src/server/request-execution-scope.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import {
5151
} from './request-binding.ts';
5252
import {
5353
beginOpenDeviceWait,
54+
findSessionDeviceConflict,
5455
readOpenWaitBudgetMs,
5556
} from '../sessions/open-device-contention-wait.ts';
5657
import {
@@ -336,6 +337,7 @@ export async function createRequestExecutionScope(params: {
336337
platformRequestScope: params.platformRequestScope,
337338
daemonPolicy: params.daemonPolicy,
338339
claimRecoveryGateway: params.claimRecoveryGateway,
340+
sessionStore,
339341
});
340342

341343
let bindingCleanup: Promise<void> | undefined;
@@ -573,13 +575,15 @@ function createRequestDeviceAccess(params: {
573575
platformRequestScope: PlatformRequestScope;
574576
daemonPolicy: DaemonPolicy | undefined;
575577
claimRecoveryGateway: ClaimRecoveryGatewayFactory;
578+
sessionStore: SessionStore;
576579
}): {
577580
claimAdmission: DeviceClaimAdmission;
578581
runtimeBindings: RequestRuntimeBindings;
579582
} {
580583
const { deviceRuntimeGateway, platformRequestScope, daemonPolicy } = params;
584+
const claimPolicy = resolveCommandDeviceClaimPolicy(params.command);
581585
const claimAdmission = createDeviceClaimAdmission({
582-
policy: resolveCommandDeviceClaimPolicy(params.command),
586+
policy: claimPolicy,
583587
command: params.command,
584588
session: params.sessionName,
585589
workspace: params.workspace,
@@ -604,9 +608,29 @@ function createRequestDeviceAccess(params: {
604608
scope: platformRequestScope,
605609
dispatchLedger: params.dispatchLedger,
606610
admitDeviceClaim: claimAdmission.admit,
607-
admitDevice: daemonPolicy
608-
? (device) => assertDaemonPolicyAdmitsDevice(daemonPolicy, device)
609-
: undefined,
611+
admitDevice:
612+
daemonPolicy || claimPolicy === 'require-owner'
613+
? (device) => {
614+
if (daemonPolicy) {
615+
assertDaemonPolicyAdmitsDevice(daemonPolicy, device);
616+
}
617+
if (claimPolicy === 'require-owner' && !params.sessionStore.get(params.sessionName)) {
618+
const refusal = findSessionDeviceConflict({
619+
req: params.req,
620+
device,
621+
sessionStore: params.sessionStore,
622+
sessionName: params.sessionName,
623+
});
624+
if (refusal) {
625+
throw new AppError(
626+
refusal.error.code,
627+
refusal.error.message,
628+
refusal.error.details,
629+
);
630+
}
631+
}
632+
}
633+
: undefined,
610634
}),
611635
};
612636
}

‎packages/daemon/src/sessions/open-device-contention-wait.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,16 @@ import { readOptionalInteger } from '@agent-device/contracts/command';
33
import { emitRequestProgress, throwIfRequestCanceled } from '@agent-device/host-kit/request';
44
import { Deadline, sleep } from '@agent-device/host-kit/retry';
55
import { AppError } from '@agent-device/kernel/errors';
6+
import type { DeviceInfo } from '@agent-device/kernel/device';
67
import type { DaemonRequest } from '../core/daemon-request.ts';
8+
import type { DaemonFailureResponse } from '@agent-device/kernel/contracts';
79
import type { SessionStore } from '../core/session-store.ts';
810
import type { SessionRecoveryOptions } from '../core/session-recovery-hints.ts';
11+
import { isImplicitSessionScopeConflict } from './session-routing.ts';
12+
import {
13+
buildDeviceInUseBySessionError,
14+
buildForeignWorkspaceSessionConflict,
15+
} from '../core/session-recovery-hints.ts';
916

1017
/**
1118
* How often a waiting open re-checks its device. Contention ends when another session closes or
@@ -129,6 +136,28 @@ function findSessionHoldingDevice(
129136
return inUse;
130137
}
131138

139+
/**
140+
* Resolves the device conflict refusal when another session already holds the target device.
141+
* Used by both session open and request-execution scope to enforce owner claims consistently.
142+
*/
143+
export function findSessionDeviceConflict(params: {
144+
req: DaemonRequest;
145+
device: DeviceInfo;
146+
sessionStore: SessionStore;
147+
sessionName?: string;
148+
}): DaemonFailureResponse | undefined {
149+
const { req, device, sessionStore, sessionName } = params;
150+
const inUse = sessionName
151+
? findSessionHoldingDevice(sessionStore, device.id, sessionName)
152+
: sessionStore.findByDevice(device.id);
153+
if (!inUse) return undefined;
154+
const attempt = describeOpenWaitForRefusal(req);
155+
if (isImplicitSessionScopeConflict(req, inUse.session)) {
156+
return buildForeignWorkspaceSessionConflict(inUse, device, attempt);
157+
}
158+
return buildDeviceInUseBySessionError(inUse, device, attempt);
159+
}
160+
132161
type LockedAttempt<Outcome> = { ran: true; outcome: Outcome } | { ran: false };
133162

134163
function createOpenDeviceWait(params: {

0 commit comments

Comments
 (0)