Skip to content

Commit 465b7a0

Browse files
committed
fix(device-pin): enforce the pin at client request finalization
Check the device pin once in the client's execute, against the request flags and every batch step's flags, so CLI batch, nested MCP batch and remote-config defaults all go through the same check. - Add assertRequestHonorsDevicePin and drop selectorOrigins, DevicePinSurface and pickExplicitSelector. - Make the hidden --device-pin flag turn the pin on. - Remove resolveConfigBackedFlagDefaults and the env policy-source fallback; document the precedence rule. - Add batch-step regression tests for the client, CLI and MCP paths and cover udid/serial pins and the exact hint.
1 parent fd9356e commit 465b7a0

18 files changed

Lines changed: 491 additions & 304 deletions
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import type { AgentDeviceDaemonTransport } from '@agent-device/contracts/client';
4+
import type { CommandFlags } from '@agent-device/contracts/command';
5+
import { runCommand, type DevicePin } from '@agent-device/command-surface';
6+
import { createAgentDeviceClient } from '../index.ts';
7+
8+
// #2161: the client enforces the workspace device pin on the finished request, so every surface
9+
// (CLI argv, CLI batch, MCP flat and nested input, remote config) is held to it in one place.
10+
11+
const PIN: DevicePin = {
12+
selector: { platform: 'ios', device: 'iPad Pro' },
13+
policySource: { kind: 'project', label: 'project config file /repo/agent-device.json' },
14+
};
15+
16+
function recordingClient(devicePin: DevicePin | undefined) {
17+
const requests: Array<Parameters<AgentDeviceDaemonTransport>[0]> = [];
18+
const transport: AgentDeviceDaemonTransport = async (request) => {
19+
requests.push(request);
20+
return { ok: true, data: { results: [], executed: 0, total: 0 } };
21+
};
22+
return { requests, client: createAgentDeviceClient({}, { transport, devicePin }) };
23+
}
24+
25+
function failsWithPinConflict(expected: { message: RegExp; conflicts: unknown[] }) {
26+
return (error: unknown): boolean => {
27+
assert.ok(error instanceof Error && 'code' in error && 'details' in error);
28+
assert.equal(error.code, 'INVALID_ARGS');
29+
assert.match(error.message, expected.message);
30+
const details = error.details as Record<string, unknown>;
31+
assert.equal(details.reason, 'device_pin_conflict');
32+
assert.equal(details.pinSource, 'project config file /repo/agent-device.json');
33+
assert.deepEqual(details.conflicts, expected.conflicts);
34+
return true;
35+
};
36+
}
37+
38+
test('a batch step naming another device fails before the request leaves the client', async () => {
39+
const { client, requests } = recordingClient(PIN);
40+
41+
await assert.rejects(
42+
runCommand(client, 'batch', {
43+
steps: [
44+
{ command: 'snapshot', input: {} },
45+
{ command: 'open', input: { app: 'com.example.app', device: 'iPhone 16' } },
46+
],
47+
}),
48+
failsWithPinConflict({
49+
message:
50+
/^Batch step 2: device "iPhone 16" conflicts with the device pin from project config file/,
51+
conflicts: [{ key: 'device', pinned: 'iPad Pro', requested: 'iPhone 16', step: 2 }],
52+
}),
53+
);
54+
assert.equal(requests.length, 0);
55+
});
56+
57+
test('a top-level selector from any layer that contradicts the pin fails', async () => {
58+
const { client, requests } = recordingClient(PIN);
59+
60+
await assert.rejects(
61+
runCommand(client, 'snapshot', { platform: 'android' }),
62+
failsWithPinConflict({
63+
message: /^platform "android" conflicts with the device pin/,
64+
conflicts: [{ key: 'platform', pinned: 'ios', requested: 'android' }],
65+
}),
66+
);
67+
assert.equal(requests.length, 0);
68+
});
69+
70+
test('a batch whose steps repeat, refine, or omit the pin is sent', async () => {
71+
const { client, requests } = recordingClient(PIN);
72+
73+
await runCommand(client, 'batch', {
74+
platform: 'ios',
75+
device: 'iPad Pro',
76+
steps: [
77+
{ command: 'snapshot', input: {} },
78+
{ command: 'open', input: { app: 'com.example.app', device: 'iPad Pro' } },
79+
// A UDID picks one device among several that share the pinned name.
80+
{ command: 'snapshot', input: { udid: 'ABCDEF' } },
81+
],
82+
});
83+
84+
assert.equal(requests.length, 1);
85+
assert.equal((requests[0]?.flags as CommandFlags | undefined)?.batchSteps?.length, 3);
86+
});
87+
88+
test('without a pin the client sends a batch step that names another device', async () => {
89+
const { client, requests } = recordingClient(undefined);
90+
91+
await runCommand(client, 'batch', {
92+
steps: [{ command: 'open', input: { app: 'com.example.app', device: 'iPhone 16' } }],
93+
});
94+
95+
const steps = (requests[0]?.flags as CommandFlags | undefined)?.batchSteps;
96+
assert.equal(steps?.[0]?.flags?.device, 'iPhone 16');
97+
});

‎packages/client/src/index.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,10 @@ import {
5353
} from './client-normalizers.ts';
5454
import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog';
5555
import {
56+
assertRequestHonorsDevicePin,
5657
buildRequestFlags,
5758
type AgentDeviceClient,
59+
type DevicePin,
5860
prepareDaemonCommandRequest,
5961
type DaemonCommandName,
6062
} from '@agent-device/command-surface';
@@ -78,7 +80,12 @@ export { pickScreenshotResultData } from './screenshot-result.ts';
7880

7981
export function createAgentDeviceClient(
8082
config: AgentDeviceClientConfig = {},
81-
deps: { transport?: AgentDeviceDaemonTransport; host?: HostEnvironment } = {},
83+
deps: {
84+
transport?: AgentDeviceDaemonTransport;
85+
host?: HostEnvironment;
86+
/** The workspace device pin (#2161), checked against every request this client sends. */
87+
devicePin?: DevicePin;
88+
} = {},
8289
): AgentDeviceClient {
8390
const host = deps.host ?? captureHostEnvironment(process);
8491
const transport = deps.transport ?? createDaemonTransport(host);
@@ -137,6 +144,9 @@ export function createAgentDeviceClient(
137144
runtime: merged.runtime,
138145
meta: { ...buildMeta(merged), requestId },
139146
};
147+
// The one place the pin is enforced: the finished request, after every default layer merged,
148+
// including each batch step, so no surface or layer can retarget a pinned project.
149+
if (deps.devicePin) assertRequestHonorsDevicePin(deps.devicePin, request);
140150
// `signal` rides the transport context (it is a live object, never wire data), and the guard
141151
// answers for a custom transport that ignores it: the caller's promise settles on abort either
142152
// way. The built-in transport closes the request's connection, which is what makes the daemon

‎packages/command-registry/src/flag-groups.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,12 @@ export const REPLAY_FLAGS = flagKeys('replayUpdate', 'replayEnv');
5757

5858
// Which flags the CLI PARSER accepts on every command — a different axis from
5959
// the common input keys in `commands/common-input-fields.ts`, which #2027
60-
// unified into one table. Neither list contains the other: 25 of the 42 keys
61-
// below (`remoteConfig`, `stateDir`, `daemonTransport`, `sessionIsolation`,
60+
// unified into one table. Neither list contains the other: many keys below
61+
// (`remoteConfig`, `stateDir`, `daemonTransport`, `sessionIsolation`,
6262
// `leaseBackend`, `sessionLock`, `devicePin`, every `provider*` and `aws*`) never become
6363
// structured command input, while the table's `cwd` and `debug` are not flags
6464
// and its `deviceTarget` row is spelled `target` here. Deriving this list from
65-
// that table would mean 25 rows carrying no schema, reader, or projection, so
65+
// that table would mean rows carrying no schema, reader, or projection, so
6666
// the two stay separate; the table declares `envFlagKeys` (which environment
6767
// variable an operator-owned input comes from) and `flagKey`/`flagIn` (which
6868
// `CliFlags` property a row reads and which reader projections it joins) —

‎packages/command-surface/src/cli-grammar/flag-declaration-admission.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { test, vi } from 'vitest';
55
import type { CliFlags } from '@agent-device/contracts/command';
66
import { getFlagDefinitionsForKey } from '@agent-device/command-registry/flag-registry';
77
import type { FlagDefinition } from '@agent-device/command-registry/flag-types';
8-
import { resolveConfigBackedFlagDefaults } from '../schema/cli-config.ts';
8+
import { resolveConfigBackedFlagDefaultsWithProvenance } from '../schema/cli-config.ts';
99
import { makeTempWorkspace } from '@agent-device/test-kit';
1010

1111
/**
@@ -42,7 +42,7 @@ test('project-config admission follows the declaration: an undeclared key is ref
4242
writeProjectConfig(shipped.project, { daemonBaseUrl: 'https://daemon.example.test' });
4343
assert.throws(
4444
() =>
45-
resolveConfigBackedFlagDefaults({
45+
resolveConfigBackedFlagDefaultsWithProvenance({
4646
command: 'devices',
4747
cwd: shipped.project,
4848
cliFlags: OPERATOR_CLI_FLAGS,
@@ -60,7 +60,7 @@ test('project-config admission follows the declaration: an undeclared key is ref
6060
const registry = await import('@agent-device/command-registry/flag-registry');
6161
const planted = getInRegistry(registry, 'daemonBaseUrl');
6262
Object.assign(planted, { projectConfig: true });
63-
const { resolveConfigBackedFlagDefaults: derivePlanted } =
63+
const { resolveConfigBackedFlagDefaultsWithProvenance: derivePlanted } =
6464
await import('../schema/cli-config.ts');
6565
const workspace = makeTempWorkspace();
6666
try {
@@ -71,7 +71,7 @@ test('project-config admission follows the declaration: an undeclared key is ref
7171
cliFlags: OPERATOR_CLI_FLAGS,
7272
env: { HOME: workspace.home },
7373
});
74-
assert.equal(defaults.daemonBaseUrl, 'https://daemon.example.test');
74+
assert.equal(defaults.flags.daemonBaseUrl, 'https://daemon.example.test');
7575
} finally {
7676
fs.rmSync(workspace.root, { recursive: true, force: true });
7777
}

‎packages/command-surface/src/index.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,9 @@ export {
3838
resolveBindingSettings,
3939
resolveConfigBackedFlagDefaultsWithProvenance,
4040
type BindingSettings,
41-
assertSelectorHonorsDevicePin,
42-
pickExplicitSelector,
41+
assertRequestHonorsDevicePin,
4342
resolveDevicePin,
44-
resolveSelectorOrigins,
4543
type DevicePin,
46-
type SelectorOrigins,
4744
} from './schema/cli-config.ts';
4845
export { mergeDefinedFlags } from './schema/merge-flags.ts';
4946

0 commit comments

Comments
 (0)