Skip to content

Commit c13c054

Browse files
committed
fix(daemon): take record stop recovery from the manifest, never from a host sweep (#3674)
A named session the daemon no longer holds was still answered on an unconstrained resolveTargetDevice for record stop, so a multi-boot host replied AMBIGUOUS_MATCH before the durable manifest — the one thing that can answer that stop — was read. The named-session rule now lives at the handler's only device selection: a request addressed to a session takes its device from a decodable manifest envelope, and a start, or a stop with nothing decodable to recover from, refuses with the typed named-session error. Selector and sessionless lanes keep their targets, and the manifest's own session and device proofs still fail closed. Co-Authored-Worked-On-By: Claude
1 parent 7be63bc commit c13c054

5 files changed

Lines changed: 235 additions & 29 deletions

File tree

‎packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@ import type {
88
ScreenRecordingCompletion,
99
} from '@agent-device/contracts/screen-recording-runtime';
1010
import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope';
11-
import { deviceIdentity, sameDeviceIdentity, type DeviceInfo } from '@agent-device/kernel/device';
11+
import {
12+
deviceIdentity,
13+
sameDeviceIdentity,
14+
type DeviceIdentity,
15+
type DeviceInfo,
16+
} from '@agent-device/kernel/device';
1217
import { AppError } from '@agent-device/kernel/errors';
1318
import { isRecord } from '@agent-device/kernel/record';
1419
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
@@ -70,6 +75,21 @@ export function screenRecordingManifestIsTerminal(params: ScreenRecordingManifes
7075
return record.status === 'decoded' && record.envelope.lifecycle === 'completed';
7176
}
7277

78+
/**
79+
* The device a stop without a held session must be answered on: the one the session's durable
80+
* manifest names, when a decodable manifest exists. `undefined` means there is nothing to recover
81+
* from, and a caller that addressed a session answers on the session instead of choosing a device.
82+
* The device is not re-picked from the host; it is read from the manifest the named session
83+
* addresses, and `assertManifestBelongsToRequest` still fails the request closed when the
84+
* resolved device or the session address does not match what the manifest recorded.
85+
*/
86+
export function screenRecordingManifestDevice(
87+
params: ScreenRecordingManifestParams,
88+
): DeviceIdentity | undefined {
89+
const { record } = readSessionManifest(params);
90+
return record.status === 'decoded' ? record.envelope.device : undefined;
91+
}
92+
7393
function readSessionManifest(params: ScreenRecordingManifestParams): Readonly<{
7494
resourcePath: string;
7595
record: DurableCaptureResourceRecord<'screen-recording'>;

‎packages/daemon/src/server/__tests__/request-router-named-session.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,24 @@ test('a record start naming a missing session answers on the session, not on app
130130
expect(listings.count).toBe(0);
131131
});
132132

133+
test('a record stop naming a missing session answers on the session, not on a host sweep', async () => {
134+
// The daemon-restart recovery (#3674): the durable manifest is the only thing that can answer
135+
// this stop, and the manifest is addressed by the session — so with two booted devices the
136+
// answer is still the typed session refusal or the manifest's own verdict, never the
137+
// AMBIGUOUS_MATCH an unconstrained sweep of this inventory would answer.
138+
const listings = { count: 0 };
139+
const { handler } = makeHandler(listings);
140+
141+
const response = await handler(request({ command: 'record', positionals: ['stop'] }));
142+
143+
expect(response.ok).toBe(false);
144+
if (response.ok) return;
145+
expect(response.error.code).toBe('SESSION_NOT_FOUND');
146+
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
147+
expect(response.error.details?.session).toBe(LOST_SESSION);
148+
expect(listings.count).toBe(0);
149+
});
150+
133151
test('the same command with no session named still resolves a device sessionlessly', async () => {
134152
// The closest negative: same daemon, same two booted simulators, same command. What changes is
135153
// only whether the caller named a session, and that is what the answer must turn on.

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

Lines changed: 104 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { expect, test, vi } from 'vitest';
22
import fs from 'node:fs';
33
import path from 'node:path';
44
import { mkdtempForTestSync } from '@agent-device/test-kit';
5+
import { AppError } from '@agent-device/kernel/errors';
56
import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store';
67
import {
78
expectDecodedCompletedRecording,
@@ -10,22 +11,33 @@ import {
1011
} from './record-runtime.fixtures.ts';
1112

1213
// The stop lane that runs WITHOUT a held session resolves its device through the selection
13-
// dispatch. The daemon-restart tests below pin that lane, so the dispatch answers with the
14-
// harness device here; the live-handle tests never reach it because their session is held.
15-
const RESTART_SELECTED_DEVICE = {
14+
// dispatch. On a host that answers anything, an unconstrained request is exactly the #3674
15+
// symptom, so the dispatch double here behaves like a multi-device host: it only answers a
16+
// request that states a device identity, and an unconstrained one gets the ambiguity a
17+
// multi-boot host really returns. The restart tests below pass only while the recovery lane
18+
// resolves from the manifest instead of sweeping the host.
19+
const RESTART_RECORDED_DEVICE = {
1620
platform: 'android',
1721
id: 'emulator-5554',
1822
name: 'Pixel',
1923
kind: 'emulator',
2024
} as const;
25+
const resolveTargetDeviceMock = vi.fn(async (flags: { udid?: string; serial?: string } = {}) => {
26+
if (flags.serial === RESTART_RECORDED_DEVICE.id || flags.udid === RESTART_RECORDED_DEVICE.id) {
27+
return { ...RESTART_RECORDED_DEVICE };
28+
}
29+
throw new AppError('AMBIGUOUS_MATCH', 'Multiple attached devices detected');
30+
});
2131
vi.mock('@agent-device/device-selection/dispatch-resolve', () => ({
22-
resolveTargetDevice: vi.fn(async () => ({ ...RESTART_SELECTED_DEVICE })),
32+
resolveTargetDevice: (...args: unknown[]) =>
33+
resolveTargetDeviceMock(...(args as [Record<string, string> | undefined])),
2334
}));
2435

2536
test('record stop after a daemon restart replays the completed export for the named session', async () => {
2637
// The #3674 state itself: sessions are memory-only, so a restart drops `recording`, while the
2738
// on-disk manifest survives. The caller still names the session (the only address that finds
28-
// the manifest at all), and `help record` promises the completed recording on that stop.
39+
// the manifest at all), and `help record` promises the completed recording on that stop — even
40+
// on a host whose unconstrained resolution would answer AMBIGUOUS_MATCH.
2941
const harness = makeRecordRuntimeHarness('record-runtime-restart-stop-');
3042
const outPath = path.join(
3143
mkdtempForTestSync('record-runtime-restart-stop-output-'),
@@ -37,9 +49,93 @@ test('record stop after a daemon restart replays the completed export for the na
3749
const ref = harness.sessionStore.lookup(harness.sessionName);
3850
if (!ref) throw new Error('Expected the stopped recording session');
3951
harness.sessionStore.retire(ref);
52+
resolveTargetDeviceMock.mockClear();
4053

4154
const recovered = await harness.run(['stop'], { sessionExplicit: true });
4255

56+
expect(recovered).toMatchObject({
57+
ok: true,
58+
data: { recording: 'stopped', outPath, recordingBackend: 'adb screenrecord' },
59+
});
60+
// The recovery re-resolves the manifest's exact device, never an unconstrained sweep.
61+
expect(resolveTargetDeviceMock).toHaveBeenCalledWith(
62+
expect.objectContaining({ serial: 'emulator-5554' }),
63+
);
64+
});
65+
66+
test('record stop for a named session with no decodable manifest refuses on the session', async () => {
67+
// No manifest means there is nothing to recover from and nothing to take a device from: the
68+
// answer is the named-session refusal, and the host is never swept for a device.
69+
const harness = makeRecordRuntimeHarness('record-runtime-restart-stop-no-manifest-');
70+
const ref = harness.sessionStore.lookup(harness.sessionName);
71+
if (!ref) throw new Error('Expected the published session');
72+
harness.sessionStore.retire(ref);
73+
74+
const response = await harness.run(['stop'], { sessionExplicit: true });
75+
76+
expect(response).toMatchObject({
77+
ok: false,
78+
error: { code: 'SESSION_NOT_FOUND', details: { reason: 'named_session_not_found' } },
79+
});
80+
expect(resolveTargetDeviceMock).not.toHaveBeenCalled();
81+
});
82+
83+
test('a named stop recovery keeps failing closed when the manifest names another session', async () => {
84+
// The manifest-first lane reads the envelope before resolving, so the session proof must stay
85+
// on the served path: a manifest whose sessionId belongs to another address never answers.
86+
const harness = makeRecordRuntimeHarness('record-runtime-restart-stop-cross-session-', {
87+
sessionName: 'recording-a',
88+
});
89+
const outPath = path.join(
90+
mkdtempForTestSync('record-runtime-restart-stop-cross-session-output-'),
91+
'capture.mp4',
92+
);
93+
fs.writeFileSync(outPath, 'mp4');
94+
await harness.run(['start', outPath]);
95+
await harness.run(['stop']);
96+
const resourcePath = recordingResourcePath(harness.sessionStore, harness.sessionName);
97+
const record = screenRecordingResourceStore.read(resourcePath);
98+
if (record.status !== 'decoded') throw new Error('Expected decoded recording manifest');
99+
screenRecordingResourceStore.write(resourcePath, {
100+
...record.envelope,
101+
sessionId: 'recording-b',
102+
});
103+
const ref = harness.sessionStore.lookup(harness.sessionName);
104+
if (!ref) throw new Error('Expected the stopped recording session');
105+
harness.sessionStore.retire(ref);
106+
107+
const response = await harness.run(['stop'], { sessionExplicit: true });
108+
109+
expect(response).toMatchObject({
110+
ok: false,
111+
error: { code: 'COMMAND_FAILED', details: { reason: 'runtime-contract-invalid' } },
112+
});
113+
});
114+
115+
test('record stop after a daemon restart answers an explicitly targeted request from its device', async () => {
116+
// The closest positive: the same unheld named session, but the request states the very device
117+
// the manifest names, so the selector lane serves the recovery — the stated target still wins.
118+
const harness = makeRecordRuntimeHarness('record-runtime-restart-stop-targeted-');
119+
const outPath = path.join(
120+
mkdtempForTestSync('record-runtime-restart-stop-targeted-output-'),
121+
'capture.mp4',
122+
);
123+
fs.writeFileSync(outPath, 'mp4');
124+
await harness.run(['start', outPath]);
125+
await harness.run(['stop']);
126+
const ref = harness.sessionStore.lookup(harness.sessionName);
127+
if (!ref) throw new Error('Expected the stopped recording session');
128+
harness.sessionStore.retire(ref);
129+
130+
const recovered = await harness.run(
131+
['stop'],
132+
{ sessionExplicit: true },
133+
{
134+
platform: 'android',
135+
serial: 'emulator-5554',
136+
},
137+
);
138+
43139
expect(recovered).toMatchObject({
44140
ok: true,
45141
data: { recording: 'stopped', outPath, recordingBackend: 'adb screenrecord' },
@@ -58,6 +154,7 @@ test('record start after a daemon restart still refuses the named missing sessio
58154
const ref = harness.sessionStore.lookup(harness.sessionName);
59155
if (!ref) throw new Error('Expected the live recording session');
60156
harness.sessionStore.retire(ref);
157+
resolveTargetDeviceMock.mockClear();
61158

62159
const response = await harness.run(['start', outPath], { sessionExplicit: true });
63160

@@ -66,6 +163,8 @@ test('record start after a daemon restart still refuses the named missing sessio
66163
error: { code: 'SESSION_NOT_FOUND', details: { reason: 'named_session_not_found' } },
67164
});
68165
expect(harness.runtime.start).toHaveBeenCalledOnce();
166+
// A start has no manifest to recover from, so the refusal answers before any device is sought.
167+
expect(resolveTargetDeviceMock).not.toHaveBeenCalled();
69168
});
70169

71170
test('record stop with a live handle binds no runtime and terminalizes the durable record', async () => {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ export function makeRecordRuntimeHarness(
7575
sessionName,
7676
sessionStore,
7777
runtime,
78-
run: (positionals: string[], meta?: DaemonRequest['meta']) =>
78+
run: (positionals: string[], meta?: DaemonRequest['meta'], flags?: DaemonRequest['flags']) =>
7979
handleRecordCommand({
8080
platformServices: daemonPlatformServicesFixture(),
8181
...common,
@@ -84,7 +84,7 @@ export function makeRecordRuntimeHarness(
8484
session: sessionName,
8585
command: 'record',
8686
positionals,
87-
flags: {},
87+
flags: flags ?? {},
8888
...(meta ? { meta } : {}),
8989
},
9090
}),

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

Lines changed: 90 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,18 @@ import {
1818
} from '@agent-device/contracts/screen-recording-runtime-plan';
1919
import { isWholeScreenRecordingScope } from '@agent-device/contracts/recording';
2020
import { AppError, normalizeError } from '@agent-device/kernel/errors';
21-
import type { Platform } from '@agent-device/kernel/device';
22-
import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve';
21+
import { namesSessionExplicitly } from '@agent-device/kernel/contracts';
22+
import {
23+
deviceIdentityFlag,
24+
type DeviceIdentity,
25+
type DeviceInfo,
26+
type Platform,
27+
} from '@agent-device/kernel/device';
28+
import {
29+
resolveTargetDevice,
30+
type ResolveDeviceFlags,
31+
} from '@agent-device/device-selection/dispatch-resolve';
32+
import { hasDeviceSelectionInput } from '../../core/device/device-selector-intent.ts';
2333
import { ensureBoundDeviceReady } from '../../core/request-runtime-binding.ts';
2434
import { type ScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger';
2535
import { createScreenRecordingRecoveryControl } from '@agent-device/capture-kit/screen-recording-recovery';
@@ -31,6 +41,7 @@ import {
3141
} from '@agent-device/capture-kit/screen-recording-session-resource';
3242
import {
3343
resolveScreenRecordingStopRecovery,
44+
screenRecordingManifestDevice,
3445
screenRecordingManifestIsTerminal,
3546
} from '@agent-device/capture-kit/screen-recording-stop-recovery';
3647
import { resolveSessionScope } from '../session-routing.ts';
@@ -100,25 +111,19 @@ async function handleRecordCommandUnsafe(
100111
const existingRef = sessionStore.lookup(sessionName);
101112
const existingSession = existingRef?.session;
102113
const { plan, scope } = resolveRecordPlan(req, existingSession);
103-
// Only the start half can be answered on a device, so only it answers on the session: a named
104-
// missing session refuses before any device is chosen, ahead of the record-specific refusals.
105-
// The stop half must reach the durable manifest first — after a daemon restart the memory-only
106-
// session is gone for exactly the callers whose manifest the named session addresses, and the
107-
// recovery lane proves the manifest's session and device before serving anything.
108-
// Only that branch pays the function-scoped import (ADR-0019 loading shape).
109-
if (!existingSession && plan.kind === 'start') {
110-
const { requireNamedSessionHoldsDevice } =
111-
await import('../../core/explicit-session-resolution.ts');
112-
requireNamedSessionHoldsDevice({
113-
req,
114-
sessionAddress: sessionName,
115-
session: existingSession,
116-
});
117-
}
118-
if (plan.kind === 'start' && !isWholeScreenRecordingScope(scope) && !existingSession) {
114+
// The app-scope refusal states what a start needs beyond a device, so it answers only for a
115+
// request that can still reach one: a start naming a session this daemon does not hold is
116+
// answered on the session first, at resolveRecordingSession below, where every record lane
117+
// meets the one named-session rule at the only device selection the handler makes.
118+
if (
119+
plan.kind === 'start' &&
120+
!isWholeScreenRecordingScope(scope) &&
121+
!existingSession &&
122+
!namesSessionWithoutTarget(req)
123+
) {
119124
return missingAppSessionResponse(req);
120125
}
121-
const resolvedSession = await resolveRecordingSession(params, existingRef);
126+
const resolvedSession = await resolveRecordingSession(params, existingRef, plan);
122127
const { session } = resolvedSession;
123128
if (plan.kind === 'start') {
124129
return await startRecording(
@@ -154,13 +159,77 @@ function resolveRecordPlan(req: DaemonRequest, session: SessionState | undefined
154159
async function resolveRecordingSession(
155160
params: RecordRuntimeHandlerParams,
156161
ref: SessionRef | undefined,
162+
plan: ReturnType<typeof resolveRecordPlan>['plan'],
157163
): Promise<Readonly<{ session: SessionState; ref?: SessionRef; needsReadiness: boolean }>> {
158-
const device = ref?.session.device ?? (await resolveTargetDevice(params.req.flags ?? {}));
159-
await params.retainDeviceExecutionLock(device.id);
160164
if (ref) return { session: params.sessionStore.requireCurrent(ref), ref, needsReadiness: false };
165+
const device = await resolveUnheldRecordingDevice(params, plan);
166+
await params.retainDeviceExecutionLock(device.id);
161167
return { session: createRecordOnlySession(params, device), needsReadiness: true };
162168
}
163169

170+
/**
171+
* The device an unheld record request is answered on, and the single place the record handler
172+
* applies the named-session rule (#3674) at its only device selection.
173+
*
174+
* A request that names a session this daemon does not hold and states no device is answered from
175+
* the durable manifest the session address finds — never from an unconstrained sweep of the host,
176+
* which with several booted devices would answer `AMBIGUOUS_MATCH` (or, worse, silently pick a
177+
* different device) before the manifest is read. A decodable manifest carries the exact device the
178+
* recording was started on, so the stop recovery resolves that device; a start, or a stop with no
179+
* decodable manifest to recover from, refuses with the named-session error. The manifest's own
180+
* session and device are still proven against the request by `assertManifestBelongsToRequest`
181+
* before anything is served, so a manifest belonging to another session or device fails closed.
182+
*
183+
* The two shapes that keep their chosen target are unchanged: a request that never named a
184+
* session resolves sessionlessly from its flags, and one that states a device selector resolves
185+
* from it, with the manifest assertion failing the request closed when the stated device is not
186+
* the one the recording was started on.
187+
*/
188+
async function resolveUnheldRecordingDevice(
189+
params: RecordRuntimeHandlerParams,
190+
plan: ReturnType<typeof resolveRecordPlan>['plan'],
191+
): Promise<DeviceInfo> {
192+
const { req, sessionName } = params;
193+
if (!namesSessionWithoutTarget(req)) return await resolveTargetDevice(req.flags ?? {});
194+
if (plan.kind === 'stop-recovery') {
195+
const recorded = screenRecordingManifestDevice({
196+
sessionName,
197+
sessionStore: params.sessionStore,
198+
});
199+
if (recorded) {
200+
return await resolveManifestDevice(params, recorded);
201+
}
202+
}
203+
const { namedSessionNotFoundError } = await import('../../core/explicit-session-resolution.ts');
204+
throw namedSessionNotFoundError(sessionName);
205+
}
206+
207+
/** Whether this request is addressed to a session and leaves its device to the session. */
208+
function namesSessionWithoutTarget(req: DaemonRequest): boolean {
209+
return namesSessionExplicitly(req) && !hasDeviceSelectionInput(req.flags);
210+
}
211+
212+
/**
213+
* Re-resolves the exact device a durable manifest names, by the identity flag that family answers
214+
* to. Families without an identity flag keep the request's own selection — an address the manifest
215+
* recorded but the request cannot restate stays resolved as it always has been, and the
216+
* device-match assertion below still refuses a different device.
217+
*/
218+
async function resolveManifestDevice(
219+
params: RecordRuntimeHandlerParams,
220+
recorded: DeviceIdentity,
221+
): Promise<DeviceInfo> {
222+
const selector: ResolveDeviceFlags = { platform: recorded.family };
223+
const identityFlag = deviceIdentityFlag(recorded.family);
224+
if (!identityFlag) {
225+
// A family whose manifest identity no flag can restate keeps the request's own selection; the
226+
// manifest assertion still refuses anything but the device the recording was started on.
227+
return await resolveTargetDevice(params.req.flags ?? {});
228+
}
229+
selector[identityFlag] = recorded.id;
230+
return await resolveTargetDevice(selector);
231+
}
232+
164233
async function startRecording(
165234
params: RecordRuntimeHandlerParams,
166235
session: SessionState,

0 commit comments

Comments
 (0)