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
20 changes: 20 additions & 0 deletions contracts/fixtures/screenshot-crop-geometry.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,26 @@
"expectedProjection": { "x": 210, "y": 678, "width": 436, "height": 71 },
"expectedIntersection": { "x": 210, "y": 678, "width": 436, "height": 71 }
},
{
"name": "webOS app at 1280x720: CSS px rects land 1:1 in the top-left of the 1920x1080 capture",
"space": "device-pixels",
"bounds": null,
"captureScale": 1,
"rect": { "x": 200, "y": 300, "width": 400, "height": 240 },
"image": { "width": 1920, "height": 1080 },
"expectedProjection": { "x": 200, "y": 300, "width": 400, "height": 240 },
"expectedIntersection": { "x": 200, "y": 300, "width": 400, "height": 240 }
},
{
"name": "Tizen page with a 1280 meta viewport: CSS px rects scale by the 1.5 capture scale",
"space": "device-pixels",
"bounds": null,
"captureScale": 1.5,
"rect": { "x": 200, "y": 300, "width": 400, "height": 240 },
"image": { "width": 1920, "height": 1080 },
"expectedProjection": { "x": 300, "y": 450, "width": 600, "height": 360 },
"expectedIntersection": { "x": 300, "y": 450, "width": 600, "height": 360 }
},
{
"name": "macOS app window: non-zero-origin bounds shift the rect before the 2x scale",
"space": "viewport-points",
Expand Down
30 changes: 29 additions & 1 deletion packages/capture-kit/src/snapshot-rect-projection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,28 @@ import fs from 'node:fs';
import path from 'node:path';
import { SCREENSHOT_CROP_REASONS } from '@agent-device/contracts/capture';
import { AppError } from '@agent-device/kernel/errors';
import { snapshotCaptureScaleFrom } from '@agent-device/kernel/rect';
import type { Rect } from '@agent-device/kernel/snapshot';
import {
intersectScreenshotRect,
projectSnapshotRectToScreenshot,
resolveScreenshotFrame,
resolveScreenshotRectSpace,
resolveSnapshotBounds,
type ScreenshotRectSpace,
} from './snapshot-rect-projection.ts';

// Golden geometry table for `screenshot --crop-on`: the numbers are the live
// evidence baseline (iOS simulator 402/1206, iOS physical 390/1170, Android 1080, macOS 586/1172),
// evidence baseline (iOS simulator 402/1206, iOS physical 390/1170, Android 1080, macOS 586/1172,
// webOS and Tizen TV pages 1920 at capture scale 1 and 1.5),
// so a projection-law change that moves any accepted cell's crop box turns this
// red before the pixel-identity cross-check could ever notice.

type FixtureCase = {
name: string;
space: ScreenshotRectSpace;
bounds: Rect | null;
captureScale?: number;
rect: Rect;
image: { width: number; height: number };
expectedProjection: Rect;
Expand Down Expand Up @@ -50,6 +54,7 @@ test('the crop projection law agrees with every golden geometry case', () => {
fixture.rect,
fixture.image.width,
fixture.image.height,
snapshotCaptureScaleFrom(fixture.captureScale),
);
assert.deepEqual(projected, fixture.expectedProjection, fixture.name);
const intersection = intersectScreenshotRect(
Expand All @@ -61,6 +66,29 @@ test('the crop projection law agrees with every golden geometry case', () => {
}
});

test('resolveScreenshotFrame is the page at its capture scale, else the whole image', () => {
const image = { width: 1920, height: 1080 };
const page = (width: number, height: number) => ({ width, height });
const scale = (value: number) => snapshotCaptureScaleFrom(value);

assert.deepEqual(resolveScreenshotFrame(image, { viewport: page(1280, 720) }), image);
assert.deepEqual(
resolveScreenshotFrame(image, { viewport: page(1280, 720), captureScale: scale(1) }),
{
width: 1280,
height: 720,
},
);
assert.deepEqual(
resolveScreenshotFrame(image, { viewport: page(1280, 720), captureScale: scale(1.5) }),
image,
);
assert.deepEqual(
resolveScreenshotFrame(image, { viewport: page(1281, 721), captureScale: scale(1.5) }),
image,
);
});

test('resolveScreenshotRectSpace maps each accepted backend to its projection space and refuses the rest', () => {
assert.equal(resolveScreenshotRectSpace('android'), 'device-pixels');
assert.equal(resolveScreenshotRectSpace('xctest'), 'viewport-points');
Expand Down
44 changes: 37 additions & 7 deletions packages/capture-kit/src/snapshot-rect-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import {
normalizeType,
} from '@agent-device/contracts/snapshot';
import { intersectRects, isPositiveFiniteRect, rectArea } from '@agent-device/kernel/rect';
import type { Rect, SnapshotNode } from '@agent-device/kernel/snapshot';
import type { Rect, SnapshotCaptureScale, SnapshotNode } from '@agent-device/kernel/snapshot';

/**
* The space a snapshot's rects are expressed in, as far as the captured image is concerned:
* `device-pixels` rects land 1:1 on the PNG (Android), `viewport-points` rects must be shifted
* by the viewport bounds and scaled to the image (Apple, where 1x/2x/3x captures all share the
* points-space tree).
* `device-pixels` rects land on the PNG at the producer's capture scale, 1:1 unless it published
* one (Android; a TV app page's CSS px), `viewport-points` rects must be shifted by the viewport
* bounds and scaled to the image (Apple, where 1x/2x/3x captures all share the points-space tree).
*/
export type ScreenshotRectSpace = 'device-pixels' | 'viewport-points';

Expand Down Expand Up @@ -40,18 +40,27 @@ export function resolveScreenshotRectSpace(backend: string | undefined): Screens
/**
* Where a snapshot rect falls in the captured image: the space-specific law only, with NO
* clamping. Callers decide what out-of-image means — the overlay clamps to a 1px box, the crop
* intersects and refuses the empty case.
* intersects and refuses the empty case. `captureScale` is the producer's published scale, which
* only `device-pixels` rects obey.
*/
export function projectSnapshotRectToScreenshot(
space: ScreenshotRectSpace,
bounds: Rect | null,
rect: Rect,
imageWidth: number,
imageHeight: number,
captureScale?: SnapshotCaptureScale,
): Rect {
if (space === 'device-pixels' || bounds === null) {
return roundRect(rect);
if (space === 'device-pixels') {
const scale = captureScale ?? 1;
return {
x: Math.round(rect.x * scale),
y: Math.round(rect.y * scale),
width: Math.round(rect.width * scale),
height: Math.round(rect.height * scale),
};
}
if (bounds === null) return roundRect(rect);
const scaleX = imageWidth / bounds.width;
const scaleY = imageHeight / bounds.height;
return {
Expand All @@ -62,6 +71,27 @@ export function projectSnapshotRectToScreenshot(
};
}

/**
* The top-left part of the image a page fills when its producer published a capture scale: the
* viewport at that scale. A webOS app at 1280x720 fills 1280x720 of a 1920x1080 capture, and the
* rest is not the page. Without a capture scale the whole image is the frame.
*/
export function resolveScreenshotFrame(
image: Readonly<{ width: number; height: number }>,
page: Readonly<{
viewport?: Readonly<{ width: number; height: number }>;
captureScale?: SnapshotCaptureScale;
}>,
): { width: number; height: number } {
if (page.captureScale === undefined || page.viewport === undefined) {
return { width: image.width, height: image.height };
}
return {
width: Math.min(image.width, Math.round(page.viewport.width * page.captureScale)),
height: Math.min(image.height, Math.round(page.viewport.height * page.captureScale)),
};
}

/**
* The crop box a projected rect actually yields: its intersection with the image frame. `null`
* means the rect occupies no image pixel — a crop cannot be taken, not a 1px sliver.
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/capture/screenshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export const screenshotCommandFacet = defineCommandFacet({
summary: 'Capture a screenshot',
searchHint: 'picture screen png',
cliDetail:
"Web defaults to the viewport; use --fullscreen, --full, or -f for the entire page. iOS simulators default to 1x logical-point output; use --pixel-density to request a different screenshot density. Use --screen-mask black to fill the iOS simulator screen outline, including rounded corners, with black for this capture. It requires simctl: physical devices, tvOS and visionOS simulators, other platforms, provider captures and XCTest runner captures are refused. A masked capture fails if simctl fails instead of falling back to an unmasked runner capture. macOS app sessions default to the app window; use --fullscreen for full desktop, --scale to downscale, --crop-on <selector> to crop the capture to the frame the selector resolves on the same screen (currently iOS simulators, Android emulators, and CoreDevice physical iPhones), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator or Android chrome. Physical iPhone crop verification covers portrait CoreDevice/devicectl captures only. XCTest, runner fallback, and physical iPad crops are refused; landscape iPhone crop is unverified. Android captures immediately by default; --normalize-status-bar also waits for transient UI to fade, and --no-stabilize keeps capture immediate. With the native macOS backend, the front window is the app's frontmost visible, nonempty normal-level (layer-0) window on the current Space: floating palettes and app-modal alerts at window level 8 are skipped, as is the small indicator window macOS adds in front of a window that a screen-sharing stream captures, and a sheet is captured as its own window. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen. On single-display iOS simulators and Android devices, the result reports displayRotation, the rotation the display rendered the capture in, when the device returns a reading in time; otherwise the field is absent. On iOS simulators a screenshot waits for that simulator's status bar to be free, and a request its caller cancelled while it waits reports the cancellation instead of capturing.",
"Web defaults to the viewport; use --fullscreen, --full, or -f for the entire page. iOS simulators default to 1x logical-point output; use --pixel-density to request a different screenshot density. Use --screen-mask black to fill the iOS simulator screen outline, including rounded corners, with black for this capture. It requires simctl: physical devices, tvOS and visionOS simulators, other platforms, provider captures and XCTest runner captures are refused. A masked capture fails if simctl fails instead of falling back to an unmasked runner capture. macOS app sessions default to the app window; use --fullscreen for full desktop, --scale to downscale, --crop-on <selector> to crop the capture to the frame the selector resolves on the same screen (currently iOS simulators, Android emulators, CoreDevice physical iPhones, and Samsung Tizen and LG webOS TV apps), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator or Android chrome. Physical iPhone crop verification covers portrait CoreDevice/devicectl captures only. XCTest, runner fallback, and physical iPad crops are refused; landscape iPhone crop is unverified. Android captures immediately by default; --normalize-status-bar also waits for transient UI to fade, and --no-stabilize keeps capture immediate. With the native macOS backend, the front window is the app's frontmost visible, nonempty normal-level (layer-0) window on the current Space: floating palettes and app-modal alerts at window level 8 are skipped, as is the small indicator window macOS adds in front of a window that a screen-sharing stream captures, and a sheet is captured as its own window. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen. On single-display iOS simulators and Android devices, the result reports displayRotation, the rotation the display rendered the capture in, when the device returns a reading in time; otherwise the field is absent. On iOS simulators a screenshot waits for that simulator's status bar to be free, and a request its caller cancelled while it waits reports the cancellation instead of capturing.",
},
metadata: screenshotCommandMetadata,
run: (client, input) => client.capture.screenshot(input),
Expand Down
3 changes: 3 additions & 0 deletions packages/contracts/src/snapshot-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
SnapshotQualityNote,
IosSnapshotObservation,
ScreenshotOverlayRef,
SnapshotCaptureScale,
SnapshotViewportSize,
} from '@agent-device/kernel/snapshot';
import type { SnapshotState } from '@agent-device/contracts/snapshot-model';
Expand Down Expand Up @@ -37,6 +38,8 @@ export type InteractorSnapshotCapture = {
* producer measured no box; see {@link SnapshotViewportSize} for what each producer measures.
*/
viewport?: SnapshotViewportSize;
/** See {@link SnapshotCaptureScale}. Absent means the producer published no scale. */
captureScale?: SnapshotCaptureScale;
analysis?: { rawNodeCount: number; maxDepth: number };
androidSnapshot?: AndroidSnapshotBackendMetadata;
freshness?: {
Expand Down
3 changes: 3 additions & 0 deletions packages/daemon/src/core/snapshot-capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
snapshotOptionsFromFlags,
type PresentedSurface,
type RawSnapshotNode,
type SnapshotCaptureScale,
type SnapshotKeyboardBandFact,
type SnapshotViewportSize,
} from '@agent-device/kernel/snapshot';
Expand Down Expand Up @@ -60,6 +61,8 @@ type SnapshotData = {
keyboard?: SnapshotKeyboardBandFact;
/** The box the capture's rects are measured in (#3182), carried to the state the response reads. */
viewport?: SnapshotViewportSize;
/** Screenshot pixels per rect unit, when the producer published one; the crop projection reads it. */
captureScale?: SnapshotCaptureScale;
/**
* iOS: whether the capture read a modal presentation over the app (#3565), carried to the state
* settle's presented-surface confirmation arms on. Absent means the producer published no fact.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
ANDROID_DEVICE,
ANDROID_EMULATOR,
ANDROID_TV_DEVICE,
IOS_DEVICE,
IOS_SIMULATOR,
IPADOS_SIMULATOR,
Expand All @@ -16,10 +17,14 @@ import {
type SessionSurface,
} from '@agent-device/contracts/session';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { expect, test } from 'vitest';
import { snapshotCaptureScaleFrom, snapshotViewportSizeFrom } from '@agent-device/kernel/rect';
import { afterEach, expect, test } from 'vitest';
import { makeProviderRuntimeOwning } from '../../__tests__/support/handlers/snapshot-handler.fixtures.ts';
import { providerDeviceAdmissionFixture } from '../../__tests__/support/provider-device-admission-fixture.ts';
import {
SCREENSHOT_CROP_TARGET_CELLS,
assertScreenshotCropPolicy,
assertScreenshotCropSnapshot,
classifyScreenshotCropTarget,
} from '../screenshot-crop-target.ts';

Expand All @@ -38,11 +43,26 @@ const IOS_DEVICE_XCTEST: DeviceInfo = {
...IOS_DEVICE,
iosPhysicalDeviceBackend: 'xctest',
};
const PROVIDER_TV: DeviceInfo = {
platform: 'android',
id: 'tizen:192.0.2.10:26101',
name: '192.0.2.10',
kind: 'device',
target: 'tv',
booted: true,
};
const TV_PROVIDER_RUNTIME = makeProviderRuntimeOwning(PROVIDER_TV, 'tizen');
const providerAdmission = providerDeviceAdmissionFixture([TV_PROVIDER_RUNTIME]);

afterEach(() => {
providerAdmission.setActive([TV_PROVIDER_RUNTIME]);
});

/** The cells with live pixel-identity evidence; every other cell stays rejected. */
const ACCEPTED_CROP_TARGETS: readonly CropTargetDevice['target'][] = [
'ios-simulator',
'android-emulator',
'provider-android-tv',
'ios-physical',
];

Expand All @@ -51,6 +71,7 @@ const CROP_TARGET_DEVICES: readonly CropTargetDevice[] = [
{ target: 'ios-simulator', device: IOS_SIMULATOR, surface: undefined },
{ target: 'android-emulator', device: ANDROID_EMULATOR, surface: undefined },
{ target: 'android-device', device: ANDROID_DEVICE, surface: undefined },
{ target: 'provider-android-tv', device: PROVIDER_TV, surface: undefined },
{ target: 'macos-app-window', device: MACOS_DEVICE, surface: 'app' },
{ target: 'ios-physical', device: IOS_DEVICE, surface: undefined },
{ target: 'ios-physical-xctest', device: IOS_DEVICE_XCTEST, surface: undefined },
Expand Down Expand Up @@ -91,6 +112,63 @@ test('the classifier and the acceptance matrix agree one-to-one, and the accepte
}
});

test('an Android TV is in the provider TV cell only while a provider runtime owns it', () => {
expect(classifyScreenshotCropTarget(PROVIDER_TV, undefined)).toBe('provider-android-tv');
expect(classifyScreenshotCropTarget(ANDROID_TV_DEVICE, undefined)).toBe('android-device');
providerAdmission.setActive([]);
expect(classifyScreenshotCropTarget(PROVIDER_TV, undefined)).toBe('android-device');
});

test('a provider-owned phone stays in the Android device cell', () => {
providerAdmission.setActive([makeProviderRuntimeOwning(ANDROID_DEVICE)]);
expect(classifyScreenshotCropTarget(ANDROID_DEVICE, undefined)).toBe('android-device');
});

test('a provider-owned Android TV emulator stays in the Android emulator cell', () => {
const tvEmulator: DeviceInfo = { ...PROVIDER_TV, kind: 'emulator' };
providerAdmission.setActive([makeProviderRuntimeOwning(tvEmulator)]);
expect(classifyScreenshotCropTarget(tvEmulator, undefined)).toBe('android-emulator');
});

const TV_PAGE = {
producer: 'cdp-dom',
captureScale: snapshotCaptureScaleFrom(1.5),
viewport: snapshotViewportSizeFrom({ x: 0, y: 0, width: 1280, height: 720 }),
} as const;

test('a provider TV crop is accepted only on the page tree the TV plugins capture', () => {
expect(() => assertScreenshotCropSnapshot(PROVIDER_TV, TV_PAGE)).not.toThrow();
expect(() =>
assertScreenshotCropSnapshot(ANDROID_EMULATOR, { producer: 'android-uiautomator' }),
).not.toThrow();
expect(() =>
assertScreenshotCropSnapshot(PROVIDER_TV, { ...TV_PAGE, producer: 'android-uiautomator' }),
).toThrow(
expect.objectContaining({
code: 'UNSUPPORTED_OPERATION',
message:
'screenshot --crop-on is not accepted on provider-android-tv-non-cdp-snapshot targets',
details: {
reason: SCREENSHOT_CROP_REASONS.targetNotAccepted,
rejectionReason: SCREENSHOT_CROP_REASONS.pendingPixelIdentityEvidence,
},
}),
);
});

test('a provider TV crop fails on a page that published no capture scale or no viewport', () => {
const unreadable = expect.objectContaining({
code: 'COMMAND_FAILED',
details: { reason: SCREENSHOT_CROP_REASONS.captureUnreadable },
});
expect(() =>
assertScreenshotCropSnapshot(PROVIDER_TV, { ...TV_PAGE, captureScale: undefined }),
).toThrow(unreadable);
expect(() =>
assertScreenshotCropSnapshot(PROVIDER_TV, { ...TV_PAGE, viewport: undefined }),
).toThrow(unreadable);
});

test('a physical iPad has its own cell, and an iPad simulator stays in the simulator cell', () => {
expect(classifyScreenshotCropTarget(IPADOS_DEVICE, undefined)).toBe('ipados-physical');
expect(classifyScreenshotCropTarget(IPADOS_SIMULATOR, undefined)).toBe('ios-simulator');
Expand Down Expand Up @@ -248,7 +326,7 @@ test('a matrix-rejected target is refused with the pending-evidence reason', ()
});

test('an accepted target with a valid selector passes the policy', () => {
for (const device of [IOS_SIMULATOR, ANDROID_EMULATOR]) {
for (const device of [IOS_SIMULATOR, ANDROID_EMULATOR, PROVIDER_TV]) {
expect(() =>
assertScreenshotCropPolicy({ device, surface: undefined, ...POLICY_BASE }),
).not.toThrow();
Expand Down
Loading
Loading