Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 94 additions & 7 deletions src/daemon/__tests__/generic-settle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { activateCompleteRefFrame, refFrameState } from '../ref-frame.ts';
import { setSessionSnapshot } from '../session-snapshot.ts';
import type { SessionStore } from '../session-store.ts';
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
import type { SessionState } from '../session-state.ts';
import type { SessionRef, SessionState } from '../session-state.ts';
import { buildSnapshotState } from '@agent-device/capture-kit/snapshot-state';

// #1638 `--settle` on the GENERIC daemon route (scroll/back): the settled diff,
Expand Down Expand Up @@ -85,19 +85,19 @@ type SettlePayload = {
const captureObservations: Array<{ postGestureStabilizationPending: boolean }> = [];

async function emulateCaptureSnapshotForSession(
session: SessionState,
ref: SessionRef,
flags: CommandFlags | undefined,
sessionStore: SessionStore,
options: { interactiveOnly: boolean },
) {
captureObservations.push({
postGestureStabilizationPending: session.postGestureStabilization !== undefined,
postGestureStabilizationPending:
sessionStore.requireCurrent(ref).postGestureStabilization !== undefined,
});
const effectiveFlags = { ...(flags ?? {}), snapshotInteractiveOnly: options.interactiveOnly };
const snapshotData = (await mockDispatch('snapshot')) as Parameters<typeof buildSnapshotState>[0];
const snapshot = buildSnapshotState(snapshotData ?? {}, effectiveFlags);
setSessionSnapshot(session, snapshot);
sessionStore.set(session.name, session);
setSessionSnapshot(sessionStore.requireCurrent(ref), snapshot);
return snapshot;
}

Expand Down Expand Up @@ -210,8 +210,7 @@ beforeEach(() => {
mockCaptureSnapshotForSession.mockImplementation(
(...args: Parameters<typeof captureSnapshotForSession>) => {
const [ref, flags, sessionStore, _contextFromFlags, options] = args;
const session = sessionStore.requireCurrent(ref);
return emulateCaptureSnapshotForSession(session, flags, sessionStore, options);
return emulateCaptureSnapshotForSession(ref, flags, sessionStore, options);
},
);
});
Expand Down Expand Up @@ -620,3 +619,91 @@ test('an orphaned --settle-quiet is rejected before the command dispatches', asy
expect(response.error?.code).toBe('INVALID_ARGS');
expect(response.error?.message).toContain('--settle-quiet');
});

test('scroll stays successful when its lifetime retires during optional settle observation', async () => {
const store = makeSessionStore();
const name = 'generic-settle-retired';
const session = seedSession(name, store);
const ref = store.lookup(name)!;
mockCommandDispatch([AFTER_NODES]);
mockCaptureSnapshotForSession.mockImplementationOnce(
async (boundRef, flags, sessionStore, _context, options) => {
const observed = await emulateCaptureSnapshotForSession(
boundRef,
flags,
sessionStore,
options,
);
queueMicrotask(() => {
store.retire(ref);
store.publish(name, makeIosSession(name));
});
return observed;
},
);
const response = await dispatchGeneric({
sessionName: name,
sessionStore: store,
session,
command: 'scroll',
positionals: ['down'],
flags: { ...SETTLE_FLAGS },
});
expect(expectOkData(response).settle).toBeUndefined();
expect(store.get(name)?.snapshot).toBeUndefined();
expect(store.get(name)?.actions).toEqual([]);
});

for (const change of ['rebuild', 'retire'] as const) {
test(`held generic settle capture respects its lifetime after ${change}`, async () => {
const store = makeSessionStore();
const name = `generic-held-settle-${change}`;
const session = seedSession(name, store);
const ref = store.lookup(name)!;
let entered!: () => void;
let release!: () => void;
const reached = new Promise<void>((resolve) => {
entered = resolve;
});
const held = new Promise<void>((resolve) => {
release = resolve;
});
mockDispatch.mockImplementation(async (command) => {
if (command !== 'snapshot') return {};
entered();
await held;
return snapshotPayload({ nodes: AFTER_NODES });
});
const pending = dispatchGeneric({
sessionName: name,
sessionStore: store,
session,
command: 'scroll',
positionals: ['down'],
flags: { ...SETTLE_FLAGS },
});
try {
await reached;
const trace = { outPath: 'latest-trace', startedAt: 1 };
const successor = makeIosSession(name);
if (change === 'rebuild') store.update(ref, { trace });
else {
store.retire(ref);
store.publish(name, successor);
}
release();
const data = expectOkData(await pending);
if (change === 'rebuild') {
expect(store.requireCurrent(ref).trace).toBe(trace);
expect(store.requireCurrent(ref).snapshot?.nodes[1]?.label).toBe('Load more');
} else {
expect(data.settle).toBeUndefined();
expect(store.get(name)).toBe(successor);
expect(successor.snapshot).toBeUndefined();
}
} finally {
release();
await pending;
}
});
}
45 changes: 45 additions & 0 deletions src/daemon/__tests__/selector-capture-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,3 +377,48 @@ test('a held selector capture updates the matching rebuilt record without restor
await running.catch(() => {});
}
});

test('selector capture and sparse recovery both use current same-lifetime app metadata', async () => {
const { runtime, sessionName, sessionStore } = makeCaptureRuntime('selector-current-metadata');
const ref = sessionStore.lookup(sessionName)!;
sessionStore.update(ref, { appBundleId: 'before-first-capture' });
boundCapture
.mockImplementationOnce(async () => {
sessionStore.update(ref, { appBundleId: 'before-recovery-capture' });
return {
backend: 'xctest',
producer: 'apple-runner',
nodes: [{ index: 0, type: 'Application' }],
};
})
.mockResolvedValueOnce({
backend: 'xctest',
producer: 'apple-runner',
nodes: [{ index: 0, type: 'Button', label: 'Recovered' }],
});
const result = await runtime.capture({
flags: { snapshotInteractiveOnly: true },
recovery: { legacyIosSparse: { query: 'Search', shouldScope: false } },
});
expect(result.snapshot.nodes[0]?.label).toBe('Recovered');
expect(boundCapture.mock.calls.map(([input]) => input.options?.appBundleId)).toEqual([
'before-first-capture',
'before-recovery-capture',
]);
expect(sessionStore.requireCurrent(ref).appBundleId).toBe('before-recovery-capture');
});

test('a retired selector runtime refuses even a reusable cached capture without touching its successor', async () => {
const { runtime, sessionName, sessionStore } = makeCaptureRuntime('selector-retired-cache');
const ref = sessionStore.lookup(sessionName)!;
await runtime.capture({ flags: {} });
sessionStore.retire(ref);
const successor = sessionStore.publish(sessionName, ref.session);
await expect(runtime.capture({ flags: {} })).rejects.toThrow(
expect.objectContaining({
details: expect.objectContaining({ reason: 'session_lifetime_ended' }),
}),
);
expect(boundCapture).toHaveBeenCalledOnce();
expect(sessionStore.requireCurrent(successor)).toBe(ref.session);
});
40 changes: 39 additions & 1 deletion src/daemon/__tests__/session-snapshot.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { expect, test } from 'vitest';
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
import type { SettleObservation } from '@agent-device/contracts/interaction';
import type { SnapshotState } from '@agent-device/kernel/snapshot';
import type { SessionState } from '../session-state.ts';
import {
markSessionPartialRefsIssued,
issueSettleRefs,
resolveRefStalenessWarning,
setSessionSnapshot,
setCommandSnapshot,
Expand Down Expand Up @@ -179,12 +182,14 @@ test('a ref pinned before a diff keeps resolving: the diff advances the counter,
// `diff` replaces the stored tree, so lineage advances the counter — but it passes
// `issuesRefsToClient: false`, so it never reactivates the frame.
const afterDiff: SessionState = { ...session };
const diffSnapshot = makeSnapshot();
setCommandSnapshot(afterDiff, {
snapshot: afterDiff.snapshot!,
snapshot: diffSnapshot,
scopeSource: undefined,
keptCurrentSnapshot: false,
previousGeneration: session.snapshotGeneration,
});
expect(afterDiff.snapshot).toBe(diffSnapshot);
expect(afterDiff.snapshotGeneration).not.toBe(session.snapshotGeneration);
expect(refFrameEpoch(afterDiff)).toBe(issuedAt);

Expand Down Expand Up @@ -220,3 +225,36 @@ test('keeping the current snapshot leaves the counter alone', () => {
});
expect(session.snapshotGeneration).toBe(before);
});

for (const retire of [false, true]) {
test(`settle ref issuance checks lifetime before publishing (${retire ? 'retired' : 'live'})`, () => {
const store = makeSessionStore();
const session = makeSession();
setSessionSnapshot(session, makeSnapshot());
const ref = store.publish('cwd:settle:default', session);
const priorFrame = refFrame(session);
if (retire) {
store.retire(ref);
store.publish(ref.address, session);
}
const observation: SettleObservation = {
settled: true,
waitedMs: 1,
captures: 2,
quietMs: 1,
timeoutMs: 20,
diff: {
summary: { additions: 1, removals: 0, unchanged: 0 },
lines: [{ kind: 'added', text: 'new button', ref: 'e1' }],
},
};
const generation = issueSettleRefs(ref, store, observation);
if (retire) {
expect(generation).toBeUndefined();
expect(refFrame(session)).toBe(priorFrame);
} else {
expect(generation).toBe(session.snapshotGeneration);
expect(refFrameScope(session)).toEqual(new Set(['e1']));
}
});
}
13 changes: 9 additions & 4 deletions src/daemon/__tests__/snapshot-command-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ for (const command of ['snapshot', 'diff snapshot'] as const) {
});
}

for (const change of ['rebuild', 'replace'] as const) {
for (const change of ['unchanged', 'rebuild', 'replace'] as const) {
test(`snapshot completion respects a scoped lifetime after ${change}`, async () => {
const sessionStore = makeSessionStore();
const address = 'cwd:snapshot-completion:default';
Expand Down Expand Up @@ -117,13 +117,18 @@ for (const change of ['rebuild', 'replace'] as const) {
);
try {
await entered.promise;
if (change === 'rebuild') {
const trace = { outPath: 'intervening-trace', startedAt: 1 };
sessionStore.update(ref, { trace });
if (change !== 'replace') {
const trace =
change === 'rebuild' ? { outPath: 'intervening-trace', startedAt: 1 } : ref.session.trace;
if (change === 'rebuild') sessionStore.update(ref, { trace });
const priorRecord = sessionStore.requireCurrent(ref);
release.resolve();
expect(await result).toMatchObject({ response: { ok: true } });
const current = sessionStore.requireCurrent(ref);
expect(current.trace).toBe(trace);
expect(current).not.toBe(priorRecord);
expect(priorRecord.snapshot).toBeUndefined();
expect(ref.session.snapshot).toBeUndefined();
expect(current.snapshot?.nodes[0]?.label).toBe('Captured');
} else {
sessionStore.retire(ref);
Expand Down
2 changes: 2 additions & 0 deletions src/daemon/generic-settle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ async function observeSettled(
session: context.sessionName,
requestId: context.req.meta?.requestId,
});
if (context.sessionRef && !context.sessionStore.resolveCurrent(context.sessionRef))
return undefined;
const refsGeneration = issueSettleRefs(context.sessionRef, context.sessionStore, observation);
return refsGeneration === undefined ? observation : { ...observation, refsGeneration };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -745,3 +745,32 @@ test('corroborated runtime taps retain target evidence through save and replay',
expect(pressCount).toBe(2);
expect(snapshotCount).toBeGreaterThanOrEqual(4);
});

test('a tap corroborates against its admitted snapshot after a same-lifetime record rebuild', async () => {
const store = makeSessionStore();
const name = 'ios-admitted-tap-baseline';
const ref = store.publish(
name,
makeIosSession(name, {
appBundleId: 'com.example.app',
snapshot: snapshot(imageViewerNodes),
}),
);
store.update(ref, { snapshot: snapshot(profileNodes) });
legacyDispatchCapture.mockImplementation(async (_device, command) => {
if (command === 'press') throw new AppError('XCTEST_RECORDED_FAILURE', 'tap failed');
if (command === 'snapshot') return snapshotPayload(imageViewerNodes);
return {};
});
const response = await handleInteractionCommands({
req: { token: 'test', session: name, command: 'click', positionals: ['104', '222'], flags: {} },
sessionName: name,
sessionRef: ref,
sessionStore: store,
contextFromFlags,
...getRuntimeBindings(),
});
expect(response?.ok).toBe(true);
if (!response?.ok) throw new Error('landed tap should be corroborated');
expect(response.data?.warning).toMatch(/same-scope post-action accessibility capture changed/);
});
Loading
Loading