From 435f4bf78fa2c3b51a5a0b0807a607e4b06dce00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 23 Nov 2026 09:19:58 +0100 Subject: [PATCH 1/5] feat(gesture): pinch an element by ref or selector gesture pinch now takes an element (`gesture pinch <@ref|selector>`, MCP `element`) in place of x/y. The runtime resolves it through the same target resolution as drag and pinches around the element's touch point; a recorded .ad line stores the selector, not the session ref. Without an element or origin the pinch still centers on the screen, which misses an off-center image. Unknown `pinch` and `zoom` commands now suggest the gesture pinch shape. Co-Authored-By: Claude Opus 5.5 --- .../interaction/runtime/gesture-command.ts | 50 ++++++++++++++++++- .../interaction/runtime/gestures.test.ts | 26 ++++++++++ .../command-surface/src/interaction/index.ts | 2 +- .../src/interaction/metadata.ts | 3 ++ .../contracts/src/daemon-command-surface.ts | 5 +- packages/contracts/src/gesture-input.ts | 2 + packages/contracts/src/gesture-plan-types.ts | 12 ++++- .../src/platform-runtime-operations.ts | 4 +- .../internal/interaction-gesture.ts | 44 +++++++++------- .../src/gesture-normalization.test.ts | 13 +++++ .../gestures/src/gesture-normalization.ts | 27 ++++++++-- .../src/gesture-payload-reader.test.ts | 7 +++ .../gestures/src/gesture-payload-reader.ts | 13 +++-- .../__tests__/command-suggestions.test.ts | 12 +++++ src/cli/parser/command-suggestions.ts | 2 + src/commands/schema/cli-help-gestures.ts | 1 + website/docs/docs/commands.md | 1 + 17 files changed, 191 insertions(+), 33 deletions(-) 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 5db1db2f0b..b4922839b8 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts @@ -4,10 +4,13 @@ import type { GestureContactCount, GestureIntent, GestureSemanticInput, + TargetedPinchGestureInput, } from '@agent-device/contracts/gesture-plan-types'; import { buildGesturePlan } from '@agent-device/gestures/gesture-plan'; import type { Point } from '@agent-device/kernel/snapshot'; import { AppError } from '@agent-device/kernel/errors'; +import { recordedSelectorExpression } from '@agent-device/selectors'; +import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy'; import { successText } from '@agent-device/kernel/success-text'; import { toBackendContext } from '../../runtime-common.ts'; import { @@ -15,7 +18,7 @@ import { type BackendResultEnvelope, type RuntimeCommand, } from '../../runtime-types.ts'; -import { assertSupportedInteractionSurface } from './resolution.ts'; +import { assertSupportedInteractionSurface, resolveInteractionTarget } from './resolution.ts'; import { dragCommand, resolveGestureViewport, @@ -27,7 +30,14 @@ type CoordinateGestureCommandOptions = CommandContext & { gesture: GestureSemanticInput; }; -export type GestureCommandOptions = CoordinateGestureCommandOptions | DragCommandOptions; +type TargetedPinchCommandOptions = CommandContext & { + gesture: TargetedPinchGestureInput; +}; + +export type GestureCommandOptions = + | CoordinateGestureCommandOptions + | DragCommandOptions + | TargetedPinchCommandOptions; export type CoordinateGestureCommandResult = { kind: GestureIntent; @@ -35,6 +45,8 @@ export type CoordinateGestureCommandResult = { pointerCount: GestureContactCount; from: Point; to: Point; + /** The selector a targeted pinch resolved, so a recorded `.ad` line replays without a ref. */ + recordedTargetSelector?: string; } & BackendResultEnvelope; export type GestureCommandResult = CoordinateGestureCommandResult | DragCommandResult; @@ -74,9 +86,43 @@ export const gestureCommand: RuntimeCommand { const gesture: GestureCommandInput = options.gesture; if (gesture.intent === 'drag') return await dragCommand(runtime, { ...options, gesture }); + if ('element' in gesture) return await targetedPinchCommand(runtime, { ...options, gesture }); return await coordinateGestureCommand(runtime, { ...options, gesture }); }; +/** Resolves the pinch element to its touch point, then pinches around that point. */ +const targetedPinchCommand: RuntimeCommand< + TargetedPinchCommandOptions, + CoordinateGestureCommandResult +> = async (runtime, options) => { + const { element, scale } = options.gesture; + const resolved = await resolveInteractionTarget( + runtime, + { + ...options, + target: element.startsWith('@') + ? { kind: 'ref', ref: element } + : { kind: 'selector', selector: element }, + }, + { + action: 'pinch', + requireInteractive: false, + pipeline: SELECTOR_PIPELINE_POLICIES.resolvedTarget, + }, + ); + if (!resolved.point) { + throw new AppError('COMMAND_FAILED', 'Interaction target resolved without coordinates'); + } + const result = await coordinateGestureCommand(runtime, { + ...options, + gesture: { intent: 'pinch', origin: resolved.point, scale }, + }); + const selectorChain = 'selectorChain' in resolved ? resolved.selectorChain : undefined; + return selectorChain?.length + ? { ...result, recordedTargetSelector: recordedSelectorExpression(selectorChain) } + : result; +}; + function centroidAt( pointers: readonly { samples: readonly { point: Point }[] }[], index: 0 | -1, diff --git a/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts b/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts index 74ba92c08f..54a513609b 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts @@ -79,6 +79,32 @@ test('runtime drag resolves generic selector endpoints before one continuous poi assert.equal(result.targets?.destination.selectorChain?.[0], 'id="drop-target"'); }); +test('runtime pinch on an element centers the plan on it and records its selector', async () => { + let capturedPlan: + | Parameters< + NonNullable + >[1] + | undefined; + const device = createInteractionDevice(dragTargetSnapshot(), { + resolveGestureViewport: async () => ({ x: 0, y: 0, width: 400, height: 800 }), + performGesture: async (_context, plan) => { + capturedPlan = plan; + }, + }); + + const result = await device.interactions.gesture({ + gesture: { intent: 'pinch', element: '@e2', scale: 2 }, + }); + + assert.equal(result.kind, 'pinch'); + assert.equal(capturedPlan?.topology, 'multi'); + assert.deepEqual(result.from, { x: 80, y: 130 }); + assert.equal( + 'recordedTargetSelector' in result ? result.recordedTargetSelector : undefined, + 'id="drag-source"', + ); +}); + test('runtime drag resolves both endpoints before dispatching any device gesture', async () => { let dispatchCount = 0; const device = createInteractionDevice(dragTargetSnapshot(), { diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index 3cd1b2dc2e..da90b14fff 100644 --- a/packages/command-surface/src/interaction/index.ts +++ b/packages/command-surface/src/interaction/index.ts @@ -667,7 +667,7 @@ const gestureCommandFacet = defineCommandFacet({ summary: 'Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures', searchHint: 'reorder zoom multi-touch', cliDetail: - 'Argument shapes: pan [durationMs], fling [distance], swipe , pinch [x] [y], 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. 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 ], 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. 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 5681b78169..a2bde474d7 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -232,6 +232,9 @@ const gestureFields = { delta: pointField('Movement delta for pan or transform gestures.'), distance: integerField('Fling distance.', { min: 0 }), scale: numberField('Pinch or transform scale.'), + element: stringField( + '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 }), pointerCount: integerField('Pan touch pointer count (1 or 2).', { min: 1, max: 2 }), diff --git a/packages/contracts/src/daemon-command-surface.ts b/packages/contracts/src/daemon-command-surface.ts index 69dd392a47..d9bcd21c11 100644 --- a/packages/contracts/src/daemon-command-surface.ts +++ b/packages/contracts/src/daemon-command-surface.ts @@ -20,6 +20,7 @@ import type { GestureContactCount, GestureIntent, GestureSemanticInput, + TargetedPinchGestureInput, } from './gesture-plan-types.ts'; import type { FindLocator } from './snapshot-types.ts'; import type { @@ -250,7 +251,7 @@ export type DaemonHoverOptions = CommandContext & export type DaemonGestureOptions = CommandContext & ( - | Readonly<{ gesture: GestureSemanticInput }> + | Readonly<{ gesture: GestureSemanticInput | TargetedPinchGestureInput }> | Readonly<{ gesture: DragGestureInput; expectedResolvedTargets?: { @@ -269,6 +270,8 @@ export type DaemonCoordinateGestureResult = Readonly<{ to: Point; backendResult?: Record; message?: string; + /** The selector a pinch element resolved, so a recorded `.ad` line replays without a ref. */ + recordedTargetSelector?: string; }>; /** A drag additionally reports its two endpoints and what a replay needs to re-issue them. */ diff --git a/packages/contracts/src/gesture-input.ts b/packages/contracts/src/gesture-input.ts index ed8bfab4fe..bc6b7d9f37 100644 --- a/packages/contracts/src/gesture-input.ts +++ b/packages/contracts/src/gesture-input.ts @@ -48,6 +48,8 @@ export type PinchGesturePayload = { kind: 'pinch'; scale: number; origin?: Point; + /** A `@ref` or selector the pinch centers on, in place of `origin`. */ + element?: string; }; export type RotateGesturePayload = { diff --git a/packages/contracts/src/gesture-plan-types.ts b/packages/contracts/src/gesture-plan-types.ts index c9d421f342..9fec453455 100644 --- a/packages/contracts/src/gesture-plan-types.ts +++ b/packages/contracts/src/gesture-plan-types.ts @@ -31,6 +31,13 @@ export type DragGestureInput = { destinationHoldMs?: number; }; +/** A pinch centered on a `@ref` or selector; the runtime resolves the element to the origin. */ +export type TargetedPinchGestureInput = { + intent: 'pinch'; + element: string; + scale: number; +}; + /** Selects one-pointer release timing without changing semantic gesture intent. */ export type GestureExecutionProfile = 'endpoint-hold' | 'timed-pan'; @@ -69,7 +76,10 @@ export type GestureSemanticInput = holdMs?: number; }; -export type GestureCommandInput = GestureSemanticInput | DragGestureInput; +export type GestureCommandInput = + | GestureSemanticInput + | DragGestureInput + | TargetedPinchGestureInput; export type PointerTrajectorySample = { offsetMs: number; point: Point }; diff --git a/packages/contracts/src/platform-runtime-operations.ts b/packages/contracts/src/platform-runtime-operations.ts index 49fc7c043e..38d3f86d43 100644 --- a/packages/contracts/src/platform-runtime-operations.ts +++ b/packages/contracts/src/platform-runtime-operations.ts @@ -16,7 +16,7 @@ import type { SnapshotRuntimeHost, SnapshotRuntimeOperations } from './snapshot- import type { SelectorObservationRuntimeOperations } from './selector-observation-runtime.ts'; import type { ViewportRuntimeOperations } from './viewport-runtime.ts'; import type { FocusRuntimeOperations } from './focus-runtime.ts'; -import type { GestureCommandInput, GestureSemanticInput } from './gesture-plan-types.ts'; +import type { GestureCommandInput } from './gesture-plan-types.ts'; import type { GestureRuntimeTier } from './gesture-tier.ts'; import type { GestureRuntimeOperations } from './gesture-runtime.ts'; import type { ScrollRuntimeOperations } from './scroll-runtime.ts'; @@ -368,7 +368,7 @@ export type GestureRuntimePlan = { /** Selects the one owner-fact-backed gesture plan a normalized gesture input needs. */ /** Pinch, rotate, transform, an explicit two-pointer pan, and a multi-finger tap hold several contacts. */ -function isMultiTouchGesture(input: GestureSemanticInput): boolean { +function isMultiTouchGesture(input: Exclude): boolean { if (input.intent === 'pan') return ('pointerCount' in input ? input.pointerCount : 1) === 2; return ( input.intent === 'pinch' || diff --git a/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts b/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts index dceacb1900..441868ff3d 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-gesture.ts @@ -178,7 +178,7 @@ function buildGestureOutcome( ? { ...result, message: `Tapped ${input.points.length} points ${input.count} times` } : result; return { - positionals: dragRecordingPositionals(input, recording), + positionals: recordedGesturePositionals(input, result), flags: gestureReplayFlags(input, flags), responseData: gestureResponseData(responseResult, { executionProfile: resolveExecutionProfile(gesture), @@ -381,13 +381,18 @@ function prepareGestureCommandInput( readiness: AndroidBlockingDialogReadinessResult, ): GestureCommandInput { const normalized = normalizeGestureCommandInput(input); - if (normalized.intent !== 'drag') return normalized; try { - return { - ...normalized, - source: prepareDragTarget(normalized.source, session), - destination: prepareDragTarget(normalized.destination, session), - }; + if (normalized.intent === 'drag') { + return { + ...normalized, + source: prepareGestureTarget(normalized.source, session), + destination: prepareGestureTarget(normalized.destination, session), + }; + } + if ('element' in normalized) { + return { ...normalized, element: prepareGestureTarget(normalized.element, session) }; + } + return normalized; } catch (error) { if (readiness.status === 'recovered') { const failure = asAppError(error); @@ -400,7 +405,7 @@ function prepareGestureCommandInput( } } -function prepareDragTarget(target: string, session: SessionState): string { +function prepareGestureTarget(target: string, session: SessionState): string { if (!target.startsWith('@')) return target; const split = splitRefGenerationSuffix(target); if (!split) { @@ -420,16 +425,19 @@ function prepareDragTarget(target: string, session: SessionState): string { return split.base; } -function dragRecordingPositionals( - input: GesturePayload, - recording: Extract['recording'], -): string[] { - if (input.kind !== 'drag' || !recording) return gesturePayloadToPositionals(input); - return gesturePayloadToPositionals({ - ...input, - source: recording.sourceSelector ?? input.source, - destination: recording.destinationSelector ?? input.destination, - }); +/** The `.ad` line for a gesture: a resolved target records its selector, never a session ref. */ +function recordedGesturePositionals(input: GesturePayload, result: GestureRuntimeResult): string[] { + if (input.kind === 'drag' && result.kind === 'drag' && result.recording) { + return gesturePayloadToPositionals({ + ...input, + source: result.recording.sourceSelector ?? input.source, + destination: result.recording.destinationSelector ?? input.destination, + }); + } + if (input.kind === 'pinch' && result.kind !== 'drag' && result.recordedTargetSelector) { + return gesturePayloadToPositionals({ ...input, element: result.recordedTargetSelector }); + } + return gesturePayloadToPositionals(input); } function readSwipeInput(input: unknown): SwipePayload { diff --git a/packages/gestures/src/gesture-normalization.test.ts b/packages/gestures/src/gesture-normalization.test.ts index 423c08e2a3..9abc5a45f8 100644 --- a/packages/gestures/src/gesture-normalization.test.ts +++ b/packages/gestures/src/gesture-normalization.test.ts @@ -257,6 +257,19 @@ test('pinch and rotate syntax rejects a partial origin', () => { }); }); +test('pinch takes an element in place of an origin and keeps it through replay', () => { + for (const element of ['@e17', 'label=Photo']) { + const payload = gesturePayloadFromPositionals(['pinch', '2', element]); + assert.deepEqual(payload, { kind: 'pinch', scale: 2, element }); + assert.deepEqual(gesturePayloadToPositionals(payload), ['pinch', '2', element]); + assert.deepEqual(normalizeGestureCommandInput(payload), { + intent: 'pinch', + element, + scale: 2, + }); + } +}); + test('swipe is fling sugar', () => { assert.deepEqual(normalizePublicGesture({ kind: 'swipe', preset: 'left' }), { gesture: { intent: 'fling', preset: 'left' }, diff --git a/packages/gestures/src/gesture-normalization.ts b/packages/gestures/src/gesture-normalization.ts index f597a85632..628a598744 100644 --- a/packages/gestures/src/gesture-normalization.ts +++ b/packages/gestures/src/gesture-normalization.ts @@ -126,7 +126,7 @@ const PUBLIC_GESTURE_SYNTAX: Record = { }, 'gesture pinch': { max: 3, - usage: 'gesture pinch accepts at most 3 arguments: scale [x] [y]', + usage: 'gesture pinch accepts at most 3 arguments: scale [x y | element]', }, 'gesture rotate': { max: 3, @@ -316,10 +316,11 @@ export function gesturePayloadFromPositionals( } case 'pinch': { assertGestureArity('gesture pinch', args); + const element = pinchElementArgument(args); return readGesturePayload({ kind, scale: Number(args[0]), - origin: optionalOrigin(args[1], args[2]), + ...(element === undefined ? { origin: optionalOrigin(args[1], args[2]) } : { element }), }); } case 'rotate': { @@ -394,7 +395,9 @@ export function gesturePayloadToPositionals(input: GesturePayload): string[] { case 'swipe': return [input.kind, input.preset]; case 'pinch': - return compact([input.kind, input.scale, input.origin?.x, input.origin?.y]); + return input.element === undefined + ? compact([input.kind, input.scale, input.origin?.x, input.origin?.y]) + : [input.kind, String(input.scale), input.element]; case 'rotate': return input.origin ? compact([input.kind, input.degrees, input.origin.x, input.origin.y]) @@ -468,6 +471,12 @@ export function normalizePublicGesture(input: GesturePayload): NormalizedPublicG case 'swipe': return { gesture: { intent: 'fling', preset: input.preset } }; case 'pinch': + if (input.element !== undefined) { + throw new AppError( + 'INVALID_ARGS', + 'gesture pinch elements must be resolved before coordinate normalization', + ); + } return { gesture: { intent: 'pinch', origin: input.origin, scale: input.scale }, }; @@ -504,6 +513,9 @@ export function normalizePublicGesture(input: GesturePayload): NormalizedPublicG /** Converts every public gesture payload into the runtime's semantic command shape. */ export function normalizeGestureCommandInput(input: GesturePayload): GestureCommandInput { + if (input.kind === 'pinch' && input.element !== undefined) { + return { intent: 'pinch', element: input.element, scale: input.scale }; + } if (input.kind !== 'drag') return normalizePublicGesture(input).gesture; return { intent: 'drag', @@ -536,6 +548,15 @@ function optionalPositionNumber(value: string | undefined): number | undefined { return value === undefined ? undefined : Number(value); } +/** `gesture pinch `: one non-numeric argument after the scale names a @ref or selector. */ +function pinchElementArgument(args: readonly string[]): string | undefined { + const candidate = args[1]; + if (args.length !== 2 || candidate === undefined || Number.isFinite(Number(candidate))) { + return undefined; + } + return candidate; +} + function optionalOrigin(x: string | undefined, y: string | undefined): Point | undefined { if ((x === undefined) !== (y === undefined)) { throw new AppError('INVALID_ARGS', 'gesture origin requires both x and y coordinates'); diff --git a/packages/gestures/src/gesture-payload-reader.test.ts b/packages/gestures/src/gesture-payload-reader.test.ts index 5b5a8a9483..1e0a9982aa 100644 --- a/packages/gestures/src/gesture-payload-reader.test.ts +++ b/packages/gestures/src/gesture-payload-reader.test.ts @@ -170,6 +170,13 @@ test('tap-only inputs are refused on other gesture kinds', () => { }); }); +test('pinch refuses an element together with an origin', () => { + assert.throws( + () => readGesturePayload({ kind: 'pinch', scale: 2, element: '@e17', origin: { x: 1, y: 2 } }), + { code: 'INVALID_ARGS', message: 'gesture pinch takes an element or an origin, not both' }, + ); +}); + test('pan accepts a hold before the move', () => { assert.deepEqual( readGesturePayload({ diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index 7872ceb187..5ac6e76e30 100644 --- a/packages/gestures/src/gesture-payload-reader.ts +++ b/packages/gestures/src/gesture-payload-reader.ts @@ -81,11 +81,14 @@ export function readGesturePayload(input: unknown): GesturePayload { }; } if (kind === 'pinch') { - return { - kind, - scale: readNumber(record, 'scale'), - origin: readOptionalPoint(record, 'origin'), - }; + const scale = readNumber(record, 'scale'); + if (record.element === undefined) { + return { kind, scale, origin: readOptionalPoint(record, 'origin') }; + } + if (record.origin !== undefined) { + throw new AppError('INVALID_ARGS', 'gesture pinch takes an element or an origin, not both'); + } + return { kind, scale, element: readNonEmptyString(record, 'element') }; } if (kind === 'rotate') { if (record.velocity !== undefined) { diff --git a/src/cli/parser/__tests__/command-suggestions.test.ts b/src/cli/parser/__tests__/command-suggestions.test.ts index ee194ed528..efe89e6f9e 100644 --- a/src/cli/parser/__tests__/command-suggestions.test.ts +++ b/src/cli/parser/__tests__/command-suggestions.test.ts @@ -71,6 +71,18 @@ for (const guess of ['start', 'restart']) { }); } +for (const guess of ['pinch', 'zoom']) { + test(`${guess} suggests gesture pinch on an element`, () => { + assert.throws( + () => parseArgs([guess, '2', '@e17']), + (error: unknown) => + error instanceof AppError && + error.message === + `Unknown command: ${guess}. Did you mean gesture pinch <@ref|selector>?`, + ); + }); +} + test('touch suggests press', () => { assert.throws( () => parseArgs(['touch', '100', '200']), diff --git a/src/cli/parser/command-suggestions.ts b/src/cli/parser/command-suggestions.ts index 5e1f0bb7ae..961cf1f1e8 100644 --- a/src/cli/parser/command-suggestions.ts +++ b/src/cli/parser/command-suggestions.ts @@ -44,6 +44,8 @@ const COMMAND_ALIAS_SUGGESTIONS: Record = { get_text: { command: 'get', example: 'get text' }, 'open-url': { command: 'open', example: 'open ' }, 'close-session': { command: 'close', example: 'close' }, + pinch: { command: 'gesture', example: 'gesture pinch <@ref|selector>' }, + zoom: { command: 'gesture', example: 'gesture pinch <@ref|selector>' }, }; /** diff --git a/src/commands/schema/cli-help-gestures.ts b/src/commands/schema/cli-help-gestures.ts index fbe1f64f42..529ce32b72 100644 --- a/src/commands/schema/cli-help-gestures.ts +++ b/src/commands/schema/cli-help-gestures.ts @@ -18,6 +18,7 @@ Shapes: agent-device scroll down --until 'id=submit' agent-device gesture fling right 200 420 180 agent-device gesture pinch 0.5 200 400 + agent-device gesture pinch 2 @e17 agent-device gesture rotate 35 200 420 agent-device gesture transform 200 420 80 -40 2 35 700 agent-device gesture tap 80 300 200 450 310 600 --count 20 --pause-ms 100 diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 18c5f1cc1c..ee23b354d3 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1008,6 +1008,7 @@ agent-device scroll down --until 'label="Sign in"' agent-device scroll refresh # pull-to-refresh at the top of the list agent-device gesture pinch 2.0 # zoom in 2x agent-device gesture pinch 0.5 200 400 # zoom out at coordinates +agent-device gesture pinch 2 @e17 # zoom in 2x centered on an element agent-device gesture rotate 35 200 420 # rotate app content agent-device gesture transform 200 420 80 -40 2 35 700 # combined pan, zoom, and rotate agent-device gesture tap 80 300 200 450 310 600 # three fingers at once From fdc29c8cb48b5a4712ac584f9f7646677a374e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 23 Nov 2026 09:25:41 +0100 Subject: [PATCH 2/5] fix(gesture): refuse misplaced pinch elements and unresolved element refs element is refused on gesture kinds other than pinch instead of being dropped, a pinch checks the backend's gesture support before resolving its element, and a recorded pinch whose element ref never resolved to a selector is refused at save time like an unresolved drag endpoint. Co-Authored-By: Claude Opus 5.5 --- .../interaction/runtime/gesture-command.ts | 3 +++ .../__tests__/session-script-writer.test.ts | 19 +++++++++---------- .../daemon/src/core/session-script-writer.ts | 12 +++++++++--- .../gestures/src/gesture-normalization.ts | 6 ++++++ .../src/gesture-payload-reader.test.ts | 7 +++++++ .../gestures/src/gesture-payload-reader.ts | 3 +++ 6 files changed, 37 insertions(+), 13 deletions(-) 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 b4922839b8..664c903aeb 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/gesture-command.ts @@ -95,6 +95,9 @@ const targetedPinchCommand: RuntimeCommand< TargetedPinchCommandOptions, CoordinateGestureCommandResult > = async (runtime, options) => { + if (!runtime.backend.performGesture) { + throw new AppError('UNSUPPORTED_OPERATION', 'gesture is not supported by this backend'); + } const { element, scale } = options.gesture; const resolved = await resolveInteractionTarget( runtime, diff --git a/packages/daemon/src/core/__tests__/session-script-writer.test.ts b/packages/daemon/src/core/__tests__/session-script-writer.test.ts index c9f1b7c018..5971ccda47 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer.test.ts @@ -283,22 +283,21 @@ test('a recorded ref that never resolved to a selectorChain throws instead of em expect(fs.existsSync(path.join(root, 'sessions'))).toBe(false); }); -test('a recorded drag refuses either unresolved ref endpoint', () => { - for (const positionals of [ - ['drag', '@e2', 'id="drop-target"'], - ['drag', 'id="drag-source"', '@e3'], - ]) { - const root = mkdtempForTestSync('agent-device-script-writer-drag-ref-'); +test('a recorded drag or pinch refuses a ref target that never resolved to a selector', () => { + for (const [positionals, message] of [ + [['drag', '@e2', 'id="drop-target"'], /recorded drag endpoint.*never resolved to a selector/], + [['drag', 'id="drag-source"', '@e3'], /recorded drag endpoint.*never resolved to a selector/], + [['pinch', '2', '@e7'], /gesture @e7.*never resolved to a selector/], + ] as const) { + const root = mkdtempForTestSync('agent-device-script-writer-gesture-ref-'); const writer = new SessionScriptWriter(path.join(root, 'sessions'), hostCwd); const session = makeRepairCompleteSession('default', { - actions: [action({ command: 'gesture', positionals })], + actions: [action({ command: 'gesture', positionals: [...positionals] })], }); const result = writer.write(session); expect(result.written).toBe(false); - expect(result.written === false && result.error?.message).toMatch( - /recorded drag endpoint.*never resolved to a selector/, - ); + expect(result.written === false && result.error?.message).toMatch(message); } }); diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index 44aa28d790..4daedc92c9 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -3,7 +3,10 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { publicPlatformString } from '@agent-device/kernel/device'; -import { dragGesturePayloadFromPositionals } from '@agent-device/gestures/gesture-normalization'; +import { + dragGesturePayloadFromPositionals, + pinchElementFromPositionals, +} from '@agent-device/gestures/gesture-normalization'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { recordedSelectorExpression } from '@agent-device/selectors'; @@ -406,8 +409,11 @@ function assertNoUnresolvedRefFallback(action: SessionAction): void { assertNoUnresolvedDragEndpoint(drag); return; } - if (!isSelectorTargetingCommand(action.command)) return; - const refPositional = action.command === 'get' ? action.positionals[1] : action.positionals[0]; + const pinchElement = + action.command === 'gesture' ? pinchElementFromPositionals(action.positionals) : undefined; + if (!pinchElement && !isSelectorTargetingCommand(action.command)) return; + const refPositional = + pinchElement ?? (action.command === 'get' ? action.positionals[1] : action.positionals[0]); if (!refPositional?.startsWith('@')) return; throw new AppError( 'COMMAND_FAILED', diff --git a/packages/gestures/src/gesture-normalization.ts b/packages/gestures/src/gesture-normalization.ts index 628a598744..3dc949704e 100644 --- a/packages/gestures/src/gesture-normalization.ts +++ b/packages/gestures/src/gesture-normalization.ts @@ -378,6 +378,12 @@ export function dragGesturePayloadFromPositionals( return payload.kind === 'drag' ? payload : undefined; } +/** Reads the element a recorded `gesture pinch ` line targets, if any. */ +export function pinchElementFromPositionals(positionals: readonly string[]): string | undefined { + if (positionals[0] !== 'pinch') return undefined; + return pinchElementArgument(positionals.slice(1)); +} + /** Serializes structured gesture input for `.ad` recordings. */ export function gesturePayloadToPositionals(input: GesturePayload): string[] { switch (input.kind) { diff --git a/packages/gestures/src/gesture-payload-reader.test.ts b/packages/gestures/src/gesture-payload-reader.test.ts index 1e0a9982aa..0ed1d6ae70 100644 --- a/packages/gestures/src/gesture-payload-reader.test.ts +++ b/packages/gestures/src/gesture-payload-reader.test.ts @@ -170,6 +170,13 @@ test('tap-only inputs are refused on other gesture kinds', () => { }); }); +test('element is refused on gesture kinds other than pinch', () => { + assert.throws(() => readGesturePayload({ kind: 'rotate', degrees: 30, element: '@e1' }), { + code: 'INVALID_ARGS', + message: 'element is supported only for gesture pinch', + }); +}); + test('pinch refuses an element together with an origin', () => { assert.throws( () => readGesturePayload({ kind: 'pinch', scale: 2, element: '@e17', origin: { x: 1, y: 2 } }), diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index 5ac6e76e30..ef0272ab04 100644 --- a/packages/gestures/src/gesture-payload-reader.ts +++ b/packages/gestures/src/gesture-payload-reader.ts @@ -42,6 +42,9 @@ export function readGesturePayload(input: unknown): GesturePayload { return readTapGesturePayload(record); } assertNoTapOnlyFields(kind, record); + if (kind !== 'pinch' && record.element !== undefined) { + throw new AppError('INVALID_ARGS', 'element is supported only for gesture pinch'); + } if (kind !== 'pan') { assertNoHoldMs(kind, record); } From eaae03e35805daf8ca2b9dac81f3230cbab0b971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 23 Nov 2026 09:30:53 +0100 Subject: [PATCH 3/5] refactor(gesture): read pinch input in its own function and share the script write failure Splits pinch payload reading out of readGesturePayload, which the change pushed over the complexity threshold, and folds the two identical script write failure wrappers into one helper. Co-Authored-By: Claude Opus 5.5 --- .../daemon/src/core/session-script-writer.ts | 28 ++++++++++------- .../gestures/src/gesture-payload-reader.ts | 30 ++++++++++++------- 2 files changed, 37 insertions(+), 21 deletions(-) diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index 4daedc92c9..d6221c6e01 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -255,11 +255,9 @@ function handleSessionScriptWriteFailure(params: { } function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): AppError { - if (error instanceof AppError) return error; - const detail = error instanceof Error ? error.message : String(error); - return new AppError( - 'COMMAND_FAILED', - `Failed to write the session script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, + return toScriptWriteFailure( + error, + `Failed to write the session script${scriptPath ? ` to ${scriptPath}` : ''}`, { reason: SCRIPT_WRITE_REASONS.writeFailed.reason, ...(scriptPath ? { path: scriptPath } : {}), @@ -269,6 +267,18 @@ function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): ); } +/** An AppError passes through; any other failure is wrapped with its message appended. */ +function toScriptWriteFailure( + error: unknown, + message: string, + details: Record, + cause?: unknown, +): AppError { + if (error instanceof AppError) return error; + const detail = error instanceof Error ? error.message : String(error); + return new AppError('COMMAND_FAILED', `${message}: ${detail}`, details, cause); +} + /** * ADR 0012 decision 6 (BLOCKER 2c): normalizes a repair-commit failure into a * distinct, surfaceable AppError. A no-clobber refusal or a bare-`@ref` failure @@ -277,11 +287,9 @@ function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): * message and hint so the two are distinguishable to the agent. */ function toRepairCommitFailure(error: unknown, scriptPath: string | undefined): AppError { - if (error instanceof AppError) return error; - const detail = error instanceof Error ? error.message : String(error); - return new AppError( - 'COMMAND_FAILED', - `Failed to write the healed script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, + return toScriptWriteFailure( + error, + `Failed to write the healed script${scriptPath ? ` to ${scriptPath}` : ''}`, { hint: 'The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.', }, diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index ef0272ab04..a2c78c94c4 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 PinchGesturePayload, type TapGesturePayload, } from '@agent-device/contracts/gesture-input'; import { readOptionalInteger } from '@agent-device/contracts/input-validation'; @@ -38,13 +39,11 @@ const TAP_ONLY_FIELDS = ['points', 'count', 'pauseMs'] as const; export function readGesturePayload(input: unknown): GesturePayload { const record = readRecord(input); const kind = readEnum(record, 'kind', GESTURE_KINDS); + assertNoPinchOnlyFields(kind, record); if (kind === 'tap') { return readTapGesturePayload(record); } assertNoTapOnlyFields(kind, record); - if (kind !== 'pinch' && record.element !== undefined) { - throw new AppError('INVALID_ARGS', 'element is supported only for gesture pinch'); - } if (kind !== 'pan') { assertNoHoldMs(kind, record); } @@ -84,14 +83,7 @@ export function readGesturePayload(input: unknown): GesturePayload { }; } if (kind === 'pinch') { - const scale = readNumber(record, 'scale'); - if (record.element === undefined) { - return { kind, scale, origin: readOptionalPoint(record, 'origin') }; - } - if (record.origin !== undefined) { - throw new AppError('INVALID_ARGS', 'gesture pinch takes an element or an origin, not both'); - } - return { kind, scale, element: readNonEmptyString(record, 'element') }; + return readPinchGesturePayload(record); } if (kind === 'rotate') { if (record.velocity !== undefined) { @@ -186,6 +178,22 @@ function assertTapSeriesFitsRequest(input: TapGesturePayload): void { ); } +function readPinchGesturePayload(record: Record): PinchGesturePayload { + const scale = readNumber(record, 'scale'); + if (record.element === undefined) { + return { kind: 'pinch', scale, origin: readOptionalPoint(record, 'origin') }; + } + if (record.origin !== undefined) { + throw new AppError('INVALID_ARGS', 'gesture pinch takes an element or an origin, not both'); + } + return { kind: 'pinch', scale, element: readNonEmptyString(record, 'element') }; +} + +function assertNoPinchOnlyFields(kind: string, record: Record): void { + if (kind === 'pinch' || record.element === undefined) return; + throw new AppError('INVALID_ARGS', 'element is supported only for gesture pinch'); +} + function assertNoTapOnlyFields(kind: string, record: Record): void { const field = TAP_ONLY_FIELDS.find((key) => record[key] !== undefined); if (field === undefined) return; From 9fa7b72d1c3d0e2b053d4f64ac8304d4881e0498 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 23 Nov 2026 09:38:38 +0100 Subject: [PATCH 4/5] docs(gestures): show the element pinch in place of the coordinate example The help first screen keeps its key rules within 30 lines. Co-Authored-By: Claude Opus 5.5 --- src/commands/schema/cli-help-gestures.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/commands/schema/cli-help-gestures.ts b/src/commands/schema/cli-help-gestures.ts index 529ce32b72..d88a87bf52 100644 --- a/src/commands/schema/cli-help-gestures.ts +++ b/src/commands/schema/cli-help-gestures.ts @@ -17,7 +17,6 @@ Shapes: agent-device gesture pan 200 420 80 -40 700 --pointer-count 2 agent-device scroll down --until 'id=submit' agent-device gesture fling right 200 420 180 - agent-device gesture pinch 0.5 200 400 agent-device gesture pinch 2 @e17 agent-device gesture rotate 35 200 420 agent-device gesture transform 200 420 80 -40 2 35 700 From 724715b8371ab6d97c8980a6fe72f5cddce3799e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 23 Nov 2026 09:51:30 +0100 Subject: [PATCH 5/5] fix(gesture): name the whole pinch step and refuse an element with extra arguments Co-Authored-By: Claude Opus 5.5 --- .../src/core/__tests__/session-script-writer.test.ts | 2 +- packages/daemon/src/core/session-script-writer.ts | 5 ++++- packages/gestures/src/gesture-normalization.test.ts | 7 +++++++ packages/gestures/src/gesture-normalization.ts | 8 ++++++-- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/core/__tests__/session-script-writer.test.ts b/packages/daemon/src/core/__tests__/session-script-writer.test.ts index 5971ccda47..df1a97affe 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer.test.ts @@ -287,7 +287,7 @@ test('a recorded drag or pinch refuses a ref target that never resolved to a sel for (const [positionals, message] of [ [['drag', '@e2', 'id="drop-target"'], /recorded drag endpoint.*never resolved to a selector/], [['drag', 'id="drag-source"', '@e3'], /recorded drag endpoint.*never resolved to a selector/], - [['pinch', '2', '@e7'], /gesture @e7.*never resolved to a selector/], + [['pinch', '2', '@e7'], /"gesture pinch 2 @e7".*never resolved to a selector/], ] as const) { const root = mkdtempForTestSync('agent-device-script-writer-gesture-ref-'); const writer = new SessionScriptWriter(path.join(root, 'sessions'), hostCwd); diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index d6221c6e01..147c0775e3 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -423,9 +423,12 @@ function assertNoUnresolvedRefFallback(action: SessionAction): void { const refPositional = pinchElement ?? (action.command === 'get' ? action.positionals[1] : action.positionals[0]); if (!refPositional?.startsWith('@')) return; + const step = pinchElement + ? `gesture ${action.positionals.join(' ')}` + : `${action.command} ${refPositional}`; throw new AppError( 'COMMAND_FAILED', - `Cannot write recorded step "${action.command} ${refPositional}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`, + `Cannot write recorded step "${step}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`, ); } diff --git a/packages/gestures/src/gesture-normalization.test.ts b/packages/gestures/src/gesture-normalization.test.ts index 9abc5a45f8..7d97555a3e 100644 --- a/packages/gestures/src/gesture-normalization.test.ts +++ b/packages/gestures/src/gesture-normalization.test.ts @@ -248,6 +248,13 @@ test('the .ad preflight defers to dispatch for values it cannot know yet', () => ); }); +test('pinch refuses an element followed by more arguments', () => { + assert.throws(() => gesturePayloadFromPositionals(['pinch', '2', '@e17', '100']), { + code: 'INVALID_ARGS', + message: 'gesture pinch takes x y or one element after the scale, not both', + }); +}); + test('pinch and rotate syntax rejects a partial origin', () => { assert.throws(() => gesturePayloadFromPositionals(['pinch', '1.5', '100']), { code: 'INVALID_ARGS', diff --git a/packages/gestures/src/gesture-normalization.ts b/packages/gestures/src/gesture-normalization.ts index 3dc949704e..ff800ba59a 100644 --- a/packages/gestures/src/gesture-normalization.ts +++ b/packages/gestures/src/gesture-normalization.ts @@ -557,8 +557,12 @@ function optionalPositionNumber(value: string | undefined): number | undefined { /** `gesture pinch `: one non-numeric argument after the scale names a @ref or selector. */ function pinchElementArgument(args: readonly string[]): string | undefined { const candidate = args[1]; - if (args.length !== 2 || candidate === undefined || Number.isFinite(Number(candidate))) { - return undefined; + if (candidate === undefined || Number.isFinite(Number(candidate))) return undefined; + if (args.length > 2) { + throw new AppError( + 'INVALID_ARGS', + 'gesture pinch takes x y or one element after the scale, not both', + ); } return candidate; }