Skip to content

Commit f7dd422

Browse files
authored
refactor: single construction site for interaction responses (ADR 0011 Layer 2) (#1083)
Every press/click/fill/longpress dispatch branch now builds its result/ responseData payloads through buildInteractionResponseData (interaction-touch-response.ts), so identity extras (ref/refLabel/ selectorChain/targetHittable/hint/evidence) are composed in exactly one place. Hand-rolled per-branch assembly is the class of bug that dropped fill @ref evidence (#1064 review); a guard test now fails any touch handler that assembles a responseData literal outside the builder. Wire shapes are byte-identical: the fill @ref backendResult+identity shape is preserved behind refBackendWireShape, and the daemon + integration suites pass unchanged. Registry: all six responseConstruction cells flip from gap waivers to the shared runtime cell; the pinned gap list shrinks accordingly. Refs #1081, ADR 0011.
1 parent b9fb4db commit f7dd422

6 files changed

Lines changed: 276 additions & 136 deletions

File tree

‎src/contracts/__tests__/interaction-guarantees.test.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,17 +180,11 @@ test('acknowledged gaps are visible and bounded', () => {
180180
// (umbrella: https://github.com/callstack/agent-device/issues/1081).
181181
assert.deepEqual(gaps.sort(), [
182182
'coordinate/offscreen',
183-
'coordinate/responseConstruction',
184183
'direct-ios-selector/disambiguation',
185184
'direct-ios-selector/errorTaxonomy',
186185
'direct-ios-selector/nonHittable',
187186
'direct-ios-selector/occlusion',
188-
'direct-ios-selector/responseConstruction',
189187
'direct-ios-selector/responseIdentity',
190188
'maestro-non-hittable-fallback/errorTaxonomy',
191-
'maestro-non-hittable-fallback/responseConstruction',
192-
'native-ref/responseConstruction',
193-
'runtime-ref/responseConstruction',
194-
'runtime-selector/responseConstruction',
195189
]);
196190
});

‎src/contracts/interaction-guarantees.ts‎

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ export const INTERACTION_GUARANTEES = [
4141
'nonHittable',
4242
// Response payloads are assembled by a single shared construction site,
4343
// never hand-rolled per branch (the class of bug that dropped fill @ref
44-
// evidence). Closure is ADR 0011 Layer 2 (buildInteractionResponseData).
44+
// evidence). Closed by ADR 0011 Layer 2: buildInteractionResponseData plus
45+
// the hand-rolled-literal guard test.
4546
'responseConstruction',
4647
// The identity fields a path can echo back: refLabel, selectorChain, the
4748
// resolved target. Distinct from construction — a path may build responses
@@ -121,6 +122,14 @@ export type InteractionPathContract = {
121122

122123
const GAPS_UMBRELLA_ISSUE = 'https://github.com/callstack/agent-device/issues/1081';
123124

125+
// Every path shares the SAME cell by construction: response payloads have one
126+
// construction site (ADR 0011 Layer 2), and the hand-rolled-literal guard test
127+
// (interaction-response-construction-guard.test.ts) keeps new branches on it.
128+
const SHARED_RESPONSE_CONSTRUCTION: GuaranteeEnforcement = {
129+
kind: 'runtime',
130+
via: 'src/daemon/handlers/interaction-touch-response.ts#buildInteractionResponseData',
131+
};
132+
124133
export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPathContract> = {
125134
'runtime-selector': {
126135
description: 'Daemon tree capture, selector chain resolution, guarded coordinate tap.',
@@ -142,12 +151,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
142151
kind: 'runtime',
143152
via: 'src/core/interaction-targeting.ts#resolveActionableTouchResolution',
144153
},
145-
responseConstruction: {
146-
kind: 'waived',
147-
reason:
148-
'gap: response payloads are assembled per handler branch; Layer-2 buildInteractionResponseData consolidation pending.',
149-
trackingIssue: GAPS_UMBRELLA_ISSUE,
150-
},
154+
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
151155
responseIdentity: {
152156
kind: 'runtime',
153157
via: 'src/daemon/handlers/interaction-touch-targets.ts#interactionResultExtra',
@@ -183,12 +187,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
183187
kind: 'runtime',
184188
via: 'src/core/interaction-targeting.ts#resolveActionableTouchResolution',
185189
},
186-
responseConstruction: {
187-
kind: 'waived',
188-
reason:
189-
'gap: the ref response branch is hand-assembled (this exact shape dropped fill @ref evidence, #1064); Layer-2 consolidation pending.',
190-
trackingIssue: GAPS_UMBRELLA_ISSUE,
191-
},
190+
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
192191
responseIdentity: {
193192
kind: 'runtime',
194193
via: 'src/daemon/handlers/interaction-touch-targets.ts#interactionResultExtra',
@@ -231,12 +230,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
231230
'gap: non-hittable matches are skipped runner-side (ELEMENT_NOT_FOUND) instead of promoted/annotated; closure strategy is delegation-on-error into the runtime path.',
232231
trackingIssue: GAPS_UMBRELLA_ISSUE,
233232
},
234-
responseConstruction: {
235-
kind: 'waived',
236-
reason:
237-
'gap: the response is assembled from the raw runner payload; Layer-2 consolidation pending.',
238-
trackingIssue: GAPS_UMBRELLA_ISSUE,
239-
},
233+
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
240234
responseIdentity: {
241235
kind: 'waived',
242236
reason: 'gap: refLabel/selectorChain are absent on the direct path.',
@@ -279,11 +273,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
279273
kind: 'runtime',
280274
via: 'src/commands/interaction/runtime/resolution.ts#preflightNativeRefInteraction',
281275
},
282-
responseConstruction: {
283-
kind: 'waived',
284-
reason: 'gap: native ref responses are hand-assembled; Layer-2 consolidation pending.',
285-
trackingIssue: GAPS_UMBRELLA_ISSUE,
286-
},
276+
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
287277
responseIdentity: {
288278
kind: 'runtime',
289279
via: 'src/daemon/handlers/interaction-touch-targets.ts#interactionResultExtra',
@@ -321,12 +311,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
321311
kind: 'inapplicable',
322312
reason: 'No element to promote or annotate.',
323313
},
324-
responseConstruction: {
325-
kind: 'waived',
326-
reason:
327-
'gap: coordinate responses flow through the same per-branch assembly; Layer-2 consolidation pending.',
328-
trackingIssue: GAPS_UMBRELLA_ISSUE,
329-
},
314+
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
330315
responseIdentity: {
331316
kind: 'inapplicable',
332317
reason: 'No resolved node, so no refLabel/selectorChain.',
@@ -364,12 +349,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
364349
kind: 'waived',
365350
reason: 'Intentional: the entire point of this path is tapping non-hittable elements.',
366351
},
367-
responseConstruction: {
368-
kind: 'waived',
369-
reason:
370-
'gap: shares the direct path payload-based assembly; Layer-2 consolidation pending.',
371-
trackingIssue: GAPS_UMBRELLA_ISSUE,
372-
},
352+
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
373353
responseIdentity: {
374354
kind: 'waived',
375355
reason: 'Intentional: replay-only path; Maestro semantics do not consume identity fields.',
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { test } from 'vitest';
5+
6+
// ADR 0011 Layer-2 guard: interaction response payloads have exactly ONE
7+
// construction site — buildInteractionResponseData in
8+
// interaction-touch-response.ts. A hand-rolled `responseData` branch is the
9+
// class of bug that dropped fill @ref `evidence` (#1064 review): the branch
10+
// compiles, ships, and silently misses a field its siblings carry. This test
11+
// reads the touch interaction handler sources and fails when a `responseData`
12+
// is assigned anything other than the shared builder's output, so a new
13+
// branch cannot regress without tripping CI.
14+
15+
const HANDLERS_DIR = path.resolve(import.meta.dirname, '..');
16+
const BUILDER_FILE = 'interaction-touch-response.ts';
17+
18+
function touchHandlerSourceFiles(): string[] {
19+
return fs
20+
.readdirSync(HANDLERS_DIR)
21+
.filter(
22+
(file) =>
23+
(file.startsWith('interaction-touch') || file === 'interaction-common.ts') &&
24+
file.endsWith('.ts') &&
25+
file !== BUILDER_FILE,
26+
);
27+
}
28+
29+
// Allowed right-hand sides after `responseData:` / `responseData =`:
30+
// - type annotations (`Record<...>`, `Promise<...>`)
31+
// - the shared builder call
32+
// - forwarding an already-built payload (bare identifier / member expression
33+
// immediately terminated, so `cond ? {...} : x` ternaries still fail)
34+
const ALLOWED_RHS = [
35+
/^(?:Record|Promise)</,
36+
/^(?:await\s+)?buildInteractionResponseData\(/,
37+
/^[A-Za-z_$][\w.$]*\s*[,;})\]]/,
38+
];
39+
40+
function findHandRolledResponseData(source: string): string[] {
41+
// Collapse whitespace so multi-line hand-rolled literals cannot hide.
42+
const collapsed = source.replace(/\s+/g, ' ');
43+
const offenders: string[] = [];
44+
const assignment = /\bresponseData\s*[:=]\s*/g;
45+
for (let match = assignment.exec(collapsed); match; match = assignment.exec(collapsed)) {
46+
const rhs = collapsed.slice(match.index + match[0].length, match.index + match[0].length + 160);
47+
if (!ALLOWED_RHS.some((pattern) => pattern.test(rhs))) {
48+
offenders.push(rhs.slice(0, 80));
49+
}
50+
}
51+
return offenders;
52+
}
53+
54+
test('interaction responses are only constructed by buildInteractionResponseData', () => {
55+
const files = touchHandlerSourceFiles();
56+
assert.ok(
57+
files.includes('interaction-touch.ts'),
58+
'guard lost sight of interaction-touch.ts — update touchHandlerSourceFiles()',
59+
);
60+
const offenders: string[] = [];
61+
for (const file of files) {
62+
const source = fs.readFileSync(path.join(HANDLERS_DIR, file), 'utf8');
63+
for (const offender of findHandRolledResponseData(source)) {
64+
offenders.push(`${file}: responseData = ${offender}...`);
65+
}
66+
}
67+
assert.deepEqual(
68+
offenders,
69+
[],
70+
`Hand-rolled interaction responseData found. Route it through ` +
71+
`buildInteractionResponseData (${BUILDER_FILE}) so identity extras ` +
72+
`(evidence, refLabel, selectorChain, hints) cannot be dropped per-branch:\n` +
73+
offenders.map((offender) => ` - ${offender}`).join('\n'),
74+
);
75+
});
76+
77+
test('the guard itself flags a hand-rolled responseData literal', () => {
78+
assert.equal(
79+
findHandRolledResponseData('const responseData = { ...backendResult, x, y };').length,
80+
1,
81+
);
82+
assert.equal(
83+
findHandRolledResponseData('const responseData = result.kind === "ref" ? { a: 1 } : built;')
84+
.length,
85+
1,
86+
);
87+
assert.equal(
88+
findHandRolledResponseData(
89+
'const responseData = buildInteractionResponseData({ source }).responseData;',
90+
).length,
91+
0,
92+
);
93+
assert.equal(findHandRolledResponseData('finalize({ result, responseData });').length, 0);
94+
});

‎src/daemon/handlers/interaction-common.ts‎

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import type { CommandFlags } from '../../core/dispatch.ts';
22
import type { SnapshotState } from '../../kernel/snapshot.ts';
3-
import type { GestureReferenceFrame } from '../../core/scroll-gesture.ts';
43
import type { DaemonCommandContext } from '../context.ts';
54
import { recordTouchVisualizationEvent } from '../recording-gestures.ts';
65
import type { DaemonRequest, DaemonResponse, SessionState } from '../types.ts';
76
import { SessionStore } from '../session-store.ts';
8-
import { successText } from '../../utils/success-text.ts';
97
import {
108
isNavigationSensitiveAction,
119
markAndroidSnapshotFreshness,
@@ -30,50 +28,6 @@ export type InteractionHandlerParams = {
3028
contextFromFlags: ContextFromFlags;
3129
};
3230

33-
export function buildTouchVisualizationResult(params: {
34-
data: Record<string, unknown> | undefined;
35-
fallbackX?: number;
36-
fallbackY?: number;
37-
referenceFrame?: GestureReferenceFrame;
38-
extra?: Record<string, unknown>;
39-
}): Record<string, unknown> {
40-
const { data, fallbackX, fallbackY, referenceFrame, extra } = params;
41-
const message =
42-
buildTouchMessage(extra, fallbackX, fallbackY) ??
43-
(typeof data?.message === 'string' ? data.message : undefined);
44-
return {
45-
...(fallbackX === undefined || fallbackY === undefined ? {} : { x: fallbackX, y: fallbackY }),
46-
...(referenceFrame ?? {}),
47-
...(extra ?? {}),
48-
...(data ?? {}),
49-
...successText(message),
50-
};
51-
}
52-
53-
function buildTouchMessage(
54-
extra: Record<string, unknown> | undefined,
55-
x: number | undefined,
56-
y: number | undefined,
57-
): string | undefined {
58-
const ref = typeof extra?.ref === 'string' ? extra.ref : undefined;
59-
const button = typeof extra?.button === 'string' ? extra.button : undefined;
60-
const gesture = typeof extra?.gesture === 'string' ? extra.gesture : undefined;
61-
const pointSuffix = x === undefined || y === undefined ? '' : ` (${x}, ${y})`;
62-
if (typeof extra?.text === 'string') {
63-
return `Filled ${Array.from(extra.text).length} chars`;
64-
}
65-
if (ref) {
66-
if (gesture === 'longpress') {
67-
return `Long pressed @${ref}${pointSuffix}`;
68-
}
69-
if (button && button !== 'primary') {
70-
return `Clicked ${button} @${ref}${pointSuffix}`;
71-
}
72-
return `Tapped @${ref}${pointSuffix}`;
73-
}
74-
return undefined;
75-
}
76-
7731
export function finalizeTouchInteraction(params: {
7832
session: SessionState;
7933
sessionStore: SessionStore;

0 commit comments

Comments
 (0)