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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/command-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 | @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.',
'Argument shapes: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge|split-view-left|split-view-right>, 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
6 changes: 4 additions & 2 deletions packages/contracts/src/gesture-plan-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,11 @@ export type SinglePointerTrajectory = {

/**
* Where a contact starts. `screen-edge` asks the platform to deliver the contact as a screen-edge
* touch, which edge gesture recognizers require.
* touch, which edge gesture recognizers require. `split-view-edge` is a screen-edge touch that
* starts the system Split View gesture; only a foldable iOS simulator with its inner panel lit
* executes it.
*/
export type GestureContactOrigin = 'screen-edge';
export type GestureContactOrigin = 'screen-edge' | 'split-view-edge';

export type SinglePointerGesturePlan = {
topology: 'single';
Expand Down
35 changes: 32 additions & 3 deletions packages/contracts/src/scroll-gesture.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import { SCROLL_REASONS } from './scroll-reasons.ts';
import { defineStringEnum } from './string-enum.ts';
import { isViewportRootNode } from './snapshot-visibility.ts';
Expand All @@ -21,8 +21,37 @@ export type ScrollInputDirection = (typeof SCROLL_INPUT_DIRECTIONS)[number];

export const SCROLL_DIRECTIONS = ['up', 'down', 'left', 'right'] as const;
export type ScrollDirection = (typeof SCROLL_DIRECTIONS)[number];
export const SWIPE_PRESETS = ['left', 'right', 'left-edge', 'right-edge'] as const;
export const SWIPE_PRESETS = [
'left',
'right',
'left-edge',
'right-edge',
'split-view-left',
'split-view-right',
] as const;
export type SwipePreset = (typeof SWIPE_PRESETS)[number];
/** Presets that move a full-screen app into one half of Split View on a foldable iOS simulator. */
export type SplitViewSwipePreset = Extract<SwipePreset, `split-view-${string}`>;
export function isSplitViewSwipePreset(preset: SwipePreset): preset is SplitViewSwipePreset {
return preset === 'split-view-left' || preset === 'split-view-right';
}
/** Why a Split View swipe preset was refused before any touch went down. */
const SPLIT_VIEW_GESTURE_REASONS = {
// Split View presets need an iOS simulator with more than one panel and its inner panel lit.
unavailable: { reason: 'split_view_unavailable' },
} as const satisfies ReasonTable<'gesture'>;
/** The refusal for a Split View preset on a device or backend without Split View. */
export function splitViewUnavailableError(
message: string,
details?: Record<string, unknown>,
): AppError {
return new AppError('UNSUPPORTED_OPERATION', message, {
...details,
reason: SPLIT_VIEW_GESTURE_REASONS.unavailable.reason,
dispatched: 'no',
hint: 'Use an iPhone Duo simulator with its inner panel lit (not closed), open the app full screen, then swipe again.',
});
}
const SCREEN_EDGE_SWIPE_PRESETS: ReadonlySet<SwipePreset> = new Set(['left-edge', 'right-edge']);
/** Edge presets drive screen-edge gestures, such as a back swipe. */
export function isScreenEdgeSwipePreset(preset: SwipePreset): boolean {
Expand Down Expand Up @@ -254,7 +283,7 @@ export function assertScrollGestureInput(options: { amount?: number; pixels?: nu
}

export function buildSwipePresetGesturePlan(
preset: SwipePreset,
preset: Exclude<SwipePreset, SplitViewSwipePreset>,
frame: GestureReferenceFrame,
): SwipePresetGesturePlan {
if (preset === 'left' || preset === 'right') {
Expand Down
34 changes: 34 additions & 0 deletions packages/gestures/src/gesture-plan-split-view.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect, test } from 'vitest';
import { buildGesturePlan } from './gesture-plan.ts';

const viewport = { x: 0, y: 0, width: 951, height: 669 };

test.each([
['split-view-left', (x: number) => x < viewport.width / 2],
['split-view-right', (x: number) => x > viewport.width / 2],
] as const)('%s drags up from the bottom edge, holds, then moves to its half', (preset, inHalf) => {
const plan = buildGesturePlan({ intent: 'fling', preset }, viewport, 'ios');
expect(plan.topology === 'single' && plan.contactOrigin).toBe('split-view-edge');
const samples = plan.pointers[0].samples;
const start = samples[0]!.point;
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const end = samples.at(-1)!.point;
expect(start.y).toBeGreaterThan(viewport.height - 2);
expect(inHalf(end.x)).toBe(true);
// The runner derives the edge touch's swipe direction from start to end; it must stay upward.
expect(Math.abs(end.x - start.x)).toBeLessThan(Math.abs(end.y - start.y));
// The pause at the middle is what lifts the app window before the sideways move.
const middle = { x: viewport.width / 2, y: viewport.height / 2 };
expect(samples.map((sample) => sample.offsetMs)).toEqual([0, 600, 1400, 1900, 2100]);
expect([samples[1]!.point, samples[2]!.point]).toEqual([middle, middle]);
});

test('a Split View preset off iOS is refused before planning a touch', () => {
expect(() =>
buildGesturePlan({ intent: 'fling', preset: 'split-view-left' }, viewport, 'android'),
).toThrow(
expect.objectContaining({
code: 'UNSUPPORTED_OPERATION',
details: expect.objectContaining({ reason: 'split_view_unavailable', dispatched: 'no' }),
}),
);
});
8 changes: 7 additions & 1 deletion packages/gestures/src/gesture-plan-viewport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ describe('viewport-aware multi-touch geometry', () => {

// Property, not another example: the planner's whole job is that a synthesized
// point never leaves the active viewport. It either plans in bounds or refuses
// with a structured INVALID_ARGS — never a silently out-of-bounds path. The
// with a structured INVALID_ARGS (UNSUPPORTED_OPERATION for a platform without
// the gesture) — never a silently out-of-bounds path. The
// generator enumerates every gesture kind from GESTURE_KINDS, so a new kind
// inherits the guarantee instead of needing its own pinned viewport case.
describe('gesture planning never synthesizes an out-of-bounds point', () => {
Expand All @@ -207,6 +208,11 @@ describe('gesture planning never synthesizes an out-of-bounds point', () => {
plan = buildGesturePlan(normalizePublicGesture(gesture).gesture, viewport, platform);
} catch (error) {
assert.ok(error instanceof AppError, `unexpected error type: ${String(error)}`);
// A Split View preset off iOS is refused for the platform, before any geometry.
if (error.details?.reason === 'split_view_unavailable') {
assert.equal(error.code, 'UNSUPPORTED_OPERATION');
return;
}
assert.equal(error.code, 'INVALID_ARGS');
return;
}
Expand Down
55 changes: 53 additions & 2 deletions packages/gestures/src/gesture-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import {
buildSwipePresetGesturePlan,
gestureDirectionDelta,
isScreenEdgeSwipePreset,
isSplitViewSwipePreset,
splitViewUnavailableError,
type SplitViewSwipePreset,
type SwipePreset,
} from '@agent-device/contracts/scroll-gesture';
import {
Expand Down Expand Up @@ -47,6 +50,7 @@ const GESTURE_PLAN_REFUSAL_REASONS = {
// two-finger path cannot keep its contacts the minimum span apart inside it.
trajectoryOutOfBounds: { reason: 'GESTURE_TRAJECTORY_OUT_OF_BOUNDS' },
} as const satisfies ReasonTable<'gesture'>;

const GESTURE_FLING_DEFAULT_DISTANCE = 180;

const GESTURE_INITIAL_SPAN_RATIO = 0.25;
Expand All @@ -56,6 +60,8 @@ const GESTURE_MINIMUM_RELIABLE_SPAN_PX = 48;
const GESTURE_VIEWPORT_INSET_PX = 1;
const DEFAULT_PAN_DURATION_MS = 500;
export const GESTURE_FLING_DURATION_MS = 100;
const SPLIT_VIEW_DURATION_MS = 2100;
const SPLIT_VIEW_EDGE_INSET_PX = 1;
const DEFAULT_MULTI_TOUCH_DURATION_MS = 300;
const MAX_ROTATION_DEGREES_PER_SAMPLE = 3;
const MAX_ROTATION_DEFAULT_DURATION_MS = 2_400;
Expand Down Expand Up @@ -94,7 +100,7 @@ export function buildGesturePlan(
const profile = gesturePlatformProfile(platform);
switch (input.intent) {
case 'fling':
return buildFlingPlan(input, frame);
return buildFlingPlan(input, frame, platform);
case 'pan':
return buildPanPlan(input, frame, profile);
case 'pinch':
Expand Down Expand Up @@ -226,8 +232,12 @@ function withContactHolds(
function buildFlingPlan(
input: Extract<GestureSemanticInput, { intent: 'fling' }>,
viewport: Rect,
platform: PublicPlatform | undefined,
): SinglePointerGesturePlan {
if ('preset' in input) {
if (isSplitViewSwipePreset(input.preset)) {
return buildSplitViewPlan(input.preset, viewport, platform);
}
const { from, to } = presetGestureEndpoints(input.preset, viewport);
const plan = buildSinglePointerPlan(
'fling',
Expand Down Expand Up @@ -264,6 +274,44 @@ function buildFlingPlan(
);
}

/**
* The system Split View drag: up from the bottom edge to the middle, a hold that lifts the app
* window, then sideways toward the requested half. The sideways end stays short of the vertical
* travel, so the edge touch keeps its upward swipe direction.
*/
function buildSplitViewPlan(
preset: SplitViewSwipePreset,
viewport: Rect,
platform: PublicPlatform | undefined,
): SinglePointerGesturePlan {
if (platform !== 'ios') {
throw splitViewUnavailableError(`gesture swipe ${preset} works only on iOS`);
}
const centerX = viewport.x + viewport.width / 2;
const middleY = viewport.y + viewport.height / 2;
const endX = viewport.x + viewport.width * (preset === 'split-view-left' ? 0.2 : 0.8);
const samples: SinglePointerTrajectory['samples'] = [
{
offsetMs: 0,
point: { x: centerX, y: viewport.y + viewport.height - SPLIT_VIEW_EDGE_INSET_PX },
},
{ offsetMs: 600, point: { x: centerX, y: middleY } },
{ offsetMs: 1400, point: { x: centerX, y: middleY } },
{ offsetMs: 1900, point: { x: endX, y: middleY } },
{ offsetMs: SPLIT_VIEW_DURATION_MS, point: { x: endX, y: middleY } },
];
assertSamplesInViewport(samples, viewport, { intent: 'fling', pointerId: 0 });
return {
topology: 'single',
intent: 'fling',
executionProfile: 'endpoint-hold',
contactOrigin: 'split-view-edge',
durationMs: SPLIT_VIEW_DURATION_MS,
viewport,
pointers: [{ pointerId: 0, samples }],
};
}

function buildPanPlan(
input: Extract<GestureSemanticInput, { intent: 'pan' }>,
viewport: Rect,
Expand Down Expand Up @@ -719,7 +767,10 @@ function interpolateGesturePoint(start: Point, end: Point, progress: number): Po
};
}

function presetGestureEndpoints(preset: SwipePreset, viewport: Rect): { from: Point; to: Point } {
function presetGestureEndpoints(
preset: Exclude<SwipePreset, SplitViewSwipePreset>,
viewport: Rect,
): { from: Point; to: Point } {
const relative = buildSwipePresetGesturePlan(preset, {
referenceWidth: viewport.width,
referenceHeight: viewport.height,
Expand Down
74 changes: 74 additions & 0 deletions packages/platform-apple/src/foldable/split-view.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import fs from 'node:fs';
import { beforeEach, expect, test, vi } from 'vitest';
import { bindTestCommandHost, createLiveTestHostEnvironment } from '@agent-device/test-kit';

vi.mock('../core/runner-client.ts', () => ({
runAppleRunnerCommand: vi.fn(async () => ({})),
}));

import type { DeviceInfo } from '@agent-device/kernel/device';
import { buildGesturePlan } from '@agent-device/gestures/gesture-plan';
import { runAppleRunnerCommand } from '../core/runner-client.ts';
import { createLocalAppleToolProvider, withAppleToolProvider } from '../core/tool-provider.ts';
import { createAppleInteractor } from '../interactor.ts';
import { IOS_DEVICE, IOS_SIMULATOR } from '../__tests__/device-fixtures.ts';
import {
IPHONE_17_SINGLE_PANEL,
IPHONE_DUO_CLOSED,
IPHONE_DUO_OPEN,
} from '../__tests__/display-fixtures.ts';

bindTestCommandHost();

const mockRunner = vi.mocked(runAppleRunnerCommand);
const viewport = { x: 0, y: 0, width: 951, height: 669 };
const splitPlan = buildGesturePlan({ intent: 'fling', preset: 'split-view-left' }, viewport, 'ios');

beforeEach(() => {
mockRunner.mockClear();
});

/** A fresh simulator id per test: the daemon keeps each simulator's resolved panel count. */
let simulatorCount = 0;
function simulator(): DeviceInfo {
simulatorCount += 1;
return { ...IOS_SIMULATOR, id: `${IOS_SIMULATOR.id}-split-${simulatorCount}` };
}

async function performSplit(device: DeviceInfo, panels: object) {
const provider = createLocalAppleToolProvider({
runCommand: async (_command, args) => {
if (args.slice(0, 4).join(' ') === 'devicectl device info displays') {
fs.writeFileSync(args.at(-1)!, JSON.stringify(panels));
}
return { stdout: '', stderr: '', exitCode: 0 };
},
});
await withAppleToolProvider(provider, () =>
createAppleInteractor(device, {}, createLiveTestHostEnvironment()).performGesture!(splitPlan),
);
}

test('an open foldable simulator sends the Split View drag as a screen-edge touch', async () => {
await performSplit(simulator(), IPHONE_DUO_OPEN);
expect(mockRunner).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
command: 'gesture',
gesturePlan: expect.objectContaining({ contactOrigin: 'screen-edge' }),
}),
expect.anything(),
);
});

test.each([
['a closed foldable simulator', simulator(), IPHONE_DUO_CLOSED],
['a single-panel simulator', simulator(), IPHONE_17_SINGLE_PANEL],
['a physical iPhone', IOS_DEVICE, IPHONE_DUO_OPEN],
] as const)('%s refuses Split View before any touch', async (_name, device, panels) => {
await expect(performSplit(device, panels)).rejects.toMatchObject({
code: 'UNSUPPORTED_OPERATION',
details: { reason: 'split_view_unavailable', dispatched: 'no' },
});
expect(mockRunner).not.toHaveBeenCalled();
});
36 changes: 36 additions & 0 deletions packages/platform-apple/src/foldable/split-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { splitViewUnavailableError } from '@agent-device/contracts/scroll-gesture';
import { IOS_APPLE_DISPLAY_PROBE_TIMEOUT_MS } from '../core/config.ts';
import { readFoldablePanelTable } from './orientation.ts';

/**
* The runner form of a Split View plan. Only a foldable simulator with its inner panel lit has
* Split View; elsewhere the same bottom-edge touch opens Home or the app switcher, so the plan is
* refused before any touch. The runner sends the contact as an ordinary screen-edge touch.
*/
export async function appleSplitViewRunnerPlan(
device: DeviceInfo,
plan: GesturePlan,
signal: AbortSignal | undefined,
): Promise<GesturePlan> {
if (plan.topology !== 'single' || plan.contactOrigin !== 'split-view-edge') return plan;
const table =
device.kind === 'simulator'
? await readFoldablePanelTable(device, {
signal,
timeoutMs: IOS_APPLE_DISPLAY_PROBE_TIMEOUT_MS,
})
: ({ kind: 'single-panel' } as const);
signal?.throwIfAborted();
const lit = table.kind === 'multi-panel' ? table.inventory : undefined;
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if (!lit?.activeDisplay || lit.ambiguous || lit.activeDisplay.primary) {
throw splitViewUnavailableError(
table.kind === 'unreadable'
? 'The panel table did not answer, so the lit panel is unknown and nothing was sent'
: 'Split View needs an iOS simulator with more than one panel and its inner panel lit',
{ deviceId: device.id, panelTable: table.kind },
);
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
return { ...plan, contactOrigin: 'screen-edge' };
}
4 changes: 3 additions & 1 deletion packages/platform-apple/src/interactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
assertScrollGestureInput,
} from '@agent-device/contracts/scroll-gesture';
import { assertAppleMultiTouchSupported } from './multitouch-support.ts';
import { appleSplitViewRunnerPlan } from './foldable/split-view.ts';
import {
isMacOs,
isTvOsDevice,
Expand Down Expand Up @@ -364,8 +365,9 @@ export async function performGestureApple(
device: DeviceInfo,
ctx: RunnerContext,
runnerOpts: RunnerOpts,
plan: GesturePlan,
requestedPlan: GesturePlan,
): Promise<Record<string, unknown>> {
const plan = await appleSplitViewRunnerPlan(device, requestedPlan, runnerOpts.signal);
if (plan.topology !== 'single') assertAppleMultiTouchSupported(device, plan.intent);
if (plan.topology === 'single' && isMacOs(device)) {
const { start: first, end: last } = singlePointerPlanEndpoints(plan);
Expand Down
4 changes: 4 additions & 0 deletions packages/provider-webdriver/src/webdriver-interactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types';
import {
type ScrollDirection,
buildScrollGesturePlan,
splitViewUnavailableError,
} from '@agent-device/contracts/scroll-gesture';
import type { TvRemoteButton } from '@agent-device/contracts/tv-remote';
import type { SettingOptions } from '@agent-device/contracts/settings';
Expand Down Expand Up @@ -279,6 +280,9 @@ class WebDriverInteractor implements Interactor {
}

async performGesture(plan: GesturePlan): Promise<Record<string, unknown>> {
if (plan.topology === 'single' && plan.contactOrigin === 'split-view-edge') {
throw splitViewUnavailableError('WebDriver providers do not support Split View');
}
this.requireSupport(webDriverOperationForGesture(plan));
await this.client.performActions(
plan.pointers.map((pointer) =>
Expand Down
2 changes: 1 addition & 1 deletion src/commands/schema/cli-help-foldable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ Changing the pose:

Home and app switcher:
On a foldable iOS simulator, home and app-switcher press the Home button through the same helper's simulator HID, once for home and twice for the app switcher, because the XCUITest Home press does not reach the home screen there. Verified closed, half-open, and open. The first press on a host or Xcode builds the helper and takes longer.
Split View on the open device: run open com.apple.springboard, longpress an app icon, press "Open in Split View", then press the icon of the second app. Take the labels from snapshot -i.`,
Split View on an unfolded device (the inner panel lit, so open or half-open; check the exact pose with UIHinge.status): with the session app full screen, run gesture swipe split-view-left or gesture swipe split-view-right. The app moves to that half and the Home Screen fills the other; open <bundle> launches a second app there and binds the session to it. Switch between the halves with open <bundle>; the split stays. Any other device, a closed Duo, or a WebDriver provider refuses with UNSUPPORTED_OPERATION and reason split_view_unavailable before any touch.`,
} as const;
Loading
Loading