diff --git a/packages/daemon/src/__tests__/support/handlers/session-command-harness.ts b/packages/daemon/src/__tests__/support/handlers/session-command-harness.ts index 0a4a8cdb10..eead23dd64 100644 --- a/packages/daemon/src/__tests__/support/handlers/session-command-harness.ts +++ b/packages/daemon/src/__tests__/support/handlers/session-command-harness.ts @@ -76,6 +76,7 @@ export const mockBindDeviceRuntime = vi.fn( async ( device: DeviceInfo, use, + _cache?: 'bypass', loadLifecycleOperations: LifecycleOperationsLoader = applicationLifecycleRuntimeFixture, ) => narrowDeviceBinding(await readinessBinding(device, loadLifecycleOperations), use), ); @@ -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', diff --git a/packages/daemon/src/core/__tests__/settle-observation-capture.test.ts b/packages/daemon/src/core/__tests__/observation-capture.test.ts similarity index 59% rename from packages/daemon/src/core/__tests__/settle-observation-capture.test.ts rename to packages/daemon/src/core/__tests__/observation-capture.test.ts index b30c312b3a..6f3328d8ef 100644 --- a/packages/daemon/src/core/__tests__/settle-observation-capture.test.ts +++ b/packages/daemon/src/core/__tests__/observation-capture.test.ts @@ -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) => { @@ -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 }[] { +/** 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; +}[] { 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 }] : [], ); } @@ -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); }); @@ -79,7 +95,7 @@ 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, @@ -87,17 +103,25 @@ test.each([ 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' })], @@ -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 }, + }, ]); }, ); diff --git a/packages/daemon/src/core/observation-capture.ts b/packages/daemon/src/core/observation-capture.ts new file mode 100644 index 0000000000..008428f880 --- /dev/null +++ b/packages/daemon/src/core/observation-capture.ts @@ -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 { + 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' }; +} diff --git a/packages/daemon/src/core/request-runtime-binding.ts b/packages/daemon/src/core/request-runtime-binding.ts index 6809fc159d..632a4436a6 100644 --- a/packages/daemon/src/core/request-runtime-binding.ts +++ b/packages/daemon/src/core/request-runtime-binding.ts @@ -32,6 +32,7 @@ export type BindDeviceRuntime = < >( device: DeviceInfo, use: RuntimeUse, + cache?: 'bypass', ) => Promise< BoundDeviceRuntime> >; @@ -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); diff --git a/packages/daemon/src/core/settle-observation-capture.ts b/packages/daemon/src/core/settle-observation-capture.ts deleted file mode 100644 index ad149ef413..0000000000 --- a/packages/daemon/src/core/settle-observation-capture.ts +++ /dev/null @@ -1,100 +0,0 @@ -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 capture a post-action observation (`--settle`) polls, for 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. Settling is best-effort by contract, so nothing here may fail or cancel the action it - * follows: every unavailability degrades to `undefined`, leaving the observation on the owner's own - * snapshot path, and discloses its typed reason. 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 resolveSettleObservationCapture( - params: Readonly<{ command: string; session: SessionState }> & RuntimeAdmissionBindings, -): Promise { - const plan = resolveSelectorCaptureRuntimePlan({ - hasActiveApp: params.session.appBundleId !== undefined, - intent: 'capture-only', - }); - const admission = await admitObservationCapturePlan(params, plan); - if (admission === undefined) return undefined; - if (!admission.admitted) { - return unavailable({ - command: params.command, - outcome: 'refused', - operation: admission.operation, - reason: admission.fact.reason, - }); - } - try { - return await bindAdmittedSnapshotCapture({ - admission, - bindDevice: params.bindDevice, - platformServices: params.platformServices, - }); - } catch (error) { - return unavailable({ command: params.command, outcome: 'bind-failed', error }); - } -} - -/** `undefined` means the owner's facts probe failed: the caller degrades like any other refusal. */ -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) { - return unavailable({ command: params.command, outcome: 'admission-probe-failed', error }); - } -} - -/** Why the observation has to go without a capture, as one typed fact the caller can read. */ -type ObservationCaptureUnavailable = Readonly<{ command: string }> & - ( - | Readonly<{ - outcome: 'refused'; - operation: string; - reason: RuntimeOperationUnavailability['reason']; - }> - | Readonly<{ outcome: 'admission-probe-failed' | 'bind-failed'; error: unknown }> - ); - -function unavailable(detail: ObservationCaptureUnavailable): undefined { - emitDiagnostic({ - // `warn`, not the default `info`: a degrade that answers `ok: true` is dropped at info level on - // the success path, which is the passing-unnoticed this discloses against. - level: 'warn', - phase: 'settle_observation_capture_unavailable', - // The error's name travels, never its message: request diagnostics keep user input out. - data: - detail.outcome === 'refused' - ? { ...detail } - : { - command: detail.command, - outcome: detail.outcome, - errorName: (detail.error as Error | undefined)?.name, - }, - }); - return undefined; -} diff --git a/packages/daemon/src/execution/generic-settle.ts b/packages/daemon/src/execution/generic-settle.ts index f2accd1537..d0fa1f5073 100644 --- a/packages/daemon/src/execution/generic-settle.ts +++ b/packages/daemon/src/execution/generic-settle.ts @@ -20,7 +20,7 @@ import { import type { BoundContextFromFlags } from '../core/context.ts'; import type { RuntimeAdmissionBindings } from '../core/request-runtime-binding.ts'; import type { DaemonPlatformServices } from '../core/platform-services.ts'; -import { resolveSettleObservationCapture } from '../core/settle-observation-capture.ts'; +import { resolveObservationCapture } from '../core/observation-capture.ts'; import { isOutdatedObservation, refFrameTree } from '../core/ref-frame.ts'; import { issueSettleRefs } from './session-snapshot.ts'; import type { SessionStore } from '../core/session-store.ts'; @@ -156,7 +156,7 @@ async function createGenericSettleRuntime( context: GenericSettleContext, ): Promise> | undefined> { try { - const boundCapture = await resolveSettleObservationCapture({ + const outcome = await resolveObservationCapture({ command: context.req.command, session: context.session, inspectFacts: context.inspectFacts, @@ -173,7 +173,7 @@ async function createGenericSettleRuntime( contextFromFlags: context.contextFromFlags, platformServices: context.platformServices, captureSnapshotForSession, - settleObservationCapture: boundCapture, + settleObservationCapture: outcome.kind === 'captured' ? outcome.capture : undefined, }); } catch { return undefined; diff --git a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts index db69ee4c16..17fd0030fa 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts @@ -192,7 +192,7 @@ export function finalizeTouchInteraction(params: FinalizeTouchInteractionInput): /** * The capture implementation every observation on this request reads the screen through: the action * binding's own capture when its runtime use carries one, otherwise the capture the request admitted - * for its observations (`settle-observation-capture.ts`). Resolved once, at construction, so a route + * for its observations (`observation-capture.ts`). Resolved once, at construction, so a route * cannot answer one capture from the request-bound runtime and the next from the legacy path. Which * backend a bound capture presents stays per-capture: the settle loop pins it once it sees a * `private-ax` verdict. diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts index f38fa831f3..21061733ac 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts @@ -7,7 +7,7 @@ import { } from '../../../core/touch-runtime.ts'; import { readSettleRequest } from './interaction-flags.ts'; import type { BoundSnapshotCapture } from '../../../core/snapshot-runtime-binding.ts'; -import { resolveSettleObservationCapture } from '../../../core/settle-observation-capture.ts'; +import { resolveObservationCapture } from '../../../core/observation-capture.ts'; import type { InteractionRouteInput } from '../../../core/interaction/internal/types.ts'; import type { DaemonFailureResponse } from '@agent-device/kernel/contracts'; import { refusedBeforeDispatch } from '../../request-dispatch-disclosure.ts'; @@ -51,8 +51,8 @@ export async function prepareTouchDispatch( const owesObservationCapture = touchExecutor.captureSnapshot === undefined && readSettleRequest(params.req.flags) !== undefined; - const settleObservationCapture = owesObservationCapture - ? await resolveSettleObservationCapture({ + const settleObservationOutcome = owesObservationCapture + ? await resolveObservationCapture({ command: params.req.command, session, inspectFacts: params.inspectFacts, @@ -63,6 +63,7 @@ export async function prepareTouchDispatch( return { ok: true, touchExecutor, - settleObservationCapture, + settleObservationCapture: + settleObservationOutcome?.kind === 'captured' ? settleObservationOutcome.capture : undefined, }; } diff --git a/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts b/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts index ed4b2c94c8..569f2d90da 100644 --- a/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts +++ b/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts @@ -2,6 +2,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { ReplayTestAttemptStepSink } from '@agent-device/replay-test'; import type { DaemonInvokeFn, DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionStore } from '../../../core/session-store.ts'; +import type { ReplayCaptureAdmission } from '../../handlers/session-replay-command.ts'; import { createReplaySession, replayDaemonDependencies, @@ -21,6 +22,8 @@ export type ReplayCommandTestInput = Readonly<{ invoke: DaemonInvokeFn; tracePath?: string; onStep?: ReplayTestAttemptStepSink; + /** The admission facts the handler passes on a live request (#4622). */ + capture?: ReplayCaptureAdmission; }>; /** @@ -29,11 +32,11 @@ export type ReplayCommandTestInput = Readonly<{ * test's `invoke` sees the same `DaemonRequest` the daemon would. */ export function replayCommandForTest(params: ReplayCommandTestInput): ReplayCommand { - const { req, sessionName, logPath, sessionStore, invoke, tracePath, onStep } = params; + const { req, sessionName, logPath, sessionStore, invoke, tracePath, onStep, capture } = params; return { ...splitReplayCommandRequest(req), host: sessionStore.host, - session: createReplaySession(sessionName, logPath, sessionStore), + session: createReplaySession(sessionName, logPath, sessionStore, capture), invoke: replayInvokeOverDispatch(invoke, req), dependencies: replayDaemonDependencies, ...(tracePath === undefined ? {} : { tracePath }), diff --git a/packages/daemon/src/sessions/__tests__/replay-target/session-replay-scenario.fixtures.ts b/packages/daemon/src/sessions/__tests__/replay-target/session-replay-scenario.fixtures.ts index 84fed0b199..2c76ffa453 100644 --- a/packages/daemon/src/sessions/__tests__/replay-target/session-replay-scenario.fixtures.ts +++ b/packages/daemon/src/sessions/__tests__/replay-target/session-replay-scenario.fixtures.ts @@ -5,6 +5,7 @@ import { makeIosAppSession } from '../../../__tests__/support/session-factories. import { SessionStore } from '../../../core/session-store.ts'; import type { DaemonInvokeFn, DaemonRequest } from '../../../core/daemon-request.ts'; import { runReplayForTest } from '../replay-runtime/replay-command-fixture.ts'; +import type { ReplayCommandTestInput } from '../replay-runtime/replay-command-fixture.ts'; import { baseReplayRequest, writeReplayFile, @@ -43,7 +44,11 @@ export type ReplayScriptScene = ReplaySessionScene & }>; /** An iOS app session plus a written `.ad` script, ready to replay. */ -export function replayScriptScene(prefix: string, lines: string[]): ReplayScriptScene { +export function replayScriptScene( + prefix: string, + lines: string[], + capture?: ReplayCommandTestInput['capture'], +): ReplayScriptScene { const scene = iosReplayScene(prefix); const filePath = writeReplayFile(scene.root, lines); const invoked: DaemonRequest[] = []; @@ -60,6 +65,7 @@ export function replayScriptScene(prefix: string, lines: string[]): ReplayScript sessionName: scene.sessionName, logPath: scene.logPath, sessionStore: scene.sessionStore, + ...(capture === undefined ? {} : { capture }), invoke: async (req) => { invoked.push(req); return invoke ? invoke(req) : { ok: true, data: {} }; diff --git a/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts new file mode 100644 index 0000000000..1cba1d6d48 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts @@ -0,0 +1,390 @@ +/** + * #4622: replay's target verification must read the screen through the SAME capture the commands it + * dispatches read it through. Recorded `target-v1` evidence describes the tree one producer builds; + * on an iOS simulator the Simulator AX bridge and the XCTest runner project one screen differently + * (the runner wraps the screen's content in an `other ""` node the bridge tree does + * not have), so a verification that captured through the other one reported `identity-mismatch` on + * `ancestry[...]` for a screen nobody had changed. + * + * These drive the whole `runReplayCommand` route, admit and bind at the request's own seams rather + * than at the legacy interactor leaf, and read the producer back off the session's stored + * observation: the recorded-evidence comparison and the store must agree on who built the tree. + */ +import { beforeEach, expect, test, vi } from 'vitest'; +import type { + CaptureSnapshotInput, + SnapshotResult, +} from '@agent-device/contracts/snapshot-runtime'; +import { IOS_SIMULATOR } from '@agent-device/test-kit'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { createRequestRuntimeBindings } from '../../core/request-runtime-binding.ts'; +import { createRequestDispatchLedger } from '../../core/request-dispatch-ledger.ts'; +import { + platformRequestScopeFixture, + unavailableBinding, + unavailableDeviceRuntimeGateway, +} from '../../__tests__/support/unavailable-device-runtime-gateway.ts'; +import { publishOpenSession } from '../session-lifecycle/internal/session-open-state.ts'; +import { + legacyDispatchCapture, + resetLegacySnapshotCapture, +} from '../../__tests__/support/legacy-snapshot-capture-fixture.ts'; +import { captureSnapshotWithInteractor } from '../../core/snapshot-interactor-capture.ts'; +import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts'; +import { selectorCaptureFixture } from '../../__tests__/support/selector-capture-fixture.ts'; +import { + SAVE_ANNOTATION, + replayScriptScene, +} from '../__tests__/replay-target/session-replay-scenario.fixtures.ts'; + +vi.mock('../../core/snapshot-interactor-capture.ts', () => ({ + captureSnapshotWithInteractor: vi.fn(), +})); + +vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal) => { + const actual = + await importOriginal(); + return { ...actual, resolveTargetDevice: vi.fn() }; +}); + +vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, emitDiagnostic: vi.fn(actual.emitDiagnostic) }; +}); + +const REQUEST_ID = 'replay-capture-request'; + +/** The bridge tree for the recorded Save button: the producer that wrote the annotation. */ +function bridgeSaveButton(): SnapshotResult { + return { + nodes: [ + { + index: 0, + depth: 0, + type: 'Button', + identifier: 'save', + label: 'Save', + rect: { x: 10, y: 10, width: 40, height: 20 }, + hittable: true, + }, + ], + truncated: false, + backend: 'xctest', + producer: 'simulator-ax-bridge', + }; +} + +function disclosures() { + return vi + .mocked(emitDiagnostic) + .mock.calls.flatMap(([event]) => + event.phase === 'observation_capture_unavailable' && event.data + ? [{ level: event.level, data: event.data }] + : [], + ); +} + +const verifiedClick = [SAVE_ANNOTATION, 'click id="save"']; + +beforeEach(() => { + vi.mocked(emitDiagnostic).mockClear(); + resetLegacySnapshotCapture(vi.mocked(captureSnapshotWithInteractor)); +}); + +test('target verification captures through the request-bound capture and records its producer', async () => { + const fixture = selectorCaptureFixture({ snapshot: bridgeSaveButton }); + const scene = replayScriptScene( + 'agent-device-replay-capture-bound-', + [...verifiedClick, ...verifiedClick], + { + meta: { requestId: REQUEST_ID, cwd: '/work' }, + inspectFacts: fixture.inspectFacts, + platformServices: daemonPlatformServicesFixture(), + bindDevice: fixture.bindDevice, + }, + ); + + const response = await scene.replay(); + + expect(response.ok).toBe(true); + expect(scene.invoked.map((req) => req.command)).toEqual(['click', 'click']); + // ADR 0019 §9 shape: the whole replay run admits once and binds once, on the session's device. + expect(fixture.inspections).toEqual([IOS_SIMULATOR]); + expect(fixture.binds).toEqual([IOS_SIMULATOR]); + expect(fixture.captures).toHaveLength(2); + // The legacy interactor leaf is no longer the route a verification takes: nothing reached it. + expect(legacyDispatchCapture).not.toHaveBeenCalled(); + + // What the platform was asked to capture: the fixed full-window diagnostic policy (#1264) plus + // this request's identity, so the capture's diagnostics land on the replay request's record. + expect(fixture.captures[0]).toMatchObject({ + options: { + appBundleId: 'com.example.app', + interactiveOnly: true, + scope: undefined, + raw: undefined, + depth: undefined, + }, + execution: { requestId: REQUEST_ID }, + }); + + // The producer equality the issue asks for: the tree the recorded evidence was compared against, + // and the one the session stores, are the bound owner's, not the runner's. + expect(scene.sessionStore.get(scene.sessionName)?.snapshot).toMatchObject({ + backend: 'xctest', + producer: 'simulator-ax-bridge', + }); + expect(disclosures()).toEqual([]); +}); + +test.each(['close and reopen', 'open with refreshed device'])( + 'replay verifies with a fresh runtime after %s on the same booted device', + async (lifecycle) => { + const { inspectFacts } = selectorCaptureFixture(); + let generation = 0; + const captures: number[] = []; + const bind = vi.fn(async ({ device }) => { + const attachedGeneration = generation; + return { + ...(await unavailableBinding(device)), + facts: await inspectFacts(device), + operations: { + captureSnapshot: async () => { + captures.push(attachedGeneration); + if (attachedGeneration !== generation) throw new Error('Stale attachment'); + return bridgeSaveButton(); + }, + }, + }; + }); + const bindings = createRequestRuntimeBindings({ + gateway: { ...unavailableDeviceRuntimeGateway, inspectFacts, bind }, + dispatchLedger: createRequestDispatchLedger(), + scope: platformRequestScopeFixture(), + admitDeviceClaim: async () => {}, + }); + const closes = lifecycle === 'close and reopen'; + const scene = replayScriptScene( + 'agent-device-replay-capture-lifecycle-', + [...verifiedClick, ...(closes ? ['close'] : []), 'open "Demo"', ...verifiedClick], + { ...bindings, platformServices: daemonPlatformServicesFixture() }, + ); + try { + const initial = scene.sessionStore.lookup(scene.sessionName)!; + expect(initial.session.device.booted).toBe(true); + const response = await scene.replay({ + invoke: async (req) => { + if (req.command === 'close') scene.sessionStore.retire(initial); + if (req.command === 'open') { + generation++; + publishOpenSession({ + req, + sessionStore: scene.sessionStore, + sessionName: scene.sessionName, + existingRef: scene.sessionStore.lookup(scene.sessionName), + device: closes ? initial.session.device : { ...initial.session.device }, + surface: 'app', + appBundleId: initial.session.appBundleId, + }); + } + return { ok: true, data: {} }; + }, + }); + expect(response.ok).toBe(true); + expect(scene.invoked.map((req) => req.command)).toEqual([ + 'click', + ...(closes ? ['close'] : []), + 'open', + 'click', + ]); + expect(bind).toHaveBeenCalledTimes(2); + expect(captures).toEqual([0, 1]); + expect(legacyDispatchCapture).not.toHaveBeenCalled(); + expect(disclosures()).toEqual([]); + } finally { + await bindings[Symbol.asyncDispose](); + } + }, +); + +// The replay cell binds `capture-only` with the cache bypassed, while every command the replay +// dispatches binds its action use through the request's device-key cache. Both bindings of one +// device are live in the same request: the cache must not hand the bypass cell the action +// projection, the two captures must not cross projections, and each binding's own dispose must +// still run exactly once when the request ends. +test('a bypassed capture binding and a cached action binding of one device coexist in one request', async () => { + const fixture = selectorCaptureFixture({ snapshot: bridgeSaveButton }); + const disposals: string[] = []; + const bind = vi.fn(async ({ device }) => ({ + ...(await unavailableBinding(device)), + facts: await fixture.inspectFacts(device), + operations: { + captureSnapshot: async (input: CaptureSnapshotInput) => { + fixture.captures.push(input); + return bridgeSaveButton(); + }, + }, + [Symbol.asyncDispose]: async () => { + disposals.push(device.id); + }, + })); + const bindings = createRequestRuntimeBindings({ + gateway: { ...unavailableDeviceRuntimeGateway, inspectFacts: fixture.inspectFacts, bind }, + dispatchLedger: createRequestDispatchLedger(), + scope: platformRequestScopeFixture(), + admitDeviceClaim: async () => {}, + }); + // What a dispatched click binds through the same request seam: the cached path, no bypass. + const actionUse = { required: ['captureSnapshot'] as const, preferred: [] as const }; + const scene = replayScriptScene( + 'agent-device-replay-capture-coexist-', + [...verifiedClick, ...verifiedClick], + { + meta: { requestId: REQUEST_ID, cwd: '/work' }, + inspectFacts: bindings.inspectFacts, + platformServices: daemonPlatformServicesFixture(), + bindDevice: bindings.bindDevice, + }, + ); + try { + const response = await scene.replay({ + invoke: async () => { + const session = scene.sessionStore.get(scene.sessionName)!; + await bindings.bindDevice(session.device, actionUse); + return { ok: true, data: {} }; + }, + }); + expect(response.ok).toBe(true); + // One bypass bind for the replay's one verification cell and one gateway bind feeding the + // cached action projection: the two routes share one device without reusing each other's + // binding, and the two dispatches reuse the cell and the cache entry, not new binds. + expect(bind).toHaveBeenCalledTimes(2); + expect(fixture.captures).toHaveLength(2); + expect(disposals).toEqual([]); + } finally { + await bindings[Symbol.asyncDispose](); + } + // Both live bindings are adopted by the request cleanup, each disposed exactly once. + expect(disposals).toHaveLength(2); +}); + +test.each(['admission-probe-failed', 'bind-failed'] as const)( + 'replay re-admits at the next verification after %s', + async (outcome) => { + const fixture = selectorCaptureFixture({ snapshot: bridgeSaveButton }); + const inspectFacts = vi.fn(fixture.inspectFacts); + const beforeBind = vi.fn(async () => {}); + (outcome === 'admission-probe-failed' ? inspectFacts : beforeBind).mockRejectedValueOnce( + new TypeError('Unavailable'), + ); + legacyDispatchCapture.mockResolvedValue({ ...bridgeSaveButton(), producer: 'apple-runner' }); + const scene = replayScriptScene( + 'agent-device-replay-capture-retry-', + [...verifiedClick, ...verifiedClick, ...verifiedClick], + { + inspectFacts, + bindDevice: async (device, use) => { + await beforeBind(); + return await fixture.bindDevice(device, use); + }, + platformServices: daemonPlatformServicesFixture(), + }, + ); + + expect((await scene.replay()).ok).toBe(true); + expect(scene.invoked.map((req) => req.command)).toEqual(['click', 'click', 'click']); + expect(inspectFacts).toHaveBeenCalledTimes(2); + expect(legacyDispatchCapture).toHaveBeenCalledTimes(1); + expect(fixture.captures).toHaveLength(2); + expect(disclosures()).toEqual([ + { level: 'warn', data: { command: 'replay', outcome, errorName: 'TypeError' } }, + ]); + }, +); + +// A refusal is the owner's declared support for the cell's plan, so the cell keeps it for its +// lifetime: the second annotated step verifies through the owner's own path again WITHOUT a second +// facts probe or a second warning. (The two transient failure outcomes are the opposite class and +// are dropped by the re-admission test above.) +test('an owner that refuses the capture keeps verification on its own path and says so once', async () => { + const fixture = selectorCaptureFixture({ + capture: { available: false, reason: 'unsupported-platform-leaf' }, + snapshot: bridgeSaveButton, + }); + legacyDispatchCapture.mockResolvedValue({ + nodes: [ + { + index: 0, + depth: 0, + type: 'Button', + identifier: 'save', + label: 'Save', + rect: { x: 10, y: 10, width: 40, height: 20 }, + hittable: true, + }, + ], + truncated: false, + backend: 'xctest', + producer: 'apple-runner', + }); + const scene = replayScriptScene( + 'agent-device-replay-capture-refused-', + [...verifiedClick, ...verifiedClick], + { + meta: { requestId: REQUEST_ID, cwd: '/work' }, + inspectFacts: fixture.inspectFacts, + platformServices: daemonPlatformServicesFixture(), + bindDevice: fixture.bindDevice, + }, + ); + + const response = await scene.replay(); + + // Refusing the optional binding costs the run nothing: the action still replays on the owner's + // own snapshot path, which is what a caller with no composed runtime keeps doing. + expect(response.ok).toBe(true); + expect(scene.invoked.map((req) => req.command)).toEqual(['click', 'click']); + expect(fixture.binds).toEqual([]); + // One probe and one disclosure for the two steps: the cached refusal answers the second. + expect(fixture.inspections).toHaveLength(1); + expect(legacyDispatchCapture).toHaveBeenCalledTimes(2); + expect(disclosures()).toEqual([ + { + level: 'warn', + data: { + command: 'replay', + outcome: 'refused', + operation: 'captureSnapshot', + reason: 'unsupported-platform-leaf', + }, + }, + ]); +}); + +test('a replay run with no composed admission captures on the owner path without probing facts', async () => { + legacyDispatchCapture.mockResolvedValue({ + nodes: [ + { + index: 0, + depth: 0, + type: 'Button', + identifier: 'save', + label: 'Save', + rect: { x: 10, y: 10, width: 40, height: 20 }, + hittable: true, + }, + ], + truncated: false, + backend: 'xctest', + }); + const scene = replayScriptScene('agent-device-replay-capture-unbound-', [ + SAVE_ANNOTATION, + 'click id="save"', + ]); + + const response = await scene.replay(); + + expect(response.ok).toBe(true); + expect(legacyDispatchCapture).toHaveBeenCalled(); + expect(disclosures()).toEqual([]); +}); diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index 8d41c4f193..e266b72b86 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -3,7 +3,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonPlatformServices } from '../../core/platform-services.ts'; import { AppError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../../core/daemon-request.ts'; -import type { SessionState } from '../../core/session-state.ts'; +import type { SessionRef, SessionState } from '../../core/session-state.ts'; import type { SessionStore } from '../../core/session-store.ts'; import { bindInternalObservationAuthority } from '../../execution/internal-observation.ts'; import type { LeaseLifecycleProvider } from '@agent-device/contracts/device'; @@ -11,6 +11,7 @@ import type { LeaseRegistry } from '../../resources/lease-registry.ts'; import type { BindDeviceRuntime, InspectDeviceRuntimeFacts, + RuntimeAdmissionBindings, } from '../../core/request-runtime-binding.ts'; import type { PlatformResourceCleanup } from '../../core/platform-resource-cleanup.ts'; import { runReplayCommand } from '@agent-device/replay-port/native-command'; @@ -29,6 +30,9 @@ import { assertSessionSelectorMatches } from '../../core/session-selector.ts'; import { resolveSessionScope } from '../session-routing.ts'; import { resolveEffectiveOpenRuntimeHints } from '../session-runtime.ts'; import { captureSnapshot } from '../../core/snapshot-capture.ts'; +import { buildRuntimeCaptureInput } from '../../core/snapshot-runtime-capture-input.ts'; +import type { BoundSnapshotCapture } from '../../core/snapshot-runtime-binding.ts'; +import { resolveObservationCapture } from '../../core/observation-capture.ts'; import { handleSessionCloseCommands } from '../session-lifecycle/internal/session-close.ts'; import { onDelegatingLedger } from '../../core/request-ended-leases.ts'; import { createReplayTestVideoOwner } from './session-replay-video-owner.ts'; @@ -37,6 +41,21 @@ import type { SessionCommandHandler } from './session-command-input.ts'; /** The daemon policy replay consults without owning. */ export const replayDaemonDependencies: ReplayDaemonDependencies = { resolveSessionScope }; +/** + * The request's admission seams (#4622), which let replay bind the SAME request-bound capture the + * commands it dispatches bind. `meta` rides along so the capture's execution metadata carries this + * request's identity, runner overrides, and lease context like any other request-bound capture. + * + * A caller that composes no admission at all — the seam of a unit test that never binds a device — + * leaves every capture on the owner's own snapshot path. Root composition always supplies one, so + * a replay run driven through the daemon never takes that branch. + */ +export type ReplayCaptureAdmission = Readonly<{ meta?: DaemonRequest['meta'] }> & + RuntimeAdmissionBindings; + +/** What a replay run with no composed admission resolves every capture cell to. */ +const NO_REPLAY_CAPTURE: Promise = Promise.resolve(undefined); + export const handleReplayCommand: SessionCommandHandler = async ({ req, host, @@ -45,11 +64,19 @@ export const handleReplayCommand: SessionCommandHandler = async ({ sessionStore, invoke, invokeReplayAction, + inspectFacts, + bindDevice, + platformServices, }) => await runReplayCommand({ ...splitReplayCommandRequest(req), host, - session: createReplaySession(sessionName, logPath, sessionStore), + session: createReplaySession(sessionName, logPath, sessionStore, { + meta: req.meta, + inspectFacts, + bindDevice, + platformServices, + }), invoke: replayInvokeOverDispatch(invokeReplayAction ?? invoke, req), dependencies: replayDaemonDependencies, }); @@ -90,6 +117,12 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ retainDeviceExecutionLock, throwIfCanceled, }); + const capture: ReplayCaptureAdmission = { + meta: req.meta, + inspectFacts, + bindDevice, + platformServices, + }; const suiteRequest = req.internal?.publicNetworkOnly ? { ...req, @@ -104,9 +137,9 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ return await runReplayTestCommand({ ...splitReplayCommandRequest(suiteRequest), host, - session: createReplaySession(sessionName, logPath, sessionStore), + session: createReplaySession(sessionName, logPath, sessionStore, capture), createSession: (testSessionName, testLogPath) => - createReplaySession(testSessionName, testLogPath, sessionStore), + createReplaySession(testSessionName, testLogPath, sessionStore, capture), invoke: replayInvokeOverDispatch(invokeReplayAction ?? invoke, req), dependencies: replayDaemonDependencies, cleanupSession: async (testSessionName) => @@ -136,6 +169,7 @@ export function createReplaySession( name: string, logPath: string, store: SessionStore, + capture?: ReplayCaptureAdmission, ): ReplaySession { const updateSession = (mutate: (session: SessionState) => void): boolean => { const session = store.get(name); @@ -151,6 +185,57 @@ export function createReplaySession( getRuntimeHints: () => store.getRuntimeHints(name), ensureSessionDir: () => store.ensureSessionDir(name), }; + let captureCell: + | { + lifetime: SessionRef['lifetime']; + device: SessionState['device']; + booted: boolean; + hasApp: boolean; + binding: Promise; + } + | undefined; + const bindDevice = capture?.bindDevice; + // Bypasses the request's device-key cache on purpose: that key can outlive a close, while this + // cell re-admits on a new lifetime or device object. Each bypass binding is owned by the request's + // cleanup stack and released when the request ends, like every other request binding; capture + // operations resolve their source per call, so a superseded binding holds no capture state. + const bindCaptureDevice: BindDeviceRuntime | undefined = bindDevice + ? (device, use) => bindDevice(device, use, 'bypass') + : undefined; + const bindCaptureFor = ( + lifetime: SessionRef['lifetime'], + session: SessionState, + ): Promise => { + if (!capture) return NO_REPLAY_CAPTURE; + const { device } = session; + const booted = device.booted === true; + const hasApp = session.appBundleId !== undefined; + // Open can publish a refreshed device in the same lifetime. Ordinary snapshot and action + // updates preserve both. Replay owns reuse here because the request device key can outlive close. + if ( + captureCell?.lifetime === lifetime && + captureCell.device === device && + captureCell.booted === booted && + captureCell.hasApp === hasApp + ) { + return captureCell.binding; + } + const binding = resolveObservationCapture({ + command: 'replay', + session, + inspectFacts: capture.inspectFacts, + platformServices: capture.platformServices, + bindDevice: bindCaptureDevice, + }).then((outcome) => { + // The owner discloses each kind and splits stable from retryable; replay only acts on + // retry eligibility: a retryable cell is dropped so the next verification re-admits, while a + // refusal or a bound capture is kept for the cell's lifetime. + if (outcome.kind === 'retryable' && captureCell?.binding === binding) captureCell = undefined; + return outcome.kind === 'captured' ? outcome.capture : undefined; + }); + captureCell = { lifetime, device, booted, hasApp, binding }; + return binding; + }; return bindReplaySession(name, logPath, reads, { createCoordinator: () => createReplayCoordinator({ @@ -181,16 +266,32 @@ export function createReplaySession( return { ...bindInternalObservationAuthority({ sessionStore: store, ref, signal }), capture: async ({ flags, logPath: captureLogPath }) => { - const session = ref ? store.requireCurrent(ref) : undefined; - if (!session) { + if (!ref) { throw new AppError('NO_ACTIVE_SESSION', `Session "${name}" is no longer active.`); } + const session = store.requireCurrent(ref); + const bound = await bindCaptureFor(ref.lifetime, session); return await captureSnapshot({ device: session.device, session, flags, logPath: captureLogPath, signal, + ...(bound + ? { + captureData: async () => + await bound( + buildRuntimeCaptureInput({ + flags, + logPath: captureLogPath, + meta: capture?.meta, + session, + snapshotScope: undefined, + signal, + }), + ), + } + : {}), }); }, }; diff --git a/packages/replay-port/docs/replay-divergence.md b/packages/replay-port/docs/replay-divergence.md index 817aae284a..61be0420af 100644 --- a/packages/replay-port/docs/replay-divergence.md +++ b/packages/replay-port/docs/replay-divergence.md @@ -31,6 +31,13 @@ Two guarantees establish this invariant. **1. Capture scope.** The capture uses the same `captureSnapshot` wrapper as the plain command's backend. It does not use a parallel single-shot dispatch. +It captures through the request's admitted capture, the same one the commands the replay dispatches use, so the tree is the producer's that recorded the target evidence. +Replay reuses that admission per capture cell: one device object, booted state, and active-app split within one session lifetime. +Binding runs only on a successful admission. +Keep a refused admission for the cell's lifetime, so each annotated step does not probe and warn again. +Drop it only for a retryable probe or bind failure, so the next verification re-admits. +A close and reopen, or a refreshed device object, starts a new cell and a fresh admission and bind. +The observation owner discloses each outcome at its own seam: `observation_capture_admitted` and `observation_capture_bound` when it binds, `observation_capture_unavailable` when it does not. It inherits full-window scope: - Android uses the snapshot-helper route.