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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ 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 {
toBackendResult,
type BackendResultEnvelope,
type RuntimeCommand,
} from '../../runtime-types.ts';
import { assertSupportedInteractionSurface } from './resolution.ts';
import { assertSupportedInteractionSurface, resolveInteractionTarget } from './resolution.ts';
import {
dragCommand,
resolveGestureViewport,
Expand All @@ -27,14 +30,23 @@ 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;
durationMs: number;
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;
Expand Down Expand Up @@ -74,9 +86,46 @@ export const gestureCommand: RuntimeCommand<GestureCommandOptions, GestureComman
) => {
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<import('@agent-device/contracts/backend').AgentDeviceBackend['performGesture']>
>[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(), {
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/interaction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge>, pinch <scale> [x] [y], rotate <degrees> [x] [y], transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs], tap <x1> <y1> <x2> <y2> [... <x5> <y5>] [--hold-ms <ms>] [--count <n>] [--pause-ms <ms>], or drag <source-selector|pinned-ref> <destination-selector|pinned-ref> [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 <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge>, pinch <scale> [x y | @ref|selector] (centered on the screen when neither is given), rotate <degrees> [x] [y], transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs], tap <x1> <y1> <x2> <y2> [... <x5> <y5>] [--hold-ms <ms>] [--count <n>] [--pause-ms <ms>], or drag <source-selector|pinned-ref> <destination-selector|pinned-ref> [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) =>
Expand Down
3 changes: 3 additions & 0 deletions packages/command-surface/src/interaction/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
Expand Down
5 changes: 4 additions & 1 deletion packages/contracts/src/daemon-command-surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
GestureContactCount,
GestureIntent,
GestureSemanticInput,
TargetedPinchGestureInput,
} from './gesture-plan-types.ts';
import type { FindLocator } from './snapshot-types.ts';
import type {
Expand Down Expand Up @@ -250,7 +251,7 @@ export type DaemonHoverOptions = CommandContext &

export type DaemonGestureOptions = CommandContext &
(
| Readonly<{ gesture: GestureSemanticInput }>
| Readonly<{ gesture: GestureSemanticInput | TargetedPinchGestureInput }>
| Readonly<{
gesture: DragGestureInput;
expectedResolvedTargets?: {
Expand All @@ -269,6 +270,8 @@ export type DaemonCoordinateGestureResult = Readonly<{
to: Point;
backendResult?: Record<string, unknown>;
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. */
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/gesture-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
12 changes: 11 additions & 1 deletion packages/contracts/src/gesture-plan-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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 };

Expand Down
4 changes: 2 additions & 2 deletions packages/contracts/src/platform-runtime-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<GestureCommandInput, { intent: 'drag' }>): boolean {
if (input.intent === 'pan') return ('pointerCount' in input ? input.pointerCount : 1) === 2;
return (
input.intent === 'pinch' ||
Expand Down
19 changes: 9 additions & 10 deletions packages/daemon/src/core/__tests__/session-script-writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});

Expand Down
45 changes: 31 additions & 14 deletions packages/daemon/src/core/session-script-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 } : {}),
Expand All @@ -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<string, unknown>,
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
Expand All @@ -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.',
},
Expand Down Expand Up @@ -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',
Comment thread
thymikee marked this conversation as resolved.
Resolved
`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.`,
);
}

Expand Down
Loading
Loading