Skip to content
Merged
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
2 changes: 1 addition & 1 deletion packages/command-registry/src/flag-definitions-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ export const ACTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
min: 0,
usageLabel: '--settle-quiet <ms>',
usageDescription:
'Settle: quiet window the UI must hold to count as settled (default 500ms). On iOS, a broad screen replacement such as a modal dismissal is confirmed for at least 1500ms whatever window is asked for, within the --timeout settle deadline',
'Settle: quiet window the UI must hold to count as settled (default 500ms; 300ms when the settled tree comes from the iOS simulator snapshot bridge). On iOS, a broad screen replacement such as a modal dismissal is confirmed for at least 1500ms whatever window is asked for, within the --timeout settle deadline',
projectConfig: true,
recorded: false,
},
Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/src/client-gesture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export type RepeatedPressOptions = {
* Opt-in (#1101): after the action, wait for the UI to go quiet and return the
* settled diff vs the pre-action tree (`settle` on the result) in the same
* response. Best-effort — never fails the action. `settleQuietMs` tunes the
* quiet window (default 500ms); `timeoutMs` bounds the settle wait (default
* quiet window (default 500ms, or 300ms when the settled tree comes from the iOS
* simulator snapshot bridge); `timeoutMs` bounds the settle wait (default
* 10s) when `settle` is true. A bare `timeoutMs` without `settle` is ignored
* for compatibility; `settleQuietMs` still requires `settle`.
*/
Expand Down
109 changes: 105 additions & 4 deletions src/__tests__/daemon-composition/generic-settle.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { composedPlatformServicesFixture } from './platform-services-fixture.ts';
import { beforeEach, expect, test, vi } from 'vitest';
import type { CommandFlags } from '@agent-device/contracts/command';
import type { CommandClock } from '@agent-device/contracts/runtime-contract';
import type { RawSnapshotNode } from '@agent-device/kernel/snapshot';
import {
APP_SURFACE,
Expand Down Expand Up @@ -113,18 +114,36 @@ async function emulateCaptureSnapshotForSession(
return snapshot;
}

function mockCommandDispatch(snapshots: Array<typeof BEFORE_NODES>) {
function mockCommandDispatch(
snapshots: Array<typeof BEFORE_NODES>,
producer: NonNullable<GenericSettleTree['producer']> = 'apple-runner',
) {
let snapshotCalls = 0;
mockDispatch.mockImplementation(async (command) => {
if (command === 'snapshot') {
const nodes = snapshots[Math.min(snapshotCalls, snapshots.length - 1)];
snapshotCalls += 1;
return { nodes, backend: 'xctest', producer: 'apple-runner' };
return { nodes, backend: 'xctest', producer };
}
return {};
});
}

/**
* A clock the settle loop advances instead of waiting. The default-window cases below assert the
* window a run RESOLVED, which needs no real elapsed time: the loop's own budget arithmetic runs on
* this clock, so the suite neither slows nor goes unstable under load.
*/
function fakeClock(stepMs = 300): CommandClock {
let elapsed = 0;
return {
now: () => elapsed,
sleep: async (ms: number) => {
elapsed += ms > 0 ? ms : stepMs;
},
};
}

const contextFromFlags = () => ({}) as never;

/**
Expand Down Expand Up @@ -161,13 +180,14 @@ function seedSession(
type GenericSettleTree = {
nodes: RawSnapshotNode[];
systemSurface?: IosSystemSurfaceProvenance;
producer?: 'apple-runner' | 'simulator-ax-bridge';
};

function snapshotPayload(tree: GenericSettleTree) {
return {
nodes: tree.nodes,
backend: 'xctest' as const,
producer: 'apple-runner' as const,
producer: tree.producer ?? ('apple-runner' as const),
...(tree.systemSurface ? { systemSurface: tree.systemSurface } : {}),
};
}
Expand Down Expand Up @@ -205,6 +225,8 @@ async function dispatchGeneric(params: {
runtimeBindings?: Readonly<
Pick<Parameters<typeof dispatchGenericCommand>[0], 'inspectFacts' | 'bindDevice'>
>;
/** Injects a clock into every command surface the route builds, so no test waits real time. */
clock?: CommandClock;
}): Promise<DaemonResponse> {
const req: DaemonRequest = {
token: 't',
Expand All @@ -214,7 +236,9 @@ async function dispatchGeneric(params: {
...(params.flags ? { flags: params.flags } : {}),
};
return await dispatchGenericCommand({
createCommandSurface: testCreateCommandSurface,
createCommandSurface: params.clock
? async (config) => await testCreateCommandSurface({ ...config, clock: params.clock })
: testCreateCommandSurface,
platformServices: composedPlatformServicesFixture(),
req,
ref: params.sessionStore.lookup(params.sessionName)!,
Expand Down Expand Up @@ -801,3 +825,80 @@ for (const change of ['rebuild', 'retire'] as const) {
}
});
}

// The default quiet window keys on the capture the settle loop PERFORMS (#3470 follow-up), not on
// the baseline it diffs: on this route the baseline is the session's stored tree, which can be
// several commands stale and served by a different producer. All three run on an injected clock, so
// they assert the resolved window without real waiting.
test('scroll --settle without --settle-quiet uses the shorter default when the loop reads the simulator bridge', async () => {
const sessionStore = makeSessionStore();
const sessionName = 'generic-settle-default-quiet';
seedSession(sessionName, sessionStore, {
nodes: BEFORE_NODES,
producer: 'simulator-ax-bridge',
});
mockCommandDispatch([AFTER_NODES], 'simulator-ax-bridge');

const response = await dispatchGeneric({
sessionName,
sessionStore,
command: 'scroll',
positionals: ['down'],
// No settleQuietMs: the route's own default window is what is under test.
flags: { settle: true, timeoutMs: 2_000 },
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
clock: fakeClock(),
});

const settle = expectOkData(response).settle as SettlePayload;
expect(settle.settled).toBe(true);
expect(settle.quietMs).toBe(300);
});

test('scroll --settle keeps the 500ms default when the loop reads the Apple runner', async () => {
const sessionStore = makeSessionStore();
const sessionName = 'generic-settle-default-quiet-runner';
seedSession(sessionName, sessionStore, {
nodes: BEFORE_NODES,
producer: 'apple-runner',
});
mockCommandDispatch([AFTER_NODES], 'apple-runner');

const response = await dispatchGeneric({
sessionName,
sessionStore,
command: 'scroll',
positionals: ['down'],
flags: { settle: true, timeoutMs: 2_000 },
clock: fakeClock(),
});

const settle = expectOkData(response).settle as SettlePayload;
expect(settle.settled).toBe(true);
expect(settle.quietMs).toBe(500);
});

test('a stale bridge-sourced baseline does not shorten a settle the Apple runner performs', async () => {
// The mismatch the stored baseline can carry: the tree on file came from the bridge, but the
// captures that pay this window come from the runner, whose read the short window was never
// measured on. Keying on the baseline would hold 300ms against an unmeasured read.
const sessionStore = makeSessionStore();
const sessionName = 'generic-settle-default-quiet-mismatch';
seedSession(sessionName, sessionStore, {
nodes: BEFORE_NODES,
producer: 'simulator-ax-bridge',
});
mockCommandDispatch([AFTER_NODES], 'apple-runner');

const response = await dispatchGeneric({
sessionName,
sessionStore,
command: 'scroll',
positionals: ['down'],
flags: { settle: true, timeoutMs: 2_000 },
clock: fakeClock(),
});

const settle = expectOkData(response).settle as SettlePayload;
expect(settle.settled).toBe(true);
expect(settle.quietMs).toBe(500);
});
1 change: 1 addition & 0 deletions src/commands/interaction/runtime/selector-wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ type StableCaptureResult = {
waitedMs: number;
captures: number;
nodeCount: number;
failure?: { error: unknown };
};

export type SelectorWaitOperations<Runtime extends SelectorWaitRuntime> = {
Expand Down
184 changes: 184 additions & 0 deletions src/commands/interaction/runtime/settle-default-quiet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import type { SnapshotProvenance, SnapshotState } from '@agent-device/kernel/snapshot';
import { ref } from './selector-read-utils.ts';
import {
buttonSnapshot,
createSettleDevice,
welcomeSnapshot,
} from './__tests__/settle-device-fixtures.ts';

// The `--settle` DEFAULT quiet window keys on the capture the settle loop PERFORMS (#3470
// follow-up), because that read is the one the window prices: the loop holds its quiet window open
// across captures of its own. The pre-action baseline cannot answer this — on the ref route it is
// the stored ref frame, on the generic route the session's stored tree, and either can be several
// commands stale and served by a producer other than the one settle then reads through. A caller
// that asks for a window with `--settle-quiet` always outranks the default.
//
// Budgets are injected (fake clock) — no real waiting.

function withProvenance<P extends SnapshotProvenance>(state: SnapshotState, provenance: P) {
return { ...state, ...provenance };
}

const BRIDGE = { backend: 'xctest', producer: 'simulator-ax-bridge' } as const;
const RUNNER = { backend: 'xctest', producer: 'apple-runner' } as const;

type LoopCapturePath = SnapshotProvenance | undefined | ((capture: number) => SnapshotProvenance);

/**
* A press whose baseline and whose loop captures come from declared capture paths, so the two can
* be made to agree or to disagree. The pressed button stays on screen, so no capture is a broad
* replacement and the window under test is the one the loop priced, not the confirmation floor.
*/
function pressWithCapturePaths(params: {
baseline?: SnapshotProvenance;
loop?: LoopCapturePath;
settle?: { quietMs?: number; timeoutMs?: number };
}) {
const baseline = params.baseline
? withProvenance(buttonSnapshot(), params.baseline)
: buttonSnapshot();
let captures = 0;
const device = createSettleDevice({
stored: baseline,
captureSnapshot: () => {
// A ref press captures nothing before the action, so every call is the loop's own sample.
captures += 1;
const provenance = typeof params.loop === 'function' ? params.loop(captures) : params.loop;
return {
snapshot: provenance ? withProvenance(buttonSnapshot(), provenance) : buttonSnapshot(),
};
},
});
return device.interactions.press(ref('@e1'), { session: 'default', settle: params.settle ?? {} });
}

test('a settle the simulator snapshot bridge performs uses the shorter default window', async () => {
const result = await pressWithCapturePaths({ loop: BRIDGE });

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.settled, true);
assert.equal(settle.quietMs, 300);
assert.ok(settle.waitedMs < 500, `bridge settle held ${settle.waitedMs}ms`);
});

test('an explicit --settle-quiet outranks the per-capture default window', async () => {
const result = await pressWithCapturePaths({ loop: BRIDGE, settle: { quietMs: 700 } });

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.quietMs, 700);
});

// Each of these is a read the 300 ms default was NOT measured on, so shortening its window would be
// an unmeasured change of behaviour rather than the measured one. The Apple runner shares the
// `xctest` CHANNEL with the bridge, which is why the rule keys on the producer.
const UNMEASURED_CAPTURES: Array<[string, SnapshotProvenance?]> = [
['the Apple runner tree read (same channel, different producer)', RUNNER],
['an Appium-sourced tree on the same channel', { backend: 'xctest', producer: 'appium-source' }],
['the Android helper', { backend: 'android', producer: 'android-uiautomator' }],
['a capture that declares no provenance at all', undefined],
];

for (const [label, provenance] of UNMEASURED_CAPTURES) {
test(`${label} keeps the 500ms default window`, async () => {
const result = await pressWithCapturePaths({ loop: provenance });

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.settled, true);
assert.equal(settle.quietMs, 500);
assert.ok(settle.waitedMs >= 500, `${label} settled after ${settle.waitedMs}ms`);
});
}

test('a bridge read during settle earns the shorter window even from a runner-issued ref frame', async () => {
// The ref frame the action was authorized against came from the runner, so keying the window on
// the baseline would hold the unmeasured 500 ms against captures the bridge answered.
const result = await pressWithCapturePaths({ baseline: RUNNER, loop: BRIDGE });

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.quietMs, 300);
assert.ok(settle.waitedMs < 500, `bridge settle held ${settle.waitedMs}ms`);
});

test('a runner read during settle keeps the 500ms window despite a bridge-issued baseline', async () => {
// The unsafe direction of the same mismatch: holding 300 ms for a read priced at 500 ms would
// settle on a window the measurement never covered.
const result = await pressWithCapturePaths({ baseline: BRIDGE, loop: RUNNER });

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.quietMs, 500);
assert.ok(settle.waitedMs >= 500, `runner settle held only ${settle.waitedMs}ms`);
});

test('the capture that decides the verdict prices the whole quiet span, even after a producer switch', async () => {
// The quiet span is elapsed time over which the tree did not change, whichever producer read it.
// A run that starts on the runner and continues on the bridge settles on the bridge's window.
const result = await pressWithCapturePaths({
loop: (capture) => (capture === 1 ? RUNNER : BRIDGE),
});

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.settled, true);
assert.equal(settle.quietMs, 300);
assert.ok(settle.waitedMs < 500, `producer switch held ${settle.waitedMs}ms`);
});

test('a capture that breaks mid-settle reports the window the run had priced', async () => {
let captures = 0;
const device = createSettleDevice({
stored: buttonSnapshot(),
captureSnapshot: () => {
captures += 1;
if (captures === 1) return { snapshot: withProvenance(buttonSnapshot(), BRIDGE) };
throw new Error('AX bridge crashed');
},
});

const result = await device.interactions.press(ref('@e1'), { session: 'default', settle: {} });

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.settled, false);
assert.match(settle.hint ?? '', /Settle observation unavailable \(AX bridge crashed\)/);
assert.equal(settle.quietMs, 300);
});

test('the shorter default window never shortens a broad-transition confirmation', async () => {
// The trap this layer owes layer 1: a 300 ms default sits under the 1.5 s floor, so a rule that
// armed on `requestedQuietMs >= DEFAULT_STABLE_QUIET_MS` would silently switch the #1831
// confirmation off for every default settle the bridge answers. Here the pre-action tree is the
// tiny-baseline shape, so the confirmation owns the wait and the 300 ms default still holds its
// 1.5 s floor (#3470).
const sparseBaseline = withProvenance(buttonSnapshot(), BRIDGE);
let captures = 0;
const device = createSettleDevice({
stored: sparseBaseline,
captureSnapshot: () => {
captures += 1;
return {
snapshot: captures === 1 ? sparseBaseline : withProvenance(welcomeSnapshot(), BRIDGE),
};
},
});

const result = await device.interactions.press(ref('@e1'), {
session: 'default',
settle: { timeoutMs: 5_000 },
});

const settle = result.settle;
assert.ok(settle);
assert.equal(settle.settled, true);
assert.equal(settle.quietMs, 300);
assert.ok(
settle.waitedMs >= 1_500,
`confirmation did not outlast the shorter default: waitedMs=${settle.waitedMs}`,
);
});
Loading
Loading