From b16451df9a3df766e0083077e011d182533c19c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 15:50:39 +0100 Subject: [PATCH 1/5] refactor(daemon): name the observation capture owner for every route, not just settle The capture a post-action observation polls is admitted for any route whose own action binding carries none. `--settle` was the first such route and the owner was named after it; the owner is the route's, not the flag's. Renamed to `observation-capture.ts` with `resolveObservationCapture` and the `observation_capture_unavailable` phase. No behavior change: same plan, same admit-once/bind-once, same degradation and disclosure. --- ...ion-capture.test.ts => observation-capture.test.ts} | 10 +++++----- ...e-observation-capture.ts => observation-capture.ts} | 8 ++++---- packages/daemon/src/execution/generic-settle.ts | 4 ++-- .../interaction/internal/interaction-runtime.ts | 2 +- .../interaction/internal/interaction-touch-prepare.ts | 4 ++-- 5 files changed, 14 insertions(+), 14 deletions(-) rename packages/daemon/src/core/__tests__/{settle-observation-capture.test.ts => observation-capture.test.ts} (94%) rename packages/daemon/src/core/{settle-observation-capture.ts => observation-capture.ts} (92%) 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 94% 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..bd68d5aaa6 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) => { @@ -17,7 +17,7 @@ vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => { // admitted, how often, and that every way an observation capture goes away degrades to no capture // while disclosing its typed reason. -const unavailablePhase = ['settle_observation_capture_unavailable']; +const unavailablePhase = ['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 }[] { @@ -37,7 +37,7 @@ beforeEach(() => { test('an available plan inspects once and binds once for the whole observation', async () => { const fixture = selectorCaptureFixture(); - const capture = await resolveSettleObservationCapture({ + const capture = await resolveObservationCapture({ command: 'back', session: makeIosSession('settle', { appBundleId: 'com.example.app' }), inspectFacts: fixture.inspectFacts, @@ -79,7 +79,7 @@ test.each([ async ({ refusal, session, operation, reason }) => { const fixture = selectorCaptureFixture(refusal); - const capture = await resolveSettleObservationCapture({ + const capture = await resolveObservationCapture({ command: 'back', session: session(), inspectFacts: fixture.inspectFacts, @@ -121,7 +121,7 @@ test.each([ }, }; - const capture = await resolveSettleObservationCapture({ + const capture = await resolveObservationCapture({ command: 'back', session: makeIosSession('settle', { appBundleId: 'com.example.app' }), platformServices: daemonPlatformServicesFixture(), diff --git a/packages/daemon/src/core/settle-observation-capture.ts b/packages/daemon/src/core/observation-capture.ts similarity index 92% rename from packages/daemon/src/core/settle-observation-capture.ts rename to packages/daemon/src/core/observation-capture.ts index ad149ef413..18f16303fa 100644 --- a/packages/daemon/src/core/settle-observation-capture.ts +++ b/packages/daemon/src/core/observation-capture.ts @@ -11,7 +11,7 @@ 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 + * 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 @@ -19,13 +19,13 @@ import type { SessionState } from './session-state.ts'; * * 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 + * before. Observing is best-effort by contract, so nothing here may fail or cancel the work 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( +export async function resolveObservationCapture( params: Readonly<{ command: string; session: SessionState }> & RuntimeAdmissionBindings, ): Promise { const plan = resolveSelectorCaptureRuntimePlan({ @@ -85,7 +85,7 @@ function unavailable(detail: ObservationCaptureUnavailable): undefined { // `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', + phase: 'observation_capture_unavailable', // The error's name travels, never its message: request diagnostics keep user input out. data: detail.outcome === 'refused' diff --git a/packages/daemon/src/execution/generic-settle.ts b/packages/daemon/src/execution/generic-settle.ts index f2accd1537..234cef33e1 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 boundCapture = await resolveObservationCapture({ command: context.req.command, session: context.session, inspectFacts: context.inspectFacts, 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..feeb40fc76 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'; @@ -52,7 +52,7 @@ export async function prepareTouchDispatch( touchExecutor.captureSnapshot === undefined && readSettleRequest(params.req.flags) !== undefined; const settleObservationCapture = owesObservationCapture - ? await resolveSettleObservationCapture({ + ? await resolveObservationCapture({ command: params.req.command, session, inspectFacts: params.inspectFacts, From 4770c205715753405a25699ea623ed2ee61f6bfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 15:50:45 +0100 Subject: [PATCH 2/5] fix(replay): verify recorded targets through the request's own capture Replay captured its target-verification tree through the legacy interactor, while the commands the replay dispatches, and so the recording itself, capture through the request- bound runtime. On an iOS simulator those are two projections of one screen: the XCTest runner's tree wraps the screen's content in an `other ""` node the Simulator AX bridge's tree does not have. `target-v1` ancestry therefore disagreed with itself and an unchanged screen replayed as `identity-mismatch` on `ancestry[...]`. Replay now admits the `capture-only` plan the selector family polls under, at the same request seams, and captures its verification through that one binding (#4622). Tested-by: iPhone 17 Pro Max simulator (iOS 27.0), Agent Device Tester 0.21.40-dev. `wait 'id="gesture-target-image"'` + `press` recorded with `--save-script`, replayed unbound on 0.21.36 fails at `press` with `ancestry[1]: recorded=scrollview observed=other/Agent Device Tester`; this build replays the same script to `Replayed 4 steps` with six `simulator-ax-bridge` acquires and zero runner `snapshot` sends on the request's log. --- .../replay-runtime/replay-command-fixture.ts | 7 +- .../session-replay-scenario.fixtures.ts | 8 +- .../session-replay-command-capture.test.ts | 206 ++++++++++++++++++ .../handlers/session-replay-command.ts | 83 ++++++- .../replay-port/docs/replay-divergence.md | 1 + 5 files changed, 299 insertions(+), 6 deletions(-) create mode 100644 packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts 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..15a067d094 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts @@ -0,0 +1,206 @@ +/** + * #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 { SnapshotResult } from '@agent-device/contracts/snapshot-runtime'; +import { IOS_SIMULATOR } from '@agent-device/test-kit'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +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 }] + : [], + ); +} + +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-', + [SAVE_ANNOTATION, 'click id="save"'], + { + 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']); + // 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(1); + // 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('an owner that refuses the capture keeps verification on its own path and says so', 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-', + [SAVE_ANNOTATION, 'click id="save"'], + { + 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']); + expect(fixture.binds).toEqual([]); + expect(legacyDispatchCapture).toHaveBeenCalled(); + 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..a3c0df473e 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -2,6 +2,7 @@ import { resolveSessionTestArtifactsRoot } from '@agent-device/daemon-contracts/ 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 { deviceIdentity, deviceIdentityKey } from '@agent-device/kernel/device'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import type { SessionState } from '../../core/session-state.ts'; import type { SessionStore } from '../../core/session-store.ts'; @@ -11,6 +12,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 +31,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 +42,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 +65,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 +118,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 +138,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 +170,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 +186,32 @@ export function createReplaySession( getRuntimeHints: () => store.getRuntimeHints(name), ensureSessionDir: () => store.ensureSessionDir(name), }; + // One admission and one bind per capture cell (device, active-app split) for this replay run: + // the SAME request-bound capture the commands this replay dispatches bind, so target verification + // compares recorded evidence against a tree from the SAME producer (#4622). The legacy interactor + // and the request-bound owner are two projections of one screen on an iOS simulator — the XCTest + // runner's tree inserts an `other ""` wrapper the Simulator AX bridge's tree does + // not have — so an unbound verification reported `identity-mismatch` on `ancestry[...]` for a + // screen nobody changed. A cell is re-admitted only when the plan could actually change: the + // session's device, or whether it has an app at all. + const boundCaptures = new Map>(); + const bindCaptureFor = (session: SessionState): Promise => { + if (!capture?.platformServices) return NO_REPLAY_CAPTURE; + const cell = `${deviceIdentityKey(deviceIdentity(session.device))}|${ + session.appBundleId === undefined ? 'no-app' : 'app' + }`; + const existing = boundCaptures.get(cell); + if (existing) return existing; + const binding = resolveObservationCapture({ + command: 'replay', + session, + inspectFacts: capture.inspectFacts, + platformServices: capture.platformServices, + bindDevice: capture.bindDevice, + }); + boundCaptures.set(cell, binding); + return binding; + }; return bindReplaySession(name, logPath, reads, { createCoordinator: () => createReplayCoordinator({ @@ -185,12 +246,28 @@ export function createReplaySession( if (!session) { throw new AppError('NO_ACTIVE_SESSION', `Session "${name}" is no longer active.`); } + const bound = await bindCaptureFor(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..cfc0090e49 100644 --- a/packages/replay-port/docs/replay-divergence.md +++ b/packages/replay-port/docs/replay-divergence.md @@ -31,6 +31,7 @@ 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. It inherits full-window scope: - Android uses the snapshot-helper route. From be1f349b5b50bc6c39cf61ecf1e264938e1fc86c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 17:03:54 +0100 Subject: [PATCH 3/5] fix(replay): refresh capture admission across session lifecycles --- .../handlers/session-command-harness.ts | 4 +- .../src/core/request-runtime-binding.ts | 21 ++- .../session-replay-command-capture.test.ts | 120 +++++++++++++++++- .../handlers/session-replay-command.ts | 63 +++++---- 4 files changed, 175 insertions(+), 33 deletions(-) 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/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/sessions/handlers/session-replay-command-capture.test.ts b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts index 15a067d094..8fba828b33 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts @@ -14,6 +14,14 @@ import { beforeEach, expect, test, vi } from 'vitest'; import type { 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, @@ -73,6 +81,8 @@ function disclosures() { ); } +const verifiedClick = [SAVE_ANNOTATION, 'click id="save"']; + beforeEach(() => { vi.mocked(emitDiagnostic).mockClear(); resetLegacySnapshotCapture(vi.mocked(captureSnapshotWithInteractor)); @@ -82,7 +92,7 @@ test('target verification captures through the request-bound capture and records const fixture = selectorCaptureFixture({ snapshot: bridgeSaveButton }); const scene = replayScriptScene( 'agent-device-replay-capture-bound-', - [SAVE_ANNOTATION, 'click id="save"'], + [...verifiedClick, ...verifiedClick], { meta: { requestId: REQUEST_ID, cwd: '/work' }, inspectFacts: fixture.inspectFacts, @@ -94,11 +104,11 @@ test('target verification captures through the request-bound capture and records const response = await scene.replay(); expect(response.ok).toBe(true); - expect(scene.invoked.map((req) => req.command)).toEqual(['click']); + 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(1); + expect(fixture.captures).toHaveLength(2); // The legacy interactor leaf is no longer the route a verification takes: nothing reached it. expect(legacyDispatchCapture).not.toHaveBeenCalled(); @@ -124,6 +134,110 @@ test('target verification captures through the request-bound capture and records 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](); + } + }, +); + +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' } }, + ]); + }, +); + test('an owner that refuses the capture keeps verification on its own path and says so', async () => { const fixture = selectorCaptureFixture({ capture: { available: false, reason: 'unsupported-platform-leaf' }, diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index a3c0df473e..958fc83c87 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -2,9 +2,8 @@ import { resolveSessionTestArtifactsRoot } from '@agent-device/daemon-contracts/ 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 { deviceIdentity, deviceIdentityKey } from '@agent-device/kernel/device'; 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'; @@ -186,30 +185,48 @@ export function createReplaySession( getRuntimeHints: () => store.getRuntimeHints(name), ensureSessionDir: () => store.ensureSessionDir(name), }; - // One admission and one bind per capture cell (device, active-app split) for this replay run: - // the SAME request-bound capture the commands this replay dispatches bind, so target verification - // compares recorded evidence against a tree from the SAME producer (#4622). The legacy interactor - // and the request-bound owner are two projections of one screen on an iOS simulator — the XCTest - // runner's tree inserts an `other ""` wrapper the Simulator AX bridge's tree does - // not have — so an unbound verification reported `identity-mismatch` on `ancestry[...]` for a - // screen nobody changed. A cell is re-admitted only when the plan could actually change: the - // session's device, or whether it has an app at all. - const boundCaptures = new Map>(); - const bindCaptureFor = (session: SessionState): Promise => { - if (!capture?.platformServices) return NO_REPLAY_CAPTURE; - const cell = `${deviceIdentityKey(deviceIdentity(session.device))}|${ - session.appBundleId === undefined ? 'no-app' : 'app' - }`; - const existing = boundCaptures.get(cell); - if (existing) return existing; + let captureCell: + | { + lifetime: SessionRef['lifetime']; + device: SessionState['device']; + booted: boolean; + hasApp: boolean; + binding: Promise; + } + | undefined; + const bindDevice = capture?.bindDevice; + 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: capture.bindDevice, + bindDevice: bindCaptureDevice, + }).then((bound) => { + if (!bound && captureCell?.binding === binding) captureCell = undefined; + return bound; }); - boundCaptures.set(cell, binding); + captureCell = { lifetime, device, booted, hasApp, binding }; return binding; }; return bindReplaySession(name, logPath, reads, { @@ -242,11 +259,11 @@ 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 bound = await bindCaptureFor(session); + const session = store.requireCurrent(ref); + const bound = await bindCaptureFor(ref.lifetime, session); return await captureSnapshot({ device: session.device, session, From 4040651866dca1cf2e6d2a5bdd03f766e6b692db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 18:24:31 +0100 Subject: [PATCH 4/5] fix(replay): keep a refused capture cell and prove binding coexistence resolveObservationCapture now resolves to a typed outcome, not a bare capture, so the replay cell can tell the classes apart. A `refused` admission is the owner's declared support for the cell's plan: the cell keeps it, and the next annotated step reuses the degradation with one probe and one warning instead of re-probing and re-warning per step. The two transient failure outcomes still drop the cell so the next verification re-admits. Also pins that a bypassed capture binding and a cached action binding of one device coexist in one request, each disposed exactly once, and documents why holding one bypass binding per re-admission for the request's lifetime is safe. --- .../__tests__/observation-capture.test.ts | 23 ++++-- .../daemon/src/core/observation-capture.ts | 44 ++++++---- .../daemon/src/execution/generic-settle.ts | 16 ++-- .../internal/interaction-touch-prepare.ts | 16 ++-- .../session-replay-command-capture.test.ts | 80 +++++++++++++++++-- .../handlers/session-replay-command.ts | 20 ++++- .../replay-port/docs/replay-divergence.md | 4 + 7 files changed, 158 insertions(+), 45 deletions(-) diff --git a/packages/daemon/src/core/__tests__/observation-capture.test.ts b/packages/daemon/src/core/__tests__/observation-capture.test.ts index bd68d5aaa6..098451b0ff 100644 --- a/packages/daemon/src/core/__tests__/observation-capture.test.ts +++ b/packages/daemon/src/core/__tests__/observation-capture.test.ts @@ -37,20 +37,22 @@ beforeEach(() => { test('an available plan inspects once and binds once for the whole observation', async () => { const fixture = selectorCaptureFixture(); - const capture = await resolveObservationCapture({ + const resolution = 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 (!resolution.capture) throw new Error('expected an admitted capture'); + // No outcome rides a bound resolution: a caching caller keeps the capture for its cell's lifetime. + expect(resolution.outcome).toBeUndefined(); expect(fixture.inspections).toEqual([IOS_SIMULATOR]); expect(fixture.binds).toEqual([IOS_SIMULATOR]); - await capture({}); - await capture({}); + await resolution.capture({}); + await resolution.capture({}); expect(fixture.binds).toEqual([IOS_SIMULATOR]); expect(fixture.captures).toHaveLength(2); }); @@ -79,7 +81,7 @@ test.each([ async ({ refusal, session, operation, reason }) => { const fixture = selectorCaptureFixture(refusal); - const capture = await resolveObservationCapture({ + const resolution = await resolveObservationCapture({ command: 'back', session: session(), inspectFacts: fixture.inspectFacts, @@ -87,7 +89,9 @@ test.each([ bindDevice: fixture.bindDevice, }); - expect(capture).toBeUndefined(); + // The outcome class rides the resolution: `refused` is the stable fact a caching caller keeps. + expect(resolution).toEqual({ outcome: 'refused' }); + expect(resolution.capture).toBeUndefined(); expect(fixture.binds).toEqual([]); expect(disclosures()).toEqual([ { level: 'warn', data: { command: 'back', outcome: 'refused', operation, reason } }, @@ -121,14 +125,17 @@ test.each([ }, }; - const capture = await resolveObservationCapture({ + const resolution = await resolveObservationCapture({ command: 'back', session: makeIosSession('settle', { appBundleId: 'com.example.app' }), platformServices: daemonPlatformServicesFixture(), ...failing, }); - expect(capture).toBeUndefined(); + // The transient class rides the resolution: a caching caller drops its cell on these two, + // unlike the stable `refused` outcome above. + expect(resolution).toEqual({ outcome }); + expect(resolution.capture).toBeUndefined(); expect(fixture.binds).toEqual([]); expect(disclosures()).toEqual([ { level: 'warn', 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 index 18f16303fa..3369624e27 100644 --- a/packages/daemon/src/core/observation-capture.ts +++ b/packages/daemon/src/core/observation-capture.ts @@ -20,20 +20,23 @@ import type { SessionState } from './session-state.ts'; * 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: 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. + * follows: every unavailability leaves `capture` absent, keeping the observation on the owner's own + * snapshot path, and is disclosed with its typed reason. The resolution's `outcome` also tells a + * caller that reuses the answer across observations which class it holds: a `refused` fact is the + * owner's declared support and stable until the plan changes, while the two failure outcomes are + * transient and worth another probe. 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 { +): Promise { const plan = resolveSelectorCaptureRuntimePlan({ hasActiveApp: params.session.appBundleId !== undefined, intent: 'capture-only', }); const admission = await admitObservationCapturePlan(params, plan); - if (admission === undefined) return undefined; + if ('outcome' in admission) return admission; if (!admission.admitted) { return unavailable({ command: params.command, @@ -43,17 +46,19 @@ export async function resolveObservationCapture( }); } try { - return await bindAdmittedSnapshotCapture({ - admission, - bindDevice: params.bindDevice, - platformServices: params.platformServices, - }); + return { + capture: 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. */ +/** A failed facts probe resolves as its own transient outcome; the observation degrades like any refusal. */ async function admitObservationCapturePlan( params: Readonly<{ command: string; session: SessionState }> & RuntimeAdmissionBindings, plan: SelectorCaptureRuntimePlan, @@ -69,8 +74,14 @@ async function admitObservationCapturePlan( } } +/** The observation's capture, or the typed class of why it has to go without one. */ +export type ObservationCaptureResolution = Readonly<{ + capture?: BoundSnapshotCapture; + outcome?: ObservationCaptureUnavailability['outcome']; +}>; + /** Why the observation has to go without a capture, as one typed fact the caller can read. */ -type ObservationCaptureUnavailable = Readonly<{ command: string }> & +export type ObservationCaptureUnavailability = Readonly<{ command: string }> & ( | Readonly<{ outcome: 'refused'; @@ -80,7 +91,10 @@ type ObservationCaptureUnavailable = Readonly<{ command: string }> & | Readonly<{ outcome: 'admission-probe-failed' | 'bind-failed'; error: unknown }> ); -function unavailable(detail: ObservationCaptureUnavailable): undefined { +/** Discloses the loss once, and names its class so a caching caller knows whether to re-probe. */ +function unavailable( + detail: ObservationCaptureUnavailability, +): Readonly<{ outcome: ObservationCaptureUnavailability['outcome'] }> { 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. @@ -96,5 +110,5 @@ function unavailable(detail: ObservationCaptureUnavailable): undefined { errorName: (detail.error as Error | undefined)?.name, }, }); - return undefined; + return { outcome: detail.outcome }; } diff --git a/packages/daemon/src/execution/generic-settle.ts b/packages/daemon/src/execution/generic-settle.ts index 234cef33e1..8249f503c4 100644 --- a/packages/daemon/src/execution/generic-settle.ts +++ b/packages/daemon/src/execution/generic-settle.ts @@ -156,13 +156,15 @@ async function createGenericSettleRuntime( context: GenericSettleContext, ): Promise> | undefined> { try { - const boundCapture = await resolveObservationCapture({ - command: context.req.command, - session: context.session, - inspectFacts: context.inspectFacts, - platformServices: context.platformServices, - bindDevice: context.bindDevice, - }); + const boundCapture = ( + await resolveObservationCapture({ + command: context.req.command, + session: context.session, + inspectFacts: context.inspectFacts, + platformServices: context.platformServices, + bindDevice: context.bindDevice, + }) + ).capture; return await createInteractionRuntime({ createCommandSurface: context.createCommandSurface, req: context.req, 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 feeb40fc76..7e9c17c307 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts @@ -52,13 +52,15 @@ export async function prepareTouchDispatch( touchExecutor.captureSnapshot === undefined && readSettleRequest(params.req.flags) !== undefined; const settleObservationCapture = owesObservationCapture - ? await resolveObservationCapture({ - command: params.req.command, - session, - inspectFacts: params.inspectFacts, - platformServices: params.platformServices, - bindDevice: params.bindDevice, - }) + ? ( + await resolveObservationCapture({ + command: params.req.command, + session, + inspectFacts: params.inspectFacts, + platformServices: params.platformServices, + bindDevice: params.bindDevice, + }) + ).capture : undefined; return { ok: true, 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 index 8fba828b33..1cba1d6d48 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts @@ -11,7 +11,10 @@ * observation: the recorded-evidence comparison and the store must agree on who built the tree. */ import { beforeEach, expect, test, vi } from 'vitest'; -import type { SnapshotResult } from '@agent-device/contracts/snapshot-runtime'; +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'; @@ -204,6 +207,67 @@ test.each(['close and reopen', 'open with refreshed device'])( }, ); +// 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) => { @@ -238,7 +302,11 @@ test.each(['admission-probe-failed', 'bind-failed'] as const)( }, ); -test('an owner that refuses the capture keeps verification on its own path and says so', async () => { +// 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, @@ -261,7 +329,7 @@ test('an owner that refuses the capture keeps verification on its own path and s }); const scene = replayScriptScene( 'agent-device-replay-capture-refused-', - [SAVE_ANNOTATION, 'click id="save"'], + [...verifiedClick, ...verifiedClick], { meta: { requestId: REQUEST_ID, cwd: '/work' }, inspectFacts: fixture.inspectFacts, @@ -275,9 +343,11 @@ test('an owner that refuses the capture keeps verification on its own path and s // 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']); + expect(scene.invoked.map((req) => req.command)).toEqual(['click', 'click']); expect(fixture.binds).toEqual([]); - expect(legacyDispatchCapture).toHaveBeenCalled(); + // 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', diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index 958fc83c87..5f74c90191 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -195,6 +195,14 @@ export function createReplaySession( } | 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 adopted into the + // request's cleanup stack and released when the request ends, the same seam every other request + // binding uses. Holding one per re-admission for the request's lifetime is safe: the count is + // bounded by the plan's close/reopen steps under the request's device lock, supersession happens + // only between steps, and the superseded binding owns no capture state — a local owner's capture + // operations resolve the bridge or runner per call, and what each binding's own dispose releases + // is its app-log reader, whose dispose is a no-op when none was started. const bindCaptureDevice: BindDeviceRuntime | undefined = bindDevice ? (device, use) => bindDevice(device, use, 'bypass') : undefined; @@ -222,9 +230,15 @@ export function createReplaySession( inspectFacts: capture.inspectFacts, platformServices: capture.platformServices, bindDevice: bindCaptureDevice, - }).then((bound) => { - if (!bound && captureCell?.binding === binding) captureCell = undefined; - return bound; + }).then((resolution) => { + // A `refused` outcome is the owner's declared support for this cell's plan: stable, so the + // cell keeps it and the next annotated step reuses the degradation without a second probe or + // warning. The two failure outcomes are transient: drop the cell so the next verification + // re-admits, and let this observation run on the owner's own snapshot path. + const transient = + resolution.outcome === 'admission-probe-failed' || resolution.outcome === 'bind-failed'; + if (transient && captureCell?.binding === binding) captureCell = undefined; + return resolution.capture; }); captureCell = { lifetime, device, booted, hasApp, binding }; return binding; diff --git a/packages/replay-port/docs/replay-divergence.md b/packages/replay-port/docs/replay-divergence.md index cfc0090e49..0e53ab3f23 100644 --- a/packages/replay-port/docs/replay-divergence.md +++ b/packages/replay-port/docs/replay-divergence.md @@ -32,6 +32,10 @@ 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 and active-app split within one session lifetime. +Keep a refused admission for the cell's lifetime, so each annotated step does not probe and warn again. +Drop it only for the transient `admission-probe-failed` and `bind-failed` outcomes, 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. It inherits full-window scope: - Android uses the snapshot-helper route. From 506b50794c10a4d40a96341c9155f8cc14caddbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 18:53:56 +0100 Subject: [PATCH 5/5] refactor(observation): split capture, refusal and retryable failure at the owner The observation owner now answers with one of three mutually exclusive kinds and discloses each at its own seam: a bound `capture`, a `refused` fact about the owner's declared support, or a `retryable` failure of its own probe or bind. Replay only acts on retry eligibility, and a live request record can now count the cells that reached a runtime capture: `observation_capture_admitted` and `observation_capture_bound` name the command, plan and device. --- .../__tests__/observation-capture.test.ts | 89 +++++++++----- .../daemon/src/core/observation-capture.ts | 111 ++++++++++-------- .../daemon/src/execution/generic-settle.ts | 18 ++- .../internal/interaction-touch-prepare.ts | 21 ++-- .../handlers/session-replay-command.ts | 25 ++-- .../replay-port/docs/replay-divergence.md | 6 +- 6 files changed, 155 insertions(+), 115 deletions(-) diff --git a/packages/daemon/src/core/__tests__/observation-capture.test.ts b/packages/daemon/src/core/__tests__/observation-capture.test.ts index 098451b0ff..6f3328d8ef 100644 --- a/packages/daemon/src/core/__tests__/observation-capture.test.ts +++ b/packages/daemon/src/core/__tests__/observation-capture.test.ts @@ -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 = ['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,22 +39,34 @@ beforeEach(() => { test('an available plan inspects once and binds once for the whole observation', async () => { const fixture = selectorCaptureFixture(); - const resolution = await resolveObservationCapture({ + const outcome = await resolveObservationCapture({ command: 'back', session: makeIosSession('settle', { appBundleId: 'com.example.app' }), inspectFacts: fixture.inspectFacts, platformServices: daemonPlatformServicesFixture(), bindDevice: fixture.bindDevice, }); - if (!resolution.capture) throw new Error('expected an admitted capture'); - // No outcome rides a bound resolution: a caching caller keeps the capture for its cell's lifetime. - expect(resolution.outcome).toBeUndefined(); + 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 resolution.capture({}); - await resolution.capture({}); + await outcome.capture({}); + await outcome.capture({}); expect(fixture.binds).toEqual([IOS_SIMULATOR]); expect(fixture.captures).toHaveLength(2); }); @@ -81,7 +95,7 @@ test.each([ async ({ refusal, session, operation, reason }) => { const fixture = selectorCaptureFixture(refusal); - const resolution = await resolveObservationCapture({ + const outcome = await resolveObservationCapture({ command: 'back', session: session(), inspectFacts: fixture.inspectFacts, @@ -89,19 +103,25 @@ test.each([ bindDevice: fixture.bindDevice, }); - // The outcome class rides the resolution: `refused` is the stable fact a caching caller keeps. - expect(resolution).toEqual({ outcome: 'refused' }); - expect(resolution.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' })], @@ -132,13 +152,28 @@ test.each([ ...failing, }); - // The transient class rides the resolution: a caching caller drops its cell on these two, - // unlike the stable `refused` outcome above. - expect(resolution).toEqual({ outcome }); - expect(resolution.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 index 3369624e27..008428f880 100644 --- a/packages/daemon/src/core/observation-capture.ts +++ b/packages/daemon/src/core/observation-capture.ts @@ -20,45 +20,56 @@ import type { SessionState } from './session-state.ts'; * 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: every unavailability leaves `capture` absent, keeping the observation on the owner's own - * snapshot path, and is disclosed with its typed reason. The resolution's `outcome` also tells a - * caller that reuses the answer across observations which class it holds: a `refused` fact is the - * owner's declared support and stable until the plan changes, while the two failure outcomes are - * transient and worth another probe. Admitting through the side-effect-free facts probe and binding + * 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 { +): Promise { const plan = resolveSelectorCaptureRuntimePlan({ hasActiveApp: params.session.appBundleId !== undefined, intent: 'capture-only', }); const admission = await admitObservationCapturePlan(params, plan); - if ('outcome' in admission) return admission; + if (admission === undefined) return { kind: 'retryable' }; if (!admission.admitted) { - return unavailable({ + return refused({ command: params.command, - outcome: 'refused', 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 { - return { - capture: await bindAdmittedSnapshotCapture({ - admission, - bindDevice: params.bindDevice, - platformServices: params.platformServices, - }), - }; + 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 unavailable({ command: params.command, outcome: 'bind-failed', error }); + return retryable({ command: params.command, failure: 'bind-failed', error }); } } -/** A failed facts probe resolves as its own transient outcome; the observation degrades like any refusal. */ +/** 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, @@ -70,45 +81,47 @@ async function admitObservationCapturePlan( inspectFacts: params.inspectFacts, }); } catch (error) { - return unavailable({ command: params.command, outcome: 'admission-probe-failed', error }); + retryable({ command: params.command, failure: 'admission-probe-failed', error }); + return undefined; } } -/** The observation's capture, or the typed class of why it has to go without one. */ -export type ObservationCaptureResolution = Readonly<{ - capture?: BoundSnapshotCapture; - outcome?: ObservationCaptureUnavailability['outcome']; -}>; +/** 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' }>; -/** Why the observation has to go without a capture, as one typed fact the caller can read. */ -export type ObservationCaptureUnavailability = Readonly<{ command: string }> & - ( - | Readonly<{ - outcome: 'refused'; - operation: string; - reason: RuntimeOperationUnavailability['reason']; - }> - | Readonly<{ outcome: 'admission-probe-failed' | 'bind-failed'; error: unknown }> - ); +/** 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 the loss once, and names its class so a caching caller knows whether to re-probe. */ -function unavailable( - detail: ObservationCaptureUnavailability, -): Readonly<{ outcome: ObservationCaptureUnavailability['outcome'] }> { +/** 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 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. + // `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: - detail.outcome === 'refused' - ? { ...detail } - : { - command: detail.command, - outcome: detail.outcome, - errorName: (detail.error as Error | undefined)?.name, - }, + data: { + command: detail.command, + outcome: detail.failure, + errorName: (detail.error as Error | undefined)?.name, + }, }); - return { outcome: detail.outcome }; + return { kind: 'retryable' }; } diff --git a/packages/daemon/src/execution/generic-settle.ts b/packages/daemon/src/execution/generic-settle.ts index 8249f503c4..d0fa1f5073 100644 --- a/packages/daemon/src/execution/generic-settle.ts +++ b/packages/daemon/src/execution/generic-settle.ts @@ -156,15 +156,13 @@ async function createGenericSettleRuntime( context: GenericSettleContext, ): Promise> | undefined> { try { - const boundCapture = ( - await resolveObservationCapture({ - command: context.req.command, - session: context.session, - inspectFacts: context.inspectFacts, - platformServices: context.platformServices, - bindDevice: context.bindDevice, - }) - ).capture; + const outcome = await resolveObservationCapture({ + command: context.req.command, + session: context.session, + inspectFacts: context.inspectFacts, + platformServices: context.platformServices, + bindDevice: context.bindDevice, + }); return await createInteractionRuntime({ createCommandSurface: context.createCommandSurface, req: context.req, @@ -175,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-touch-prepare.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts index 7e9c17c307..21061733ac 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-prepare.ts @@ -51,20 +51,19 @@ export async function prepareTouchDispatch( const owesObservationCapture = touchExecutor.captureSnapshot === undefined && readSettleRequest(params.req.flags) !== undefined; - const settleObservationCapture = owesObservationCapture - ? ( - await resolveObservationCapture({ - command: params.req.command, - session, - inspectFacts: params.inspectFacts, - platformServices: params.platformServices, - bindDevice: params.bindDevice, - }) - ).capture + const settleObservationOutcome = owesObservationCapture + ? await resolveObservationCapture({ + command: params.req.command, + session, + inspectFacts: params.inspectFacts, + platformServices: params.platformServices, + bindDevice: params.bindDevice, + }) : undefined; return { ok: true, touchExecutor, - settleObservationCapture, + settleObservationCapture: + settleObservationOutcome?.kind === 'captured' ? settleObservationOutcome.capture : undefined, }; } diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index 5f74c90191..e266b72b86 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -196,13 +196,9 @@ export function createReplaySession( | 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 adopted into the - // request's cleanup stack and released when the request ends, the same seam every other request - // binding uses. Holding one per re-admission for the request's lifetime is safe: the count is - // bounded by the plan's close/reopen steps under the request's device lock, supersession happens - // only between steps, and the superseded binding owns no capture state — a local owner's capture - // operations resolve the bridge or runner per call, and what each binding's own dispose releases - // is its app-log reader, whose dispose is a no-op when none was started. + // 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; @@ -230,15 +226,12 @@ export function createReplaySession( inspectFacts: capture.inspectFacts, platformServices: capture.platformServices, bindDevice: bindCaptureDevice, - }).then((resolution) => { - // A `refused` outcome is the owner's declared support for this cell's plan: stable, so the - // cell keeps it and the next annotated step reuses the degradation without a second probe or - // warning. The two failure outcomes are transient: drop the cell so the next verification - // re-admits, and let this observation run on the owner's own snapshot path. - const transient = - resolution.outcome === 'admission-probe-failed' || resolution.outcome === 'bind-failed'; - if (transient && captureCell?.binding === binding) captureCell = undefined; - return resolution.capture; + }).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; diff --git a/packages/replay-port/docs/replay-divergence.md b/packages/replay-port/docs/replay-divergence.md index 0e53ab3f23..61be0420af 100644 --- a/packages/replay-port/docs/replay-divergence.md +++ b/packages/replay-port/docs/replay-divergence.md @@ -32,10 +32,12 @@ 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 and active-app split within one session lifetime. +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 the transient `admission-probe-failed` and `bind-failed` outcomes, so the next verification re-admits. +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.