Skip to content

Commit 7595f82

Browse files
committed
fix(record): carry lease discovery context and pin every scoping half
Manifest re-resolution forwarded the host-scoping selectors but dropped the request's lease/provider-discovery fields (leaseId, leaseProvider, deviceKey, clientId), which flow into provider discovery — a leased named record stop resolved outside its lease, unlike base, which passed the whole request flags. The non-identity discovery context now has one owning read in device-selector-intent next to the selector classification, and resolveManifestDevice forwards it. Pins: apple-manifest recovery carries iosSimulatorDeviceSet (the surviving drop-spread mutant; deleting either spread line now fails a test), recovery carries the lease context (drop-context mutant caught), and the sessionless plain-advice test asserts the resolver call on the stated udid so a refusal that skips resolving an invalid UDID fails it. The record fixture builds its durable envelope with the same kernel deviceIdentity() the transports use, so an apple manifest is decodable and every pin asserts a healthy start/stop and a decoded manifest before exercising recovery.
1 parent 83626c0 commit 7595f82

5 files changed

Lines changed: 153 additions & 18 deletions

File tree

‎packages/daemon/src/core/device/device-selector-intent.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,39 @@ const LOCKABLE_DEVICE_SCOPE_KEYS: ReadonlyArray<keyof CommandFlags> = [
88
'androidDeviceAllowlist',
99
];
1010

11+
/**
12+
* Request-scoped lease and provider-discovery context. These say WHO may see which devices
13+
* (a lease or a provider client narrows the inventory the resolver can reach), never WHICH
14+
* device, so a lane that rebuilds a selector must forward them or resolution silently
15+
* widens outside the lease. `device-selector-intent` classifies selectors; this is the one
16+
* read that keeps that classification's non-identity discovery keys together.
17+
*/
18+
export type LeaseDiscoveryContext = {
19+
leaseId?: string;
20+
leaseProvider?: string;
21+
deviceKey?: string;
22+
clientId?: string;
23+
};
24+
25+
const LEASE_DISCOVERY_KEYS = [
26+
'leaseId',
27+
'leaseProvider',
28+
'deviceKey',
29+
'clientId',
30+
] as const satisfies ReadonlyArray<keyof LeaseDiscoveryContext & keyof CommandFlags>;
31+
32+
export function leaseDiscoveryContextFromFlags(
33+
flags: CommandFlags | undefined,
34+
): LeaseDiscoveryContext {
35+
if (!flags) return {};
36+
const context: Record<string, string> = {};
37+
for (const key of LEASE_DISCOVERY_KEYS) {
38+
const value = flags[key];
39+
if (typeof value === 'string' && value.trim().length > 0) context[key] = value;
40+
}
41+
return context;
42+
}
43+
1144
export function hasExplicitDeviceSelector(flags: CommandFlags | undefined): boolean {
1245
return hasExplicitDeviceIdentitySelector({
1346
deviceName: flags?.device,

‎packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts‎

Lines changed: 87 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ const RESTART_RECORDED_DEVICE = {
2020
name: 'Pixel',
2121
kind: 'emulator',
2222
} as const;
23+
const APPLE_RECORDED_DEVICE = {
24+
platform: 'apple',
25+
appleOs: 'ios',
26+
id: 'IOS-UDID-1',
27+
name: 'iPhone 17 Pro',
28+
kind: 'simulator',
29+
target: 'mobile',
30+
} as const;
2331
const FLAGLESS_RECORDED_DEVICE = {
2432
platform: 'linux',
2533
id: 'linux',
@@ -31,6 +39,7 @@ const resolveTargetDeviceMock = vi.fn(async (flags: Record<string, string | unde
3139
if (flags.serial === RESTART_RECORDED_DEVICE.id || flags.udid === RESTART_RECORDED_DEVICE.id) {
3240
return { ...RESTART_RECORDED_DEVICE };
3341
}
42+
if (flags.udid === APPLE_RECORDED_DEVICE.id) return { ...APPLE_RECORDED_DEVICE };
3443
if (flags.platform === 'linux') return { ...FLAGLESS_RECORDED_DEVICE };
3544
throw new AppError('AMBIGUOUS_MATCH', 'Multiple attached devices detected');
3645
});
@@ -78,8 +87,11 @@ test('record stop recovery after a daemon restart keeps the request host-scoping
7887
'capture.mp4',
7988
);
8089
fs.writeFileSync(outPath, 'mp4');
81-
await harness.run(['start', outPath], undefined, { androidDeviceAllowlist: 'emulator-5554' });
82-
await harness.run(['stop']);
90+
expect(
91+
await harness.run(['start', outPath], undefined, { androidDeviceAllowlist: 'emulator-5554' }),
92+
).toMatchObject({ ok: true });
93+
expect(await harness.run(['stop'])).toMatchObject({ ok: true });
94+
expectDecodedCompletedRecording(harness.sessionStore, harness.sessionName);
8395
const ref = harness.sessionStore.lookup(harness.sessionName);
8496
if (!ref) throw new Error('Expected the stopped recording session');
8597
harness.sessionStore.retire(ref);
@@ -105,6 +117,76 @@ test('record stop recovery after a daemon restart keeps the request host-scoping
105117
);
106118
});
107119

120+
test('record stop recovery on an Apple manifest keeps the request simulator-device-set', async () => {
121+
// The apple-family twin of the allowlist pin: --ios-simulator-device-set scopes where an Apple
122+
// recovery may look, and the identity it re-states is the udid.
123+
const harness = makeRecordRuntimeHarness('record-runtime-restart-stop-ios-set-', {
124+
platform: 'apple',
125+
});
126+
const outPath = path.join(
127+
mkdtempForTestSync('record-runtime-restart-stop-ios-set-output-'),
128+
'capture.mp4',
129+
);
130+
fs.writeFileSync(outPath, 'mp4');
131+
expect(
132+
await harness.run(['start', outPath], undefined, { iosSimulatorDeviceSet: '/sets/qa.set' }),
133+
).toMatchObject({ ok: true });
134+
expect(await harness.run(['stop'])).toMatchObject({ ok: true });
135+
expectDecodedCompletedRecording(harness.sessionStore, harness.sessionName);
136+
const ref = harness.sessionStore.lookup(harness.sessionName);
137+
if (!ref) throw new Error('Expected the stopped recording session');
138+
harness.sessionStore.retire(ref);
139+
resolveTargetDeviceMock.mockClear();
140+
141+
const recovered = await harness.run(
142+
['stop'],
143+
{ sessionExplicit: true },
144+
{
145+
iosSimulatorDeviceSet: '/sets/qa.set',
146+
},
147+
);
148+
149+
expect(recovered).toMatchObject({ ok: true, data: { recording: 'stopped', outPath } });
150+
expect(resolveTargetDeviceMock).toHaveBeenCalledWith(
151+
expect.objectContaining({
152+
platform: 'apple',
153+
udid: 'IOS-UDID-1',
154+
iosSimulatorDeviceSet: '/sets/qa.set',
155+
}),
156+
);
157+
});
158+
159+
test('record stop recovery carries the request lease and discovery context', async () => {
160+
// Lease fields say WHO may see the inventory, not WHICH device; a recovery that resolved
161+
// without them would look outside the lease the recording was started under.
162+
const harness = makeRecordRuntimeHarness('record-runtime-restart-stop-lease-');
163+
const outPath = path.join(
164+
mkdtempForTestSync('record-runtime-restart-stop-lease-output-'),
165+
'capture.mp4',
166+
);
167+
fs.writeFileSync(outPath, 'mp4');
168+
const leaseFlags = {
169+
leaseId: 'lease-1',
170+
leaseProvider: 'proxy',
171+
deviceKey: 'android:mobile:emulator-5554',
172+
clientId: 'client-1',
173+
};
174+
expect(await harness.run(['start', outPath], undefined, { ...leaseFlags })).toMatchObject({
175+
ok: true,
176+
});
177+
expect(await harness.run(['stop'])).toMatchObject({ ok: true });
178+
expectDecodedCompletedRecording(harness.sessionStore, harness.sessionName);
179+
const ref = harness.sessionStore.lookup(harness.sessionName);
180+
if (!ref) throw new Error('Expected the stopped recording session');
181+
harness.sessionStore.retire(ref);
182+
resolveTargetDeviceMock.mockClear();
183+
184+
const recovered = await harness.run(['stop'], { sessionExplicit: true }, { ...leaseFlags });
185+
186+
expect(recovered).toMatchObject({ ok: true, data: { recording: 'stopped', outPath } });
187+
expect(resolveTargetDeviceMock).toHaveBeenCalledWith(expect.objectContaining(leaseFlags));
188+
});
189+
108190
test('record stop recovery for a family without identity flags resolves under the manifest family', async () => {
109191
// A linux manifest names no identity flag the request could restate. The recovery still must
110192
// not sweep the host from the request's (empty) flags: it asks for the manifest's family, and
@@ -117,8 +199,9 @@ test('record stop recovery for a family without identity flags resolves under th
117199
'capture.mp4',
118200
);
119201
fs.writeFileSync(outPath, 'mp4');
120-
await harness.run(['start', outPath]);
121-
await harness.run(['stop']);
202+
expect(await harness.run(['start', outPath])).toMatchObject({ ok: true });
203+
expect(await harness.run(['stop'])).toMatchObject({ ok: true });
204+
expectDecodedCompletedRecording(harness.sessionStore, harness.sessionName);
122205
const ref = harness.sessionStore.lookup(harness.sessionName);
123206
if (!ref) throw new Error('Expected the stopped recording session');
124207
harness.sessionStore.retire(ref);

‎packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations';
1313
import type { ScreenRecordingLiveHandle } from '@agent-device/contracts/screen-recording-runtime';
1414
import type { DaemonRequest } from '../../../core/daemon-request.ts';
15+
import { deviceIdentity } from '@agent-device/kernel/device';
1516
import { unavailableDeploymentSnapshotAndShutdownOperationFacts } from '@agent-device/test-kit';
1617
import { createDurableResourceEnvelope } from '@agent-device/capture-kit';
1718
import { makeSessionStore } from '../../../__tests__/support/store-factory.ts';
@@ -38,7 +39,7 @@ export function makeRecordRuntimeHarness(
3839
sessionName?: string;
3940
appBundleId?: string;
4041
recordOnlySession?: boolean;
41-
platform?: 'android' | 'linux' | 'vega';
42+
platform?: 'android' | 'apple' | 'linux' | 'vega';
4243
runtime?: RuntimeOptions;
4344
} = {},
4445
) {
@@ -51,7 +52,16 @@ export function makeRecordRuntimeHarness(
5152
? { platform: 'linux', id: 'linux', name: 'Linux', kind: 'device', target: 'desktop' }
5253
: options.platform === 'vega'
5354
? { platform: 'vega', id: 'vega', name: 'Vega', kind: 'device', target: 'tv' }
54-
: { platform: 'android', id: 'emulator-5554', name: 'Pixel', kind: 'emulator' },
55+
: options.platform === 'apple'
56+
? {
57+
platform: 'apple',
58+
appleOs: 'ios',
59+
id: 'IOS-UDID-1',
60+
name: 'iPhone 17 Pro',
61+
kind: 'simulator',
62+
target: 'mobile',
63+
}
64+
: { platform: 'android', id: 'emulator-5554', name: 'Pixel', kind: 'emulator' },
5565
...(options.appBundleId ? { appBundleId: options.appBundleId } : {}),
5666
...(options.recordOnlySession ? { recordOnlySession: true } : {}),
5767
createdAt: 1,
@@ -154,12 +164,9 @@ function makeRuntime(session: SessionState, options: RuntimeOptions = {}) {
154164
envelope: createDurableResourceEnvelope({
155165
resourceKind: 'screen-recording',
156166
sessionId: input.sessionId,
157-
device: {
158-
id: session.device.id,
159-
family: session.device.platform,
160-
kind: session.device.kind,
161-
...(session.device.target === undefined ? {} : { target: session.device.target }),
162-
},
167+
// Same authoritative identity projection the recording transports build their
168+
// envelopes with, so a fixture manifest carries exactly what a real one would.
169+
device: deviceIdentity(session.device),
163170
owner,
164171
fence: input.fence,
165172
lifecycle: 'open',

‎packages/daemon/src/sessions/handlers/__tests__/session-appstate.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,13 @@ test('appstate --udid on an Apple device without naming a session keeps the plai
154154
expect(response.error.code).toBe('SESSION_NOT_FOUND');
155155
expect(response.error.message).toMatch(/iOS appstate requires an active session/i);
156156
expect(response.error.details?.reason).toBeUndefined();
157+
// Resolution-first holds for the plain advice too: the stated UDID is proven before the
158+
// refusal, so an implementation that skipped resolving an invalid UDID fails here.
159+
expect(resolved).toHaveBeenCalledTimes(1);
160+
expect(resolved).toHaveBeenCalledWith(
161+
expect.objectContaining({ udid: 'SIM-UDID-B' }),
162+
expect.anything(),
163+
);
157164
} finally {
158165
resolved.mockReset();
159166
}

‎packages/daemon/src/sessions/handlers/record-runtime.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ import {
2929
resolveTargetDevice,
3030
type ResolveDeviceFlags,
3131
} from '@agent-device/device-selection/dispatch-resolve';
32-
import { hasDeviceSelectionInput } from '../../core/device/device-selector-intent.ts';
32+
import {
33+
hasDeviceSelectionInput,
34+
leaseDiscoveryContextFromFlags,
35+
} from '../../core/device/device-selector-intent.ts';
3336
import { ensureBoundDeviceReady } from '../../core/request-runtime-binding.ts';
3437
import { type ScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger';
3538
import { createScreenRecordingRecoveryControl } from '@agent-device/capture-kit/screen-recording-recovery';
@@ -208,11 +211,12 @@ function namesSessionWithoutTarget(req: DaemonRequest): boolean {
208211

209212
/**
210213
* Re-resolves the device a durable manifest names: the manifest's family always, its identity flag
211-
* where the family has one, plus the request's host-scoping selectors — `iosSimulatorDeviceSet`
212-
* and `androidDeviceAllowlist` say WHERE to look, not which device, so carrying them preserves a
213-
* recovery scoped to a simulator set or allowlist instead of regressing it to DEVICE_NOT_FOUND.
214-
* No request device/identity selector reaches here: `assertManifestBelongsToRequest` proves the
215-
* resolved device against the manifest.
214+
* where the family has one, plus the request's host-scoping and lease/discovery selectors —
215+
* `iosSimulatorDeviceSet` and `androidDeviceAllowlist` say WHERE to look, the lease fields say WHO
216+
* may see the inventory, and none of them states WHICH device. Dropping any of them would resolve
217+
* a scoped or leased recording outside the scope or lease it started under. No request
218+
* device/identity selector reaches here: `assertManifestBelongsToRequest` proves the resolved
219+
* device against the manifest.
216220
*/
217221
async function resolveManifestDevice(
218222
params: RecordRuntimeHandlerParams,
@@ -221,6 +225,7 @@ async function resolveManifestDevice(
221225
const { iosSimulatorDeviceSet, androidDeviceAllowlist } = params.req.flags ?? {};
222226
const selector: ResolveDeviceFlags = {
223227
platform: recorded.family,
228+
...leaseDiscoveryContextFromFlags(params.req.flags),
224229
...(iosSimulatorDeviceSet === undefined ? {} : { iosSimulatorDeviceSet }),
225230
...(androidDeviceAllowlist === undefined ? {} : { androidDeviceAllowlist }),
226231
};

0 commit comments

Comments
 (0)