From cb3b699a389fc658697271f9f66fd5529186b385 Mon Sep 17 00:00:00 2001 From: Tejesh Mehta Date: Sat, 5 Dec 2026 14:23:27 -0800 Subject: [PATCH 1/3] feat: add a sampled path gesture for one timed contact A path moves one contact through 2 to 256 caller-authored samples, so it can reverse, pause, or curve where pan and drag only go straight. It runs through the target-authored-drag tier, so backends that keep intermediate samples execute it and the rest refuse it before dispatch. Co-Authored-By: Claude Opus 5.5 --- .../src/internal/__tests__/script.test.ts | 10 ++ .../interaction/runtime/gesture-command.ts | 2 + .../command-surface/src/interaction/index.ts | 8 +- .../src/interaction/metadata.ts | 26 ++++- packages/contracts/src/gesture-input.ts | 15 ++- packages/contracts/src/gesture-plan-types.ts | 3 +- .../src/platform-runtime-operations.test.ts | 11 ++ .../src/platform-runtime-operations.ts | 2 + packages/daemon/src/core/gesture-runtime.ts | 1 + .../internal/interaction-gesture-path.test.ts | 105 ++++++++++++++++++ .../internal/interaction-gesture.ts | 2 +- .../request-router-coordinate-unit.test.ts | 31 ++++++ packages/daemon/src/server/coordinate-unit.ts | 15 ++- .../src/gesture-normalization.test.ts | 27 +++++ .../gestures/src/gesture-normalization.ts | 27 +++++ .../src/gesture-payload-reader.test.ts | 51 +++++++++ .../gestures/src/gesture-payload-reader.ts | 74 +++++++++++- packages/gestures/src/gesture-plan.test.ts | 28 +++++ packages/gestures/src/gesture-plan.ts | 10 ++ .../src/__tests__/touch-plan-lowering.test.ts | 25 +++++ packages/selectors/src/interaction-action.ts | 4 +- src/commands/schema/cli-help-gestures.ts | 1 + src/commands/schema/cli-help-topics.test.ts | 2 +- src/commands/schema/cli-help.ts | 2 +- src/mcp/__tests__/command-tools.test.ts | 17 ++- website/docs/docs/client-api.md | 15 +++ website/docs/docs/commands.md | 9 +- 27 files changed, 501 insertions(+), 22 deletions(-) create mode 100644 packages/daemon/src/execution/interaction/internal/interaction-gesture-path.test.ts diff --git a/packages/ad-script/src/internal/__tests__/script.test.ts b/packages/ad-script/src/internal/__tests__/script.test.ts index 382dcbfd56f..4a1759ac7a5 100644 --- a/packages/ad-script/src/internal/__tests__/script.test.ts +++ b/packages/ad-script/src/internal/__tests__/script.test.ts @@ -960,6 +960,16 @@ test('a recorded gesture tap round-trips its contacts and series flags', () => { assert.deepEqual(parsed?.flags, { holdMs: 40, count: 3, pauseMs: 100 }); }); +test('a recorded gesture path keeps its JSON argument through the script line', () => { + const json = + '{"durationMs":500,"samples":[{"offsetMs":0,"point":{"x":1,"y":2}},{"offsetMs":500,"point":{"x":1,"y":4}}]}'; + const line = formatReplayScriptForTest([ + { ts: 0, command: 'gesture', positionals: ['path', json], flags: {} }, + ]); + const [parsed] = parseReplayScriptDetailed(line).actions; + assert.deepEqual(parsed?.positionals, ['path', json]); +}); + test('an .ad gesture tap with an odd coordinate count is refused before replay', () => { assert.throws(() => parseReplayScriptDetailed('gesture tap 80 300 200\n'), { code: 'INVALID_ARGS', diff --git a/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts b/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts index 664c903aeba..26063430ef3 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts @@ -145,6 +145,8 @@ function centroidAt( function gestureMessage(input: GestureSemanticInput, from: Point, to: Point): string { switch (input.intent) { + case 'path': + return `Moved one contact through ${input.samples.length} samples over ${input.durationMs} ms`; case 'pan': { const origin = 'preset' in input ? from : input.origin; const delta = 'preset' in input ? { x: to.x - from.x, y: to.y - from.y } : input.delta; diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index bc88d209637..3ab5eaae9da 100644 --- a/packages/command-surface/src/interaction/index.ts +++ b/packages/command-surface/src/interaction/index.ts @@ -458,10 +458,10 @@ const interactionCliSchemas = { ], }, gesture: { - usageOverride: 'gesture ...', + usageOverride: 'gesture ...', usageFlags: [], - listUsageOverride: 'gesture ...', - positionalArgs: ['pan|fling|swipe|pinch|rotate|transform|tap|drag', 'args?'], + listUsageOverride: 'gesture ...', + positionalArgs: ['pan|fling|swipe|pinch|rotate|transform|tap|drag|path', 'args?'], allowsExtraPositionals: true, allowedFlags: [...GESTURE_CLI_FLAGS, ...postActionObservationCliFlags('gesture')], flagsByAction: GESTURE_FLAGS_BY_ACTION, @@ -692,7 +692,7 @@ const gestureCommandFacet = defineCommandFacet({ name: 'gesture', effect: 'destructive', text: { - summary: 'Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures', + summary: 'Run pan, fling, swipe, pinch, rotate, transform, tap, drag, or path', searchHint: 'reorder zoom multi-touch', cliDetail: 'Argument shapes: pan [durationMs], fling [distance], swipe , pinch [x y | @ref|selector] (centered on the screen when neither is given), rotate [x] [y], transform [durationMs], tap [... ] [--hold-ms ] [--count ] [--pause-ms ], or drag [sourceHoldMs] [moveMs] [destinationHoldMs]; drag holds the source down first (800 ms by default) before moving, which is what engages a reorder handle. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values. Use --settle to wait for the UI to go quiet after the last repetition and compare with the last observed tree. gesture swipe accepts --no-post-gesture-stabilization to skip the stabilization wait before the next read, for a caller whose own polling verifies the screen.', diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index 254a44c48f9..2136555a72a 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -30,6 +30,7 @@ import { enumField, integerField, interactionTargetFields, + jsonSchemaField, numberField, operatorField, pointArrayField, @@ -83,7 +84,7 @@ const interactionCommandDescriptions = { is: 'Check whether a selector satisfies a UI predicate such as visible, hidden, exists, absent, editable, selected, checked, focused, or text. `absent` passes only when one readable, complete, settled, unscoped, full-depth accessibility capture has zero matches. This command checks the current condition without polling.', find: 'Find by text/label/value/role/id and run action; the action defaults to click. The role locator matches snapshot kind vocabulary (button, text, text-field, switch, ...); pre-reconciliation leaf spellings (statictext, edittext, textview) stay accepted on the nodes that carried them during a deprecation window. The focus and type actions aim at a text field: the match or the field holding it, even beside other fields, or else the one enabled on-screen field inside the match. Several enabled on-screen fields inside the match refuse with AMBIGUOUS_MATCH and the field candidates, and a disabled target refuses with reason target_disabled. Web text boxes are not recognized as text fields.', gesture: - 'Perform a structured pan, fling, swipe, pinch, rotate, transform, tap, or drag gesture. Each gesture kind has its own inputs. A tap touches 2 to 5 points at once; count and pauseMs control repetition. A drag takes a source and a destination ref or selector and holds the source down for 800 ms by default before carrying it over, which is how a list item changes position or a drop target is hit. Settle observes the UI once after the last repetition and compares with the last observed tree.', + 'Perform a structured pan, fling, swipe, pinch, rotate, transform, tap, drag, or path gesture. Each gesture kind has its own inputs. A tap touches 2 to 5 points at once; count and pauseMs control repetition. A drag takes a source and a destination ref or selector and holds the source down for 800 ms by default before carrying it over, which is how a list item changes position or a drop target is hit. A path moves one contact through timed samples, so it can reverse, pause, or curve; it works where drag works. Settle observes the UI once after the last repetition and compares with the last observed tree.', } as const; type InteractionCommandName = keyof typeof interactionCommandDescriptions; @@ -242,7 +243,28 @@ const gestureFields = { 'Element to pinch, as an @ref or selector; the pinch centers on it, in place of origin.', ), degrees: numberField('Rotation in degrees.'), - durationMs: integerField('Pan/transform duration.', { min: 16, max: 10_000 }), + durationMs: integerField('Pan, transform, or path duration.', { min: 16, max: 10_000 }), + samples: jsonSchemaField({ + type: 'array', + description: + 'Path samples for one contact: 2 to 256 points with offsetMs from touch-down. Offsets start at 0, strictly increase, and end at durationMs. A repeated point at a later offset holds the contact there.', + items: { + type: 'object', + properties: { + offsetMs: { type: 'number' }, + point: { + type: 'object', + properties: { x: { type: 'number' }, y: { type: 'number' } }, + required: ['x', 'y'], + additionalProperties: false, + }, + }, + required: ['offsetMs', 'point'], + additionalProperties: false, + }, + minItems: 2, + maxItems: 256, + }), pointerCount: integerField('Pan touch pointer count (1 or 2).', { min: 1, max: 2 }), points: pointArrayField('Tap contact points, held together for holdMs.', { min: GESTURE_TAP_MIN_CONTACTS, diff --git a/packages/contracts/src/gesture-input.ts b/packages/contracts/src/gesture-input.ts index bc6b7d9f379..fc341070125 100644 --- a/packages/contracts/src/gesture-input.ts +++ b/packages/contracts/src/gesture-input.ts @@ -1,6 +1,6 @@ import type { Point } from '@agent-device/kernel/snapshot'; import type { ScrollDirection, SwipePreset } from './scroll-gesture.ts'; -import type { GesturePointerCount } from './gesture-plan-types.ts'; +import type { GesturePointerCount, SinglePointerTrajectory } from './gesture-plan-types.ts'; export const COORDINATE_GESTURE_KINDS = [ 'pan', @@ -11,7 +11,7 @@ export const COORDINATE_GESTURE_KINDS = [ 'transform', 'tap', ] as const; -export const GESTURE_KINDS = [...COORDINATE_GESTURE_KINDS, 'drag'] as const; +export const GESTURE_KINDS = [...COORDINATE_GESTURE_KINDS, 'drag', 'path'] as const; export type DragGesturePayload = { kind: 'drag'; @@ -75,7 +75,18 @@ export type TapGesturePayload = { pauseMs?: number; }; +/** + * One contact that follows caller-authored samples. Each sample's offset is measured from touch-down, + * and a repeated point at a later offset holds the contact there. + */ +export type PathGesturePayload = { + kind: 'path'; + durationMs: number; + samples: SinglePointerTrajectory['samples']; +}; + export type GesturePayload = + | PathGesturePayload | PanGesturePayload | FlingGesturePayload | SwipeGesturePayload diff --git a/packages/contracts/src/gesture-plan-types.ts b/packages/contracts/src/gesture-plan-types.ts index 6606c176207..475fcfd9e37 100644 --- a/packages/contracts/src/gesture-plan-types.ts +++ b/packages/contracts/src/gesture-plan-types.ts @@ -20,7 +20,7 @@ export const DEFAULT_DRAG_SOURCE_HOLD_MS = 800; export const DEFAULT_DRAG_MOVE_MS = 500; export const DEFAULT_DRAG_DESTINATION_HOLD_MS = 0; -export type GestureIntent = 'fling' | 'pan' | 'pinch' | 'rotate' | 'transform' | 'tap'; +export type GestureIntent = 'path' | 'fling' | 'pan' | 'pinch' | 'rotate' | 'transform' | 'tap'; export type DragGestureInput = { intent: 'drag'; @@ -42,6 +42,7 @@ export type TargetedPinchGestureInput = { export type GestureExecutionProfile = 'endpoint-hold' | 'timed-pan'; export type GestureSemanticInput = + | { intent: 'path'; durationMs: number; samples: SinglePointerTrajectory['samples'] } | { intent: 'fling'; from: Point; to: Point } | { intent: 'fling'; preset: SwipePreset } | { diff --git a/packages/contracts/src/platform-runtime-operations.test.ts b/packages/contracts/src/platform-runtime-operations.test.ts index 41970815c2e..61088548d7a 100644 --- a/packages/contracts/src/platform-runtime-operations.test.ts +++ b/packages/contracts/src/platform-runtime-operations.test.ts @@ -180,3 +180,14 @@ test('a held pan needs the target-authored-drag tier; an unheld one stays on pla assert.equal(resolveGestureRuntimePlan({ ...pan, holdMs: 0 }).tier, 'plan'); assert.equal(resolveGestureRuntimePlan(pan).tier, 'plan'); }); + +test('a path needs the target-authored-drag tier, which keeps its intermediate samples', () => { + const samples = [ + { offsetMs: 0, point: { x: 10, y: 20 } }, + { offsetMs: 100, point: { x: 10, y: 120 } }, + ] as const; + assert.equal( + resolveGestureRuntimePlan({ intent: 'path', durationMs: 100, samples }).tier, + 'target-authored-drag', + ); +}); diff --git a/packages/contracts/src/platform-runtime-operations.ts b/packages/contracts/src/platform-runtime-operations.ts index c6af90d618a..89ae650db30 100644 --- a/packages/contracts/src/platform-runtime-operations.ts +++ b/packages/contracts/src/platform-runtime-operations.ts @@ -404,6 +404,8 @@ function gestureRuntimeTier(input: GestureCommandInput): GestureRuntimeTier { // drops them, so admit it through the tier whose fact promises hold-preserving execution and let // backends without that fact refuse before dispatch. if (input.intent === 'pan' && (input.holdMs ?? 0) > 0) return 'target-authored-drag'; + // An authored path lives in its intermediate samples for the same reason. + if (input.intent === 'path') return 'target-authored-drag'; if (isMultiTouchGesture(input)) return 'multi-touch'; // A direction-authored fling carries speed semantics a coordinate fling does not, which is the // one thing the Linux drag primitive cannot reproduce. diff --git a/packages/daemon/src/core/gesture-runtime.ts b/packages/daemon/src/core/gesture-runtime.ts index ee0772d48e5..ad43e4b60ad 100644 --- a/packages/daemon/src/core/gesture-runtime.ts +++ b/packages/daemon/src/core/gesture-runtime.ts @@ -162,6 +162,7 @@ function gestureViewportScope(input: GestureCommandInput): GestureViewportScope if (input.intent === 'fling' && 'preset' in input && input.preset === 'split-view-exit') { return 'display'; } + if (input.intent === 'path') return 'including-keyboard'; if ( input.intent === 'pan' && (input.pointerCount ?? 1) === 1 && diff --git a/packages/daemon/src/execution/interaction/internal/interaction-gesture-path.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-gesture-path.test.ts new file mode 100644 index 00000000000..90aab18cf90 --- /dev/null +++ b/packages/daemon/src/execution/interaction/internal/interaction-gesture-path.test.ts @@ -0,0 +1,105 @@ +import { expect, test } from 'vitest'; +import { buildGesturePlan } from '@agent-device/gestures/gesture-plan'; +import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface'; +import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts'; +import { makeIosSession } from '../../../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; +import { touchCreateCommandSurface } from '../../../__tests__/support/touch-command-surface-fake.ts'; +import { handleInteractionCommands } from '../index.ts'; +import { gestureRuntimeBindingsFixture } from './__tests__/gesture-runtime-bindings.fixtures.ts'; + +const reversal = { + kind: 'path', + durationMs: 1000, + samples: [ + { offsetMs: 0, point: { x: 100, y: 160 } }, + { offsetMs: 400, point: { x: 100, y: 300 } }, + { offsetMs: 800, point: { x: 100, y: 160 } }, + { offsetMs: 1000, point: { x: 100, y: 160 } }, + ], +}; + +/** Plans and performs a coordinate gesture through the daemon's bound backend, as the runtime does. */ +function executingSurface(sessionName: string): CreateDaemonCommandSurface { + return async (config) => { + const surface = await touchCreateCommandSurface(config); + return { + ...surface, + interactions: { + ...surface.interactions, + gesture: async (options) => { + if ('intent' in options.gesture && options.gesture.intent === 'path') { + const context = { session: sessionName }; + const viewport = await config.backend.resolveGestureViewport!(context); + if (!viewport) throw new Error('expected a gesture viewport'); + const plan = buildGesturePlan(options.gesture, viewport, 'ios'); + await config.backend.performGesture!(context, plan); + } + return await surface.interactions.gesture(options); + }, + }, + }; + }; +} + +async function runPath(input: Record, gestures = gestureRuntimeBindingsFixture()) { + const sessionName = 'gesture-path'; + const sessionStore = makeSessionStore(); + const session = makeIosSession(sessionName, { appBundleId: 'com.example.app' }); + sessionStore.publish(sessionName, session); + const response = await handleInteractionCommands({ + createCommandSurface: executingSurface(sessionName), + platformServices: daemonPlatformServicesFixture(), + req: { + token: 't', + session: sessionName, + command: 'gesture', + positionals: [], + flags: {}, + input, + }, + sessionName, + sessionStore, + captureSnapshotForSession: async ({ session: s }) => s.snapshot!, + contextFromFlags: () => ({}), + inspectFacts: gestures.inspectFacts, + bindDevice: gestures.bindDevice, + }); + return { response, session, gestures }; +} + +test('a path dispatches every authored sample through the target-authored-drag tier', async () => { + const { response, gestures } = await runPath(reversal); + + expect(response).toMatchObject({ ok: true }); + expect(gestures.performGesturePlan).not.toHaveBeenCalled(); + expect(gestures.performTargetAuthoredDrag).toHaveBeenCalledOnce(); + const { plan } = gestures.performTargetAuthoredDrag.mock.calls[0]![0]; + expect(plan).toMatchObject({ + topology: 'single', + executionProfile: 'timed-pan', + durationMs: 1000, + }); + expect(plan.pointers[0]?.samples).toEqual(reversal.samples); + expect(gestures.gestureViewport.mock.calls[0]?.[0].scope).toBe('including-keyboard'); +}); + +test('a backend without the target-authored-drag tier refuses a path before dispatch', async () => { + const gestures = gestureRuntimeBindingsFixture({ unavailable: ['performTargetAuthoredDrag'] }); + const { response } = await runPath(reversal, gestures); + + expect(response?.ok).toBe(false); + if (response && !response.ok) expect(response.error.code).toBe('UNSUPPORTED_OPERATION'); + expect(gestures.performGesturePlan).not.toHaveBeenCalled(); +}); + +test('a recorded path keeps every sample for replay', async () => { + const { session } = await runPath(reversal); + + const [kind, payload] = session.actions[0]?.positionals ?? []; + expect(kind).toBe('path'); + expect(JSON.parse(payload!)).toEqual({ + durationMs: reversal.durationMs, + samples: reversal.samples, + }); +}); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts b/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts index c907c168897..164f5f5ae7e 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts @@ -466,7 +466,7 @@ function resolveExecutionProfile( ): GestureExecutionProfile | undefined { if (gesture.intent === 'fling') return 'endpoint-hold'; if (gesture.intent === 'pan') return gesture.executionProfile ?? 'timed-pan'; - if (gesture.intent === 'drag') return 'timed-pan'; + if (gesture.intent === 'drag' || gesture.intent === 'path') return 'timed-pan'; return undefined; } diff --git a/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts b/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts index 868b6cb5d61..c84e5dd4107 100644 --- a/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-coordinate-unit.test.ts @@ -632,3 +632,34 @@ test('a coordinateDensity that is not a positive number is refused before dispat expect(response).toMatchObject({ ok: false, error: { code: 'INVALID_ARGS' } }); expect(sent.taps).toEqual([]); }); + +test('a dp path converts every sample point and keeps every offset', async () => { + const { handler } = makeHandler(); + + const response = await handler( + request('gesture', { + input: { + kind: 'path', + durationMs: 300, + samples: [ + { offsetMs: 0, point: { x: 100, y: 200 } }, + { offsetMs: 150, point: { x: 100, y: 240 } }, + { offsetMs: 300, point: { x: 100, y: 200 } }, + ], + }, + }), + ); + + expect(response).toMatchObject({ ok: true }); + expect(sent.gestures).toEqual([ + { + intent: 'path', + durationMs: 300, + samples: [ + { offsetMs: 0, point: { x: 250, y: 500 } }, + { offsetMs: 150, point: { x: 250, y: 600 } }, + { offsetMs: 300, point: { x: 250, y: 500 } }, + ], + }, + ]); +}); diff --git a/packages/daemon/src/server/coordinate-unit.ts b/packages/daemon/src/server/coordinate-unit.ts index dac496a622e..d6195230d33 100644 --- a/packages/daemon/src/server/coordinate-unit.ts +++ b/packages/daemon/src/server/coordinate-unit.ts @@ -309,7 +309,9 @@ function readRequestGeometry(req: DaemonRequest): ((toPixels: Scale) => DaemonRe const input = isRecord(req.input) ? req.input : undefined; const inputGeometry = input !== undefined && - ['from', 'to', 'origin', 'delta', 'points', 'distance'].some((key) => input[key] !== undefined); + ['from', 'to', 'origin', 'delta', 'points', 'samples', 'distance'].some( + (key) => input[key] !== undefined, + ); const flagGeometry = typeof req.flags?.jitterPx === 'number' || typeof req.flags?.pixels === 'number'; if (!point && !inputGeometry && !flagGeometry) return undefined; @@ -326,6 +328,7 @@ function readRequestGeometry(req: DaemonRequest): ((toPixels: Scale) => DaemonRe origin: scalePoint(input.origin, toPixels), delta: scalePoint(input.delta, toPixels), points: scalePoints(input.points, toPixels), + samples: scaleSamples(input.samples, toPixels), distance: scaleNumber(input.distance, toPixels), }), } @@ -508,3 +511,13 @@ function scalePoint(value: unknown, scale: Scale): Record | und function scalePoints(value: unknown, scale: Scale): unknown[] | undefined { return Array.isArray(value) ? value.map((point) => scalePoint(point, scale) ?? point) : undefined; } + +/** A path sample keeps its offset; only its point is on the screen. */ +function scaleSamples(value: unknown, scale: Scale): unknown[] | undefined { + if (!Array.isArray(value)) return undefined; + return value.map((sample) => + isRecord(sample) && sample.point !== undefined + ? { ...sample, point: scalePoint(sample.point, scale) ?? sample.point } + : sample, + ); +} diff --git a/packages/gestures/src/gesture-normalization.test.ts b/packages/gestures/src/gesture-normalization.test.ts index 5c83dc7152f..40458c6516c 100644 --- a/packages/gestures/src/gesture-normalization.test.ts +++ b/packages/gestures/src/gesture-normalization.test.ts @@ -397,3 +397,30 @@ test('a positional fling distance is whole pixels, as replay and the CLI send na 12, ); }); + +test('a path replays from the line its recording writes', () => { + const path = { + kind: 'path', + durationMs: 500, + samples: [ + { offsetMs: 0, point: { x: 100, y: 200 } }, + { offsetMs: 250, point: { x: 100, y: 400 } }, + { offsetMs: 500, point: { x: 100, y: 200 } }, + ], + } as const; + const line = gesturePayloadToPositionals(path); + + assert.equal(line[0], 'path'); + assert.deepEqual(gesturePayloadFromPositionals(line), path); + assert.deepEqual(normalizePublicGesture(path).gesture, { + intent: 'path', + durationMs: 500, + samples: path.samples, + }); +}); + +test('a path line takes exactly one JSON object', () => { + assert.throws(() => gesturePayloadFromPositionals(['path', 'not json']), /expects a JSON object/); + assert.throws(() => gesturePayloadFromPositionals(['path', '[]']), /expects a JSON object/); + assert.throws(() => gesturePayloadFromPositionals(['path']), /gesture path accepts 1 argument/); +}); diff --git a/packages/gestures/src/gesture-normalization.ts b/packages/gestures/src/gesture-normalization.ts index 948bff35261..7ffd1c63a12 100644 --- a/packages/gestures/src/gesture-normalization.ts +++ b/packages/gestures/src/gesture-normalization.ts @@ -49,6 +49,7 @@ export const GESTURE_FLAGS_BY_KIND = { rotate: [], transform: [], drag: [], + path: [], } as const satisfies Record<(typeof GESTURE_KINDS)[number], readonly GestureFlagKey[]>; /** The `.ad` refusal for a gesture line that carries a flag its kind does not read. */ @@ -147,6 +148,11 @@ const PUBLIC_GESTURE_SYNTAX: Record = { pairs: true, usage: 'gesture tap accepts 4 to 10 arguments: x1 y1 x2 y2 [x3 y3 [x4 y4 [x5 y5]]]', }, + 'gesture path': { + max: 1, + min: 1, + usage: 'gesture path accepts 1 argument: a JSON object with durationMs and samples', + }, 'gesture drag': { max: 5, usage: @@ -287,6 +293,21 @@ export function gesturePayloadFromPositionals( const kind = positionals[0]; const args = positionals.slice(1); switch (kind) { + case 'path': { + assertGestureArity('gesture path', args); + let payload: unknown; + try { + payload = JSON.parse(args[0]!); + } catch { + throw new AppError('INVALID_ARGS', 'gesture path expects a JSON object', { + hint: `Example: gesture path '{"durationMs":500,"samples":[{"offsetMs":0,"point":{"x":100,"y":200}},{"offsetMs":500,"point":{"x":100,"y":400}}]}'`, + }); + } + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + throw new AppError('INVALID_ARGS', 'gesture path expects a JSON object'); + } + return readGesturePayload({ ...payload, kind }); + } case 'pan': { assertGestureArity('gesture pan', args); const { origin, delta } = readOriginDelta(args); @@ -392,6 +413,8 @@ export function pinchElementFromPositionals(positionals: readonly string[]): str /** Serializes structured gesture input for `.ad` recordings. */ export function gesturePayloadToPositionals(input: GesturePayload): string[] { switch (input.kind) { + case 'path': + return [input.kind, JSON.stringify({ durationMs: input.durationMs, samples: input.samples })]; case 'pan': return compact([ input.kind, @@ -459,6 +482,10 @@ export function swipePayloadFromPositionals( /** The only public gesture interpretation point. */ export function normalizePublicGesture(input: GesturePayload): NormalizedPublicGesture { switch (input.kind) { + case 'path': + return { + gesture: { intent: 'path', durationMs: input.durationMs, samples: input.samples }, + }; case 'pan': return { gesture: { diff --git a/packages/gestures/src/gesture-payload-reader.test.ts b/packages/gestures/src/gesture-payload-reader.test.ts index 40a552bd98a..1388cf3fa0c 100644 --- a/packages/gestures/src/gesture-payload-reader.test.ts +++ b/packages/gestures/src/gesture-payload-reader.test.ts @@ -282,3 +282,54 @@ test('pan refuses a two-pointer hold and out-of-range holdMs', () => { { code: 'INVALID_ARGS' }, ); }); + +const PATH = { + kind: 'path', + durationMs: 1000, + samples: [ + { offsetMs: 0, point: { x: 100, y: 160 } }, + { offsetMs: 400, point: { x: 100, y: 300 } }, + { offsetMs: 800, point: { x: 100, y: 160 } }, + { offsetMs: 1000, point: { x: 100, y: 160 } }, + ], +}; + +test('a path keeps its samples, including a reversal and a final hold', () => { + assert.deepEqual(readGesturePayload(PATH), PATH); +}); + +test.each([ + ['a field another kind reads', { ...PATH, origin: { x: 1, y: 2 } }, /does not accept origin/], + ['no durationMs', { ...PATH, durationMs: undefined }, /requires durationMs/], + ['one sample', { ...PATH, samples: PATH.samples.slice(0, 1) }, /2 to 256 samples/], + [ + '257 samples', + { + ...PATH, + durationMs: 256, + samples: Array.from({ length: 257 }, (_, offsetMs) => ({ offsetMs, point: { x: 1, y: 1 } })), + }, + /2 to 256 samples/, + ], + [ + 'a first offset after touch-down', + { ...PATH, samples: [{ ...PATH.samples[0]!, offsetMs: 10 }, ...PATH.samples.slice(1)] }, + /start at 0 and strictly increase/, + ], + [ + 'a repeated offset', + { ...PATH, samples: [PATH.samples[0]!, PATH.samples[0]!, ...PATH.samples.slice(1)] }, + /start at 0 and strictly increase/, + ], + ['a last offset before durationMs', { ...PATH, durationMs: 1200 }, /must equal durationMs/], + [ + 'a non-finite point', + { ...PATH, samples: [PATH.samples[0]!, { offsetMs: 1000, point: { x: Number.NaN, y: 1 } }] }, + /finite number/, + ], +])('a path with %s is refused', (_name, input, message) => { + assert.throws( + () => readGesturePayload(input), + (error: unknown) => error instanceof AppError && message.test(error.message), + ); +}); diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index fce867667dc..ee79393a7fc 100644 --- a/packages/gestures/src/gesture-payload-reader.ts +++ b/packages/gestures/src/gesture-payload-reader.ts @@ -5,6 +5,7 @@ import { type DragGesturePayload, type GesturePayload, type PanGesturePayload, + type PathGesturePayload, type PinchGesturePayload, type TapGesturePayload, } from '@agent-device/contracts/gesture-input'; @@ -26,6 +27,7 @@ import { GESTURE_MAX_CONTACTS, GESTURE_TAP_MIN_CONTACTS, type GesturePointerCount, + type PointerTrajectorySample, } from '@agent-device/contracts/gesture-plan-types'; /** @@ -36,20 +38,42 @@ const TAP_SERIES_OVERHEAD_ALLOWANCE_MS = 500; const TAP_ONLY_FIELDS = ['points', 'count', 'pauseMs'] as const; +const PATH_GESTURE_MAX_SAMPLES = 256; + +/** Every field another gesture kind reads. A path takes its whole motion from its samples. */ +const NON_PATH_GESTURE_FIELDS = [ + 'origin', + 'delta', + 'pointerCount', + 'holdMs', + 'direction', + 'distance', + 'preset', + 'scale', + 'element', + 'degrees', + 'velocity', + ...TAP_ONLY_FIELDS, + 'source', + 'destination', + 'sourceHoldMs', + 'moveMs', + 'destinationHoldMs', +] as const; + export function readGesturePayload(input: unknown): GesturePayload { const record = readRecord(input); const kind = readEnum(record, 'kind', GESTURE_KINDS); + if (kind === 'path') return readPathGesturePayload(record); assertNoPinchOnlyFields(kind, record); if (kind === 'tap') { return readTapGesturePayload(record); } assertNoTapOnlyFields(kind, record); - if (kind !== 'pan') { - assertNoHoldMs(kind, record); - } if (kind === 'pan') { return readPanGesturePayload(record); } + assertNoHoldMs(kind, record); if (kind === 'drag') { return readDragGesturePayload(record); } @@ -233,6 +257,50 @@ function readPanGesturePayload(record: Record): PanGesturePaylo }; } +function readPathGesturePayload(record: Record): PathGesturePayload { + const field = NON_PATH_GESTURE_FIELDS.find((key) => record[key] !== undefined); + if (field !== undefined) { + throw new AppError('INVALID_ARGS', `gesture path does not accept ${field}`, { + hint: 'A path takes its whole motion from samples and durationMs.', + }); + } + const durationMs = readOptionalGestureDuration(record); + if (durationMs === undefined) { + throw new AppError('INVALID_ARGS', 'gesture path requires durationMs'); + } + const values = record.samples; + if (!Array.isArray(values) || values.length < 2 || values.length > PATH_GESTURE_MAX_SAMPLES) { + throw new AppError( + 'INVALID_ARGS', + `gesture path requires 2 to ${PATH_GESTURE_MAX_SAMPLES} samples`, + ); + } + const samples = values.map((value: unknown, index) => readPathSample(value, index)); + for (const [index, sample] of samples.entries()) { + const previous = samples[index - 1]; + if (index === 0 ? sample.offsetMs !== 0 : sample.offsetMs <= previous!.offsetMs) { + throw new AppError( + 'INVALID_ARGS', + 'gesture path sample offsets must start at 0 and strictly increase', + { index, offsetMs: sample.offsetMs }, + ); + } + } + if (samples.at(-1)!.offsetMs !== durationMs) { + throw new AppError('INVALID_ARGS', 'gesture path final sample offset must equal durationMs'); + } + const [first, second, ...rest] = samples; + return { kind: 'path', durationMs, samples: [first!, second!, ...rest] }; +} + +function readPathSample(value: unknown, index: number): PointerTrajectorySample { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new AppError('INVALID_ARGS', `Expected samples[${index}] to be an object.`); + } + const sample = value as Record; + return { offsetMs: readNumber(sample, 'offsetMs'), point: readPoint(sample, 'point') }; +} + function readDragGesturePayload(record: Record): DragGesturePayload { const source = readNonEmptyString(record, 'source'); const destination = readNonEmptyString(record, 'destination'); diff --git a/packages/gestures/src/gesture-plan.test.ts b/packages/gestures/src/gesture-plan.test.ts index 199f3c63c52..0092a3f67fb 100644 --- a/packages/gestures/src/gesture-plan.test.ts +++ b/packages/gestures/src/gesture-plan.test.ts @@ -250,3 +250,31 @@ for (const [name, offsets] of [ }); }); } + +test('a path plans one timed contact over exactly its authored samples', () => { + const samples = [ + { offsetMs: 0, point: { x: 100, y: 160 } }, + { offsetMs: 400, point: { x: 100, y: 300 } }, + { offsetMs: 800, point: { x: 100, y: 160 } }, + { offsetMs: 1000, point: { x: 100, y: 160 } }, + ] as const; + + const plan = buildGesturePlan({ intent: 'path', durationMs: 1000, samples }, VIEWPORT, 'ios'); + + assert.equal(plan.topology, 'single'); + assert.equal(plan.topology === 'single' && plan.executionProfile, 'timed-pan'); + assert.equal(plan.durationMs, 1000); + assert.deepEqual(plan.pointers[0]?.samples, samples); +}); + +test('a path with a sample outside the viewport is refused before dispatch', () => { + const samples = [ + { offsetMs: 0, point: { x: 100, y: 160 } }, + { offsetMs: 100, point: { x: 100, y: 900 } }, + ] as const; + + assert.throws( + () => buildGesturePlan({ intent: 'path', durationMs: 100, samples }, VIEWPORT), + /Gesture point \(100, 900\) is outside/, + ); +}); diff --git a/packages/gestures/src/gesture-plan.ts b/packages/gestures/src/gesture-plan.ts index 3b886ee8ad0..567dc405e0a 100644 --- a/packages/gestures/src/gesture-plan.ts +++ b/packages/gestures/src/gesture-plan.ts @@ -100,6 +100,16 @@ export function buildGesturePlan( const frame = normalizeViewport(viewport); const profile = gesturePlatformProfile(platform); switch (input.intent) { + case 'path': + assertSamplesInViewport(input.samples, frame, { intent: 'path', pointerId: 0 }); + return { + topology: 'single', + intent: 'pan', + executionProfile: 'timed-pan', + durationMs: input.durationMs, + viewport: frame, + pointers: [{ pointerId: 0, samples: input.samples }], + }; case 'fling': return buildFlingPlan(input, frame, platform); case 'pan': diff --git a/packages/platform-android/src/__tests__/touch-plan-lowering.test.ts b/packages/platform-android/src/__tests__/touch-plan-lowering.test.ts index 57abf2121af..afbc0384b4f 100644 --- a/packages/platform-android/src/__tests__/touch-plan-lowering.test.ts +++ b/packages/platform-android/src/__tests__/touch-plan-lowering.test.ts @@ -180,3 +180,28 @@ test('Android controlled scroll sampling preserves the inertial path and viewpor { numRuns: PROPERTY_RUNS_SMALL }, ); }); + +test('lowers an authored path through its turn and its hold at their offsets', () => { + const plan = buildGesturePlan( + { + intent: 'path', + durationMs: 1000, + samples: [ + { offsetMs: 0, point: { x: 200, y: 300 } }, + { offsetMs: 400, point: { x: 200, y: 600 } }, + { offsetMs: 800, point: { x: 200, y: 350 } }, + { offsetMs: 1000, point: { x: 200, y: 350 } }, + ], + }, + viewport, + ); + const samples = lowerAndroidTouchPlan(plan).pointers[0].samples; + + assert.deepEqual(samples.find(({ offsetMs }) => offsetMs === 400)?.point, { x: 200, y: 600 }); + assert.equal(Math.max(...samples.map(({ point }) => point.y)), 600); + assert.ok( + samples.filter(({ offsetMs }) => offsetMs >= 800).every(({ point }) => point.y === 350), + 'the contact holds at the last authored point', + ); + assert.equal(samples.at(-1)?.offsetMs, 1000); +}); diff --git a/packages/selectors/src/interaction-action.ts b/packages/selectors/src/interaction-action.ts index 5786a867920..10650f0b86f 100644 --- a/packages/selectors/src/interaction-action.ts +++ b/packages/selectors/src/interaction-action.ts @@ -20,7 +20,8 @@ export type InteractionAction = | 'fling' | 'rotate' | 'transform' - | 'tap'; + | 'tap' + | 'path'; /** * The passive verb a refusal uses for the action it declined, so every acting guard that refuses @@ -49,6 +50,7 @@ export function interactionVerb(action: InteractionAction): string { case 'pinch': return 'be pinched'; case 'pan': + case 'path': return 'be panned'; case 'drag': return 'be dragged'; diff --git a/src/commands/schema/cli-help-gestures.ts b/src/commands/schema/cli-help-gestures.ts index e582d957be6..1f19033390d 100644 --- a/src/commands/schema/cli-help-gestures.ts +++ b/src/commands/schema/cli-help-gestures.ts @@ -36,6 +36,7 @@ Platform quirks: Gesture planning prefers the active-app frame; a backend without a gesture viewport resolver falls back to the visible snapshot union, which can be less accurate near edges. Rare iOS accessibility gap: a row shown disabled/hittable:false where press reports success but no UI change, or a collapsed composite control with no child refs -- run snapshot -i --json, compute the target center from rects, press x y, then diff snapshot -i. Coordinates are fallback-only; document why you used them. Drag to reorder or drop: gesture drag @e12 @e40 holds the source (800 ms by default; positional sourceHoldMs overrides it), moves, and releases on the destination. Its source and destination are refs or selectors, not coordinates; for a coordinate hold-then-drag, use gesture pan [durationMs] --hold-ms . swipe and fling never hold, so they do not start a reorder. + Authored path: gesture path '{"durationMs":1000,"samples":[{"offsetMs":0,"point":{"x":100,"y":160}},{"offsetMs":400,"point":{"x":100,"y":300}},{"offsetMs":800,"point":{"x":100,"y":160}},{"offsetMs":1000,"point":{"x":100,"y":160}}]}' moves one contact through 2 to 256 timed samples, so it can reverse, pause, or curve where pan only goes straight. Offsets start at 0, strictly increase, and end at durationMs; a repeated point at a later offset holds the contact. It works where gesture drag works, such as Android touch devices and iOS/iPadOS. The SDK and MCP take the same object as kind: 'path' input. On mobile, after scroll, swipe, or gesture swipe, the next read waits for two captures to agree; web and desktop targets do not wait. A scroll --until, top, or bottom that reports passes: 0 sent no gesture and adds no wait of its own; a wait owed by an earlier gesture still applies. A caller whose own polling verifies the screen adds --no-post-gesture-stabilization to skip that wait; a directional scroll then also skips its movement check. Add --settle to swipe or any supported gesture kind to wait for the UI to go quiet after the final repetition. A settle diff compares with the last observed tree. If settle is inconclusive, the action result stays available. Run snapshot -i if the response lacks the ref you need. diff --git a/src/commands/schema/cli-help-topics.test.ts b/src/commands/schema/cli-help-topics.test.ts index f9fd2c58449..fd997c68c3e 100644 --- a/src/commands/schema/cli-help-topics.test.ts +++ b/src/commands/schema/cli-help-topics.test.ts @@ -15,7 +15,7 @@ test('commands topic includes concise command catalog entries', async () => { assert.match(usageText, /trigger-app-event\s{2,}Invoke an app-defined automation event/); assert.match( usageText, - /gesture \.\.\./, + /gesture \.\.\./, ); assert.doesNotMatch(usageText, /prepare ios-runner --platform ios\|macos/); assert.doesNotMatch(usageText, /metro prepare --public-base-url /); diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 03741cbceff..6757a50bab4 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -82,7 +82,7 @@ Command shape: Chain confident consecutive steps with &&: press 'label="Search"' --settle && fill 'label="Search"' "query" --settle. Fall back to one command at a time when a step is uncertain (ambiguous match, network-backed result, unseen screen). Refs look like @e12; use the exact ref from the latest snapshot -i, never a placeholder (@ref, @eN, @Label_Name). Pin with -s (press @e12-s4); every platform rejects a stale pinned ref -- refresh with snapshot -i or use a selector. close = agent-device close. App back is back; system back is back --system. Single taps are press/click; gesture tap touches 2 to 5 points at once. type never takes --settle: run type, then diff snapshot to verify. Known flow: batch --steps-file ./steps.json (help batch). - Gestures: scroll/swipe for lists/flicks; gesture pan|fling|pinch|rotate|transform|tap|drag for multi-touch. Shapes and platform quirks: help gestures. + Gestures: scroll/swipe for lists/flicks; gesture pan|fling|pinch|rotate|transform|tap|drag|path for multi-touch. Shapes and platform quirks: help gestures. Bootstrap: open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback. diff --git a/src/mcp/__tests__/command-tools.test.ts b/src/mcp/__tests__/command-tools.test.ts index 33408110692..49a82367151 100644 --- a/src/mcp/__tests__/command-tools.test.ts +++ b/src/mcp/__tests__/command-tools.test.ts @@ -188,25 +188,36 @@ test('MCP gesture tool exposes and forwards two-finger pan topology', async () = ]); }); -test('MCP gesture metadata exposes pan/transform duration', () => { +test('MCP gesture metadata exposes pan, transform, and path duration', () => { const gesture = listCommandTools({ outputSchemas: true }).find((tool) => tool.name === 'gesture'); assert.ok(gesture); assert.equal(gesture.inputSchema.properties?.velocity, undefined); assert.deepEqual(gesture.inputSchema.properties?.durationMs, { type: 'integer', - description: 'Pan/transform duration.', + description: 'Pan, transform, or path duration.', minimum: 16, maximum: 10_000, }); }); +test('MCP gesture tool bounds path samples to one timed contact', () => { + const gesture = listCommandTools({ outputSchemas: true }).find((tool) => tool.name === 'gesture'); + assert.ok(gesture); + const samples = gesture.inputSchema.properties?.samples as Record | undefined; + assert.ok(samples); + assert.equal(samples.type, 'array'); + assert.equal(samples.minItems, 2); + assert.equal(samples.maxItems, 256); + assert.deepEqual((samples.items as { required?: unknown }).required, ['offsetMs', 'point']); +}); + test('MCP gesture tool exposes generic drag endpoints and bounded timing phases', () => { const gesture = listCommandTools({ outputSchemas: true }).find((tool) => tool.name === 'gesture'); assert.ok(gesture); assert.deepEqual(gesture.inputSchema.properties?.kind, { type: 'string', description: 'Gesture variant.', - enum: ['pan', 'fling', 'swipe', 'pinch', 'rotate', 'transform', 'tap', 'drag'], + enum: ['pan', 'fling', 'swipe', 'pinch', 'rotate', 'transform', 'tap', 'drag', 'path'], }); assert.deepEqual(gesture.inputSchema.properties?.source, { type: 'string', diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index e007922daf4..ab77ddeb093 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -430,6 +430,21 @@ Use `client.interactions.gesture()` with a `kind` and the corresponding [gesture await client.interactions.gesture({ kind: 'pan', origin: { x: 100, y: 200 }, delta: { x: 40, y: -20 } }); ``` +A `path` gesture moves one contact through timed samples, so it can reverse, pause, or curve. It works where `drag` works, such as Android touch devices and iOS/iPadOS: + +```ts +await client.interactions.gesture({ + kind: 'path', + durationMs: 1000, + samples: [ + { offsetMs: 0, point: { x: 100, y: 160 } }, + { offsetMs: 400, point: { x: 100, y: 300 } }, + { offsetMs: 800, point: { x: 100, y: 160 } }, + { offsetMs: 1000, point: { x: 100, y: 160 } }, + ], +}); +``` + If the daemon returns a missing or non-object lease, or a lease without a non-empty string for `leaseId`, `tenantId`, `runId`, or `backend`, `client.leases.allocate()` and `client.leases.heartbeat()` reject with `COMMAND_FAILED` and `details.reason: "INVALID_LEASE_RESPONSE"`. The original daemon response is available in `error.details.response`. diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 0e42169a5ac..6973b95c902 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1232,10 +1232,10 @@ Exact behavior: `agent-device help swipe`. -Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures. +Run pan, fling, swipe, pinch, rotate, transform, tap, drag, or path. ```bash -agent-device gesture ... +agent-device gesture ... ``` **`gesture pan`** @@ -1279,6 +1279,10 @@ Reads no options. Reads no options. +**`gesture path`** + +Reads no options. + Also accepts: [common options](#common-options): `--settle`, `--settle-quiet `, `--timeout `. Supported targets: [Gesture plans and swipes](/docs/capabilities#interact-with-the-app). @@ -1292,6 +1296,7 @@ Exact behavior: `agent-device help gesture`. - `swipe` is a quick throw. `gesture pan` is a deliberate timed drag with one pointer, or two with `--pointer-count 2`. `gesture fling` is a fast directional throw. To update old scripts, see [Rewrite old gesture commands](/docs/migrating-gestures). - `gesture pan --hold-ms ` holds one pointer before it moves, for drag handles that expose no element and so no ref, such as reorder grips. - `gesture drag source destination` holds one pointer from a selector or ref to another. It refuses coordinates; for a coordinate drag, use `gesture pan [ms] --hold-ms `. It and `--hold-ms` work on Android touch devices and iOS/iPadOS only. +- `gesture path ''` moves one contact through 2 to 256 timed samples, so it can reverse, pause, or curve. The JSON object has `durationMs` and `samples`, each `{ "offsetMs": , "point": { "x": , "y": } }`. Offsets start at 0, strictly increase, and end at `durationMs`; a repeated point at a later offset holds the contact. It works where `gesture drag` works, and a recording replays every sample. - `gesture pinch`, `gesture rotate`, `gesture transform`, and two-finger `gesture pan` work in Android, iOS, and iPadOS app sessions. iOS sessions through a WebDriver provider refuse them. A path that does not fit the viewport fails instead of being clamped. Use `orientation` to rotate the device. - `swipe` and `gesture` coordinates use the units `snapshot` reports: points on Apple platforms and physical pixels on Android (dp when the Node.js client sets `coordinateUnit: 'dp'`), not screenshot pixels. A gesture that leaves the viewport fails with `GESTURE_TRAJECTORY_OUT_OF_BOUNDS`, and the message names the viewport size and the first point outside it. A `gesture pinch`, `rotate`, `transform`, or two-finger `pan` that cannot keep its fingers far enough apart in the viewport fails the same way, and its message names only the viewport. - `gesture tap` touches 2 to 5 points at once in Android and iOS/iPadOS app sessions. WebDriver providers refuse it unless they declare `tapGesture` support. Three or more fingers can trigger iOS system gestures such as undo, so verify app state afterwards. Use `press` for one finger. From 116b3499175e8426428a0be03d6f8c97bbbefa85 Mon Sep 17 00:00:00 2001 From: Tejesh Mehta Date: Sat, 5 Dec 2026 15:44:42 -0800 Subject: [PATCH 2/3] fix(gestures): refuse fractional path offsets and stray path samples A fractional offsetMs passed every reader and failed later in the Android helper. One timeline check now owns the path rules, so the reader and the planner refuse it with INVALID_ARGS before dispatch, and the MCP schema types offsetMs as an integer. samples on another gesture kind is refused instead of dropped, and SDK callers can pass a computed samples array. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/command-input.ts | 2 +- .../command-surface/src/interaction/index.ts | 2 +- .../src/interaction/metadata.ts | 12 ++---- packages/contracts/src/gesture-input.ts | 4 +- packages/contracts/src/gesture-plan-types.ts | 2 +- .../src/gesture-payload-reader.test.ts | 24 ++++++++++- .../gestures/src/gesture-payload-reader.ts | 37 ++++++---------- packages/gestures/src/gesture-plan.test.ts | 16 +++++++ packages/gestures/src/gesture-plan.ts | 9 ++-- packages/gestures/src/path-timeline.ts | 43 +++++++++++++++++++ .../selectors/src/interaction-action.test.ts | 1 + src/commands/schema/cli-help.ts | 2 +- src/mcp/__tests__/command-tools.test.ts | 31 ++++++++++--- 13 files changed, 135 insertions(+), 50 deletions(-) create mode 100644 packages/gestures/src/path-timeline.ts diff --git a/packages/command-surface/src/command-input.ts b/packages/command-surface/src/command-input.ts index 31a6a14e72b..7f4c9ec16c7 100644 --- a/packages/command-surface/src/command-input.ts +++ b/packages/command-surface/src/command-input.ts @@ -86,7 +86,7 @@ export function objectSchema( }; } -function pointSchema(description: string): JsonSchema { +export function pointSchema(description: string): JsonSchema { return { type: 'object', description, diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index 3ab5eaae9da..90a17d3dd0c 100644 --- a/packages/command-surface/src/interaction/index.ts +++ b/packages/command-surface/src/interaction/index.ts @@ -695,7 +695,7 @@ const gestureCommandFacet = defineCommandFacet({ summary: 'Run pan, fling, swipe, pinch, rotate, transform, tap, drag, or path', searchHint: 'reorder zoom multi-touch', cliDetail: - 'Argument shapes: pan [durationMs], fling [distance], swipe , pinch [x y | @ref|selector] (centered on the screen when neither is given), rotate [x] [y], transform [durationMs], tap [... ] [--hold-ms ] [--count ] [--pause-ms ], or drag [sourceHoldMs] [moveMs] [destinationHoldMs]; drag holds the source down first (800 ms by default) before moving, which is what engages a reorder handle. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values. Use --settle to wait for the UI to go quiet after the last repetition and compare with the last observed tree. gesture swipe accepts --no-post-gesture-stabilization to skip the stabilization wait before the next read, for a caller whose own polling verifies the screen.', + 'Argument shapes: pan [durationMs], fling [distance], swipe , pinch [x y | @ref|selector] (centered on the screen when neither is given), rotate [x] [y], transform [durationMs], tap [... ] [--hold-ms ] [--count ] [--pause-ms ], drag [sourceHoldMs] [moveMs] [destinationHoldMs], or path \'\' with durationMs and 2 to 256 samples of {offsetMs, point}; drag holds the source down first (800 ms by default) before moving, which is what engages a reorder handle. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values. Use --settle to wait for the UI to go quiet after the last repetition and compare with the last observed tree. gesture swipe accepts --no-post-gesture-stabilization to skip the stabilization wait before the next read, for a caller whose own polling verifies the screen.', }, metadata: metadata('gesture'), run: (client, input) => diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index 2136555a72a..d12ca6f62d8 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -45,6 +45,7 @@ import { type CommandFieldMap, type InferCommandInput, type TargetedInput, + pointSchema, } from '../command-input.ts'; import { readCommonInput, type CommonCommandInput } from '../common-input-fields.ts'; import { optionalBoolean, readInputRecord } from '../input-readers.ts'; @@ -247,17 +248,12 @@ const gestureFields = { samples: jsonSchemaField({ type: 'array', description: - 'Path samples for one contact: 2 to 256 points with offsetMs from touch-down. Offsets start at 0, strictly increase, and end at durationMs. A repeated point at a later offset holds the contact there.', + 'Path samples for one contact: 2 to 256 points with whole-millisecond offsetMs from touch-down. Offsets start at 0, strictly increase, and end at durationMs. A repeated point at a later offset holds the contact there.', items: { type: 'object', properties: { - offsetMs: { type: 'number' }, - point: { - type: 'object', - properties: { x: { type: 'number' }, y: { type: 'number' } }, - required: ['x', 'y'], - additionalProperties: false, - }, + offsetMs: { type: 'integer', minimum: 0 }, + point: pointSchema('Contact position at offsetMs.'), }, required: ['offsetMs', 'point'], additionalProperties: false, diff --git a/packages/contracts/src/gesture-input.ts b/packages/contracts/src/gesture-input.ts index fc341070125..82b3b32d527 100644 --- a/packages/contracts/src/gesture-input.ts +++ b/packages/contracts/src/gesture-input.ts @@ -1,6 +1,6 @@ import type { Point } from '@agent-device/kernel/snapshot'; import type { ScrollDirection, SwipePreset } from './scroll-gesture.ts'; -import type { GesturePointerCount, SinglePointerTrajectory } from './gesture-plan-types.ts'; +import type { GesturePointerCount, PointerTrajectorySample } from './gesture-plan-types.ts'; export const COORDINATE_GESTURE_KINDS = [ 'pan', @@ -82,7 +82,7 @@ export type TapGesturePayload = { export type PathGesturePayload = { kind: 'path'; durationMs: number; - samples: SinglePointerTrajectory['samples']; + samples: readonly PointerTrajectorySample[]; }; export type GesturePayload = diff --git a/packages/contracts/src/gesture-plan-types.ts b/packages/contracts/src/gesture-plan-types.ts index 475fcfd9e37..b3cf2ab04a2 100644 --- a/packages/contracts/src/gesture-plan-types.ts +++ b/packages/contracts/src/gesture-plan-types.ts @@ -42,7 +42,7 @@ export type TargetedPinchGestureInput = { export type GestureExecutionProfile = 'endpoint-hold' | 'timed-pan'; export type GestureSemanticInput = - | { intent: 'path'; durationMs: number; samples: SinglePointerTrajectory['samples'] } + | { intent: 'path'; durationMs: number; samples: readonly PointerTrajectorySample[] } | { intent: 'fling'; from: Point; to: Point } | { intent: 'fling'; preset: SwipePreset } | { diff --git a/packages/gestures/src/gesture-payload-reader.test.ts b/packages/gestures/src/gesture-payload-reader.test.ts index 1388cf3fa0c..1913a68fed3 100644 --- a/packages/gestures/src/gesture-payload-reader.test.ts +++ b/packages/gestures/src/gesture-payload-reader.test.ts @@ -314,14 +314,26 @@ test.each([ [ 'a first offset after touch-down', { ...PATH, samples: [{ ...PATH.samples[0]!, offsetMs: 10 }, ...PATH.samples.slice(1)] }, - /start at 0 and strictly increase/, + /whole milliseconds that start at 0 and strictly increase/, ], [ 'a repeated offset', { ...PATH, samples: [PATH.samples[0]!, PATH.samples[0]!, ...PATH.samples.slice(1)] }, - /start at 0 and strictly increase/, + /whole milliseconds that start at 0 and strictly increase/, ], ['a last offset before durationMs', { ...PATH, durationMs: 1200 }, /must equal durationMs/], + [ + 'a fractional offset', + { + ...PATH, + samples: [ + PATH.samples[0]!, + { ...PATH.samples[1]!, offsetMs: 400.5 }, + ...PATH.samples.slice(2), + ], + }, + /whole milliseconds/, + ], [ 'a non-finite point', { ...PATH, samples: [PATH.samples[0]!, { offsetMs: 1000, point: { x: Number.NaN, y: 1 } }] }, @@ -333,3 +345,11 @@ test.each([ (error: unknown) => error instanceof AppError && message.test(error.message), ); }); + +test.each(['pan', 'fling', 'pinch', 'drag', 'tap'])('gesture %s refuses path samples', (kind) => { + assert.throws( + () => readGesturePayload({ kind, samples: PATH.samples }), + (error: unknown) => + error instanceof AppError && error.message === 'samples is supported only for gesture path', + ); +}); diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index ee79393a7fc..6e3a695057b 100644 --- a/packages/gestures/src/gesture-payload-reader.ts +++ b/packages/gestures/src/gesture-payload-reader.ts @@ -29,6 +29,7 @@ import { type GesturePointerCount, type PointerTrajectorySample, } from '@agent-device/contracts/gesture-plan-types'; +import { pathTimeline } from './path-timeline.ts'; /** * Per-iteration time a tap series budgets beyond its hold and pause: a whole repetition measured @@ -38,8 +39,6 @@ const TAP_SERIES_OVERHEAD_ALLOWANCE_MS = 500; const TAP_ONLY_FIELDS = ['points', 'count', 'pauseMs'] as const; -const PATH_GESTURE_MAX_SAMPLES = 256; - /** Every field another gesture kind reads. A path takes its whole motion from its samples. */ const NON_PATH_GESTURE_FIELDS = [ 'origin', @@ -66,6 +65,7 @@ export function readGesturePayload(input: unknown): GesturePayload { const kind = readEnum(record, 'kind', GESTURE_KINDS); if (kind === 'path') return readPathGesturePayload(record); assertNoPinchOnlyFields(kind, record); + assertNoPathOnlyFields(kind, record); if (kind === 'tap') { return readTapGesturePayload(record); } @@ -218,6 +218,13 @@ function assertNoPinchOnlyFields(kind: string, record: Record): throw new AppError('INVALID_ARGS', 'element is supported only for gesture pinch'); } +function assertNoPathOnlyFields(kind: string, record: Record): void { + if (record.samples === undefined) return; + throw new AppError('INVALID_ARGS', 'samples is supported only for gesture path', { + hint: `gesture ${kind} does not read samples.`, + }); +} + function assertNoTapOnlyFields(kind: string, record: Record): void { const field = TAP_ONLY_FIELDS.find((key) => record[key] !== undefined); if (field === undefined) return; @@ -268,29 +275,11 @@ function readPathGesturePayload(record: Record): PathGesturePay if (durationMs === undefined) { throw new AppError('INVALID_ARGS', 'gesture path requires durationMs'); } - const values = record.samples; - if (!Array.isArray(values) || values.length < 2 || values.length > PATH_GESTURE_MAX_SAMPLES) { - throw new AppError( - 'INVALID_ARGS', - `gesture path requires 2 to ${PATH_GESTURE_MAX_SAMPLES} samples`, - ); - } - const samples = values.map((value: unknown, index) => readPathSample(value, index)); - for (const [index, sample] of samples.entries()) { - const previous = samples[index - 1]; - if (index === 0 ? sample.offsetMs !== 0 : sample.offsetMs <= previous!.offsetMs) { - throw new AppError( - 'INVALID_ARGS', - 'gesture path sample offsets must start at 0 and strictly increase', - { index, offsetMs: sample.offsetMs }, - ); - } - } - if (samples.at(-1)!.offsetMs !== durationMs) { - throw new AppError('INVALID_ARGS', 'gesture path final sample offset must equal durationMs'); + if (!Array.isArray(record.samples)) { + throw new AppError('INVALID_ARGS', 'gesture path requires a samples array'); } - const [first, second, ...rest] = samples; - return { kind: 'path', durationMs, samples: [first!, second!, ...rest] }; + const samples = record.samples.map((value: unknown, index) => readPathSample(value, index)); + return { kind: 'path', durationMs, samples: pathTimeline(samples, durationMs) }; } function readPathSample(value: unknown, index: number): PointerTrajectorySample { diff --git a/packages/gestures/src/gesture-plan.test.ts b/packages/gestures/src/gesture-plan.test.ts index 0092a3f67fb..02bd10fc8c8 100644 --- a/packages/gestures/src/gesture-plan.test.ts +++ b/packages/gestures/src/gesture-plan.test.ts @@ -278,3 +278,19 @@ test('a path with a sample outside the viewport is refused before dispatch', () /Gesture point \(100, 900\) is outside/, ); }); + +test('a computed path that disagrees with its duration is refused when planned', () => { + const samples = Array.from({ length: 5 }, (_, index) => ({ + offsetMs: index * 20, + point: { x: 100, y: 160 + index * 10 }, + })); + + assert.deepEqual( + buildGesturePlan({ intent: 'path', durationMs: 80, samples }, VIEWPORT).pointers[0]?.samples, + samples, + ); + assert.throws( + () => buildGesturePlan({ intent: 'path', durationMs: 100, samples }, VIEWPORT), + /final sample offset must equal durationMs/, + ); +}); diff --git a/packages/gestures/src/gesture-plan.ts b/packages/gestures/src/gesture-plan.ts index 567dc405e0a..b5766c6ac52 100644 --- a/packages/gestures/src/gesture-plan.ts +++ b/packages/gestures/src/gesture-plan.ts @@ -32,6 +32,7 @@ import type { TapPointerId, TwoContactGesturePlan, } from '@agent-device/contracts/gesture-plan-types'; +import { pathTimeline } from './path-timeline.ts'; export const GESTURE_SAMPLE_INTERVAL_MS = 16; export const GESTURE_INITIAL_ANGLE_DEGREES = -90; @@ -100,16 +101,18 @@ export function buildGesturePlan( const frame = normalizeViewport(viewport); const profile = gesturePlatformProfile(platform); switch (input.intent) { - case 'path': - assertSamplesInViewport(input.samples, frame, { intent: 'path', pointerId: 0 }); + case 'path': { + const samples = pathTimeline(input.samples, input.durationMs); + assertSamplesInViewport(samples, frame, { intent: 'path', pointerId: 0 }); return { topology: 'single', intent: 'pan', executionProfile: 'timed-pan', durationMs: input.durationMs, viewport: frame, - pointers: [{ pointerId: 0, samples: input.samples }], + pointers: [{ pointerId: 0, samples }], }; + } case 'fling': return buildFlingPlan(input, frame, platform); case 'pan': diff --git a/packages/gestures/src/path-timeline.ts b/packages/gestures/src/path-timeline.ts new file mode 100644 index 00000000000..953004ae7b5 --- /dev/null +++ b/packages/gestures/src/path-timeline.ts @@ -0,0 +1,43 @@ +import { AppError } from '@agent-device/kernel/errors'; +import type { + PointerTrajectorySample, + SinglePointerTrajectory, +} from '@agent-device/contracts/gesture-plan-types'; + +const PATH_GESTURE_MAX_SAMPLES = 256; + +/** + * Checks an authored path timeline. The Android helper and WebDriver take whole-millisecond offsets, + * so a fractional offset is refused here instead of failing after dispatch. + */ +export function pathTimeline( + samples: readonly PointerTrajectorySample[], + durationMs: number, +): SinglePointerTrajectory['samples'] { + if (samples.length < 2 || samples.length > PATH_GESTURE_MAX_SAMPLES) { + throw new AppError( + 'INVALID_ARGS', + `gesture path requires 2 to ${PATH_GESTURE_MAX_SAMPLES} samples`, + { sampleCount: samples.length }, + ); + } + for (const [index, sample] of samples.entries()) { + const ordered = + index === 0 ? sample.offsetMs === 0 : sample.offsetMs > samples[index - 1]!.offsetMs; + if (!ordered || !Number.isInteger(sample.offsetMs)) { + throw new AppError( + 'INVALID_ARGS', + 'gesture path sample offsets must be whole milliseconds that start at 0 and strictly increase', + { index, offsetMs: sample.offsetMs }, + ); + } + } + if (samples.at(-1)!.offsetMs !== durationMs) { + throw new AppError('INVALID_ARGS', 'gesture path final sample offset must equal durationMs', { + durationMs, + finalOffsetMs: samples.at(-1)!.offsetMs, + }); + } + const [first, second, ...rest] = samples; + return [first!, second!, ...rest]; +} diff --git a/packages/selectors/src/interaction-action.test.ts b/packages/selectors/src/interaction-action.test.ts index bbb959240b5..a2655abea1b 100644 --- a/packages/selectors/src/interaction-action.test.ts +++ b/packages/selectors/src/interaction-action.test.ts @@ -17,6 +17,7 @@ test('every action names itself in the refusal', () => { ['swipe', 'be swiped'], ['pinch', 'be pinched'], ['pan', 'be panned'], + ['path', 'be panned'], ['drag', 'be dragged'], ['fling', 'be flung'], ['rotate', 'be rotated'], diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 6757a50bab4..01cc0490da0 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -82,7 +82,7 @@ Command shape: Chain confident consecutive steps with &&: press 'label="Search"' --settle && fill 'label="Search"' "query" --settle. Fall back to one command at a time when a step is uncertain (ambiguous match, network-backed result, unseen screen). Refs look like @e12; use the exact ref from the latest snapshot -i, never a placeholder (@ref, @eN, @Label_Name). Pin with -s (press @e12-s4); every platform rejects a stale pinned ref -- refresh with snapshot -i or use a selector. close = agent-device close. App back is back; system back is back --system. Single taps are press/click; gesture tap touches 2 to 5 points at once. type never takes --settle: run type, then diff snapshot to verify. Known flow: batch --steps-file ./steps.json (help batch). - Gestures: scroll/swipe for lists/flicks; gesture pan|fling|pinch|rotate|transform|tap|drag|path for multi-touch. Shapes and platform quirks: help gestures. + Gestures: scroll/swipe for lists/flicks; gesture pan|fling|pinch|rotate|transform|tap|drag|path for touch gestures. Shapes and platform quirks: help gestures. Bootstrap: open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback. diff --git a/src/mcp/__tests__/command-tools.test.ts b/src/mcp/__tests__/command-tools.test.ts index 49a82367151..d514c148243 100644 --- a/src/mcp/__tests__/command-tools.test.ts +++ b/src/mcp/__tests__/command-tools.test.ts @@ -200,15 +200,32 @@ test('MCP gesture metadata exposes pan, transform, and path duration', () => { }); }); -test('MCP gesture tool bounds path samples to one timed contact', () => { +test('MCP gesture tool bounds path samples and forwards a path unchanged', async () => { const gesture = listCommandTools({ outputSchemas: true }).find((tool) => tool.name === 'gesture'); - assert.ok(gesture); - const samples = gesture.inputSchema.properties?.samples as Record | undefined; + const samples = gesture?.inputSchema.properties?.samples as Record | undefined; assert.ok(samples); - assert.equal(samples.type, 'array'); - assert.equal(samples.minItems, 2); - assert.equal(samples.maxItems, 256); - assert.deepEqual((samples.items as { required?: unknown }).required, ['offsetMs', 'point']); + assert.deepEqual([samples.minItems, samples.maxItems], [2, 256]); + const item = samples.items as { properties: Record }; + assert.deepEqual(item.properties.offsetMs, { type: 'integer', minimum: 0 }); + + const calls: unknown[] = []; + const executor = createCommandToolExecutor({ + createClient: () => ({}) as AgentDeviceClient, + runCommand: async (_client, name, input) => { + calls.push({ name, input }); + return { message: 'Moved' }; + }, + }); + const path = { + kind: 'path', + durationMs: 100, + samples: [ + { offsetMs: 0, point: { x: 1, y: 2 } }, + { offsetMs: 100, point: { x: 1, y: 9 } }, + ], + }; + await executor.execute('gesture', path); + assert.deepEqual(calls, [{ name: 'gesture', input: path }]); }); test('MCP gesture tool exposes generic drag endpoints and bounded timing phases', () => { From 5e1de7f9f2540851bbc92bdc8f114b04344a4b7f Mon Sep 17 00:00:00 2001 From: Tejesh Mehta Date: Sat, 5 Dec 2026 16:12:21 -0800 Subject: [PATCH 3/3] fix(gestures): check path timelines in an already loaded contracts module The eager-closure budget refuses a new module on import. Move pathTimeline into scroll-gesture, which the payload reader and the planner both load. Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/scroll-gesture.ts | 44 ++++++++++++++++++- .../gestures/src/gesture-payload-reader.ts | 2 +- packages/gestures/src/gesture-plan.ts | 2 +- packages/gestures/src/path-timeline.ts | 43 ------------------ 4 files changed, 45 insertions(+), 46 deletions(-) delete mode 100644 packages/gestures/src/path-timeline.ts diff --git a/packages/contracts/src/scroll-gesture.ts b/packages/contracts/src/scroll-gesture.ts index b9fe111ef72..177fd89cba6 100644 --- a/packages/contracts/src/scroll-gesture.ts +++ b/packages/contracts/src/scroll-gesture.ts @@ -1,5 +1,9 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -import type { GestureContactOrigin } from './gesture-plan-types.ts'; +import type { + GestureContactOrigin, + PointerTrajectorySample, + SinglePointerTrajectory, +} from './gesture-plan-types.ts'; import { SCROLL_REASONS } from './scroll-reasons.ts'; import { defineStringEnum } from './string-enum.ts'; import { isViewportRootNode } from './snapshot-visibility.ts'; @@ -600,3 +604,41 @@ function isMeasurableRect(rect: Rect): boolean { rect.height > 0 ); } + +const PATH_GESTURE_MAX_SAMPLES = 256; + +/** + * Checks an authored path timeline. The Android helper and WebDriver take whole-millisecond offsets, + * so a fractional offset is refused here instead of failing after dispatch. + */ +export function pathTimeline( + samples: readonly PointerTrajectorySample[], + durationMs: number, +): SinglePointerTrajectory['samples'] { + if (samples.length < 2 || samples.length > PATH_GESTURE_MAX_SAMPLES) { + throw new AppError( + 'INVALID_ARGS', + `gesture path requires 2 to ${PATH_GESTURE_MAX_SAMPLES} samples`, + { sampleCount: samples.length }, + ); + } + for (const [index, sample] of samples.entries()) { + const ordered = + index === 0 ? sample.offsetMs === 0 : sample.offsetMs > samples[index - 1]!.offsetMs; + if (!ordered || !Number.isInteger(sample.offsetMs)) { + throw new AppError( + 'INVALID_ARGS', + 'gesture path sample offsets must be whole milliseconds that start at 0 and strictly increase', + { index, offsetMs: sample.offsetMs }, + ); + } + } + if (samples.at(-1)!.offsetMs !== durationMs) { + throw new AppError('INVALID_ARGS', 'gesture path final sample offset must equal durationMs', { + durationMs, + finalOffsetMs: samples.at(-1)!.offsetMs, + }); + } + const [first, second, ...rest] = samples; + return [first!, second!, ...rest]; +} diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index 6e3a695057b..1cf172e6ab8 100644 --- a/packages/gestures/src/gesture-payload-reader.ts +++ b/packages/gestures/src/gesture-payload-reader.ts @@ -16,6 +16,7 @@ import { SWIPE_PRESETS, SWIPE_REPETITION_MAX, SWIPE_SERIES_MAX_SCHEDULED_DURATION_MS, + pathTimeline, } from '@agent-device/contracts/scroll-gesture'; import { DEFAULT_DRAG_DESTINATION_HOLD_MS, @@ -29,7 +30,6 @@ import { type GesturePointerCount, type PointerTrajectorySample, } from '@agent-device/contracts/gesture-plan-types'; -import { pathTimeline } from './path-timeline.ts'; /** * Per-iteration time a tap series budgets beyond its hold and pause: a whole repetition measured diff --git a/packages/gestures/src/gesture-plan.ts b/packages/gestures/src/gesture-plan.ts index b5766c6ac52..97e313167ec 100644 --- a/packages/gestures/src/gesture-plan.ts +++ b/packages/gestures/src/gesture-plan.ts @@ -9,6 +9,7 @@ import { splitViewUnavailableError, type SplitViewSwipePreset, type SwipePreset, + pathTimeline, } from '@agent-device/contracts/scroll-gesture'; import { DEFAULT_DRAG_DESTINATION_HOLD_MS, @@ -32,7 +33,6 @@ import type { TapPointerId, TwoContactGesturePlan, } from '@agent-device/contracts/gesture-plan-types'; -import { pathTimeline } from './path-timeline.ts'; export const GESTURE_SAMPLE_INTERVAL_MS = 16; export const GESTURE_INITIAL_ANGLE_DEGREES = -90; diff --git a/packages/gestures/src/path-timeline.ts b/packages/gestures/src/path-timeline.ts deleted file mode 100644 index 953004ae7b5..00000000000 --- a/packages/gestures/src/path-timeline.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { AppError } from '@agent-device/kernel/errors'; -import type { - PointerTrajectorySample, - SinglePointerTrajectory, -} from '@agent-device/contracts/gesture-plan-types'; - -const PATH_GESTURE_MAX_SAMPLES = 256; - -/** - * Checks an authored path timeline. The Android helper and WebDriver take whole-millisecond offsets, - * so a fractional offset is refused here instead of failing after dispatch. - */ -export function pathTimeline( - samples: readonly PointerTrajectorySample[], - durationMs: number, -): SinglePointerTrajectory['samples'] { - if (samples.length < 2 || samples.length > PATH_GESTURE_MAX_SAMPLES) { - throw new AppError( - 'INVALID_ARGS', - `gesture path requires 2 to ${PATH_GESTURE_MAX_SAMPLES} samples`, - { sampleCount: samples.length }, - ); - } - for (const [index, sample] of samples.entries()) { - const ordered = - index === 0 ? sample.offsetMs === 0 : sample.offsetMs > samples[index - 1]!.offsetMs; - if (!ordered || !Number.isInteger(sample.offsetMs)) { - throw new AppError( - 'INVALID_ARGS', - 'gesture path sample offsets must be whole milliseconds that start at 0 and strictly increase', - { index, offsetMs: sample.offsetMs }, - ); - } - } - if (samples.at(-1)!.offsetMs !== durationMs) { - throw new AppError('INVALID_ARGS', 'gesture path final sample offset must equal durationMs', { - durationMs, - finalOffsetMs: samples.at(-1)!.offsetMs, - }); - } - const [first, second, ...rest] = samples; - return [first!, second!, ...rest]; -}