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..664c903aeb 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,46 @@ 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) => { + 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, + { + ...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/core/__tests__/session-script-writer.test.ts b/packages/daemon/src/core/__tests__/session-script-writer.test.ts index c9f1b7c018..df1a97affe 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 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); 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..147c0775e3 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'; @@ -252,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 } : {}), @@ -266,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 @@ -274,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.', }, @@ -406,12 +417,18 @@ 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; + 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/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..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', @@ -257,6 +264,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..ff800ba59a 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': { @@ -377,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) { @@ -394,7 +401,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 +477,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 +519,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 +554,19 @@ 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 (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; +} + 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..0ed1d6ae70 100644 --- a/packages/gestures/src/gesture-payload-reader.test.ts +++ b/packages/gestures/src/gesture-payload-reader.test.ts @@ -170,6 +170,20 @@ 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 } }), + { 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..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,6 +39,7 @@ 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); } @@ -81,11 +83,7 @@ export function readGesturePayload(input: unknown): GesturePayload { }; } if (kind === 'pinch') { - return { - kind, - scale: readNumber(record, 'scale'), - origin: readOptionalPoint(record, 'origin'), - }; + return readPinchGesturePayload(record); } if (kind === 'rotate') { if (record.velocity !== undefined) { @@ -180,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; 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..d88a87bf52 100644 --- a/src/commands/schema/cli-help-gestures.ts +++ b/src/commands/schema/cli-help-gestures.ts @@ -17,7 +17,7 @@ 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 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