Skip to content

Commit d919876

Browse files
authored
refactor(daemon): one interface for the deferred interaction outcome (#1633)
* refactor(daemon): one interface for the deferred interaction outcome (#1629) The machinery answering "did that mutation actually take effect?" was three modules coordinated only through raw SessionState fields: two independent marking sites (finalizeTouchInteraction vs dispatchGenericCommand, plus a third in session-open), a resolve side buried as private functions in snapshot-capture.ts with no direct tests, freshness heuristics split across the seam, and two raw reads of session.postGestureStabilization outside the owning module. - src/daemon/deferred-interaction-outcome.ts is now the one interface: markDeferredInteractionOutcome (every mutating route, one ordering) and resolveDeferredInteractionOutcome (every snapshot capture, parameterized over the capture primitive so it is directly testable). - getAndroidFreshnessReason moves beside its state machine in android-snapshot-freshness.ts, with the module's first direct test file. - isPostGestureStabilizationPending replaces the raw field reads in direct-ios-selector.ts and selector-capture-runtime.ts. - snapshot-capture.ts shrinks 617 -> 359 lines and keeps only capture, state building, and scope resolution. - No behavior change. The R9 type cycle drops 76 -> 74 files; zone ceiling lowered accordingly. CONTEXT.md gains the "deferred interaction outcome" term. * style: format android-snapshot-freshness.test.ts * fix(layering): record the honest R9 delta — the new module joins the cycle (+1 node) The earlier 76 -> 74 measurement was an artifact: the layering scan reads tracked files, and deferred-interaction-outcome.ts was still untracked. The real delta vs main is 76 -> 77 / daemon-server 20 -> 21: the choke point sits inline on value paths that already ran member-to-member, so the cycle gains one node and zero new edges. Ceiling raised explicitly with the rationale at the baseline, per the R9 rule's own escape hatch. * refactor(daemon): host the deferred-outcome seam in the stabilization owner (#1633 review) Zero R9 growth, per review: a NEW aggregator file cannot stay out of the cycle by shedding type imports — its value imports of the two member owners close the loop regardless. The unique zero-growth host is an existing cycle node, and the stabilization owner is the only legal one (the policy module cannot value-import stabilization back, R4; the freshness module would join as a new member). So deferred-interaction-outcome.ts absorbs the post-gesture-stabilization implementation and becomes the R7 owner of postGestureStabilization: the seam lives in a node that was already on the member-to-member paths it concentrates. - markPostGestureStabilization is now module-private behind markDeferredInteractionOutcome; stabilization marking tests drive the public interface. - The freshness retry loop moves beside its classifier in android-snapshot-freshness.ts; gesture-no-effect helpers move to a leaf file. Both stay outside the cycle. - Ratchet reverted to main's exact values (76 files, daemon-server 20) — measured member-by-member vs main: the diff is empty. * refactor(daemon): extract the pure stability loop into a leaf (#1633 review) The deferred-interaction-outcome owner keeps the seam, the pending-record ownership, and the R7 clear; the quiet-window polling loop and the baseline-distrust verdict move to post-gesture-stability.ts, parameterized by hooks (capture, surface reader, the three signature comparators) so the leaf imports no cycle owners and no SessionState — verified outside the R9 cycle, which stays at main's exact 76/20. Owner drops 539 -> 374 lines. The no-effect corroboration keeps comparing against the ORIGINAL pre-gesture baseline (never a mid-loop rebased one), now stated in the leaf's doc. The stabilization loop suite drives the unchanged public adapter; the verdict suite wires the real classifier through the leaf's hook.
1 parent 4a3ed1e commit d919876

19 files changed

Lines changed: 1343 additions & 654 deletions

‎CONTEXT.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,16 @@ task touches:
114114
- Ref generation pin: optional `~s<n>` suffix on an @ref carrying the snapshot generation it was
115115
minted from. Accepted as input everywhere, emitted by no tree output (snapshot token budget),
116116
auto-appended by the MCP layer, stripped and ignored by replay.
117+
- Deferred interaction outcome: the daemon's post-response answer to "did that mutation actually
118+
take effect" — pending interaction outcome retry, post-gesture stabilization, and Android
119+
snapshot freshness recovery. `src/daemon/deferred-interaction-outcome.ts` is its one interface:
120+
every mutating route marks through it after dispatch, and every snapshot capture resolves
121+
through it; the three `SessionState` fields stay with their R7 owners (the module itself owns
122+
`postGestureStabilization`, so the seam adds no node to the R9 cycle). Marking
123+
order is load-bearing (pending outcome retry before stabilization), each marker keeps its own
124+
eligibility gate, and the module owns only these post-action markers — never ADR 0014 ref-frame
125+
expiry or the ADR 0012/0016 staged protocols. Distinct from the same-response settled
126+
observation below.
117127
- Settled observation: opt-in (`--settle`) post-action payload on press/click/fill/longpress — the
118128
quiet-window stable loop re-captures until the UI settles, and the response carries the diff vs the
119129
pre-action tree (changed lines only, added lines with fresh refs, `refsGeneration` when the settled

‎scripts/layering/session-state.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export const SESSION_STATE_FIELD_OWNERS: Readonly<Record<string, readonly string
7979
nativePerf: ['src/daemon/session-teardown.ts'],
8080
audioProbe: ['src/daemon/audio-probe.ts'],
8181
pendingInteractionOutcome: ['src/daemon/interaction-outcome-policy.ts'],
82-
postGestureStabilization: ['src/daemon/post-gesture-stabilization.ts'],
82+
postGestureStabilization: ['src/daemon/deferred-interaction-outcome.ts'],
8383

8484
// Snapshot lineage on a freshly BUILT record. snapshot-runtime.ts constructs a new
8585
// SessionState rather than mutating the stored one, so it cannot call setSessionSnapshot —
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
import assert from 'node:assert/strict';
2+
import { afterEach, test, vi } from 'vitest';
3+
import type { RawSnapshotNode } from '@agent-device/kernel/snapshot';
4+
import { makeSnapshotState } from '../../__tests__/test-utils/index.ts';
5+
import {
6+
buildSnapshotSignatures,
7+
clearAndroidSnapshotFreshness,
8+
getActiveAndroidSnapshotFreshness,
9+
getAndroidFreshnessReason,
10+
isLikelySnapshotStuckOnPreviousRoute,
11+
isLikelyStaleSnapshotDrop,
12+
markAndroidSnapshotFreshness,
13+
type AndroidSnapshotFreshness,
14+
} from '../android-snapshot-freshness.ts';
15+
import { makeSession } from './post-gesture-stabilization-fixtures.ts';
16+
17+
afterEach(() => {
18+
vi.useRealTimers();
19+
});
20+
21+
function labeledNodes(count: number, prefix = 'item'): RawSnapshotNode[] {
22+
return Array.from({ length: count }, (_, index) => ({
23+
index,
24+
type: 'Button',
25+
label: `${prefix}-${index}`,
26+
}));
27+
}
28+
29+
function anonymousNodes(count: number): RawSnapshotNode[] {
30+
return Array.from({ length: count }, (_, index) => ({ index, type: 'View' }));
31+
}
32+
33+
function freshnessRecord(
34+
overrides: Partial<AndroidSnapshotFreshness> = {},
35+
): AndroidSnapshotFreshness {
36+
return {
37+
action: 'click',
38+
markedAt: Date.now(),
39+
baselineCount: 50,
40+
routeComparable: false,
41+
...overrides,
42+
};
43+
}
44+
45+
// --- getAndroidFreshnessReason: the whole three-reason classification ---
46+
47+
test('empty interactive capture over a dozen raw nodes reads as a transitional frame', () => {
48+
const reason = getAndroidFreshnessReason(
49+
{ snapshot: makeSnapshotState([]), rawNodeCount: 12 },
50+
freshnessRecord(),
51+
{ interactiveOnly: true },
52+
);
53+
assert.equal(reason, 'empty-interactive');
54+
});
55+
56+
test('empty interactive capture stays trusted below the raw-node floor or without disclosure', () => {
57+
const belowFloor = getAndroidFreshnessReason(
58+
{ snapshot: makeSnapshotState([]), rawNodeCount: 11 },
59+
freshnessRecord({ baselineCount: 0 }),
60+
{ interactiveOnly: true },
61+
);
62+
const undisclosed = getAndroidFreshnessReason(
63+
{ snapshot: makeSnapshotState([]), rawNodeCount: undefined },
64+
freshnessRecord({ baselineCount: 0 }),
65+
{ interactiveOnly: true },
66+
);
67+
assert.equal(belowFloor, null);
68+
assert.equal(undisclosed, null);
69+
});
70+
71+
test('ref-refresh mode only ever reports the empty-interactive shape', () => {
72+
const suppressed = getAndroidFreshnessReason(
73+
{ snapshot: makeSnapshotState(anonymousNodes(3)), rawNodeCount: undefined },
74+
freshnessRecord({ baselineCount: 50 }),
75+
{ interactiveOnly: false, mode: 'ref-refresh' },
76+
);
77+
assert.equal(suppressed, null);
78+
});
79+
80+
test('a sharp node-count drop with no meaningful content reads as stale', () => {
81+
const reason = getAndroidFreshnessReason(
82+
{ snapshot: makeSnapshotState(anonymousNodes(3)), rawNodeCount: undefined },
83+
freshnessRecord({ baselineCount: 50 }),
84+
{ interactiveOnly: false },
85+
);
86+
assert.equal(reason, 'sharp-drop');
87+
});
88+
89+
test('a sharp drop onto a screen with real content is trusted (deliberately minimal screens)', () => {
90+
const reason = getAndroidFreshnessReason(
91+
{ snapshot: makeSnapshotState(labeledNodes(3)), rawNodeCount: undefined },
92+
freshnessRecord({ baselineCount: 50 }),
93+
{ interactiveOnly: false },
94+
);
95+
assert.equal(reason, null);
96+
});
97+
98+
test('a near-identical tree after a navigation-sensitive action reads as stuck on the previous route', () => {
99+
const nodes = labeledNodes(20);
100+
const baseline = makeSnapshotState(nodes);
101+
const reason = getAndroidFreshnessReason(
102+
{ snapshot: makeSnapshotState(nodes), rawNodeCount: undefined },
103+
freshnessRecord({
104+
baselineCount: baseline.nodes.length,
105+
baselineSignatures: buildSnapshotSignatures(baseline.nodes),
106+
routeComparable: true,
107+
}),
108+
{ interactiveOnly: false },
109+
);
110+
assert.equal(reason, 'stuck-route');
111+
});
112+
113+
test('stuck-route never fires without a route-comparable baseline or for a non-navigation action', () => {
114+
const nodes = labeledNodes(20);
115+
const signatures = buildSnapshotSignatures(makeSnapshotState(nodes).nodes);
116+
const notComparable = getAndroidFreshnessReason(
117+
{ snapshot: makeSnapshotState(nodes), rawNodeCount: undefined },
118+
freshnessRecord({ baselineCount: 20, baselineSignatures: signatures, routeComparable: false }),
119+
{ interactiveOnly: false },
120+
);
121+
const steadyStateAction = getAndroidFreshnessReason(
122+
{ snapshot: makeSnapshotState(nodes), rawNodeCount: undefined },
123+
freshnessRecord({
124+
action: 'type',
125+
baselineCount: 20,
126+
baselineSignatures: signatures,
127+
routeComparable: true,
128+
}),
129+
{ interactiveOnly: false },
130+
);
131+
assert.equal(notComparable, null);
132+
assert.equal(steadyStateAction, null);
133+
});
134+
135+
test('a genuinely new route is trusted', () => {
136+
const baseline = makeSnapshotState(labeledNodes(20, 'catalog'));
137+
const reason = getAndroidFreshnessReason(
138+
{ snapshot: makeSnapshotState(labeledNodes(20, 'checkout')), rawNodeCount: undefined },
139+
freshnessRecord({
140+
baselineCount: baseline.nodes.length,
141+
baselineSignatures: buildSnapshotSignatures(baseline.nodes),
142+
routeComparable: true,
143+
}),
144+
{ interactiveOnly: false },
145+
);
146+
assert.equal(reason, null);
147+
});
148+
149+
// --- the underlying predicates ---
150+
151+
test('isLikelyStaleSnapshotDrop needs both the 12-node floor and the 20% ratio', () => {
152+
assert.equal(isLikelyStaleSnapshotDrop(11, 0), false);
153+
assert.equal(isLikelyStaleSnapshotDrop(50, 10), true);
154+
assert.equal(isLikelyStaleSnapshotDrop(50, 11), false);
155+
});
156+
157+
test('isLikelySnapshotStuckOnPreviousRoute ignores missing baselines and tiny trees', () => {
158+
const nodes = makeSnapshotState(labeledNodes(20)).nodes;
159+
assert.equal(isLikelySnapshotStuckOnPreviousRoute(undefined, nodes), false);
160+
assert.equal(isLikelySnapshotStuckOnPreviousRoute([], nodes), false);
161+
const tiny = makeSnapshotState(labeledNodes(5)).nodes;
162+
assert.equal(isLikelySnapshotStuckOnPreviousRoute(buildSnapshotSignatures(tiny), tiny), false);
163+
});
164+
165+
// --- mark / get / clear lifecycle ---
166+
167+
test('mark records a route-comparable baseline only from a comparison-safe snapshot', () => {
168+
const session = makeSession('android');
169+
session.snapshot = makeSnapshotState(labeledNodes(20), { comparisonSafe: true });
170+
171+
markAndroidSnapshotFreshness(session, 'click');
172+
173+
assert.equal(session.androidSnapshotFreshness?.routeComparable, true);
174+
assert.equal(session.androidSnapshotFreshness?.baselineSignatures?.length, 20);
175+
});
176+
177+
test('mark keeps a pruned baseline usable for count comparison but not route comparison', () => {
178+
const session = makeSession('android');
179+
session.snapshot = makeSnapshotState(labeledNodes(20));
180+
181+
markAndroidSnapshotFreshness(session, 'click');
182+
183+
assert.equal(session.androidSnapshotFreshness?.routeComparable, false);
184+
assert.equal(session.androidSnapshotFreshness?.baselineSignatures, undefined);
185+
assert.equal(session.androidSnapshotFreshness?.baselineCount, 20);
186+
});
187+
188+
test('mark is Android-only and the active window expires', () => {
189+
vi.useFakeTimers();
190+
const iosSession = makeSession('ios');
191+
markAndroidSnapshotFreshness(iosSession, 'click');
192+
assert.equal(iosSession.androidSnapshotFreshness, undefined);
193+
194+
const session = makeSession('android');
195+
markAndroidSnapshotFreshness(session, 'click');
196+
assert.ok(getActiveAndroidSnapshotFreshness(session));
197+
198+
vi.advanceTimersByTime(2_501);
199+
assert.equal(getActiveAndroidSnapshotFreshness(session), undefined);
200+
assert.equal(session.androidSnapshotFreshness, undefined);
201+
});
202+
203+
test('clear removes an active freshness window', () => {
204+
const session = makeSession('android');
205+
markAndroidSnapshotFreshness(session, 'click');
206+
clearAndroidSnapshotFreshness(session);
207+
assert.equal(session.androidSnapshotFreshness, undefined);
208+
});

0 commit comments

Comments
 (0)