diff --git a/packages/daemon/src/__tests__/support/find-session-authority-fixture.ts b/packages/daemon/src/__tests__/support/find-session-authority-fixture.ts new file mode 100644 index 0000000000..9ead3ed748 --- /dev/null +++ b/packages/daemon/src/__tests__/support/find-session-authority-fixture.ts @@ -0,0 +1,24 @@ +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import type { SessionStore } from '../../core/session-store.ts'; +import { SessionCoordinator } from '../../core/session-store.ts'; +import type { FindSessionAuthority } from '../../core/interaction/internal/types.ts'; + +/** + * The session authority the dispatcher hands a `find` route for its admitted lifetime, built from the + * store a test published into. A test that calls the find route directly uses this rather than a + * hand-rolled stand-in, so it exercises the same lifetime-bound operations the dispatcher constructs. + * Returns `undefined` for an address with no session, which is what the route sees for one. + */ +export function bindFindSessionForTest(params: { + sessionStore: SessionStore; + sessionName: string; + req: DaemonRequest; +}): FindSessionAuthority | undefined { + const { sessionStore, sessionName, req } = params; + const ref = sessionStore.lookup(sessionName); + if (!ref) return undefined; + return { + captureRef: ref, + mutations: new SessionCoordinator(sessionStore).mutate(req, ref, () => true), + }; +} diff --git a/packages/daemon/src/core/__tests__/session-store-mutation-authority.test.ts b/packages/daemon/src/core/__tests__/session-store-mutation-authority.test.ts new file mode 100644 index 0000000000..cfa186459e --- /dev/null +++ b/packages/daemon/src/core/__tests__/session-store-mutation-authority.test.ts @@ -0,0 +1,117 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request'; +import { AppError } from '@agent-device/kernel/errors'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { DaemonRequest } from '../daemon-request.ts'; +import { SessionCoordinator } from '../session-store.ts'; +import { activateCompleteRefFrame, refFrameState } from '../ref-frame.ts'; +import { makeSession } from '../../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; + +const device: DeviceInfo = { + platform: 'android', + id: 'emulator-5554', + name: 'Android', + kind: 'emulator', +}; + +function request(requestId: string): DaemonRequest { + return { + token: 't', + session: 'agent', + command: 'find', + positionals: ['Save', 'focus'], + flags: {}, + meta: { requestId }, + }; +} + +function admittedMutation(requestId: string) { + const store = makeSessionStore(); + const coordinator = new SessionCoordinator(store); + const session = makeSession('agent', { device }); + const ref = store.publish('agent', session); + const mutations = coordinator.mutate(request(requestId), ref, () => true); + return { store, ref, mutations }; +} + +test.each(['cancellation', 'replacement'])( + 'a revoked mutation authority refuses new work on %s', + (reason) => { + const requestId = `mutation-${reason}`; + const { store, ref, mutations } = admittedMutation(requestId); + const successor = makeSession('agent', { device, appBundleId: 'com.example.successor' }); + + try { + if (reason === 'cancellation') markRequestCanceled(requestId); + if (reason === 'replacement') { + store.retire(ref); + store.publish('agent', successor); + } + + // Observing the successor is refused, and the refusal names the revoked authority's own + // situation rather than the session that now occupies the address. + assert.throws( + () => mutations.requireTargetContext(), + (error) => + error instanceof AppError && + error.details?.reason === + (reason === 'cancellation' ? 'request_canceled' : 'session_lifetime_ended'), + ); + // Crossing the side-effect seam is refused rather than silently skipped: a caller must not + // read a no-op on a dead lifetime as its own expiry. + assert.throws(() => mutations.expireRefFrame()); + // A completed effect belongs to the admitted lifetime even when the request was canceled. + mutations.recordAction({ command: 'find', positionals: ['Save', 'focus'], flags: {} }); + if (reason === 'cancellation') { + assert.deepEqual( + store.requireCurrent(ref).actions.map(({ command }) => command), + ['find'], + ); + } else { + assert.deepEqual(successor.actions, []); + } + } finally { + clearRequestCanceled(requestId); + } + }, +); + +test('a stale authority cannot expire the ref frame of the session that replaced its own', () => { + const requestId = 'mutation-stale-frame'; + const { store, ref, mutations } = admittedMutation(requestId); + + // Close and reopen the same address: the successor has its own active frame to lose. + store.retire(ref); + const successor = makeSession('agent', { device }); + store.publish('agent', successor); + activateCompleteRefFrame(successor); + + // The stale capability answers with its own ended lifetime and leaves the successor's frame active: + // expiring through an unresolved address is exactly the cross-lifetime damage the seam forbids. + assert.throws( + () => mutations.expireRefFrame(), + (error) => error instanceof AppError, + ); + assert.equal(refFrameState(successor), 'active'); +}); + +test('a mutation authority answers with the current facts of the lifetime it was given', () => { + const requestId = 'mutation-live-facts'; + const { store, ref, mutations } = admittedMutation(requestId); + + // The request's own `open` narrowed the admitted lifetime to an app after admission, so the read + // has to follow that lifetime: this is why find builds its runtime context at dispatch time. + const session = store.requireCurrent(ref); + session.appBundleId = 'com.example.admitted'; + assert.equal(mutations.requireTargetContext().appBundleId, 'com.example.admitted'); + + // Once that lifetime ends, the authority reports its own end rather than the successor's app scope. + store.retire(ref); + store.publish('agent', makeSession('agent', { device, appBundleId: 'com.example.successor' })); + assert.throws( + () => mutations.requireTargetContext(), + (error) => error instanceof AppError && error.details?.reason === 'session_lifetime_ended', + ); +}); diff --git a/packages/daemon/src/core/interaction/internal/types.ts b/packages/daemon/src/core/interaction/internal/types.ts index 0976cbf806..8dd2921b05 100644 --- a/packages/daemon/src/core/interaction/internal/types.ts +++ b/packages/daemon/src/core/interaction/internal/types.ts @@ -19,7 +19,7 @@ import type { BoundGestureExecutor } from '../../gesture-runtime.ts'; import type { BoundTouchExecutor } from '../../touch-runtime.ts'; import type { BoundSnapshotCapture } from '../../snapshot-runtime-binding.ts'; import type { recordTouchVisualizationEvent } from '../../recording-gestures.ts'; -import type { SessionStore } from '../../session-store.ts'; +import type { AuthorizedMutation, SessionStore } from '../../session-store.ts'; import type { BindDeviceRuntime, InspectDeviceRuntimeFacts, @@ -62,12 +62,34 @@ export type SettleObservationCaptureInput = { settleObservationCapture?: BoundSnapshotCapture; }; +/** + * The session authority the dispatcher hands the `find` route, for the one lifetime it admitted. + */ +export type FindSessionAuthority = Readonly<{ + /** Lifetime-bound session effects: target-context read, ADR 0014 ref-frame expiry, recording. */ + mutations: AuthorizedMutation; + /** + * Retained adapter (#5064 remaining debt): find's own target capture writes its observation + * through the store's snapshot choke point, which is a store-private write no command may hold as + * an operation yet. So that one leg gets the dispatcher's admitted ref instead of resolving the + * address again, and no action branch reads it. + */ + captureRef: SessionRef; +}>; + export type FindRouteInput = { createCommandSurface: CreateDaemonCommandSurface; req: DaemonRequest; sessionName: string; logPath: string; + /** + * Retained adapter (#5064 remaining debt): the read-only selector-runtime path (`exists`/`wait`/ + * `list`/`get text`/`get attrs`) still resolves its session by address. The mutating actions use + * `findSession` and reach no store at all. + */ sessionStore: SessionStore; + /** The admitted session's authority; absent when the address has no session. */ + findSession?: FindSessionAuthority; invoke: DaemonInvokeFn; inspectFacts?: InspectDeviceRuntimeFacts; platformServices: DaemonPlatformServices; diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 3357922363..322c8505bd 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -36,6 +36,7 @@ import type { SessionState, } from './session-state.ts'; import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts'; +import { expireRefFrame } from './ref-frame.ts'; import { isSafeSessionSegment, safeSessionName } from '@agent-device/host-kit/session-paths'; import { readRepairTombstoneFile, @@ -674,6 +675,7 @@ function removeEmptySessionDirectory(directory: string): void { const sessionAuthority: unique symbol = Symbol(); const openAuthority: unique symbol = Symbol(); +const mutationAuthority: unique symbol = Symbol(); export type AuthorizedSession = Readonly<{ [sessionAuthority]: true; @@ -695,6 +697,37 @@ export type WithSessionExecutionLock = ( signal?: AbortSignal, ) => Promise; +/** + * What a command may learn about the session it acts on: the neutral facts its guards, runtime + * inputs and refusal wording need. The mutable session record stays behind this projection, so a + * converted caller can neither read nor write a session field it did not declare. + */ +export type SessionTargetContext = Readonly<{ + /** Public session name, for refusal wording only. */ + name: string; + device: DeviceInfo; + appBundleId?: string; + traceLogPath?: string; +}>; + +/** + * The session effects of one admitted lifetime, handed to a mutating command by the dispatcher: the + * target context it reads before it acts, the ADR 0014 ref-frame expiry at its device side-effect + * seam, and its recorded action. They are constructed behind a private brand, so a route the + * dispatcher did not admit holds none of them, and every operation re-checks its own lifetime when + * used. An operation of an ended lifetime resolves only that lifetime and never the address again, so + * a stale capability can neither observe nor change a replacement session. + */ +export type AuthorizedMutation = Readonly<{ + [mutationAuthority]: true; + /** The admitted facts, refusing with the ended lifetime's own typed reason. */ + requireTargetContext(): SessionTargetContext; + /** Expires the admitted lifetime's ref frame, refusing with that lifetime's own typed reason. */ + expireRefFrame(): void; + /** Records the action against the admitted lifetime; a no-op once that lifetime has ended. */ + recordAction(entry: RecordActionEntry): void; +}>; + export class SessionCoordinator { readonly #store: SessionStore; @@ -714,6 +747,42 @@ export class SessionCoordinator { return this.bind(ref, () => active() && !isRequestCanceled(req.meta?.requestId)); } + /** + * Hands the admitted request the session effects a mutating command owns: the target context it + * reads, the ref-frame expiry at its side-effect seam, and its recorded action. The brand is + * constructed here only, so nothing outside the dispatcher can forge one, and every operation + * checks the admitted lifetime again when used. An ended lifetime refuses with its own typed + * reason and never resolves the address again, so a stale capability cannot reach a successor. + */ + mutate(req: DaemonRequest, ref: SessionRef, active: () => boolean): AuthorizedMutation { + const session = this.#store.requireCurrent(ref); + assertRequestHoldsSessionLease(req, session); + const admitted = () => active() && !isRequestCanceled(req.meta?.requestId); + return { + [mutationAuthority]: true, + requireTargetContext: () => { + // Revocation is checked before the read, and the store owns the refusal: an ended lifetime + // reports its own typed reason, exactly as the direct read this operation replaced did. + if (!admitted()) throw createRequestCanceledError(); + const current = this.#store.requireCurrent(ref); + return Object.freeze({ + name: current.name, + device: current.device, + ...(current.appBundleId === undefined ? {} : { appBundleId: current.appBundleId }), + ...(current.trace?.outPath === undefined ? {} : { traceLogPath: current.trace.outPath }), + }); + }, + expireRefFrame: () => { + if (!admitted()) throw createRequestCanceledError(); + expireRefFrame(this.#store.requireCurrent(ref)); + }, + recordAction: (entry) => { + if (!this.#store.resolveCurrent(ref)) return; + this.#store.recordAction(ref, entry); + }, + }; + } + observeDevice( req: DaemonRequest, device: DeviceInfo, diff --git a/packages/daemon/src/core/snapshot-runtime-binding.ts b/packages/daemon/src/core/snapshot-runtime-binding.ts index 302728d012..e2300e1516 100644 --- a/packages/daemon/src/core/snapshot-runtime-binding.ts +++ b/packages/daemon/src/core/snapshot-runtime-binding.ts @@ -120,12 +120,14 @@ export type AdmittedSnapshotCapture = * side-effect-free facts inspection, refusal before any binding, then exactly one bind on * the admitted device. `snapshot`/`diff` supply the four-way custom-actions plan and the * selector family the active-app plan; a new consumer supplies a plan and a command name. + * The session is named, not carried: this path binds a device, and the name is all its refusal + * wording needs. */ export async function admitAndBindSnapshotCapture( params: Readonly<{ command: string; device: SessionState['device']; - session: SessionState | undefined; + session: Readonly<{ name: string }> | undefined; plan: SnapshotRuntimePlan | SelectorCaptureRuntimePlan; inspectFacts?: InspectDeviceRuntimeFacts; platformServices: DaemonPlatformServices; @@ -490,7 +492,7 @@ function selectSnapshotWithoutActiveApp( type SnapshotPlanUnavailableParams = { operation: (SnapshotRuntimePlan | SelectorCaptureRuntimePlan)['use']['required'][number]; fact: RuntimeOperationFact; - session: SessionState | undefined; + session: Readonly<{ name: string }> | undefined; device: SessionState['device']; command: string; platformServices: DaemonPlatformServices; diff --git a/packages/daemon/src/execution/interaction/index-capture-disclosure.test.ts b/packages/daemon/src/execution/interaction/index-capture-disclosure.test.ts index ba62502cb5..46ba585084 100644 --- a/packages/daemon/src/execution/interaction/index-capture-disclosure.test.ts +++ b/packages/daemon/src/execution/interaction/index-capture-disclosure.test.ts @@ -12,6 +12,8 @@ import { ANDROID_SYSTEM_SURFACE_DISCLOSURE } from '@agent-device/contracts/syste import { iosSystemSurfaceDisclosure } from '@agent-device/contracts/ios-system-surface'; import { snapshotRuntimeFixture } from '../../__tests__/support/snapshot-runtime-fixture.ts'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { bindFindSessionForTest } from '../../__tests__/support/find-session-authority-fixture.ts'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; import { makeAndroidSession, makeIosSession } from '../../__tests__/support/session-factories.ts'; import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; const platformResourceCleanup = platformResourceCleanupFixture(); @@ -105,18 +107,20 @@ test('mutating find on a system-surface capture discloses the occlusion on the f const session = makeAndroidSession('default'); sessionStore.publish('default', session); + const req: DaemonRequest = { + token: 't', + session: 'default', + command: 'find', + positionals: ['Internet', 'click'], + flags: {}, + }; const response = await handleFindCommands({ createCommandSurface: testCreateCommandSurface, - req: { - token: 't', - session: 'default', - command: 'find', - positionals: ['Internet', 'click'], - flags: {}, - }, + req, sessionName: 'default', logPath: '/tmp/test.log', sessionStore, + findSession: bindFindSessionForTest({ sessionStore, sessionName: 'default', req })!, invoke: async () => ({ ok: true, data: {} }) as DaemonResponse, ...getRuntimeBindings(), }); @@ -340,18 +344,20 @@ test('mutating find on an in-place system surface discloses it on the found outc const sessionStore = makeSessionStore(); sessionStore.publish('default', makeIosSession('default', { appBundleId: 'com.example.app' })); + const req: DaemonRequest = { + token: 't', + session: 'default', + command: 'find', + positionals: ['LOGIN', 'click'], + flags: {}, + }; const response = await handleFindCommands({ createCommandSurface: testCreateCommandSurface, - req: { - token: 't', - session: 'default', - command: 'find', - positionals: ['LOGIN', 'click'], - flags: {}, - }, + req, sessionName: 'default', logPath: '/tmp/test.log', sessionStore, + findSession: bindFindSessionForTest({ sessionStore, sessionName: 'default', req })!, invoke: async () => ({ ok: true, data: {} }) as DaemonResponse, ...getRuntimeBindings(), }); @@ -368,18 +374,20 @@ test('mutating find that misses on an in-place system surface still discloses it const sessionStore = makeSessionStore(); sessionStore.publish('default', makeIosSession('default', { appBundleId: 'com.example.app' })); + const req: DaemonRequest = { + token: 't', + session: 'default', + command: 'find', + positionals: ['Bakery list', 'click'], + flags: {}, + }; const response = await handleFindCommands({ createCommandSurface: testCreateCommandSurface, - req: { - token: 't', - session: 'default', - command: 'find', - positionals: ['Bakery list', 'click'], - flags: {}, - }, + req, sessionName: 'default', logPath: '/tmp/test.log', sessionStore, + findSession: bindFindSessionForTest({ sessionStore, sessionName: 'default', req })!, invoke: async () => ({ ok: true, data: {} }) as DaemonResponse, ...getRuntimeBindings(), }); diff --git a/packages/daemon/src/execution/interaction/internal/__tests__/find-handler-fixture.ts b/packages/daemon/src/execution/interaction/internal/__tests__/find-handler-fixture.ts index 744631cc2f..7b0763b1ff 100644 --- a/packages/daemon/src/execution/interaction/internal/__tests__/find-handler-fixture.ts +++ b/packages/daemon/src/execution/interaction/internal/__tests__/find-handler-fixture.ts @@ -1,6 +1,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { SessionStore } from '../../../../core/session-store.ts'; import type { DaemonRequest } from '../../../../core/daemon-request.ts'; +import { bindFindSessionForTest } from '../../../../__tests__/support/find-session-authority-fixture.ts'; import { handleFindCommands } from '../find.ts'; import { getRuntimeBindings } from '../../../__tests__/interaction-get-runtime-fixture.ts'; import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface'; @@ -12,6 +13,9 @@ import { fakeCreateCommandSurface } from '../../../../__tests__/support/command- * Read-only `find` constructs a BOUND selector backend — it shares the element read with `get` — * so every caller needs the request-runtime seams. It lives in its own sibling fixture module, * rather than in any one `find*.test.ts` file, because several of those files share it. + * + * The mutating actions take their session effects from the dispatcher, so this builds the same + * lifetime-bound authority the dispatcher's `bindSession` hands them rather than a stand-in. */ export function invokeFindHandler(params: { createCommandSurface?: CreateDaemonCommandSurface; @@ -22,12 +26,20 @@ export function invokeFindHandler(params: { invoke: (req: DaemonRequest) => Promise; }) { const { sessionName, sessionStore, positionals, flags, createCommandSurface } = params; + const req: DaemonRequest = { + token: 't', + session: sessionName, + command: 'find', + positionals, + flags: flags ?? {}, + }; return handleFindCommands({ createCommandSurface: createCommandSurface ?? fakeCreateCommandSurface, - req: { token: 't', session: sessionName, command: 'find', positionals, flags: flags ?? {} }, + req, sessionName, logPath: '/tmp/test.log', sessionStore, + findSession: bindFindSessionForTest({ sessionStore, sessionName, req }), ...getRuntimeBindings(), invoke: params.invoke, }); diff --git a/packages/daemon/src/execution/interaction/internal/__tests__/find-target-activation-disclosure.test.ts b/packages/daemon/src/execution/interaction/internal/__tests__/find-target-activation-disclosure.test.ts index 237ef4b86f..14ee9431fb 100644 --- a/packages/daemon/src/execution/interaction/internal/__tests__/find-target-activation-disclosure.test.ts +++ b/packages/daemon/src/execution/interaction/internal/__tests__/find-target-activation-disclosure.test.ts @@ -4,6 +4,8 @@ import type { IosTargetActivation } from '@agent-device/kernel/snapshot'; import type { PostGestureOutcome } from '@agent-device/contracts/snapshot-model'; import { iosTargetActivationDisclosure } from '@agent-device/contracts/ios-target-activation'; import { makeSessionStore } from '../../../../__tests__/support/store-factory.ts'; +import { bindFindSessionForTest } from '../../../../__tests__/support/find-session-authority-fixture.ts'; +import type { DaemonRequest } from '../../../../core/daemon-request.ts'; import { makeIosSession } from '../../../../__tests__/support/session-factories.ts'; import { legacyDispatchCapture } from '../../../../__tests__/support/legacy-snapshot-capture-fixture.ts'; import { getRuntimeBindings } from '../../../__tests__/interaction-get-runtime-fixture.ts'; @@ -91,18 +93,20 @@ async function findClick(captures: Record[] | CaptureScript, af : captures[Math.min(call++, captures.length - 1)], ); + const req: DaemonRequest = { + token: 't', + session: 'default', + command: 'find', + positionals: ['General', 'click'], + flags: {}, + }; const response = await handleFindCommands({ createCommandSurface: fakeCreateCommandSurface, - req: { - token: 't', - session: 'default', - command: 'find', - positionals: ['General', 'click'], - flags: {}, - }, + req, sessionName: 'default', logPath: '/tmp/find-target-activation.log', sessionStore, + findSession: bindFindSessionForTest({ sessionStore, sessionName: 'default', req })!, invoke: async () => ({ ok: true, data: {} }) as DaemonResponse, ...getRuntimeBindings(), }); diff --git a/packages/daemon/src/execution/interaction/internal/find.ts b/packages/daemon/src/execution/interaction/internal/find.ts index a917c561ff..e2e9f22ca1 100644 --- a/packages/daemon/src/execution/interaction/internal/find.ts +++ b/packages/daemon/src/execution/interaction/internal/find.ts @@ -42,15 +42,15 @@ import { type SnapshotKeyboardBandFact, } from '@agent-device/kernel/snapshot'; import { type SnapshotState } from '@agent-device/contracts/snapshot-model'; -import { expireRefFrame } from '../../../core/ref-frame.ts'; +import type { CommandFlags } from '@agent-device/contracts/command'; import type { DaemonInvokeFn, DaemonRequest } from '../../../core/daemon-request.ts'; -import type { SessionRef, SessionState } from '../../../core/session-state.ts'; -import { SessionStore } from '../../../core/session-store.ts'; +import type { SessionState } from '../../../core/session-state.ts'; +import type { AuthorizedMutation, SessionTargetContext } from '../../../core/session-store.ts'; +import type { RecordActionEntry } from '../../../core/session-action-recorder.ts'; import { contextFromFlags } from '../../../core/context.ts'; import { readCommandMessage, successText } from '@agent-device/kernel/success-text'; import type { RequestCaptureProof } from '../../../core/capture-disclosure.ts'; import { withCaptureDisclosures } from '../../../core/capture-disclosure.ts'; -import { recordSessionAction } from '../../../core/session-action-recorder.ts'; import { stripInternalInteractionFlags } from '../../../core/deferred-interaction-outcome.ts'; import { resolveFindMatch } from './find-match-resolution.ts'; import { executeFocusPoint } from '../../focus-runtime.ts'; @@ -75,14 +75,14 @@ type FindContext = { req: DaemonRequest; sessionName: string; logPath: string; - sessionStore: SessionStore; invoke: DaemonInvokeFn; - sessionRef: SessionRef; + /** This request's admitted session effects (ADR 0040): target context, frame expiry, and recording. */ + mutations: AuthorizedMutation; device: SessionState['device']; command: string; locator: FindLocator; query: string; - publicFlags: Record; + publicFlags: CommandFlags; /** The one action-selected bind's directly-executed operations (ADR 0019 §9). */ boundFocusPoint?: (input: FocusPointInput) => Promise; boundTypeText?: TypeTextRuntimeOperations['typeText']; @@ -109,7 +109,6 @@ type ResolvedMatch = { export async function handleFindCommands(params: FindRouteInput): Promise { const { req, sessionName, logPath, sessionStore, invoke } = params; - const sessionRef = sessionStore.lookup(sessionName); const command = req.command; if (command !== 'find') return null; @@ -142,10 +141,13 @@ export async function handleFindCommands(params: FindRouteInput): Promise { - const { - req, - sessionName, - sessionStore, - sessionRef, - invoke, - command, - locator, - query, - publicFlags, - } = ctx; + const { req, sessionName, invoke, locator, query } = ctx; const response = await invoke({ token: req.token, session: sessionName, @@ -336,14 +327,7 @@ async function handleFindClick(ctx: FindContext, match: ResolvedMatch): Promise< readCommandMessage(response.data as Record) ?? `Tapped ${match.ref}${matchCoords ? ` (${matchCoords.x}, ${matchCoords.y})` : ''}`; Object.assign(matchData, successText(clickMessage)); - recordSessionAction( - sessionStore, - sessionRef, - req, - command, - { ref: match.ref, action: 'click', locator, query }, - { flags: publicFlags }, - ); + recordFindAction(ctx, match, 'click', { ref: match.ref, action: 'click', locator, query }); return { ok: true, data: matchData }; } @@ -352,7 +336,7 @@ async function handleFindFill( match: ResolvedMatch, value: string | undefined, ): Promise { - const { req, sessionName, sessionStore, sessionRef, invoke, command, publicFlags } = ctx; + const { req, sessionName, invoke } = ctx; // `''` is the clear request (#2063); only a MISSING value is an error. if (value === undefined) { return errorResponse('INVALID_ARGS', 'find fill requires text (use "" to clear the field)'); @@ -366,14 +350,7 @@ async function handleFindFill( internal: { findResolvedTarget: preresolvedTarget(match) }, }); if (!response.ok) return response; - recordSessionAction( - sessionStore, - sessionRef, - req, - command, - { ref: match.ref, action: 'fill' }, - { flags: publicFlags }, - ); + recordFindAction(ctx, match, 'fill', { ref: match.ref, action: 'fill' }); return response; } @@ -389,22 +366,17 @@ async function handleFindType( match: ResolvedMatch, value: string | undefined, ): Promise { - const { req, logPath } = ctx; if (!value) { return errorResponse('INVALID_ARGS', 'find type requires text'); } - const context = () => { - const session = ctx.sessionStore.requireCurrent(ctx.sessionRef); - return contextFromFlags(logPath, req.flags, session.appBundleId, session.trace?.outPath); - }; + const context = () => contextFromTargetContext(ctx); // The value is always text here, so a leading `@e12` is typed, not refused as a target ref. const request = parseTypeTextRequest([value], context(), { rejectRefTarget: false }); const focused = await dispatchFocusForFindMatch(ctx, match, 'type'); if (!focused.ok) return focused; - const session = ctx.sessionStore.requireCurrent(ctx.sessionRef); // The focus above already crossed the seam; expiry is idempotent, but keep it // explicit at the type dispatch so it does not rely on the focus-first order. - expireRefFrame(session); + ctx.mutations.expireRefFrame(); // R41/R35: the operation came from the handler's ONE action-selected bind; the shared // executor is the single lexical owner of the `typeText` call and of the leaf's parse. const typeText = ctx.boundTypeText; @@ -433,7 +405,6 @@ async function dispatchFocusForFindMatch( match: ResolvedMatch, action: 'focus' | 'type', ): Promise { - const { req, logPath } = ctx; const coveredResponse = rejectCoveredFindMatch(match, 'focus'); if (coveredResponse) return coveredResponse; const focusTarget = resolveFocusTarget({ @@ -496,8 +467,7 @@ async function dispatchFocusForFindMatch( // ADR 0014 side-effect seam: mutating find focus/type dispatch the device // command directly (they do not re-enter the interaction leaf), so expire the // frame here before the device op. Pre-seam guards above preserve the frame. - const session = ctx.sessionStore.requireCurrent(ctx.sessionRef); - expireRefFrame(session); + ctx.mutations.expireRefFrame(); // R40/R35: the operation came from the handler's ONE action-selected bind; the shared // executor is the single lexical owner of the `focusPoint` call. const focusPoint = ctx.boundFocusPoint; @@ -507,7 +477,7 @@ async function dispatchFocusForFindMatch( const response = await executeFocusPoint( { operations: { focusPoint } }, coords, - contextFromFlags(logPath, req.flags, session.appBundleId, session.trace?.outPath), + contextFromTargetContext(ctx), ); return { ok: true, data: response, targetAnnotation: describeNonHittableTarget(target, 'focus') }; } @@ -535,18 +505,16 @@ function offscreenRescue(ctx: FindContext): Parameters { const nodeValue = exactSelector.key === 'id' ? node.identifier?.trim() : node.label?.trim(); if (nodeValue !== exactSelector.value) return null; return await confirmIosOffscreenTargetVisible({ - session, + session: target, node, rootViewport, querySelector, - execution: runtimeExecutionFromContext( - contextFromFlags(ctx.logPath, ctx.req.flags, session.appBundleId, session.trace?.outPath), - ), + execution: runtimeExecutionFromContext(contextFromTargetContext(ctx, target)), exactSelector, }); }; @@ -570,20 +538,38 @@ function coveredFindResponse( ); } -function recordFindAction(ctx: FindContext, match: ResolvedMatch, action: string): void { - const { req, sessionStore, sessionRef, command, publicFlags } = ctx; - recordSessionAction( - sessionStore, - sessionRef, - req, +/** + * The runtime context of the admitted session: the same three facts the direct store read used to + * hand the executors, taken from the lifetime-bound projection instead. + */ +function contextFromTargetContext( + ctx: FindContext, + target: SessionTargetContext = ctx.mutations.requireTargetContext(), +) { + return contextFromFlags(ctx.logPath, ctx.req.flags, target.appBundleId, target.traceLogPath); +} + +/** + * Records find's action against the admitted lifetime. `click` and `fill` pass their own result + * payload; every other action records the resolved ref and its own name. + */ +function recordFindAction( + ctx: FindContext, + match: ResolvedMatch, + action: string, + result?: RecordActionEntry['result'], +): void { + const { req, command, publicFlags } = ctx; + ctx.mutations.recordAction({ command, - { ref: match.ref, action }, - { flags: publicFlags }, - ); + positionals: req.positionals ?? [], + flags: publicFlags, + result: result ?? { ref: match.ref, action }, + }); } // --- Helpers --- -function publicFindFlags(flags: DaemonRequest['flags']): Record { +function publicFindFlags(flags: CommandFlags | undefined): CommandFlags { return { ...(stripInternalInteractionFlags(flags) ?? {}) }; } diff --git a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts index 17fd0030fa..e7974d8bd8 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts @@ -31,7 +31,7 @@ import { markDeferredInteractionOutcome } from '../../../core/deferred-interacti import { isSessionRecording } from '../../../core/session-script-publication-capability.ts'; import { recordTouchVisualizationEvent } from '../../../core/recording-gestures.ts'; import type { SessionStore } from '../../../core/session-store.ts'; -import type { SessionRef } from '../../../core/session-state.ts'; +import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import type { BoundTouchExecutor } from '../../../core/touch-runtime.ts'; import type { BoundGestureExecutor } from '../../../core/gesture-runtime.ts'; import type { BoundSnapshotCapture } from '../../../core/snapshot-runtime-binding.ts'; @@ -125,7 +125,7 @@ function readOffscreenTargetRescue( touchExecutor?: BoundTouchExecutor; gestures?: BoundGestureExecutor; }, - session: Parameters[0]['session'], + session: SessionState, ): InteractionRuntimeInput['confirmOffscreenTargetVisible'] { const querySelector = params.touchExecutor?.querySelector ?? params.gestures?.querySelector; if (!querySelector) return undefined; diff --git a/packages/daemon/src/execution/offscreen-target-probe.ts b/packages/daemon/src/execution/offscreen-target-probe.ts index 805f31336d..3a8277fc22 100644 --- a/packages/daemon/src/execution/offscreen-target-probe.ts +++ b/packages/daemon/src/execution/offscreen-target-probe.ts @@ -3,7 +3,6 @@ import { isConfirmedOnScreenProbe } from '@agent-device/capture-kit/mobile-snaps import type { QuerySelectorRuntimeOperations } from '@agent-device/contracts/selector-observation-runtime'; import type { SnapshotRuntimeExecution } from '@agent-device/contracts/snapshot-runtime'; import { deriveDirectIosNodeSelector } from '../core/direct-ios-selector.ts'; -import type { SessionState } from '../core/session-state.ts'; /** * The #1542 rescue read: one live `querySelector` on the caller's request-bound operation, @@ -14,7 +13,8 @@ import type { SessionState } from '../core/session-state.ts'; * crash inside a guard that was about to refuse anyway. */ export async function confirmIosOffscreenTargetVisible(params: { - session: SessionState; + /** The app scope of the session this read runs for; the probe reads no other session field. */ + session: Readonly<{ appBundleId?: string }>; node: Pick; rootViewport: Rect | null; querySelector: QuerySelectorRuntimeOperations['querySelector']; diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index fe08df478a..a95be2faa5 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -102,6 +102,7 @@ import type { Admission, LeaseSessionEnd, LockedAttempt } from './lease-session- import type { LeaseRegistry } from '../resources/lease-registry.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; +import type { FindSessionAuthority } from '../core/interaction/internal/types.ts'; import type { DeviceRuntimeGateway } from '@agent-device/contracts/platform-runtime'; import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; @@ -163,6 +164,7 @@ export type RequestExecutionScope = AsyncDisposable & { ): { req: DaemonRequest; doctorSession?: AuthorizedSession; + findSession?: FindSessionAuthority; }; recordFinished(req: DaemonRequest, response: DaemonResponse): void; retainDeviceExecutionLock(deviceId: string): Promise; @@ -184,6 +186,8 @@ export type LockedRequestScope = { existingRef: SessionRef | undefined; resolveSessionRef: ResolveRequestSessionRef; doctorSession?: AuthorizedSession; + /** The admitted session's authority, for the one converted mutating route (ADR 0040). */ + findSession?: FindSessionAuthority; retainDeviceExecutionLock(deviceId: string): Promise; bindDevice: BindDeviceRuntime; platformServices: DaemonPlatformServices; @@ -574,8 +578,8 @@ export async function createRequestExecutionScope(params: { dispatchLedger, throwIfCanceled: () => throwIfRequestCanceled(scopedReq.meta?.requestId), bindSession(req, ref) { - const session = ref && coordinator.authorize(req, ref, () => true); - if (!session) return { req }; + if (!ref) return { req }; + const session = coordinator.authorize(req, ref, () => true); const { journal } = session; if (command === 'events') { return { @@ -583,6 +587,13 @@ export async function createRequestExecutionScope(params: { }; } startJournal(journal); + // ADR 0040 step 7, find slice: `find` gets its session effects as operations pinned to this + // admitted lifetime, so its action branches hold no store and never resolve the address + // again. Every other command still reaches the store the old way. + if (command === 'find') { + const mutations = coordinator.mutate(req, ref, () => true); + return { req, findSession: { mutations, captureRef: ref } }; + } return command === 'doctor' ? { req, doctorSession: session } : { req }; }, recordFinished, @@ -875,7 +886,8 @@ export async function prepareLockedRequestScope(params: { req: scope.req, existingRef: preparedSessionRef(ref, scope, sessionStore, canDetach), }); - const { req: lockedReq, doctorSession } = scope.bindSession(binding.req, binding.existingRef); + const bound = scope.bindSession(binding.req, binding.existingRef); + const { req: lockedReq, doctorSession, findSession } = bound; // `scope.sessionName` is the resolved store key, so `existingRef` carries the address every // recovery producer below must name — `existingRef.session.name` is only the public name. const existingRef = binding.existingRef; @@ -923,6 +935,7 @@ export async function prepareLockedRequestScope(params: { existingSession, existingRef, doctorSession, + findSession, resolveSessionRef: (req, ref) => { const resolved = resolveRequestSessionRef(req, ref); return resolved?.lifetime === existingRef?.lifetime ? resolved : undefined; diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index 0571b27614..86f2fc0347 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -477,6 +477,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { screenRecordingAdmissionLedger, hostDiagnostics, doctorSession: lockedScope.doctorSession, + findSession: lockedScope.findSession, withSessionExecutionLock, resolveSessionRef: lockedScope.resolveSessionRef, requestScope, diff --git a/packages/daemon/src/sessions/request-handler-chain.ts b/packages/daemon/src/sessions/request-handler-chain.ts index c520dc87de..46300e8158 100644 --- a/packages/daemon/src/sessions/request-handler-chain.ts +++ b/packages/daemon/src/sessions/request-handler-chain.ts @@ -18,6 +18,7 @@ import type { WithSessionExecutionLock, } from '../core/session-store.ts'; import type { DaemonInvokeFn, DaemonRequest } from '../core/daemon-request.ts'; +import type { FindSessionAuthority } from '../core/interaction/internal/types.ts'; import type { BindDeviceRuntime, BindExactDeviceRuntime, @@ -76,6 +77,8 @@ type RequestHandlerChainParams = { screenRecordingAdmissionLedger: ScreenRecordingAdmissionLedger; hostDiagnostics?: HostDiagnostics; doctorSession?: AuthorizedSession; + /** The admitted session's authority, for the one converted mutating route (ADR 0040). */ + findSession?: FindSessionAuthority; resolveSessionRef?: ResolveRequestSessionRef; withSessionExecutionLock?: WithSessionExecutionLock; requestScope: PlatformRequestScope; @@ -303,6 +306,7 @@ async function runFindHandler( sessionName: params.sessionName, logPath: params.logPath, sessionStore: params.sessionStore, + findSession: params.findSession, createCommandSurface: params.createCommandSurface, invoke: params.invoke, inspectFacts: params.inspectFacts,