Skip to content

Commit 5fd8fa7

Browse files
committed
feat: establish interaction application facade (#2177)
1 parent 1522126 commit 5fd8fa7

56 files changed

Lines changed: 930 additions & 818 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.fallowrc.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"scripts/help-conformance-sample-outputs.d.mts",
4747
"scripts/help-conformance-runner-output.d.mts"
4848
],
49+
"dynamicallyLoaded": ["src/daemon/interaction/index.ts"],
4950
"ignoreDependencies": [
5051
"@theme",
5152
// @agent-device/maestro owns the source import, while the published root

‎scripts/__tests__/help-conformance-sample-producers.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ import { snapshotCliOutput } from '../../src/commands/capture/output.ts';
2020
import { openCliOutput } from '../../src/commands/management/output.ts';
2121
import { NEVER_SETTLED_HINT } from '../../src/commands/interaction/runtime/settle.ts';
2222
import { buildAmbiguousMatchError } from '../../src/daemon/handlers/find-match-resolution.ts';
23-
import { refMutationAdmissionResponse } from '../../src/daemon/handlers/interaction-ref-policy.ts';
23+
import { refMutationAdmissionResponse } from '../../src/daemon/interaction/index.ts';
2424
import { buildDeviceInUseBySessionError } from '../../src/daemon/session-recovery-hints.ts';
2525
import { buildDeviceClaimConflictError } from '../../src/daemon/device-claim-conflict.ts';
26+
import { readRefMutationFrame } from '../../src/daemon/ref-frame.ts';
2627
import { resolveRefStalenessWarning } from '../../src/daemon/session-snapshot.ts';
2728
import type { SessionState } from '../../src/daemon/types.ts';
2829
import { buildAppNotInstalledError } from '@agent-device/platform-apple/app-resolution';
@@ -428,6 +429,7 @@ export const SAMPLE_PRODUCERS: SampleProducer[] = [
428429
ref: '@e12',
429430
mintedGeneration: 5,
430431
staleRefsWarning: resolveRefStalenessWarning({ session, ref: '@e12', mintedGeneration: 5 }),
432+
frame: readRefMutationFrame({ session, ref: '@e12', mintedGeneration: 5 }),
431433
});
432434
assertErrorResponse(response, 'a superseded pin');
433435
return renderErrorResponse(response);

‎scripts/help-conformance-sample-outputs.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ Hint: Inspect the owner with: agent-device device status --platform android --se
100100
};
101101

102102
// ADR 0014 mutation rejection from
103-
// src/daemon/handlers/interaction-ref-policy.ts: a pinned ref minted from a
103+
// src/daemon/interaction/index.ts: a pinned ref minted from a
104104
// superseded generation is rejected before dispatch. The daemon strips the
105105
// `~s5` pin at the boundary (interaction-touch-targets.ts), so the message
106106
// names the plain ref; the hint is the precise resolveRefStalenessWarning.

‎scripts/layering/architecture-ownership.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export type LogicalModulePolicy = Readonly<{
77
name: string;
88
roots: readonly string[];
99
forbiddenTargetRoots: readonly string[];
10+
internalForbiddenTargetRoots?: readonly string[];
1011
facade?: FacadeDeclaration;
1112
}>;
1213

@@ -38,6 +39,27 @@ export const SESSION_LIFECYCLE_RETIRED_HANDLER_PATHS = [
3839
'src/daemon/handlers/session-startup-metrics.ts',
3940
] as const;
4041

42+
const DAEMON_INTERACTION_FACADE = {
43+
root: 'src/daemon/interaction/index.ts',
44+
exports: [
45+
'CaptureSnapshotForSession',
46+
'ContextFromFlags',
47+
'InteractionRouteInput',
48+
'RefSnapshotFlagGuardResponse',
49+
'assertRecordedFillParameterization',
50+
'assertRefMutationAdmitted',
51+
'captureSnapshotForSession',
52+
'createInteractionRuntime',
53+
'finalizeTouchInteraction',
54+
'publishInteractionAmbiguityCandidates',
55+
'readSettleRequest',
56+
'readTextForNode',
57+
'refMutationAdmissionResponse',
58+
'refSnapshotFlagGuardResponse',
59+
'settleFlagGuardResponse',
60+
],
61+
} as const;
62+
4163
export const LOGICAL_MODULE_POLICIES = [
4264
{
4365
name: 'ad-replay',
@@ -77,6 +99,13 @@ export const LOGICAL_MODULE_POLICIES = [
7799
forbiddenTargetRoots: ['src/daemon/handlers/'],
78100
facade: DAEMON_SESSION_LIFECYCLE_FACADE,
79101
},
102+
{
103+
name: 'daemon-interaction',
104+
roots: ['src/daemon/interaction/'],
105+
forbiddenTargetRoots: [],
106+
internalForbiddenTargetRoots: ['src/daemon/handlers/'],
107+
facade: DAEMON_INTERACTION_FACADE,
108+
},
80109
] as const satisfies readonly LogicalModulePolicy[];
81110

82111
export const ARCHITECTURE_OWNERSHIP = {

‎scripts/layering/daemon-modularity.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,67 @@ test('session lifecycle rejects handler deep imports in both directions', () =>
309309
);
310310
});
311311

312+
test('interaction rejects handler crossings and deep imports around its facade', () => {
313+
const edges = resolveImportEdges(
314+
new Map([
315+
[
316+
'src/daemon/handlers/interaction.ts',
317+
"import { refSnapshotFlagGuardResponse } from '../interaction/internal/interaction-flags.ts';\nexport function handleInteractionCommands() {}",
318+
],
319+
[
320+
'src/daemon/interaction/internal/interaction-runtime.ts',
321+
"import { handleInteractionCommands } from '../../handlers/interaction.ts';\nexport function createInteractionRuntime() {}",
322+
],
323+
[
324+
'src/daemon/generic-settle.ts',
325+
"import { createInteractionRuntime } from './interaction/internal/interaction-runtime.ts';",
326+
],
327+
[
328+
'src/daemon/selector-runtime.ts',
329+
"import { refSnapshotFlagGuardResponse } from './interaction/internal/interaction-flags.ts';",
330+
],
331+
[
332+
'src/daemon/selector-runtime-backend.ts',
333+
"import { readTextForNode } from './interaction/internal/interaction-read.ts';",
334+
],
335+
[
336+
'src/daemon/interaction/internal/interaction-flags.ts',
337+
'export function refSnapshotFlagGuardResponse() {}',
338+
],
339+
[
340+
'src/daemon/interaction/internal/interaction-read.ts',
341+
'export function readTextForNode() {}',
342+
],
343+
]),
344+
);
345+
346+
const violations = checkDaemonModularityRatchets(
347+
[...baselineEdges(), ...edges],
348+
baselineTypeCycleMembers(),
349+
);
350+
assert.equal(violations.length, 5);
351+
assert.ok(
352+
violations.some(({ message }) =>
353+
message.includes(
354+
"src/daemon/handlers/interaction.ts must not import daemon-interaction's internal tree",
355+
),
356+
),
357+
);
358+
assert.ok(
359+
violations.some(({ message }) =>
360+
message.includes(
361+
"src/daemon/interaction/internal/interaction-runtime.ts must not import src/daemon/handlers/interaction.ts from daemon-interaction's internal tree",
362+
),
363+
),
364+
);
365+
assert.equal(
366+
violations.filter(({ message }) =>
367+
message.includes("must not import daemon-interaction's internal tree"),
368+
).length,
369+
4,
370+
);
371+
});
372+
312373
test('session lifecycle rejects restored neutral helper paths', () => {
313374
const violations = checkRetiredSessionLifecyclePaths([
314375
'src/daemon/session-device-resolution.ts',

‎scripts/layering/daemon-modularity.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,23 @@ function checkLogicalModuleImports(edges: readonly ResolvedImportEdge[]): Layeri
196196
for (const edge of edges) {
197197
const sourceModule = moduleForFile(edge.file);
198198
const targetModule = moduleForFile(edge.target);
199+
if (
200+
sourceModule &&
201+
isInsideInternalTree(edge.file, sourceModule.roots) &&
202+
sourceModule.internalForbiddenTargetRoots?.some((root) =>
203+
matchesDeclaredRoot(edge.target, root),
204+
)
205+
) {
206+
violations.push({
207+
rule: 'R10 daemon-modularity',
208+
file: edge.file,
209+
line: edge.line,
210+
message:
211+
`${edge.file} must not import ${edge.target} from ${sourceModule.name}'s internal tree; ` +
212+
'keep handler adapters above the interaction façade.',
213+
});
214+
continue;
215+
}
199216
if (
200217
targetModule &&
201218
sourceModule !== targetModule &&

‎src/daemon/__tests__/generic-settle.test.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ import { buildSnapshotState } from '../../core/snapshot-state.ts';
1515
// a resolution, and the observation must run after the deferred-outcome
1616
// markers. Quiet windows are tuned down so no test waits real time.
1717

18-
vi.mock('../handlers/interaction-snapshot.ts', async (importOriginal) => {
19-
const actual = await importOriginal<typeof import('../handlers/interaction-snapshot.ts')>();
18+
vi.mock('../interaction/index.ts', async (importOriginal) => {
19+
const actual = await importOriginal<typeof import('../interaction/index.ts')>();
2020
return {
2121
...actual,
2222
captureSnapshotForSession: vi.fn(async () => ({
@@ -27,7 +27,7 @@ vi.mock('../handlers/interaction-snapshot.ts', async (importOriginal) => {
2727
};
2828
});
2929

30-
import { captureSnapshotForSession } from '../handlers/interaction-snapshot.ts';
30+
import { captureSnapshotForSession } from '../interaction/index.ts';
3131
import { dispatchGenericCommand } from '../request-generic-dispatch.ts';
3232

3333
const mockCaptureSnapshotForSession = vi.mocked(captureSnapshotForSession);
@@ -167,8 +167,10 @@ beforeEach(() => {
167167
mockDispatch.mockResolvedValue({});
168168
mockCaptureSnapshotForSession.mockReset();
169169
mockCaptureSnapshotForSession.mockImplementation(
170-
(session, flags, sessionStore, _contextFromFlags, options) =>
171-
emulateCaptureSnapshotForSession(session, flags, sessionStore, options),
170+
(...args: Parameters<typeof captureSnapshotForSession>) => {
171+
const [session, flags, sessionStore, _contextFromFlags, options] = args;
172+
return emulateCaptureSnapshotForSession(session, flags, sessionStore, options);
173+
},
172174
);
173175
});
174176

‎src/daemon/__tests__/selector-runtime.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const { mockRunAppleRunnerCommand } = vi.hoisted(() => ({
99
mockRunAppleRunnerCommand: vi.fn(),
1010
}));
1111

12-
import { queryDirectIosSelector } from '../selector-runtime.ts';
12+
import { queryDirectIosSelector } from '../direct-ios-selector.ts';
1313

1414
beforeEach(() => {
1515
mockRunAppleRunnerCommand.mockReset();

‎src/daemon/deferred-interaction-outcome.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,7 @@ const INTERACTION_CHANGE_RECHECK_DELAY_MS = 500;
5959
* post-gesture stabilization) and each marker keeps its own eligibility gate,
6060
* so callers do not pre-filter — an ineligible action simply marks nothing.
6161
*/
62-
export function markDeferredInteractionOutcome(params: {
63-
session: SessionState;
62+
export type DeferredInteractionOutcomeMark = {
6463
command: string;
6564
/** Action used for freshness/stabilization eligibility; defaults to `command`. */
6665
action?: string;
@@ -69,7 +68,11 @@ export function markDeferredInteractionOutcome(params: {
6968
/** True only when no post-action observation already proved the interaction landed. */
7069
scheduleOutcomeRetry?: boolean;
7170
androidFreshnessBaseline?: SnapshotState | undefined;
72-
}): void {
71+
};
72+
73+
export function markDeferredInteractionOutcome(
74+
params: DeferredInteractionOutcomeMark & { session: SessionState },
75+
): void {
7376
const {
7477
session,
7578
command,

‎src/daemon/direct-ios-selector.ts‎

Lines changed: 36 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,17 @@ import type { SessionState } from './types.ts';
66
import { readSimpleSelectorTarget } from '@agent-device/selectors';
77
import { asAppError } from '@agent-device/kernel/errors';
88
import type { ElementSelectorTapOptions } from '@agent-device/contracts/interactor-types';
9+
import { queryAppleRuntimeSelector } from '../platform-runtime-apple-resources.ts';
10+
import type { AppleRunnerRequestOptions } from './apple-runner-options.ts';
911

1012
export type DirectIosSelectorTarget = ElementSelectorTapOptions & { raw: string };
1113

12-
/**
13-
* Is this session eligible for a direct, tree-independent local XCTest
14-
* runner read/tap? Both the Maestro selector-tap route and the offscreen
15-
* refusal double-check probe (`src/daemon/offscreen-target-probe.ts`) share
16-
* this "local runner, not a provider-owned device" boundary — provider-owned
17-
* iOS devices resolve through their own interactor-backed runtime instead.
18-
*
19-
* The one difference between the two callers is explicit, not baked in: the
20-
* Maestro tap route skips itself while a post-gesture stabilization is
21-
* pending (it hands off to the tree-based runtime path instead), but the
22-
* double-check must NOT inherit that skip — it exists specifically to cover
23-
* the window where the bulk AX tree is stale (pending or just-cleared
24-
* stabilization), so excluding that window would defeat its purpose.
25-
*/
2614
export function isLocalIosRunnerSession(
2715
session: SessionState | undefined,
2816
options: { skipPendingPostGestureStabilization: boolean },
2917
): session is SessionState {
3018
if (!session) return false;
3119
if (!isIosFamily(session.device)) return false;
32-
// This fast path talks directly to the local XCTest runner. Provider-owned
33-
// iOS devices must resolve through their interactor-backed snapshot runtime
34-
// instead, which keeps selectors and interaction guarantees on one backend.
3520
if (isActiveProviderDevice(session.device)) return false;
3621
if (options.skipPendingPostGestureStabilization && isPostGestureStabilizationPending(session)) {
3722
return false;
@@ -50,12 +35,6 @@ export function readSimpleIosSelectorTarget(params: {
5035
return readSimpleSelectorTarget(selectorExpression);
5136
}
5237

53-
/**
54-
* The selector a bulk-tree node's OWN attributes give us for a direct runner
55-
* re-read: prefer the stable `id` (accessibility identifier), fall back to
56-
* `label`. Neither is guaranteed unique on the runner side — an ambiguous
57-
* match is the caller's problem to fail closed on, not this parser's.
58-
*/
5938
export function deriveDirectIosNodeSelector(
6039
node: Pick<SnapshotNode, 'identifier' | 'label'>,
6140
): { key: 'id' | 'label'; value: string } | null {
@@ -66,23 +45,44 @@ export function deriveDirectIosNodeSelector(
6645
return null;
6746
}
6847

48+
export type DirectIosSelectorQueryResult = {
49+
found: boolean;
50+
text?: string;
51+
node?: SnapshotNode;
52+
};
53+
54+
export async function queryDirectIosSelector(
55+
session: SessionState,
56+
selector: Pick<DirectIosSelectorTarget, 'key' | 'value'>,
57+
requestOptions: AppleRunnerRequestOptions,
58+
): Promise<DirectIosSelectorQueryResult> {
59+
const data = await queryAppleRuntimeSelector(
60+
session.device,
61+
selector,
62+
session.appBundleId,
63+
requestOptions,
64+
);
65+
const found = data.found === true;
66+
const node = readDirectIosSelectorNode(data);
67+
return {
68+
found,
69+
...(typeof data.text === 'string' ? { text: data.text } : {}),
70+
...(node ? { node } : {}),
71+
};
72+
}
73+
74+
function readDirectIosSelectorNode(data: Record<string, unknown>): SnapshotNode | undefined {
75+
const nodes = data.nodes;
76+
if (!Array.isArray(nodes)) return undefined;
77+
const node = nodes[0];
78+
if (!node || typeof node !== 'object') return undefined;
79+
return node as SnapshotNode;
80+
}
81+
6982
export function isDirectIosSelectorFallbackError(
7083
error: unknown,
7184
options: {
72-
/**
73-
* Read/query callers (wait/get/is): a runner ELEMENT_NOT_FOUND re-resolves
74-
* against the daemon tree, but AMBIGUOUS_MATCH still surfaces as-is.
75-
*/
7685
allowElementNotFound?: boolean;
77-
/**
78-
* ADR 0011 delegation-on-error for interaction dispatches: the runner's
79-
* semantic failure shapes (ELEMENT_NOT_FOUND, AMBIGUOUS_MATCH) fall back
80-
* to the tree-based runtime path, which supplies runtime disambiguation,
81-
* non-hittable promotion/annotation, occlusion refusal, and rich selector
82-
* diagnostics/hints. Must stay OFF for Maestro replay dispatches
83-
* (allowNonHittableCoordinateFallback): replay matching is intentionally
84-
* runner-native, so those error shapes must surface unchanged.
85-
*/
8686
delegateSemanticFailures?: boolean;
8787
} = {},
8888
): boolean {
@@ -91,22 +91,10 @@ export function isDirectIosSelectorFallbackError(
9191
return options.delegateSemanticFailures === true || options.allowElementNotFound === true;
9292
}
9393
if (appError.code === 'AMBIGUOUS_MATCH') return options.delegateSemanticFailures === true;
94-
// Regular interactions delegate off-screen matches to the shared tree, which
95-
// can prefer an on-screen candidate or raise offscreen_selector. Maestro
96-
// replay keeps the typed runner outcome so its compatibility resolver can
97-
// apply Maestro-specific ranking and tab-strip inference instead.
9894
if (appError.code === 'ELEMENT_OFFSCREEN') {
9995
return options.delegateSemanticFailures !== false;
10096
}
10197
if (appError.code !== 'COMMAND_FAILED') return false;
102-
// Transport-failure classification stays message-based deliberately: the
103-
// sniffed shapes originate at 4+ scattered throw sites (runner-transport
104-
// deadline errors, runner-contract connect errors, runner-session's invalid
105-
// response) plus raw undici "fetch failed" TypeErrors that are only wrapped
106-
// into AppError at this boundary — and isRetryableRunnerError performs the
107-
// same message sniffing for retry policy. A typed transport marker needs a
108-
// wrapping layer around all of them in one change; tracked as Tier-3 error
109-
// cleanup, not worth entangling with this fallback decision.
11098
const message = appError.message.toLowerCase();
11199
return (
112100
message.includes('fetch failed') ||

0 commit comments

Comments
 (0)