Skip to content

Commit fa06c8c

Browse files
authored
fix(daemon): fence managed readiness behind runtime admission (#2280)
1 parent 5bb3ea3 commit fa06c8c

28 files changed

Lines changed: 309 additions & 72 deletions

‎scripts/layering/architecture-ownership.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,10 +191,12 @@ export const ARCHITECTURE_OWNERSHIP = {
191191
exports: [
192192
'BindDeviceRuntime',
193193
'BindExactDeviceRuntime',
194+
'BoundDeviceIdentity',
194195
'InspectDeviceRuntimeFacts',
195196
'RequestRuntimeBindings',
196197
'RuntimeAdmissionBindings',
197198
'createRequestRuntimeBindings',
199+
'ensureBoundDeviceReady',
198200
],
199201
},
200202
{

‎src/daemon/__tests__/request-runtime-binding.test.ts‎

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { expect, test, vi } from 'vitest';
1+
import { beforeEach, expect, test, vi } from 'vitest';
22
import { applicationLifecycleOperationFacts } from '@agent-device/contracts/application-lifecycle-runtime';
33
import {
44
appLogAdmissionUse,
@@ -11,14 +11,23 @@ import {
1111
type DeviceRuntimeGateway,
1212
type RuntimeOwnerRef,
1313
localRuntimeOwner,
14+
managedLocalRuntimeOwner,
15+
providerRuntimeOwner,
1416
} from '@agent-device/contracts/platform-runtime';
1517
import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations';
1618
import { screenRecordingRecoveryUse } from '@agent-device/contracts/screen-recording-runtime-plan';
1719
import type { DeviceInfo } from '@agent-device/kernel/device';
1820
import { unavailableDeploymentSnapshotAndShutdownOperationFacts } from '../../__tests__/test-utils/runtime-operation-facts.ts';
1921
import { createDurableResourceEnvelope } from '@agent-device/capture-kit';
2022
import { acquireDurableCaptureRecoveryAuthorityBeforeDeadline } from '../durable-capture-recovery-authority.ts';
21-
import { createRequestRuntimeBindings } from '../request-runtime-binding.ts';
23+
import {
24+
createRequestRuntimeBindings,
25+
ensureBoundDeviceReady,
26+
} from '../request-runtime-binding.ts';
27+
import { ensureDeviceReady } from '../device-ready.ts';
28+
import { admitRuntimeUse } from '../runtime-admission.ts';
29+
30+
vi.mock('../device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) }));
2231

2332
const inspectPlan = resolveLogsRuntimePlan({ action: 'path' });
2433
const doctorPlan = resolveLogsRuntimePlan({ action: 'doctor' });
@@ -35,6 +44,72 @@ const scope = {
3544
};
3645

3746
const admitDeviceClaim = async () => {};
47+
const mockEnsureDeviceReady = vi.mocked(ensureDeviceReady);
48+
49+
beforeEach(() => {
50+
mockEnsureDeviceReady.mockReset();
51+
mockEnsureDeviceReady.mockResolvedValue(undefined);
52+
});
53+
54+
test('bound readiness preserves local behavior after the binding fence', async () => {
55+
const selected = device('ready-after-bind');
56+
const options = { focusExisting: true };
57+
58+
await ensureBoundDeviceReady({ device: selected, owner: localRuntimeOwner('android') }, options);
59+
60+
expect(mockEnsureDeviceReady).toHaveBeenCalledWith(selected, options);
61+
});
62+
63+
test('bound readiness leaves provider-owned devices alone', async () => {
64+
await ensureBoundDeviceReady({
65+
device: device('provider-ready'),
66+
owner: providerRuntimeOwner('test', 'provider-ready'),
67+
});
68+
69+
expect(mockEnsureDeviceReady).not.toHaveBeenCalled();
70+
});
71+
72+
test('bound readiness refuses managed devices without allocator confirmation', async () => {
73+
await expect(
74+
ensureBoundDeviceReady({
75+
device: device('managed-ready'),
76+
owner: managedLocalRuntimeOwner('simlock-test'),
77+
}),
78+
).rejects.toMatchObject({
79+
code: 'UNSUPPORTED_OPERATION',
80+
details: { reason: 'managed-readiness-unavailable' },
81+
});
82+
expect(mockEnsureDeviceReady).not.toHaveBeenCalled();
83+
});
84+
85+
test('runtime readiness follows allocator claim admission', async () => {
86+
const events: string[] = [];
87+
const runtime = makeGateway();
88+
const admit = vi.fn(async () => {
89+
events.push('claim');
90+
});
91+
const bindings = createRequestRuntimeBindings({
92+
gateway: runtime.gateway,
93+
scope,
94+
admitDeviceClaim: admit,
95+
});
96+
mockEnsureDeviceReady.mockImplementation(async () => {
97+
events.push('ready');
98+
});
99+
100+
const admission = await admitRuntimeUse({
101+
command: 'logs',
102+
device: device('claim-order'),
103+
use: appLogInspectUse,
104+
inspectFacts: bindings.inspectFacts,
105+
bindDevice: bindings.bindDevice,
106+
readiness: {},
107+
});
108+
109+
expect(admission.type).toBe('runtime');
110+
expect(events).toEqual(['claim', 'ready']);
111+
await bindings[Symbol.asyncDispose]();
112+
});
38113

39114
test('request runtime binding caches one broad owner and projects each declared use', async () => {
40115
const runtime = makeGateway();

‎src/daemon/__tests__/session-device-resolution.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
import { getRunnerSessionSnapshot } from '@agent-device/platform-apple/runner/operations';
1010
import { resolveTargetDevice } from '../../core/dispatch-resolve.ts';
1111
import { isActiveProviderDevice } from '../../provider-device-runtime.ts';
12+
import { ensureDeviceReady } from '../device-ready.ts';
1213

1314
vi.mock('@agent-device/platform-apple/runner/operations', () => ({
1415
getRunnerSessionSnapshot: vi.fn(async () => null),
@@ -26,13 +27,16 @@ vi.mock('../device-ready.ts', () => ({
2627
const mockGetRunnerSessionSnapshot = vi.mocked(getRunnerSessionSnapshot);
2728
const mockResolveTargetDevice = vi.mocked(resolveTargetDevice);
2829
const mockIsActiveProviderDevice = vi.mocked(isActiveProviderDevice);
30+
const mockEnsureDeviceReady = vi.mocked(ensureDeviceReady);
2931

3032
beforeEach(() => {
3133
mockGetRunnerSessionSnapshot.mockReset();
3234
mockGetRunnerSessionSnapshot.mockResolvedValue(null);
3335
mockResolveTargetDevice.mockReset();
3436
mockIsActiveProviderDevice.mockReset();
3537
mockIsActiveProviderDevice.mockReturnValue(false);
38+
mockEnsureDeviceReady.mockReset();
39+
mockEnsureDeviceReady.mockResolvedValue(undefined);
3640
});
3741

3842
const iosSimulatorSession: SessionState = {
@@ -73,14 +77,23 @@ test('resolveCommandDevice keeps an existing session for a platform-only filter'
7377
await resolveCommandDevice({
7478
session: iosSimulatorSession,
7579
flags: { platform: 'ios' },
76-
ensureReady: false,
7780
}),
7881
);
7982

8083
expect(device).toBe(iosSimulatorSession.device);
8184
expect(mockResolveTargetDevice).not.toHaveBeenCalled();
8285
});
8386

87+
test('resolveCommandDevice does not prepare a sessionless device', async () => {
88+
const device = { ...iosSimulatorSession.device, id: 'sessionless-sim' };
89+
mockResolveTargetDevice.mockResolvedValue(device);
90+
91+
await resolveCommandDevice({ session: undefined, flags: { platform: 'ios' } });
92+
93+
expect(mockResolveTargetDevice).toHaveBeenCalledOnce();
94+
expect(mockEnsureDeviceReady).not.toHaveBeenCalled();
95+
});
96+
8497
test('refreshSessionDeviceIfNeeded keeps provider-owned iOS simulators out of local refresh', async () => {
8598
mockIsActiveProviderDevice.mockReturnValue(true);
8699

‎src/daemon/__tests__/snapshot-runtime-binding.test.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
import type { DeviceInfo } from '@agent-device/kernel/device';
2-
import { expect, test } from 'vitest';
2+
import { expect, test, vi } from 'vitest';
3+
import { resolveSnapshotRuntimePlan } from '@agent-device/contracts/platform-runtime-operations';
34
import { IOS_SIMULATOR } from '../../__tests__/test-utils/device-fixtures.ts';
45
import { makeIosSession } from '../../__tests__/test-utils/session-factories.ts';
56
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
67
import type { BindDeviceRuntime } from '../request-runtime-binding.ts';
7-
import { resolveBoundSnapshotCaptureRuntime } from '../snapshot-runtime-binding.ts';
8+
import {
9+
admitAndBindSnapshotCapture,
10+
resolveBoundSnapshotCaptureRuntime,
11+
} from '../snapshot-runtime-binding.ts';
812
import type { DaemonRequest } from '../types.ts';
913
import { snapshotRuntimeFixture } from './snapshot-runtime-fixture.ts';
14+
import { ensureDeviceReady } from '../device-ready.ts';
15+
16+
vi.mock('../device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) }));
17+
18+
const mockEnsureDeviceReady = vi.mocked(ensureDeviceReady);
1019

1120
// The owning interface (ADR 0019 §9): one plan, one facts-first admission, one bind — and the
1221
// bind target is whatever the admission was minted for, read back by token identity. The binder
@@ -46,3 +55,29 @@ test('the owning interface binds exactly the session device the facts were admit
4655
expect(resolved.ok).toBe(true);
4756
expect(boundDevices).toEqual([IOS_SIMULATOR]);
4857
});
58+
59+
test('sessionless capture readiness follows runtime binding', async () => {
60+
const fixture = snapshotRuntimeFixture();
61+
const events: string[] = [];
62+
mockEnsureDeviceReady.mockReset();
63+
mockEnsureDeviceReady.mockImplementation(async () => {
64+
events.push('ready');
65+
});
66+
const recordingBind: BindDeviceRuntime = async (device, use) => {
67+
events.push('bind');
68+
return await fixture.bindDevice(device, use);
69+
};
70+
71+
const resolved = await admitAndBindSnapshotCapture({
72+
command: 'snapshot',
73+
device: IOS_SIMULATOR,
74+
session: undefined,
75+
plan: resolveSnapshotRuntimePlan({ customActions: false, hasActiveApp: true }),
76+
inspectFacts: fixture.inspectFacts,
77+
bindDevice: recordingBind,
78+
readiness: {},
79+
});
80+
81+
expect(resolved.ok).toBe(true);
82+
expect(events).toEqual(['bind', 'ready']);
83+
});

‎src/daemon/app-event-runtime.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { DaemonCommandContext } from './context.ts';
88
import { admitRuntimeUse, type RuntimeAdmissionBindings } from './runtime-admission.ts';
99
import { runtimeExecutionFromContext } from './snapshot-runtime-capture-input.ts';
1010
import type { DaemonFailureResponse } from './response.ts';
11+
import type { DeviceReadyOptions } from './device-ready.ts';
1112

1213
/**
1314
* What the admit-then-bind step reports: either the refusal an unadmitted cell produced, or the
@@ -55,16 +56,21 @@ async function executeAppEvent(
5556
* argument is read.
5657
*/
5758
export async function resolveBoundAppEventRuntime(
58-
params: Readonly<{ device: DeviceInfo; positionals: readonly string[] }> &
59+
params: Readonly<{
60+
device: DeviceInfo;
61+
positionals: readonly string[];
62+
readiness?: DeviceReadyOptions;
63+
}> &
5964
RuntimeAdmissionBindings,
6065
): Promise<ResolvedAppEventExecution> {
61-
const { device, positionals, inspectFacts, bindDevice } = params;
66+
const { device, positionals, inspectFacts, bindDevice, readiness } = params;
6267
const admission = await admitRuntimeUse({
6368
command: 'trigger-app-event',
6469
device,
6570
use: appEventRuntimeUse,
6671
inspectFacts,
6772
bindDevice,
73+
readiness,
6874
});
6975
if (admission.type === 'response') return { ok: false, response: admission.response };
7076
const runtime = admission.runtime;

‎src/daemon/handlers/__tests__/session-clipboard.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,12 @@ import type {
1717
BindDeviceRuntime,
1818
InspectDeviceRuntimeFacts,
1919
} from '../../request-runtime-binding.ts';
20-
import { makeSession, makeSessionStore, mockResolveTargetDevice } from './session-test-harness.ts';
20+
import {
21+
makeSession,
22+
makeSessionStore,
23+
mockEnsureDeviceReady,
24+
mockResolveTargetDevice,
25+
} from './session-test-harness.ts';
2126
import { handleSessionClipboardCommand } from '../session-clipboard.ts';
2227

2328
// File-scoped id, not a shared literal: this owner binding's `local-family` kind reaches the real
@@ -97,6 +102,21 @@ test('clipboard read admits clipboardReadUse and reports the platform-labelled t
97102
expect(spies.writeClipboard).not.toHaveBeenCalled();
98103
});
99104

105+
test('clipboard readiness follows runtime binding', async () => {
106+
const spies = harness({ read: available, write: available });
107+
const response = await handleSessionClipboardCommand({ ...request(['read']), ...spies });
108+
109+
expect(response.ok).toBe(true);
110+
expect(spies.bindDevice).toHaveBeenCalledTimes(1);
111+
expect(mockEnsureDeviceReady).toHaveBeenCalledTimes(1);
112+
const bindSpy = vi.mocked(spies.bindDevice);
113+
const bindOrder = bindSpy.mock.invocationCallOrder[0];
114+
const readyOrder = mockEnsureDeviceReady.mock.invocationCallOrder[0];
115+
expect(bindOrder).toBeDefined();
116+
expect(readyOrder).toBeDefined();
117+
expect(bindOrder!).toBeLessThan(readyOrder!);
118+
});
119+
100120
test('clipboard write joins its positionals and reports the code-point length', async () => {
101121
const spies = harness({ read: available, write: available });
102122
const response = await handleSessionClipboardCommand({

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

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { isWholeScreenRecordingScope } from '@agent-device/contracts/recording';
1111
import { deviceIdentity, sameDeviceIdentity } from '@agent-device/kernel/device';
1212
import { AppError, normalizeError } from '@agent-device/kernel/errors';
1313
import { resolveTargetDevice } from '../../core/dispatch-resolve.ts';
14-
import { ensureDeviceReady } from '../device-ready.ts';
14+
import { ensureBoundDeviceReady } from '../request-runtime-binding.ts';
1515
import type { ScreenRecordingAdmissionLedger } from '../screen-recording-admission-ledger.ts';
1616
import {
1717
adoptStartedScreenRecording,
@@ -69,11 +69,18 @@ async function handleRecordCommandUnsafe(
6969
if (plan.kind === 'start' && !isWholeScreenRecordingScope(scope) && !existingSession) {
7070
return missingAppSessionResponse(req);
7171
}
72-
const session = await resolveRecordingSession(params, existingSession);
72+
const resolvedSession = await resolveRecordingSession(params, existingSession);
73+
const { session } = resolvedSession;
7374
if (plan.kind === 'start') {
74-
return await startRecording(params, session, prepareRecordingRequest(req), plan.use);
75+
return await startRecording(
76+
params,
77+
session,
78+
prepareRecordingRequest(req),
79+
plan.use,
80+
resolvedSession.needsReadiness,
81+
);
7582
}
76-
return await stopRecording(params, session, plan.kind);
83+
return await stopRecording(params, session, plan.kind, resolvedSession.needsReadiness);
7784
}
7885

7986
function resolveRecordPlan(req: DaemonRequest, session: SessionState | undefined) {
@@ -91,24 +98,25 @@ function resolveRecordPlan(req: DaemonRequest, session: SessionState | undefined
9198
async function resolveRecordingSession(
9299
params: RecordRuntimeHandlerParams,
93100
existing: SessionState | undefined,
94-
): Promise<SessionState> {
101+
): Promise<Readonly<{ session: SessionState; needsReadiness: boolean }>> {
95102
const device = existing?.device ?? (await resolveTargetDevice(params.req.flags ?? {}));
96103
await params.retainDeviceExecutionLock(device.id);
97-
if (existing) return existing;
98-
await ensureDeviceReady(device);
99-
return createRecordOnlySession(params, device);
104+
if (existing) return { session: existing, needsReadiness: false };
105+
return { session: createRecordOnlySession(params, device), needsReadiness: true };
100106
}
101107

102108
async function startRecording(
103109
params: RecordRuntimeHandlerParams,
104110
session: SessionState,
105111
prepared: ReturnType<typeof prepareRecordingRequest>,
106112
use: typeof screenRecordingStartUse,
113+
needsReadiness: boolean,
107114
): Promise<DaemonResponse> {
108115
if (session.screenRecording) {
109116
return { ok: false, error: { code: 'INVALID_ARGS', message: 'recording already in progress' } };
110117
}
111118
const admission = await params.bindDevice(session.device, screenRecordingAdmissionUse);
119+
if (needsReadiness) await ensureBoundDeviceReady(admission);
112120
const startFact = admission.facts.screenRecordingStart;
113121
if (!startFact.available) return buildRecordingUnsupportedResponse(startFact);
114122
const runtime = await params.bindDevice(session.device, use);
@@ -195,6 +203,7 @@ async function stopRecording(
195203
params: RecordRuntimeHandlerParams,
196204
session: SessionState,
197205
kind: 'stop-live' | 'stop-recovery',
206+
needsReadiness: boolean,
198207
): Promise<DaemonResponse> {
199208
let completion;
200209
try {
@@ -205,7 +214,7 @@ async function stopRecording(
205214
sessionName: params.sessionName,
206215
sessionStore: params.sessionStore,
207216
})
208-
: await finishRecovered(params, session);
217+
: await finishRecovered(params, session, needsReadiness);
209218
} catch (error) {
210219
deleteTerminalRecordOnlySession(params, session);
211220
throw error;
@@ -237,7 +246,11 @@ function deleteTerminalRecordOnlySession(
237246
}
238247
}
239248

240-
async function finishRecovered(params: RecordRuntimeHandlerParams, session: SessionState) {
249+
async function finishRecovered(
250+
params: RecordRuntimeHandlerParams,
251+
session: SessionState,
252+
needsReadiness: boolean,
253+
) {
241254
const resourcePath = screenRecordingDurableResource.store.resolvePath(
242255
params.sessionStore.resolveSessionDir(params.sessionName),
243256
);
@@ -270,6 +283,7 @@ async function finishRecovered(params: RecordRuntimeHandlerParams, session: Sess
270283
screenRecordingRecoveryUse,
271284
recoveryScope,
272285
);
286+
if (needsReadiness) await ensureBoundDeviceReady(runtime);
273287
return createScreenRecordingRecoveryControl({ runtime, dispose: async () => {} });
274288
},
275289
});

0 commit comments

Comments
 (0)