diff --git a/contracts/fixtures/screenshot-crop-geometry.json b/contracts/fixtures/screenshot-crop-geometry.json index bb8db5e6df..9cf1435095 100644 --- a/contracts/fixtures/screenshot-crop-geometry.json +++ b/contracts/fixtures/screenshot-crop-geometry.json @@ -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", diff --git a/packages/capture-kit/src/snapshot-rect-projection.test.ts b/packages/capture-kit/src/snapshot-rect-projection.test.ts index b318ea96b3..c027e32132 100644 --- a/packages/capture-kit/src/snapshot-rect-projection.test.ts +++ b/packages/capture-kit/src/snapshot-rect-projection.test.ts @@ -4,17 +4,20 @@ 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. @@ -22,6 +25,7 @@ type FixtureCase = { name: string; space: ScreenshotRectSpace; bounds: Rect | null; + captureScale?: number; rect: Rect; image: { width: number; height: number }; expectedProjection: Rect; @@ -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( @@ -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'); diff --git a/packages/capture-kit/src/snapshot-rect-projection.ts b/packages/capture-kit/src/snapshot-rect-projection.ts index 3e056679ca..f5dfe76bc4 100644 --- a/packages/capture-kit/src/snapshot-rect-projection.ts +++ b/packages/capture-kit/src/snapshot-rect-projection.ts @@ -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'; @@ -40,7 +40,8 @@ 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, @@ -48,10 +49,18 @@ export function projectSnapshotRectToScreenshot( 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 { @@ -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. diff --git a/packages/command-surface/src/capture/screenshot.ts b/packages/command-surface/src/capture/screenshot.ts index 634305d3da..2d61adf37f 100644 --- a/packages/command-surface/src/capture/screenshot.ts +++ b/packages/command-surface/src/capture/screenshot.ts @@ -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 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 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), diff --git a/packages/contracts/src/snapshot-types.ts b/packages/contracts/src/snapshot-types.ts index dd843f06a3..6b3d553828 100644 --- a/packages/contracts/src/snapshot-types.ts +++ b/packages/contracts/src/snapshot-types.ts @@ -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'; @@ -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?: { diff --git a/packages/daemon/src/core/snapshot-capture.ts b/packages/daemon/src/core/snapshot-capture.ts index d79c429fc7..e67d79066b 100644 --- a/packages/daemon/src/core/snapshot-capture.ts +++ b/packages/daemon/src/core/snapshot-capture.ts @@ -13,6 +13,7 @@ import { snapshotOptionsFromFlags, type PresentedSurface, type RawSnapshotNode, + type SnapshotCaptureScale, type SnapshotKeyboardBandFact, type SnapshotViewportSize, } from '@agent-device/kernel/snapshot'; @@ -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. diff --git a/packages/daemon/src/execution/__tests__/screenshot-crop-target.test.ts b/packages/daemon/src/execution/__tests__/screenshot-crop-target.test.ts index 52bf1f8306..15c89c7ecc 100644 --- a/packages/daemon/src/execution/__tests__/screenshot-crop-target.test.ts +++ b/packages/daemon/src/execution/__tests__/screenshot-crop-target.test.ts @@ -1,6 +1,7 @@ import { ANDROID_DEVICE, ANDROID_EMULATOR, + ANDROID_TV_DEVICE, IOS_DEVICE, IOS_SIMULATOR, IPADOS_SIMULATOR, @@ -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'; @@ -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', ]; @@ -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 }, @@ -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'); @@ -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(); diff --git a/packages/daemon/src/execution/screenshot-crop-target.ts b/packages/daemon/src/execution/screenshot-crop-target.ts index 1e476e123c..50bb325d81 100644 --- a/packages/daemon/src/execution/screenshot-crop-target.ts +++ b/packages/daemon/src/execution/screenshot-crop-target.ts @@ -4,9 +4,12 @@ import { type ScreenshotCropReason, } from '@agent-device/contracts/capture'; import type { SessionSurface } from '@agent-device/contracts/session'; +import type { SnapshotProducer } from '@agent-device/contracts/snapshot-producers'; +import type { SnapshotCaptureScale, SnapshotViewportSize } from '@agent-device/kernel/snapshot'; import { resolveDeviceAppleOs, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { validateSelectorExpression } from '@agent-device/selectors'; +import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; /** * The `--crop-on` target policy: which device capture frame the crop is accepted on, and the @@ -18,6 +21,7 @@ type CropTarget = | 'ios-simulator' | 'android-emulator' | 'android-device' + | 'provider-android-tv' | 'macos-app-window' | 'ios-physical' | 'ios-physical-xctest' @@ -48,6 +52,7 @@ export const SCREENSHOT_CROP_TARGET_CELLS: readonly CropTargetCell[] = [ { target: 'ios-simulator', status: 'accepted' }, { target: 'android-emulator', status: 'accepted' }, { target: 'android-device', status: 'rejected', rejectionReason: PENDING }, + { target: 'provider-android-tv', status: 'accepted' }, { target: 'macos-app-window', status: 'rejected', rejectionReason: PENDING }, { target: 'ios-physical', status: 'accepted' }, { target: 'ios-physical-xctest', status: 'rejected', rejectionReason: PENDING }, @@ -69,7 +74,7 @@ export function classifyScreenshotCropTarget( case 'apple': return classifyAppleCropTarget(device, surface); case 'android': - return device.kind === 'device' ? 'android-device' : 'android-emulator'; + return classifyAndroidCropTarget(device); case 'harmonyos': return 'harmonyos'; case 'vega': @@ -81,6 +86,14 @@ export function classifyScreenshotCropTarget( } } +function classifyAndroidCropTarget(device: DeviceInfo): CropTarget { + // A TV web app plugin serves its TV as an Android TV device it owns: the frame is the app page. + if (device.target === 'tv' && device.kind === 'device' && isActiveProviderDevice(device)) { + return 'provider-android-tv'; + } + return device.kind === 'device' ? 'android-device' : 'android-emulator'; +} + function classifyAppleCropTarget( device: DeviceInfo, surface: SessionSurface | undefined, @@ -169,3 +182,29 @@ export function assertScreenshotCropCapture( throw cropRefusal('ios-physical-non-coredevice-capture', PENDING); } } + +/** + * Provider TV crop evidence covers the TV web app plugins' page tree, not any provider tree. The + * crop places that tree's rects in the capture by the page's viewport and capture scale, so a page + * missing either cannot be cropped: a zoomed page would crop the wrong region. + */ +export function assertScreenshotCropSnapshot( + device: DeviceInfo, + snapshot: Readonly<{ + producer?: SnapshotProducer; + captureScale?: SnapshotCaptureScale; + viewport?: SnapshotViewportSize; + }>, +): void { + if (classifyScreenshotCropTarget(device, undefined) !== 'provider-android-tv') return; + if (snapshot.producer !== 'cdp-dom') { + throw cropRefusal('provider-android-tv-non-cdp-snapshot', PENDING); + } + if (snapshot.captureScale === undefined || snapshot.viewport === undefined) { + throw new AppError( + 'COMMAND_FAILED', + 'the TV page published no capture scale or viewport, so --crop-on cannot place its rects in the capture: its browser has no visualViewport, or the visual viewport is panned', + { reason: SCREENSHOT_CROP_REASONS.captureUnreadable }, + ); + } +} diff --git a/packages/daemon/src/execution/screenshot-crop.ts b/packages/daemon/src/execution/screenshot-crop.ts index 964cfd0ec1..a02a7c2053 100644 --- a/packages/daemon/src/execution/screenshot-crop.ts +++ b/packages/daemon/src/execution/screenshot-crop.ts @@ -9,6 +9,7 @@ import { cropPngFile } from '@agent-device/capture-kit/png-crop'; import { intersectScreenshotRect, projectSnapshotRectToScreenshot, + resolveScreenshotFrame, resolveScreenshotRectSpace, resolveSnapshotBounds, } from '@agent-device/capture-kit/snapshot-rect-projection'; @@ -19,6 +20,7 @@ import type { DaemonCommandContext } from '../core/context.ts'; import { captureSnapshotData } from '../core/snapshot-capture.ts'; import { runtimeExecutionFromContext } from '../core/snapshot-runtime-capture-input.ts'; import type { BoundScreenshotRuntime } from './screenshot-runtime-binding.ts'; +import { assertScreenshotCropSnapshot } from './screenshot-crop-target.ts'; import type { SessionState } from '../core/session-state.ts'; export type ScreenshotCropOutcome = Readonly<{ partialIntersection: boolean }>; @@ -65,6 +67,7 @@ export async function cropScreenshotToSelector(params: { }), }); const snapshot = buildSnapshotState(snapshotData, flags); + assertScreenshotCropSnapshot(device, snapshotData); if (snapshot.snapshotQuality?.state === 'sparse') { throw new AppError( @@ -82,8 +85,10 @@ export async function cropScreenshotToSelector(params: { node.rect!, image.width, image.height, + snapshotData.captureScale, ); - const box = intersectScreenshotRect(projected, image.width, image.height); + const frame = resolveScreenshotFrame(image, snapshotData); + const box = intersectScreenshotRect(projected, frame.width, frame.height); if (box === null) { throw new AppError( 'COMMAND_FAILED', diff --git a/packages/daemon/src/execution/screenshot-runtime-execution.test.ts b/packages/daemon/src/execution/screenshot-runtime-execution.test.ts index 8ea092d454..bb7a566d25 100644 --- a/packages/daemon/src/execution/screenshot-runtime-execution.test.ts +++ b/packages/daemon/src/execution/screenshot-runtime-execution.test.ts @@ -9,6 +9,8 @@ import { bindLocalScreenshotInteractor, defaultCaptureOnly, } from '@agent-device/contracts/screenshot-runtime'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { snapshotCaptureScaleFrom, snapshotViewportSizeFrom } from '@agent-device/kernel/rect'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; import { ANDROID_EMULATOR, @@ -17,6 +19,8 @@ import { mkdtempForTestSync, } from '@agent-device/test-kit'; import { makeSession } from '../__tests__/support/session-factories.ts'; +import { makeProviderRuntimeOwning } from '../__tests__/support/handlers/snapshot-handler.fixtures.ts'; +import { providerDeviceAdmissionFixture } from '../__tests__/support/provider-device-admission-fixture.ts'; import { contextFromFlags } from '../core/context.ts'; import type { GenericPlatformExecutionParams } from '../core/generic-leaf-execution.ts'; import { resolveScreenshotGenericExecution } from './screenshot-runtime.ts'; @@ -620,6 +624,114 @@ test('a partial crop surfaces its warning once in the result record and annotate expect(session.snapshot).toBeUndefined(); }); +const PROVIDER_TV: DeviceInfo = { + platform: 'android', + id: 'webos:192.0.2.20:9922', + name: 'living-room', + kind: 'device', + target: 'tv', + booted: true, +}; +providerDeviceAdmissionFixture([makeProviderRuntimeOwning(PROVIDER_TV, 'webos')]); + +const TV_PAGE_TREE: RawSnapshotNode[] = [ + { index: 0, depth: 0, type: 'main', label: 'Home', rect: { x: 0, y: 0, width: 60, height: 40 } }, + { + index: 1, + depth: 1, + parentIndex: 0, + type: 'button', + label: 'Save', + hittable: true, + rect: { x: 10, y: 10, width: 40, height: 20 }, + }, + { + index: 2, + depth: 1, + parentIndex: 0, + type: 'button', + label: 'Tile', + hittable: true, + rect: { x: 1200, y: 100, width: 300, height: 200 }, + }, +]; + +async function cropProviderTv(page: { + producer?: 'cdp-dom' | 'android-uiautomator'; + captureScale: number; + viewport: { width: number; height: number }; + cropOn?: string; +}) { + const { producer = 'cdp-dom', cropOn = 'label="Save"' } = page; + const captureScale = snapshotCaptureScaleFrom(page.captureScale); + const viewport = snapshotViewportSizeFrom({ x: 0, y: 0, ...page.viewport }); + const fixture = screenshotRuntimeFixture({ + onCapture: ({ outPath }) => writeSolidPng(outPath, 1920, 1080), + snapshotResult: () => ({ + nodes: TV_PAGE_TREE, + backend: 'android', + producer, + captureScale, + viewport, + }), + }); + const session = makeSession('tv', { device: PROVIDER_TV }); + const outPath = path.join(mkdtempForTestSync('provider-tv-crop'), 'tv.png'); + const req = screenshotRequest({ + positionals: [outPath], + flags: { screenshotCropOn: cropOn }, + }); + const resolved = await resolveScreenshotGenericExecution({ + hostCwd: process.cwd(), + createCommandSurface: testCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + req, + session, + inspectFacts: fixture.inspectFacts, + bindDevice: fixture.bindDevice, + }); + return await executeResult(resolved, session, req); +} + +const PAGE_720 = { width: 1280, height: 720 }; + +test('a provider TV crop cuts the CSS px frame 1:1 from a capture larger than the page', async () => { + const result = await cropProviderTv({ captureScale: 1, viewport: PAGE_720 }); + + expect(result).toMatchObject({ width: 40, height: 20 }); +}); + +test("a provider TV crop magnifies the CSS px frame by the page's capture scale", async () => { + const result = await cropProviderTv({ captureScale: 1.5, viewport: PAGE_720 }); + + expect(result).toMatchObject({ width: 60, height: 30 }); +}); + +test('a provider TV crop clips a node at the page edge to the page, not to the larger capture', async () => { + const result = await cropProviderTv({ + captureScale: 1, + viewport: PAGE_720, + cropOn: 'label="Tile"', + }); + + expect(result).toMatchObject({ width: 80, height: 200 }); + expect(result.warnings).toEqual([ + expect.stringMatching(new RegExp(`^${SCREENSHOT_CROP_REASONS.partialIntersection}:`)), + ]); +}); + +test('a provider TV crop is refused on a tree the TV plugins did not capture', async () => { + await expect( + cropProviderTv({ producer: 'android-uiautomator', captureScale: 1, viewport: PAGE_720 }), + ).rejects.toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { + reason: SCREENSHOT_CROP_REASONS.targetNotAccepted, + rejectionReason: SCREENSHOT_CROP_REASONS.pendingPixelIdentityEvidence, + }, + }); +}); + test('the crop plan is refused up front when the target cannot capture a tree', async () => { const fixture = screenshotRuntimeFixture({ snapshot: { available: false, reason: 'unsupported-platform-leaf' }, diff --git a/packages/kernel/src/rect.test.ts b/packages/kernel/src/rect.test.ts index 73e3837c29..3ddc4bd22e 100644 --- a/packages/kernel/src/rect.test.ts +++ b/packages/kernel/src/rect.test.ts @@ -9,6 +9,7 @@ import { isRectVisibleInViewport, pickLargestRect, readSnapshotViewportSize, + snapshotCaptureScaleFrom, snapshotViewportSizeFrom, unionRects, } from './rect.ts'; @@ -67,6 +68,13 @@ test('the sentinel would survive any check that only looks at components and ext // #3182: the viewport a response publishes has exactly one construction path and exactly one wire // re-read, and both answer a box they cannot accept with absence. A zero the producer answered with // has to become "unknown", never a claim that the screen has no width. +test('snapshotCaptureScaleFrom publishes only a positive finite scale', () => { + assert.equal(snapshotCaptureScaleFrom(1.5), 1.5); + for (const value of [undefined, null, 0, -1, Number.NaN, Number.POSITIVE_INFINITY]) { + assert.equal(snapshotCaptureScaleFrom(value), undefined, String(value)); + } +}); + test('snapshotViewportSizeFrom publishes only a box the rect guard accepts (#3182)', () => { assert.deepEqual(snapshotViewportSizeFrom({ x: 12, y: -40, width: 390, height: 844 }), { width: 390, diff --git a/packages/kernel/src/rect.ts b/packages/kernel/src/rect.ts index b1b82f9ed8..65208df750 100644 --- a/packages/kernel/src/rect.ts +++ b/packages/kernel/src/rect.ts @@ -1,4 +1,4 @@ -import type { Rect, SnapshotViewportSize } from './snapshot.ts'; +import type { Rect, SnapshotCaptureScale, SnapshotViewportSize } from './snapshot.ts'; /** * CoreGraphics' `CGRectInfinite`, spelled in the four doubles Apple builds it from. This is what a @@ -63,6 +63,18 @@ export function snapshotViewportSizeFrom(box: Rect | undefined): SnapshotViewpor return { width: box.width, height: box.height } as SnapshotViewportSize; } +/** + * The ONE construction path for the capture scale a snapshot publishes: a positive finite reading + * becomes the scale, and anything else is the absence that means unknown, never a zero or infinite + * magnification. + */ +export function snapshotCaptureScaleFrom( + value: number | null | undefined, +): SnapshotCaptureScale | undefined { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined; + return value as SnapshotCaptureScale; +} + /** * Re-read of a viewport this repo already published, out of an untyped wire payload: only a * `{ width, height }` pair the guard accepts survives, and anything else is the absence that means diff --git a/packages/kernel/src/snapshot.ts b/packages/kernel/src/snapshot.ts index e8dc06b0c0..8df8fc5d27 100644 --- a/packages/kernel/src/snapshot.ts +++ b/packages/kernel/src/snapshot.ts @@ -426,7 +426,9 @@ export type PresentedSurface = 'presented' | 'absent' | 'unknown'; * It is the box of the surface the producer read, which is not always the physical panel. iOS * reports the app window in the app's orientation space (ADR 0004), which is smaller than the panel * under iPad Split View and is never the foldable panel `fold` reports (ADR 0025); Android and the - * Apple TV runner report the screen the bounds were measured on. A producer that has no box of its + * Apple TV runner report the screen the bounds were measured on. The Tizen and webOS TV plugins + * report the page's layout viewport in CSS px, which is not the screenshot size: a webOS app at + * 1280x720 fills only the top-left 1280x720 of a 1920x1080 capture. A producer that has no box of its * own to answer with leaves the field off: the macOS desktop, whose rects are absolute in window * space and answer to no single frame, and the web and Linux backends, which read a tree without * reading a screen. A consumer that needs a *gesture* band inside those bounds still reads `keyboard` @@ -450,6 +452,21 @@ export type SnapshotViewportSizeBrand = { readonly [SNAPSHOT_VIEWPORT_SIZE_BRAND]: 'validated'; }; +/** + * Screenshot pixels per rect unit, published by a producer whose own screenshots magnify its rects: + * a TV app page's `visualViewport.scale`, which a meta viewport sets and which the page's + * `devicePixelRatio` does not predict. Positive and finite by construction: + * `snapshotCaptureScaleFrom` from `@agent-device/kernel/rect` is the sole construction path, and the + * brand keeps a plain number from standing in for one. + */ +export type SnapshotCaptureScale = number & SnapshotCaptureScaleBrand; + +/** @internal Exported only so `kernel/rect` can mint values of {@link SnapshotCaptureScale}. */ +export declare const SNAPSHOT_CAPTURE_SCALE_BRAND: unique symbol; +export type SnapshotCaptureScaleBrand = { + readonly [SNAPSHOT_CAPTURE_SCALE_BRAND]: 'validated'; +}; + export type SnapshotNode = RawSnapshotNode & { /** * The ref an agent addresses this node by, or absent when nothing can address it. diff --git a/packages/provider-tizen/README.md b/packages/provider-tizen/README.md index 8b6ccfdbb3..b6efd1a93a 100644 --- a/packages/provider-tizen/README.md +++ b/packages/provider-tizen/README.md @@ -7,7 +7,8 @@ DevTools Protocol: remote keys, pointer, text, snapshots, screenshots and consol Status: experimental. Verified on a Samsung Smart Monitor M7 (Tizen 9.0): `connect`, `open`, `open --relaunch`, `snapshot -i`, `tv-remote` (directions, select, back and the media buttons), `back`, `is focused`, `press`, `find ... click`, `hover`, `longpress`, `fill`, `type`, `wait`, -`scroll`, `screenshot`, `logs`, `apps`, `appstate`, `close`, `disconnect`. +`scroll`, `screenshot`, `screenshot --crop-on`, `logs`, `apps`, `appstate`, `close`, +`disconnect`. ## How it plugs in @@ -82,7 +83,7 @@ The TV is a leased device, so every command from `connect` to `disconnect` names | `apps` | `sdb shell 0 vd_applist`: user-installed apps with their titles | | `logs` | console calls, exceptions and browser log entries of the attached page, one line each | | `snapshot`, `find`, `is`, `get`, `wait` | DOM walk over `Runtime.evaluate`: visible interactive, labelled or text nodes, focus from `document.activeElement`; `-s`, `-d` and `-i` apply to the walk | -| `screenshot` | `Page.captureScreenshot` | +| `screenshot` | `Page.captureScreenshot`; `--crop-on ` crops it to the frame of the node the selector resolves in a snapshot taken on the same screen | | `click`, `press `, `longpress`, `hover` | `Input.dispatchMouseEvent` | | `fill` | pointer press on the field, select its contents, then `Input.insertText`, or Backspace for an empty value | | `type` | `Input.insertText` into the focused element | @@ -115,9 +116,11 @@ Not yet: system buttons (`home`, menu, volume and channel), `network dump`, `per in them show as `Object`. Messages logged after the attach show their properties. - **A second DevTools client on the same page can hang the session.** Close Chrome DevTools and other inspector clients attached to the app before a session. -- **Snapshots are DOM-derived.** Labels come from `aria-label`, `alt`, `title` or own text; - rects are CSS px, which match screenshot pixels only at `devicePixelRatio` 1 (1080p apps). - The walk does not enter iframes or shadow roots. `is text` on an input compares its label, not - its value; the value is in `snapshot --raw`. +- **Snapshots are DOM-derived.** Labels come from `aria-label`, `alt`, `title` or own text; rects + are CSS px. The screenshot magnifies them by the page's `visualViewport.scale`: a `width=1280` + meta viewport on a 1920x1080 TV gives 1.5. `screenshot --crop-on` applies that scale, and refuses + a page whose browser has no `visualViewport` or whose visual viewport is panned. The walk does not + enter iframes or shadow roots. `is text` on an input compares its label, not its value; the value + is in `snapshot --raw`. - **System overlays are outside the page.** The Samsung menu, on-screen keyboard and other system layers never appear in `screenshot` or `snapshot`. diff --git a/packages/provider-webos/README.md b/packages/provider-webos/README.md index 6774d901de..c088ac60c3 100644 --- a/packages/provider-webos/README.md +++ b/packages/provider-webos/README.md @@ -6,8 +6,8 @@ DevTools Protocol: remote keys, pointer, text, snapshots, screenshots and consol Status: experimental. Verified on an LG 32LQ63006LA (webOS TV 22): `connect`, `open`, `snapshot -i`, `snapshot -s`, `tv-remote` (directions, select, back and the media buttons), -`is focused`, `press @ref --settle`, `wait text`, `find`, `screenshot`, `logs`, `apps`, -`appstate`, `close`, `disconnect`. +`is focused`, `press @ref --settle`, `wait text`, `find`, `screenshot`, `screenshot --crop-on`, +`logs`, `apps`, `appstate`, `close`, `disconnect`. ## How it plugs in @@ -77,7 +77,7 @@ The TV is a leased device, so every command from `connect` to `disconnect` names | `apps` | `ares-install --listfull` | | `logs` | console calls, exceptions and browser log entries of the attached page, one line each | | `snapshot`, `find`, `is`, `get`, `wait` | DOM walk over `Runtime.evaluate`: visible interactive, labelled or text nodes, focus from `document.activeElement`; `-s`, `-d` and `-i` apply to the walk. A control whose centre hit-tests to another element is marked `[covered]` | -| `screenshot` | `Page.captureScreenshot` | +| `screenshot` | `Page.captureScreenshot`; `--crop-on ` crops it to the frame of the node the selector resolves in a snapshot taken on the same screen | | `click`, `press `, `longpress`, `hover` | `Input.dispatchMouseEvent` (Magic Remote pointer), ending each move with a small wiggle that wakes the cursor | | `fill` | pointer press on the field, select its contents, then `Input.insertText`, or Backspace for an empty value | | `type` | `Input.insertText` into the focused element | @@ -111,10 +111,14 @@ in `open`, `power`. webOS has separate Play and Pause key codes and no play-paus rather than an error. `open --relaunch` closes the app first, for a cold start. - **A second DevTools client on the same page hung in testing.** Close Chrome DevTools and other inspector clients attached to the app before a session. -- **Snapshots are DOM-derived.** Labels come from `aria-label`, `alt`, `title` or own text; - rects are CSS px, which match screenshot pixels only at `devicePixelRatio` 1 (1080p apps). - The walk does not enter iframes or shadow roots, so overlays rendered there (for example a - dev-server error overlay) appear in screenshots but not in snapshots. +- **Snapshots are DOM-derived.** Labels come from `aria-label`, `alt`, `title` or own text; rects + are CSS px, and the screenshot holds the page at CSS px whatever its `devicePixelRatio`: on a + 1920x1080 TV, an app at `"resolution": "1280x720"` reports 1.5 yet fills only the top-left + 1280x720 of the capture. `screenshot --crop-on` scales rects by the page's `visualViewport.scale`, + which is 1 because webOS ignores the meta viewport, and clips the crop to the page. It refuses a + page whose browser has no `visualViewport` or whose visual viewport is panned. The walk does not + enter iframes or shadow roots, so overlays rendered there (for example a dev-server error overlay) + appear in screenshots but not in snapshots. - **`click`, `press`, `fill` and `focus` refuse a control marked `[covered]`.** A tap at its centre would land on the element on top, such as a card's own pressable area. `snapshot -i` still lists it, and `tv-remote` reaches it through focus. diff --git a/packages/tv-cdp/src/page-interactor.ts b/packages/tv-cdp/src/page-interactor.ts index 34b9320e85..35fd99fc99 100644 --- a/packages/tv-cdp/src/page-interactor.ts +++ b/packages/tv-cdp/src/page-interactor.ts @@ -12,6 +12,7 @@ import type { ScrollDirection } from '@agent-device/contracts/scroll-gesture'; import type { TvRemoteButton } from '@agent-device/contracts/tv-remote'; import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry'; import { AppError } from '@agent-device/kernel/errors'; +import { snapshotCaptureScaleFrom, snapshotViewportSizeFrom } from '@agent-device/kernel/rect'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; import { connectCdp, listTargets, withTunnelRemoval } from './cdp.ts'; @@ -329,6 +330,8 @@ export function createPageInteractor( }, async snapshot(options = {}) { const capture = await page().evaluate(SNAPSHOT_EXPRESSION); + const captureScale = snapshotCaptureScaleFrom(capture.pageScale); + const viewport = snapshotViewportSizeFrom({ x: 0, y: 0, ...capture.viewport }); return shapeDesktopSurfaceSnapshot( stampSnapshotIdentity( { @@ -339,6 +342,10 @@ export function createPageInteractor( truncated: capture.truncated, appName: capture.title, appBundleId: session.appId, + // Page.captureScreenshot magnifies CSS px by the page scale and not by + // devicePixelRatio: webOS reports 1.5 for a 1280x720 app yet captures it unscaled. + ...(captureScale ? { captureScale } : {}), + ...(viewport ? { viewport } : {}), }, { backend: 'android', producer: 'cdp-dom' }, ), diff --git a/packages/tv-cdp/src/runtime.test.ts b/packages/tv-cdp/src/runtime.test.ts index d971172926..a14edde74d 100644 --- a/packages/tv-cdp/src/runtime.test.ts +++ b/packages/tv-cdp/src/runtime.test.ts @@ -26,6 +26,8 @@ const FRAME = Buffer.from('png frame'); const CAPTURE: SnapshotCapture = { title: 'Example', truncated: false, + viewport: VIEWPORT, + pageScale: 1, // The DOM walk gives every node it keeps a rect. nodes: [ { index: 0, depth: 0, type: 'main', label: 'Home' }, @@ -103,6 +105,7 @@ async function fakePage() { let running = true; let loaded = true; let visibility = 'visible'; + let pageScale: number | null = 1; let readinessChecks = 0; const evaluated = (expression: string) => { if (expression.includes('readyState')) { @@ -111,7 +114,7 @@ async function fakePage() { } if (expression === '({ width: innerWidth, height: innerHeight })') return VIEWPORT; if (expression === 'document.visibilityState') return visibility; - return CAPTURE; + return { ...CAPTURE, pageScale }; }; const answer = (method: string, params: Record) => { if (method === 'Page.captureScreenshot') return { data: FRAME.toString('base64') }; @@ -161,6 +164,9 @@ async function fakePage() { hide: () => { visibility = 'hidden'; }, + zoom: (scale: number | null) => { + pageScale = scale; + }, readinessChecks: () => readinessChecks, close: async () => { page.drop(); @@ -462,8 +468,10 @@ test('filling an empty value selects the field contents and deletes them with Ba assert.deepEqual(steps, ['select', 'keyDown Backspace', 'keyUp Backspace']); }); -async function capturedNodes(options: Readonly<{ scope?: string; interactiveOnly?: boolean }>) { - const { runtime, device } = await openedTv(); +async function captureThroughBinding( + { runtime, device }: Awaited>, + options: Readonly<{ scope?: string; interactiveOnly?: boolean }> = {}, +) { const operations = bindProviderSnapshotInteractor({ device, signal: new AbortController().signal, @@ -471,7 +479,11 @@ async function capturedNodes(options: Readonly<{ scope?: string; interactiveOnly }); const result = await operations.captureSnapshot({ options }); assert.ok('nodes' in result); - return result.nodes ?? []; + return result; +} + +async function capturedNodes(options: Readonly<{ scope?: string; interactiveOnly?: boolean }>) { + return (await captureThroughBinding(await openedTv(), options)).nodes ?? []; } async function capturedLabels(options: Readonly<{ scope?: string; interactiveOnly?: boolean }>) { @@ -482,6 +494,27 @@ test('a scoped capture through the provider snapshot binding returns only that s assert.deepEqual(await capturedLabels({ scope: 'Settings' }), ['Settings', 'Sound']); }); +test('a capture publishes the page scale its screenshots magnify rects by, and its viewport', async () => { + const opened = await openedTv(); + opened.page.zoom(1.5); + + const result = await captureThroughBinding(opened); + + assert.deepEqual( + { captureScale: result.captureScale, viewport: result.viewport }, + { captureScale: 1.5, viewport: VIEWPORT }, + ); +}); + +test('a capture from a page without visualViewport publishes no capture scale', async () => { + const opened = await openedTv(); + opened.page.zoom(null); + + const result = await captureThroughBinding(opened); + + assert.equal('captureScale' in result, false); +}); + test('an interactive-only capture drops text-only nodes and keeps the ancestors of controls', async () => { assert.deepEqual(await capturedLabels({ interactiveOnly: true }), [ 'Home', diff --git a/packages/tv-cdp/src/snapshot.test.ts b/packages/tv-cdp/src/snapshot.test.ts new file mode 100644 index 0000000000..548f8aa8c5 --- /dev/null +++ b/packages/tv-cdp/src/snapshot.test.ts @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import { runInNewContext } from 'node:vm'; +import { test } from 'vitest'; + +import { SNAPSHOT_EXPRESSION, type SnapshotCapture } from './snapshot.ts'; + +function evaluateOnPage(visualViewport: Record | undefined) { + const page = { + window: { visualViewport }, + document: { activeElement: null, body: null, title: 'Example' }, + innerWidth: 1280, + innerHeight: 720, + }; + return runInNewContext(SNAPSHOT_EXPRESSION, page) as SnapshotCapture; +} + +test('the page reports its layout viewport and its visual viewport scale', () => { + const capture = evaluateOnPage({ scale: 1.5, offsetLeft: 0, offsetTop: 0 }); + + assert.deepEqual( + { viewport: { ...capture.viewport }, pageScale: capture.pageScale }, + { viewport: { width: 1280, height: 720 }, pageScale: 1.5 }, + ); +}); + +test('a panned visual viewport reports no page scale', () => { + assert.equal(evaluateOnPage({ scale: 2, offsetLeft: 40, offsetTop: 0 }).pageScale, null); + assert.equal(evaluateOnPage({ scale: 2, offsetLeft: 0, offsetTop: 30 }).pageScale, null); +}); + +test('a browser without visualViewport reports no page scale', () => { + assert.equal(evaluateOnPage(undefined).pageScale, null); +}); diff --git a/packages/tv-cdp/src/snapshot.ts b/packages/tv-cdp/src/snapshot.ts index 93bd5ff8ba..4040f0e136 100644 --- a/packages/tv-cdp/src/snapshot.ts +++ b/packages/tv-cdp/src/snapshot.ts @@ -119,7 +119,16 @@ export const SNAPSHOT_EXPRESSION = `(function () { } if (document.body) walk(document.body, -1, 0, { left: 0, top: 0, right: innerWidth, bottom: innerHeight }, false); - return { nodes: nodes, covers: covers, truncated: truncated, title: document.title }; + var visual = window.visualViewport; + var pageScale = visual && visual.offsetLeft === 0 && visual.offsetTop === 0 ? visual.scale : null; + return { + nodes: nodes, + covers: covers, + truncated: truncated, + title: document.title, + viewport: { width: innerWidth, height: innerHeight }, + pageScale: pageScale + }; })()`; export type SnapshotCapture = Readonly<{ @@ -128,4 +137,11 @@ export type SnapshotCapture = Readonly<{ covers: Readonly>; truncated: boolean; title: string; + /** The layout viewport, the box the rects are measured in. */ + viewport: Readonly<{ width: number; height: number }>; + /** + * `visualViewport.scale`, or null where the page's Chromium predates the API or the visual + * viewport is panned away from the layout viewport's origin. + */ + pageScale: number | null; }>; diff --git a/src/commands/schema/cli-help-command-usage.test.ts b/src/commands/schema/cli-help-command-usage.test.ts index 127637a415..6ff5f833fd 100644 --- a/src/commands/schema/cli-help-command-usage.test.ts +++ b/src/commands/schema/cli-help-command-usage.test.ts @@ -32,7 +32,7 @@ test('usageForCommand documents screenshot web aliases and stabilization flags', assert.match(help, /crop the capture to the frame of the selector/); assert.match( help, - /currently iOS simulators, Android emulators, and CoreDevice physical iPhones/, + /currently iOS simulators, Android emulators, CoreDevice physical iPhones, and Samsung Tizen and LG webOS TV apps/, ); }); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 56f200bae9..93fcf749fe 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1084,7 +1084,7 @@ agent-device record stop # Stop active recording - `--scale ` resizes both dimensions, from `0.01` to `1` (full resolution). Set `AGENT_DEVICE_SCREENSHOT_SCALE=0.3` or `screenshotScale` in config as a token-conscious default; an explicit `--scale` overrides it. Leave it unset or pass `--scale 1` for pixel-diff baselines. `--max-size` is refused everywhere (CLI, `.ad` scripts, Node options, config, `AGENT_DEVICE_SCREENSHOT_MAX_SIZE`) with guidance to use `--scale`. - ADB-backed Android screenshots capture immediately by default. Use `--normalize-status-bar` to set deterministic status-bar chrome and wait for transient UI to fade. In the Node client, `stabilize: true` also enables this wait. - `--overlay-refs` takes a fresh snapshot and burns visible `@eN` refs and their rectangles into the PNG. With `--scale`, refs are drawn at the final size, so avoid scales where labels become unreadable. In `--json` mode each ref also has a screenshot-space `center` for `press ` fallback. -- `--crop-on ` crops the capture to the frame the selector resolves on the same screen. It works only on iOS simulators, Android emulators, and physical iPhones. A physical iPhone crop is verified only in portrait using CoreDevice/devicectl; the XCTest backend and runner fallback are not accepted. Physical iPads remain rejected for crop, and landscape iPhone crop remains unverified. It needs exactly one framed node, cannot be combined with `--overlay-refs` or `--fullscreen`, and warns when the frame is clipped. The crop is re-encoded, so do not byte-compare it with an older crop. +- `--crop-on ` crops the capture to the frame the selector resolves on the same screen. It works only on iOS simulators, Android emulators, physical iPhones, and the Samsung Tizen and LG webOS TV plugins. A physical iPhone crop is verified only in portrait using CoreDevice/devicectl; the XCTest backend and runner fallback are not accepted. Physical iPads remain rejected for crop, and landscape iPhone crop remains unverified. It needs exactly one framed node, cannot be combined with `--overlay-refs` or `--fullscreen`, and warns when the frame is clipped. The crop is re-encoded, so do not byte-compare it with an older crop. - `--fullscreen` on macOS applies only to app sessions. Other surfaces (`desktop`, `menubar`, `frontmost-app`) always capture the main display and refuse `--fullscreen` with `INVALID_ARGS`. - `--capture-backend runner` captures an Apple target through the XCTest runner (`XCUIScreen`), as XCTest-based tools such as Maestro do, instead of `simctl io screenshot`. On iOS simulators with a Dynamic Island, `simctl` draws the island into every capture and no `--mask` policy removes it; the runner capture leaves it out. The capture skips the simctl pipeline, so `--pixel-density` and `--normalize-status-bar` are refused with it (`INVALID_ARGS`). Each capture owner declares the backends it serves: other platforms, provider-backed sessions, and macOS surfaces the helper captures (`desktop`, `menubar`, `frontmost-app`, and app sessions with the native app backend) refuse it with `UNSUPPORTED_OPERATION`. Node and MCP take `captureBackend: 'runner'`. - `--normalize-status-bar` temporarily normalizes iOS simulator status-bar chrome for reusable baselines. Each status-bar read or preparation command has a 10-second timeout. Each restore command has a 30-second timeout, so clearing and reapplying overrides can take up to 60 seconds. The request timeout includes the wait and can expire before these steps finish. diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index 2d9b37df26..aa6c83a8da 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -211,6 +211,8 @@ snapshot was taken on instead of guessing it from the largest rect. - iOS reports the app window, so iPad Split View and a foldable panel do not inflate it. - Android and Apple TV report the measured screen. Android reports it under `--raw` too, since the raw rects are measured on the same screen. +- The Tizen and webOS TV plugins report the page's layout viewport in CSS pixels, which is not the + screenshot size: a webOS app at 1280x720 fills only the top-left 1280x720 of a 1920x1080 capture. - It is absent when the capture measured no box: a macOS capture, whose rects are absolute in window space; a web or Linux capture, which reads a tree without reading a screen; and `--raw` on an Apple target. diff --git a/website/docs/docs/tizen.md b/website/docs/docs/tizen.md index aa74cbcac2..96b2f4b497 100644 --- a/website/docs/docs/tizen.md +++ b/website/docs/docs/tizen.md @@ -76,7 +76,7 @@ Every command on that device goes to the plugin, never to adb. | `apps` | `sdb shell 0 vd_applist` | | `logs` | Console calls, exceptions, and browser log entries of the attached page, one line each | | `snapshot`, `find`, `is`, `get`, `wait` | A DOM walk over `Runtime.evaluate`: visible interactive, labelled, or text nodes, with focus from `document.activeElement`. `-s`, `-d`, and `-i` apply to the walk. | -| `screenshot` | `Page.captureScreenshot` | +| `screenshot` | `Page.captureScreenshot`. `--crop-on ` crops the capture to the frame of the node that the selector resolves in a snapshot taken on the same screen. | | `click`, `press `, `longpress`, `hover` | `Input.dispatchMouseEvent` | | `fill` | Pointer press on the field, select its contents, then `Input.insertText`, or Backspace for an empty value | | `type` | `Input.insertText` into the focused element | @@ -105,6 +105,8 @@ Not supported yet: system buttons (`home`, menu, volume, and channel), `network - Console messages logged before the attach are replayed without object previews. - A second DevTools client on the same page can hang the session. Close Chrome DevTools and other inspector clients attached to the app first. -- Snapshots are read from the DOM. Labels come from `aria-label`, `alt`, `title`, or own text. - Rects are CSS pixels, which match screenshot pixels only at `devicePixelRatio` 1. The walk does - not enter iframes or shadow roots. +- Snapshots are read from the DOM. Labels come from `aria-label`, `alt`, `title`, or own text. Rects + are CSS pixels. The screenshot magnifies them by the page's `visualViewport.scale`: a `width=1280` + meta viewport on a 1920x1080 TV gives 1.5. `screenshot --crop-on` applies that scale, and refuses + a page whose browser has no `visualViewport` or whose visual viewport is panned. The walk does not + enter iframes or shadow roots. diff --git a/website/docs/docs/webos.md b/website/docs/docs/webos.md index 406052d8a7..5284433ff8 100644 --- a/website/docs/docs/webos.md +++ b/website/docs/docs/webos.md @@ -76,7 +76,7 @@ plugin, never to adb. | `apps` | `ares-install --listfull` | | `logs` | Console calls, exceptions, and browser log entries of the attached page, one line each | | `snapshot`, `find`, `is`, `get`, `wait` | A DOM walk over `Runtime.evaluate`: visible interactive, labelled, or text nodes, with focus from `document.activeElement`. `-s`, `-d`, and `-i` apply to the walk. A control whose centre hit-tests to another element is marked `[covered]`. | -| `screenshot` | `Page.captureScreenshot` | +| `screenshot` | `Page.captureScreenshot`. `--crop-on ` crops the capture to the frame of the node that the selector resolves in a snapshot taken on the same screen. | | `click`, `press `, `longpress`, `hover` | `Input.dispatchMouseEvent`, the Magic Remote pointer | | `fill` | Pointer press on the field, select its contents, then `Input.insertText`, or Backspace for an empty value | | `type` | `Input.insertText` into the focused element | @@ -104,9 +104,13 @@ play-pause toggle, so `media-play-pause` is refused; use `media-play` or `media- closes the app first for a cold start. - A second DevTools client on the same page can hang the session. Close Chrome DevTools and other inspector clients attached to the app first. -- Snapshots are read from the DOM. Labels come from `aria-label`, `alt`, `title`, or own text. - Rects are CSS pixels, which match screenshot pixels only at `devicePixelRatio` 1. The walk does - not enter iframes or shadow roots. +- Snapshots are read from the DOM. Labels come from `aria-label`, `alt`, `title`, or own text. Rects + are CSS pixels, and the screenshot holds the page at CSS pixels whatever its `devicePixelRatio`: + on a 1920x1080 TV, an app at `"resolution": "1280x720"` reports 1.5 yet fills only the top-left + 1280x720 of the capture. `screenshot --crop-on` scales rects by the page's `visualViewport.scale`, + which is 1 because webOS ignores the meta viewport, and clips the crop to the page. It refuses a + page whose browser has no `visualViewport` or whose visual viewport is panned. The walk does not + enter iframes or shadow roots. - `click`, `press`, `fill`, and `focus` refuse a control marked `[covered]`, because a tap at its centre would land on the element on top, such as a card's own pressable area. `snapshot -i` still lists it, and `tv-remote` reaches it through focus.