Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export const mockBindDeviceRuntime = vi.fn(
async (
device: DeviceInfo,
use,
_cache?: 'bypass',
loadLifecycleOperations: LifecycleOperationsLoader = applicationLifecycleRuntimeFixture,
) => narrowDeviceBinding(await readinessBinding(device, loadLifecycleOperations), use),
);
Expand Down Expand Up @@ -128,7 +129,8 @@ export async function handleSessionCommands(
params.bindDevice ??
(lifecycleOperationsLoader === undefined
? mockBindDeviceRuntime
: (device, use) => mockBindDeviceRuntime(device, use, lifecycleOperationsLoader)),
: (device, use, cache) =>
mockBindDeviceRuntime(device, use, cache, lifecycleOperationsLoader)),
platformResourceCleanup: params.platformResourceCleanup ?? platformResourceCleanupFixture(),
reconcileOrphanedDeviceClaim: async () => ({
status: 'retained',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { IOS_SIMULATOR } from '@agent-device/test-kit';
import { makeIosSession } from '../../__tests__/support/session-factories.ts';
import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts';
import { selectorCaptureFixture } from '../../__tests__/support/selector-capture-fixture.ts';
import { resolveSettleObservationCapture } from '../settle-observation-capture.ts';
import { resolveObservationCapture } from '../observation-capture.ts';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';

vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => {
Expand All @@ -14,18 +14,20 @@ vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => {
// #3510: the capture a `--settle` observation polls on a route whose action runtime use carries
// none. The guarantee it owes is producer identity with the command the caller runs next; the one it
// must not break is that settling never fails the action it follows. These pin which plan gets
// admitted, how often, and that every way an observation capture goes away degrades to no capture
// while disclosing its typed reason.
// admitted, how often, and that the owner itself discloses each of its three outcomes: a bound
// capture (admitted + bound), a declared refusal, or a retryable failure of its own machinery.

const unavailablePhase = ['settle_observation_capture_unavailable'];

/** Level included: a degrade the caller cannot see must not be info-only, which success drops. */
function disclosures(): { level: string | undefined; data: Record<string, unknown> }[] {
/** Everything the owner discloses, with level: a loss on an ok-answering route must not be info-only. */
function disclosures(): {
level: string | undefined;
phase: string;
data: Record<string, unknown>;
}[] {
return vi
.mocked(emitDiagnostic)
.mock.calls.flatMap(([event]) =>
event.phase === unavailablePhase[0] && event.data
? [{ level: event.level, data: event.data }]
event.phase?.startsWith('observation_capture_') && event.data
? [{ level: event.level, phase: event.phase, data: event.data }]
: [],
);
}
Expand All @@ -37,20 +39,34 @@ beforeEach(() => {
test('an available plan inspects once and binds once for the whole observation', async () => {
const fixture = selectorCaptureFixture();

const capture = await resolveSettleObservationCapture({
const outcome = await resolveObservationCapture({
command: 'back',
session: makeIosSession('settle', { appBundleId: 'com.example.app' }),
inspectFacts: fixture.inspectFacts,
platformServices: daemonPlatformServicesFixture(),
bindDevice: fixture.bindDevice,
});
if (!capture) throw new Error('expected an admitted capture');
if (outcome.kind !== 'captured') throw new Error('expected an admitted capture');

expect(fixture.inspections).toEqual([IOS_SIMULATOR]);
expect(fixture.binds).toEqual([IOS_SIMULATOR]);
// The success path is observable on the request's own record: one admitted and one bound entry
// name the cell that reached a runtime capture, so a live trace counts binds without a fake.
expect(disclosures()).toEqual([
{
level: 'info',
phase: 'observation_capture_admitted',
data: { command: 'back', plan: 'selector-active-app', deviceId: IOS_SIMULATOR.id },
},
{
level: 'info',
phase: 'observation_capture_bound',
data: { command: 'back', plan: 'selector-active-app', deviceId: IOS_SIMULATOR.id },
},
]);

await capture({});
await capture({});
await outcome.capture({});
await outcome.capture({});
expect(fixture.binds).toEqual([IOS_SIMULATOR]);
expect(fixture.captures).toHaveLength(2);
});
Expand Down Expand Up @@ -79,25 +95,33 @@ test.each([
async ({ refusal, session, operation, reason }) => {
const fixture = selectorCaptureFixture(refusal);

const capture = await resolveSettleObservationCapture({
const outcome = await resolveObservationCapture({
command: 'back',
session: session(),
inspectFacts: fixture.inspectFacts,
platformServices: daemonPlatformServicesFixture(),
bindDevice: fixture.bindDevice,
});

expect(capture).toBeUndefined();
// The discriminated kind is all a caching caller reads: `refused` is stable until its plan
// changes, and the owner discloses why.
expect(outcome).toEqual({ kind: 'refused' });
expect(fixture.binds).toEqual([]);
expect(disclosures()).toEqual([
{ level: 'warn', data: { command: 'back', outcome: 'refused', operation, reason } },
{
level: 'warn',
phase: 'observation_capture_unavailable',
data: { command: 'back', outcome: 'refused', operation, reason },
},
]);
},
);

// The two ways the owner's own machinery can fail the observation after a valid plan. Both are
// best-effort by contract: the command the loop follows must still run, and each is disclosed at
// `warn` — an info-only record is dropped on the success path, and these cells answer `ok: true`.
// The two ways the owner's own machinery can fail the observation. Both are best-effort by
// contract: the command the loop follows must still run, and each is disclosed at `warn` — an
// info-only record is dropped on the success path, and these cells answer `ok: true`. A probe
// failure never reaches admission, so it discloses no admitted entry; a bind failure admits first,
// which is what makes the two failures tell apart in a live trace while one kind covers both.
test.each([
// Apple's inspection reads the host's screen-recording state and re-throws on a cancelled probe.
['admission-probe-failed', Object.assign(new Error('probe cancelled'), { name: 'AbortError' })],
Expand All @@ -121,17 +145,35 @@ test.each([
},
};

const capture = await resolveSettleObservationCapture({
const resolution = await resolveObservationCapture({
command: 'back',
session: makeIosSession('settle', { appBundleId: 'com.example.app' }),
platformServices: daemonPlatformServicesFixture(),
...failing,
});

expect(capture).toBeUndefined();
// One kind covers both failures: a caching caller re-probes on it, unlike a stable refusal.
expect(resolution).toEqual({ kind: 'retryable' });
expect(fixture.binds).toEqual([]);
expect(disclosures()).toEqual([
{ level: 'warn', data: { command: 'back', outcome, errorName: failure.name } },
...(outcome === 'bind-failed'
? [
{
level: 'info' as const,
phase: 'observation_capture_admitted',
data: {
command: 'back',
plan: 'selector-active-app',
deviceId: IOS_SIMULATOR.id,
},
},
]
: []),
{
level: 'warn',
phase: 'observation_capture_unavailable',
data: { command: 'back', outcome, errorName: failure.name },
},
]);
},
);
127 changes: 127 additions & 0 deletions packages/daemon/src/core/observation-capture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import type { BoundSnapshotCapture } from './snapshot-runtime-binding.ts';
import { bindAdmittedSnapshotCapture } from './snapshot-runtime-binding.ts';
import { admitRuntimePlan } from './session-runtime-admission.ts';
import {
resolveSelectorCaptureRuntimePlan,
type SelectorCaptureRuntimePlan,
} from '@agent-device/contracts/platform-runtime-operations';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import type { RuntimeOperationUnavailability } from '@agent-device/contracts/platform-runtime';
import type { RuntimeAdmissionBindings } from './request-runtime-binding.ts';
import type { SessionState } from './session-state.ts';

/**
* The request-bound capture for an internal observation, on a request whose own action binding
* carries none: a coordinate-targeted `press`/`fill` (whose point use declares none) or a
* generic-route action (#3510). Those routes polled the legacy interactor while the commands the
* caller runs next read the request-bound runtime, and on an iOS simulator those are two projections
* of one tree.
*
* Admitting the `capture-only` plan the selector family polls under closes the split; where both
* paths already reached the same tree, the admitted operation resolves to the implementation used
* before. Observing is best-effort by contract, so nothing here may fail or cancel the work it
* follows: the result is one of three mutually exclusive kinds — a bound `capture`, a `refused`
* fact about the owner's declared support, or a `retryable` probe or bind failure. A caller that
* reuses the answer across observations keeps `refused` until its plan changes and re-probes only
* on `retryable`; it never restates what a probe or bind cost the observation. Every kind is
* disclosed where it is decided: `admitted` and `bound` at info, so a request's own record shows
* which cells reached a runtime capture, and the loss kinds at `warn` — an info-only degrade on a
* route that answers `ok: true` is dropped on the success path, which is the passing-unnoticed the
* loss disclosures guard against. Admitting through the side-effect-free facts probe and binding
* only on admission keeps an optional observation from building a command-facing refusal response,
* whose Apple branch live-probes the booted simulator set for a hint nothing shows.
*/
export async function resolveObservationCapture(
params: Readonly<{ command: string; session: SessionState }> & RuntimeAdmissionBindings,
): Promise<ObservationCaptureOutcome> {
const plan = resolveSelectorCaptureRuntimePlan({
hasActiveApp: params.session.appBundleId !== undefined,
intent: 'capture-only',
});
const admission = await admitObservationCapturePlan(params, plan);
if (admission === undefined) return { kind: 'retryable' };
if (!admission.admitted) {
return refused({
command: params.command,
operation: admission.operation,
reason: admission.fact.reason,
});
}
emitDiagnostic({
level: 'info',
phase: 'observation_capture_admitted',
data: { command: params.command, plan: plan.kind, deviceId: params.session.device.id },
});
try {
const capture = await bindAdmittedSnapshotCapture({
admission,
bindDevice: params.bindDevice,
platformServices: params.platformServices,
});
emitDiagnostic({
level: 'info',
phase: 'observation_capture_bound',
data: { command: params.command, plan: plan.kind, deviceId: params.session.device.id },
});
return { kind: 'captured', capture };
} catch (error) {
return retryable({ command: params.command, failure: 'bind-failed', error });
}
}

/** A failed facts probe is the owner's own machinery failing: the retryable kind, disclosed once here. */
async function admitObservationCapturePlan(
params: Readonly<{ command: string; session: SessionState }> & RuntimeAdmissionBindings,
plan: SelectorCaptureRuntimePlan,
) {
try {
return await admitRuntimePlan({
device: params.session.device,
plan,
inspectFacts: params.inspectFacts,
});
} catch (error) {
retryable({ command: params.command, failure: 'admission-probe-failed', error });
return undefined;
}
}

/** The three mutually exclusive answers; each carries only what its own branch decided. */
export type ObservationCaptureOutcome =
| Readonly<{ kind: 'captured'; capture: BoundSnapshotCapture }>
| Readonly<{ kind: 'refused' }>
| Readonly<{ kind: 'retryable' }>;

/** Discloses the declared refusal; the caller keeps it while its plan is unchanged. */
function refused(detail: {
command: string;
operation: string;
reason: RuntimeOperationUnavailability['reason'];
}): Readonly<{ kind: 'refused' }> {
emitDiagnostic({
level: 'warn',
phase: 'observation_capture_unavailable',
data: { ...detail, outcome: 'refused' },
});
return { kind: 'refused' };
}

/** Discloses a failure of the owner's own machinery; the caller may try again at the next observation. */
function retryable(detail: {
command: string;
failure: 'admission-probe-failed' | 'bind-failed';
error: unknown;
}): Readonly<{ kind: 'retryable' }> {
emitDiagnostic({
// `warn`, not info: a degrade on a route that answers `ok: true` must survive the success-path filter.
level: 'warn',
phase: 'observation_capture_unavailable',
// The error's name travels, never its message: request diagnostics keep user input out.
data: {
command: detail.command,
outcome: detail.failure,
errorName: (detail.error as Error | undefined)?.name,
},
});
return { kind: 'retryable' };
}
21 changes: 15 additions & 6 deletions packages/daemon/src/core/request-runtime-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type BindDeviceRuntime = <
>(
device: DeviceInfo,
use: RuntimeUse<PlatformRuntimeOperations, Required, Preferred, Conditional>,
cache?: 'bypass',
) => Promise<
BoundDeviceRuntime<RuntimeUse<PlatformRuntimeOperations, Required, Preferred, Conditional>>
>;
Expand Down Expand Up @@ -125,16 +126,24 @@ export function createRequestRuntimeBindings(params: {
return binding;
};

const bindDevice: BindDeviceRuntime = async (device, use) => {
const bindOrdinary = (device: DeviceInfo) =>
params.gateway
.bind({ device, intent: { kind: 'ordinary' }, scope: params.scope })
.then(async (binding) => await adoptBinding(cleanups, binding, params.scope))
.then(admitBinding);

const bindDevice: BindDeviceRuntime = async (device, use, cache) => {
params.admitDevice?.(device);
if (cache === 'bypass') {
return recordBoundMutations(
narrowDeviceBinding(await bindOrdinary(device), use),
params.dispatchLedger,
);
}
const key = JSON.stringify([deviceIdentityKey(deviceIdentity(device)), device.booted === true]);
let bindingPromise = bindings.get(key);
if (!bindingPromise) {
const intent: DeviceBindingIntent = { kind: 'ordinary' };
bindingPromise = params.gateway
.bind({ device, intent, scope: params.scope })
.then(async (binding) => await adoptBinding(cleanups, binding, params.scope))
.then(admitBinding);
bindingPromise = bindOrdinary(device);
bindings.set(key, bindingPromise);
void bindingPromise.catch(() => {
if (bindings.get(key) === bindingPromise) bindings.delete(key);
Expand Down
Loading
Loading