diff --git a/packages/provider-revyl/src/facts-runtime.test.ts b/packages/provider-revyl/src/facts-runtime.test.ts index 4015b33bc9..f3da32cd3a 100644 --- a/packages/provider-revyl/src/facts-runtime.test.ts +++ b/packages/provider-revyl/src/facts-runtime.test.ts @@ -18,7 +18,7 @@ type RevylOperation = keyof ReturnType['operations']; /** * Every operation cell Revyl's facts report, with the verdict each one has to carry. `available` is - * a cell the facts admit; `mode` is a cell refused because the worker has no action for it; `kind` is + * a cell the facts admit; `subjects` is a cell admitted for the subjects it lists; `mode` is a cell refused because the worker has no action for it; `kind` is * a cell refused because the rented device is the wrong shape for the command at all. * * The map is typed over the whole catalog, so a cell added to or dropped from `revylFacts` is a @@ -40,6 +40,8 @@ const EXPECTED_CELLS = { prepareApplicationOpen: 'available', resolveOpenTarget: 'available', scrollDirection: 'available', + setOrientation: 'available', + setSetting: 'subjects', tapPoint: 'available', acceptAlert: 'mode', @@ -106,8 +108,6 @@ const EXPECTED_CELLS = { sendPushNotification: 'mode', sendTelephonyEvent: 'mode', setFoldPose: 'mode', - setOrientation: 'mode', - setSetting: 'mode', setViewport: 'mode', shutdownTarget: 'mode', sleep: 'mode', @@ -123,7 +123,7 @@ const EXPECTED_CELLS = { volumeUp: 'mode', wake: 'mode', writeClipboard: 'mode', -} as const satisfies Readonly>; +} as const satisfies Readonly>; /** The typed reason one verdict of the matrix carries. */ const REFUSAL_REASONS = { mode: 'unsupported-provider-mode', kind: 'unsupported-device-kind' }; @@ -138,13 +138,18 @@ test('every operation cell reports the verdict its matrix row promises', () => { ); for (const [cell, expected] of Object.entries(EXPECTED_CELLS) as [ RevylOperation, - 'available' | 'mode' | 'kind', + 'available' | 'subjects' | 'mode' | 'kind', ][]) { const fact = operations[cell]; if (expected === 'available') { assert.deepEqual(fact, { available: true }, cell); continue; } + if (expected === 'subjects') { + assert.equal(fact.available, true, cell); + assert.ok(fact.available && fact.subjects !== undefined, cell); + continue; + } assert.equal(fact.available, false, cell); assert.equal(fact.reason, REFUSAL_REASONS[expected], cell); } @@ -174,6 +179,29 @@ test('back is an Android button; iOS refuses it with the substitute', () => { assert.match(ios.available ? '' : (ios.hint ?? ''), /only on Android/); }); +test('settings admit what the worker has actions for, and the keychain only on iOS', () => { + const android: DeviceInfo = { + ...IOS_DEVICE, + platform: 'android', + appleOs: undefined, + id: 'revyl:android:lease-1', + kind: 'emulator', + }; + const subjects = (device: DeviceInfo) => { + const fact = revylFacts(device).operations.setSetting; + assert.ok(fact.available && fact.subjects !== undefined); + return Object.fromEntries( + Object.entries(fact.subjects).map(([name, subject]) => [name, subject.available]), + ); + }; + const served = { appearance: true, location: true, permission: true, 'clear-app-state': true }; + assert.deepEqual(subjects(IOS_DEVICE), { ...served, 'reset-keychain': true }); + assert.deepEqual(subjects(android), { ...served, 'reset-keychain': false }); + const setSetting = revylFacts(android).operations.setSetting; + assert.ok(setSetting.available); + assert.equal(setSetting.unlisted?.reason, 'unsupported-provider-mode'); +}); + test('the facts report the canonical device shape beside the provider mode', () => { assert.deepEqual(revylFacts(IOS_DEVICE).device, { family: 'apple', diff --git a/packages/provider-revyl/src/facts-runtime.ts b/packages/provider-revyl/src/facts-runtime.ts index f494cf6d01..b40d8b174d 100644 --- a/packages/provider-revyl/src/facts-runtime.ts +++ b/packages/provider-revyl/src/facts-runtime.ts @@ -15,6 +15,7 @@ import { liveSessionUnavailable, revylInteractionOperationFacts, revylNavigationOperationFacts, + revylSettingsOperationFacts, revylUnsupportedOperationFacts, REVYL_FOLD_UNAVAILABLE, REVYL_PUSH_UNAVAILABLE, @@ -176,6 +177,7 @@ export function revylFacts(device: DeviceInfo): RuntimeFacts) { + return settingsRuntimeOperationFacts({ + target: available, + unsupported: settingUnavailable, + write: { + appearance: available, + location: available, + permission: available, + 'clear-app-state': available, + 'reset-keychain': device.platform === 'apple' ? available : keychainUnavailable, + }, + }); +} + /** * Binds the operations that reach the device through the session's interactor: the two captures, * focus, touch and scroll. Refused cells stay absent from the binding, so a refusal is the facts' diff --git a/packages/provider-revyl/src/interactor-settings.test.ts b/packages/provider-revyl/src/interactor-settings.test.ts new file mode 100644 index 0000000000..35f8908003 --- /dev/null +++ b/packages/provider-revyl/src/interactor-settings.test.ts @@ -0,0 +1,156 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; +import type { Interactor } from '@agent-device/contracts/interactor-types'; +import { + revylLease, + startRevylFixtureBackend, + type RevylFixtureBackend, +} from './revyl-backend.fixtures.ts'; + +const openBackends: RevylFixtureBackend[] = []; + +afterEach(async () => { + await Promise.all(openBackends.splice(0).map((fixture) => fixture.close())); +}); + +/** The interactor of one live session against a fake Revyl backend, with that backend. */ +async function liveInteractor( + platform: 'ios' | 'android', + options?: Parameters[0], +): Promise> { + const fixture = await startRevylFixtureBackend(options); + openBackends.push(fixture); + const runtime = fixture.createRuntime(); + await runtime.leaseLifecycle?.allocate?.(revylLease(platform)); + const device = ( + await runtime.deviceInventoryProvider?.({ + leaseProvider: 'revyl', + leaseId: 'lease-1', + platform, + }) + )?.[0]; + if (!device) throw new Error('Expected the live session to be listed.'); + const interactor = runtime.getInteractor(device); + if (!interactor) throw new Error('Expected a live session interactor.'); + return { fixture, interactor }; +} + +const refusedForMode = (error: unknown) => + error instanceof AppError && error.details?.reason === 'unsupported-provider-mode'; + +test('orientation sends the worker name of each rotation on a worker that rotates precisely', async () => { + const { fixture, interactor } = await liveInteractor('android', { preciseOrientation: true }); + assert.deepEqual(await interactor.setOrientation('landscape-left'), { + orientation: 'landscape-left', + }); + await interactor.setOrientation('portrait-upside-down'); + + assert.deepEqual( + fixture.requests + .filter((request) => request.path.endsWith('/set_orientation')) + .map((request) => request.body), + [{ orientation: 'landscape_left' }, { orientation: 'upside_down' }], + ); +}); + +test('a worker without precise orientation rotates to portrait and landscape-left only', async () => { + const { fixture, interactor } = await liveInteractor('ios'); + await interactor.setOrientation('portrait'); + await interactor.setOrientation('landscape-left'); + for (const orientation of ['landscape-right', 'portrait-upside-down'] as const) { + await assert.rejects(interactor.setOrientation(orientation), refusedForMode); + } + assert.deepEqual( + fixture.requests + .filter((request) => request.path.endsWith('/set_orientation')) + .map((request) => request.body), + [{ orientation: 'portrait' }, { orientation: 'landscape' }], + ); +}); + +test('appearance sets the named mode, and toggle flips the mode the worker reports', async () => { + const { fixture, interactor } = await liveInteractor('ios', { + respond: { + 'GET /api/v1/execution/device-proxy/run-1/appearance': { body: { appearance: 'dark' } }, + }, + }); + assert.deepEqual(await interactor.setSetting('appearance', 'dark'), { appearance: 'dark' }); + assert.deepEqual(await interactor.setSetting('appearance', 'toggle'), { appearance: 'light' }); + + assert.deepEqual( + fixture.requests + .filter((request) => request.path.endsWith('/set_appearance')) + .map((request) => request.body), + [{ appearance: 'dark' }, { appearance: 'light' }], + ); +}); + +test('location sets the coordinates and refuses switching location services', async () => { + const { fixture, interactor } = await liveInteractor('android'); + await interactor.setSetting('location', 'set', undefined, { latitude: 43.65, longitude: -79.38 }); + await assert.rejects(interactor.setSetting('location', 'off'), refusedForMode); + + assert.deepEqual(fixture.bodyFor('set_location'), { latitude: 43.65, longitude: -79.38 }); + assert.equal(fixture.paths().filter((request) => request.endsWith('/set_location')).length, 1); +}); + +test('a permission change names the app and the Maestro permission the worker takes', async () => { + const { fixture, interactor } = await liveInteractor('android'); + await interactor.setSetting('permission', 'grant', 'com.example.app', { + permissionTarget: 'media-library', + }); + await interactor.setSetting('permission', 'reset', 'com.example.app', { + permissionTarget: 'camera', + }); + + assert.deepEqual( + fixture.requests + .filter((request) => request.path.endsWith('/set_permissions')) + .map((request) => request.body), + [ + { bundle_id: 'com.example.app', permissions: { medialibrary: 'allow' } }, + { bundle_id: 'com.example.app', permissions: { camera: 'unset' } }, + ], + ); +}); + +test('a permission without a Maestro name, or with a mode, is refused before the worker', async () => { + const { fixture, interactor } = await liveInteractor('ios'); + for (const options of [ + { permissionTarget: 'location-always' }, + { permissionTarget: 'photos', permissionMode: 'limited' }, + ]) { + await assert.rejects( + interactor.setSetting('permission', 'grant', 'com.example.app', options), + refusedForMode, + ); + } + assert.equal( + fixture.paths().some((request) => request.endsWith('/set_permissions')), + false, + ); +}); + +test('an app setting falls back to the launched app and refuses when none is known', async () => { + const { fixture, interactor } = await liveInteractor('ios'); + await assert.rejects( + interactor.setSetting('clear-app-state', 'clear'), + (error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS', + ); + await interactor.open('com.example.app'); + await interactor.setSetting('clear-app-state', 'clear'); + await interactor.setSetting('reset-keychain', 'clear'); + + assert.deepEqual(fixture.bodyFor('clear_app_state'), { bundle_id: 'com.example.app' }); + assert.equal(fixture.paths().at(-1), 'POST /api/v1/execution/device-proxy/run-1/clear_keychain'); +}); + +test('a setting the worker has no action for is refused rather than sent', async () => { + const { fixture, interactor } = await liveInteractor('android'); + await assert.rejects(interactor.setSetting('airplane', 'on'), refusedForMode); + assert.equal( + fixture.paths().some((request) => request.includes('airplane')), + false, + ); +}); diff --git a/packages/provider-revyl/src/interactor.ts b/packages/provider-revyl/src/interactor.ts index f69a871c9e..988c62c92f 100644 --- a/packages/provider-revyl/src/interactor.ts +++ b/packages/provider-revyl/src/interactor.ts @@ -15,6 +15,16 @@ import type { SnapshotOptions, } from '@agent-device/contracts/interactor-types'; import type { DeviceRotation } from '@agent-device/contracts/device'; +import { + parseAppearanceAction, + parsePermissionAction, + parsePermissionTarget, + type SettingOptions, +} from '@agent-device/contracts/settings'; +import type { + MobilePermissionTarget, + PermissionAction, +} from '@agent-device/contracts/settings-catalog'; import { AppError, discloseDispatch, @@ -27,6 +37,48 @@ import { captureRevylSnapshot, createRevylSnapshotReader } from './snapshot.ts'; /** Revyl's worker holds the touch this long when the caller names no hold. */ const DEFAULT_LONG_PRESS_DURATION_MS = 1_500; +/** The orientation names `/set_orientation` takes for each rotation on a worker that rotates precisely. */ +const REVYL_ORIENTATIONS = { + portrait: 'portrait', + 'landscape-left': 'landscape_left', + 'landscape-right': 'landscape_right', + 'portrait-upside-down': 'upside_down', +} as const satisfies Record; + +/** + * A worker without precise orientation (an iOS simulator) takes `portrait` and `landscape`, and its + * `landscape` turns the device's top to the left: landscape-left. + */ +const REVYL_IMPRECISE_ORIENTATIONS: Partial> = { + portrait: 'portrait', + 'landscape-left': 'landscape', +}; + +/** + * The Maestro permission names `/set_permissions` takes. `contacts-limited` and `location-always` + * have no Maestro name of their own, so they are absent and refused. + */ +const REVYL_PERMISSIONS = { + all: 'all', + camera: 'camera', + microphone: 'microphone', + photos: 'photos', + contacts: 'contacts', + notifications: 'notifications', + calendar: 'calendar', + location: 'location', + 'media-library': 'medialibrary', + motion: 'motion', + reminders: 'reminders', + siri: 'siri', +} as const satisfies Partial>; + +const REVYL_PERMISSION_VALUES = { + grant: 'allow', + deny: 'deny', + reset: 'unset', +} as const satisfies Record; + /** * One Revyl session's device actions. * @@ -337,13 +389,130 @@ class RevylInteractor implements Interactor { await this.workerAction('go_home'); } - /** Revyl keeps the device in the orientation its session started in; no action rotates it. */ - setOrientation(_orientation: DeviceRotation): never { - throw unsupported('orientation', 'Revyl does not expose orientation control.'); + /** + * A worker that reports `supports_precise_orientation` rotates to each side by name. Any other + * worker rotates only to portrait and landscape-left, so the other two are refused rather than + * reported for a side the device is not on. + */ + async setOrientation(orientation: DeviceRotation): Promise<{ orientation: DeviceRotation }> { + const name = this.session.preciseOrientation + ? REVYL_ORIENTATIONS[orientation] + : REVYL_IMPRECISE_ORIENTATIONS[orientation]; + if (name === undefined) { + throw new AppError( + 'UNSUPPORTED_OPERATION', + `This Revyl worker cannot rotate to ${orientation}; it rotates to portrait and landscape-left only.`, + { + reason: 'unsupported-provider-mode', + command: 'orientation', + runId: this.session.runId, + hint: 'Rotate to portrait or landscape-left.', + }, + ); + } + await this.workerAction('set_orientation', { orientation: name }); + return { orientation }; } - setSetting(): never { - throw unsupported('settings', 'Revyl does not expose settings control.'); + /** + * The settings the worker has an action for. The facts admit only these, so any other name is a + * routing bug and is refused rather than sent. + */ + async setSetting( + setting: string, + state: string, + appId?: string, + options?: SettingOptions, + ): Promise | void> { + switch (setting) { + case 'appearance': + return await this.setAppearance(parseAppearanceAction(state)); + case 'location': + return await this.setLocation(state, options); + case 'permission': + return await this.setPermission(state, this.settingsApp(setting, appId), options); + case 'clear-app-state': + await this.workerAction('clear_app_state', { + bundle_id: this.settingsApp(setting, appId), + }); + return; + case 'reset-keychain': + await this.workerAction('clear_keychain', {}); + return; + } + throw unsupported('settings', `Revyl does not expose the ${setting} setting.`); + } + + private async setAppearance( + action: 'light' | 'dark' | 'toggle', + ): Promise<{ appearance: 'light' | 'dark' }> { + let appearance: 'light' | 'dark'; + if (action === 'toggle') { + const current = await this.workerAction('appearance'); + if (current.appearance !== 'light' && current.appearance !== 'dark') { + throw new AppError('COMMAND_FAILED', 'Revyl did not report the current appearance.', { + reason: 'provider-invalid-response', + runId: this.session.runId, + }); + } + appearance = current.appearance === 'dark' ? 'light' : 'dark'; + } else { + appearance = action; + } + await this.workerAction('set_appearance', { appearance }); + return { appearance }; + } + + /** + * `/set_location` moves the device's own coordinates. The worker has no action that switches + * location services, so `on` and `off` are refused rather than reported as applied. + */ + private async setLocation( + state: string, + options: SettingOptions | undefined, + ): Promise<{ latitude: number; longitude: number }> { + const latitude = options?.latitude; + const longitude = options?.longitude; + if (latitude === undefined || longitude === undefined) { + throw unsupported( + 'settings', + `Revyl sets a location fix with set ; it cannot switch location services ${state}.`, + ); + } + await this.workerAction('set_location', { latitude, longitude }); + return { latitude, longitude }; + } + + private async setPermission( + state: string, + bundleId: string, + options: SettingOptions | undefined, + ): Promise> { + const action = parsePermissionAction(state); + const target = parsePermissionTarget(options?.permissionTarget); + if (options?.permissionMode !== undefined) { + throw unsupported('settings', 'Revyl does not take a permission mode such as limited.'); + } + if (!Object.hasOwn(REVYL_PERMISSIONS, target)) { + throw unsupported('settings', `Revyl has no permission named ${target}.`); + } + const permission = REVYL_PERMISSIONS[target as keyof typeof REVYL_PERMISSIONS]; + await this.workerAction('set_permissions', { + bundle_id: bundleId, + permissions: { [permission]: REVYL_PERMISSION_VALUES[action] }, + }); + return { app: bundleId, permission: target, action }; + } + + /** The app a setting names, else the one this session launched; the worker needs a bundle id. */ + private settingsApp(setting: string, appId: string | undefined): string { + const app = appId?.trim() || this.session.launchedApp.bundleId; + if (app) return app; + throw new AppError('INVALID_ARGS', `The ${setting} setting needs an app.`, { + reason: 'provider-app-not-launched', + command: 'settings', + hint: 'Pass --app, or open the app first.', + }); } /** diff --git a/packages/provider-revyl/src/revyl-backend.fixtures.ts b/packages/provider-revyl/src/revyl-backend.fixtures.ts index e55f885b07..8253eea449 100644 --- a/packages/provider-revyl/src/revyl-backend.fixtures.ts +++ b/packages/provider-revyl/src/revyl-backend.fixtures.ts @@ -40,6 +40,8 @@ export type RevylFixtureOptions = Readonly<{ withoutScreen?: boolean; /** Reports `supports_explicit_drag_duration: true`, which a newer worker does. */ dragDuration?: boolean; + /** Reports `supports_precise_orientation: true`, which an Android worker does. */ + preciseOrientation?: boolean; /** The body every `hierarchy` answer carries: iOS JSON or Android XML. */ hierarchy?: string; /** The start response body; a run id is generated when absent. */ @@ -251,6 +253,7 @@ export async function startRevylFixtureBackend( ? {} : { screen_width: screen.width, screen_height: screen.height }), ...(options.dragDuration ? { supports_explicit_drag_duration: true } : {}), + ...(options.preciseOrientation ? { supports_precise_orientation: true } : {}), }, }; } diff --git a/packages/provider-revyl/src/revyl-client.test.ts b/packages/provider-revyl/src/revyl-client.test.ts index 02de2166e5..098e6076e4 100644 --- a/packages/provider-revyl/src/revyl-client.test.ts +++ b/packages/provider-revyl/src/revyl-client.test.ts @@ -215,6 +215,21 @@ test('a hierarchy read that Revyl answers with a 500 is replayed', async () => { assert.equal(attempts, 1, 'only the hierarchy read opts into replaying a 500'); }); +test('an install status read that Revyl answers with a 500 is replayed', async () => { + let attempts = 0; + const client = clientResponding(() => { + attempts += 1; + return attempts === 1 + ? jsonError(500, 'Internal server error') + : jsonResponse({ install_id: 'install-1', status: 'running' }); + }); + assert.deepEqual(await client.getInstallStatus('run-1', 'install-1'), { + install_id: 'install-1', + status: 'running', + }); + assert.equal(attempts, 2); +}); + test('a readiness read answers the polling loop on its first attempt', async () => { // The readiness loop owns the poll beat and the deadline, so a transport replay in front of these // two would hide Revyl's not-ready answer and stall the very wait being polled for. diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index b6569f6d1a..4404bb6181 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -30,7 +30,13 @@ export const REVYL_START_DEVICE_TIMEOUT_MS = 120_000; const RETRY_DELAYS_MS = [500, 1_500] as const; /** Device-proxy actions Revyl answers to a GET; every other action is a POST. */ -const DEVICE_PROXY_GET_ACTIONS = new Set(['screenshot', 'health', 'device_info', 'hierarchy']); +const DEVICE_PROXY_GET_ACTIONS = new Set([ + 'screenshot', + 'health', + 'device_info', + 'hierarchy', + 'appearance', +]); export type RevylClientOptions = Readonly<{ apiKey: string; @@ -290,6 +296,9 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { return json({ ...workerRequest(workflowRunId, `install_status/${encodeURIComponent(installId)}`, signal), method: 'GET', + // A status read changes nothing, and one 500 from Revyl mid-install would otherwise end an + // install the worker is still carrying out. + retryServerError: true, }); }, async verifyCredentials(signal) { diff --git a/packages/provider-revyl/src/revyl-session.ts b/packages/provider-revyl/src/revyl-session.ts index c158eb3d32..2cd0590e12 100644 --- a/packages/provider-revyl/src/revyl-session.ts +++ b/packages/provider-revyl/src/revyl-session.ts @@ -12,6 +12,7 @@ import { revylSessionIdForLease } from './session-identity.ts'; import type { RevylStartDeviceRequest, RevylStartDeviceResponse, + RevylWorkerConnection, RevylWorkerHealth, } from './revyl-types.ts'; @@ -27,10 +28,17 @@ export const REVYL_ALLOCATION_TIMEOUT_MS = REVYL_START_DEVICE_TIMEOUT_MS + READY_TIMEOUT_MS + READY_ANSWER_MARGIN_MS; /** Revyl's worker answers `health` with 503 until the device is attached; the CLI polls on that beat. */ const READY_POLL_INTERVAL_MS = 2_000; -/** Revyl releases an idle session on its own; this is the lease the runtime asks for. */ -const DEFAULT_IDLE_TIMEOUT_SECONDS = 30 * 60; +/** + * Revyl releases a session that sees no device action for this long. The runtime refreshes that clock + * while it holds the lease, so the timeout ends only a device whose holder is gone without `/stop`. + */ +const DEFAULT_IDLE_TIMEOUT_SECONDS = 5 * 60; +/** How often a held session refreshes Revyl's idle clock: well inside `DEFAULT_IDLE_TIMEOUT_SECONDS`. */ +export const REVYL_KEEP_ALIVE_INTERVAL_MS = 60_000; /** Revyl answers a device-proxy action the worker cannot serve yet with these. */ const NOT_READY_STATUSES = new Set([503, 409]); +/** A server error on the worker-connection read, which changes nothing, leaves the start pending. */ +const CONNECTION_PENDING_STATUSES = new Set([500, 502, 503, 504]); export type RevylScreenSize = Readonly<{ width: number; height: number }>; @@ -45,6 +53,11 @@ export type RevylSession = Readonly<{ screen: RevylScreenSize | undefined; /** Read from `health`: whether `/drag` takes the finger's travel time as `duration_ms`. */ dragDuration: boolean; + /** + * Read from `health`: whether `/set_orientation` rotates to a named landscape side and upside down. + * A worker without it rotates only to portrait or to a landscape side it does not name. + */ + preciseOrientation: boolean; device: DeviceInfo; client: RevylClient; lease: DeviceLease; @@ -181,6 +194,7 @@ export async function startRevylSession( sessionId, screen: readRevylScreenSize(health), dragDuration: health.supports_explicit_drag_duration === true, + preciseOrientation: health.supports_precise_orientation === true, device: buildRevylDevice(input.platform, lease, runId), client, lease, @@ -398,12 +412,12 @@ async function untilRevylWorkerReady( ): Promise { for (;;) { requireTime(deadline, input); - const connection = await runWithinDeadline( - () => client.getWorkerConnection(runId, pollSignal(deadline, input)), - deadline, - input, - ); + const connection = await readWorkerConnection(client, runId, deadline, input); requireTime(deadline, input); + if (connection === undefined) { + await sleepBefore(deadline, input.signal); + continue; + } if (connection.status === 'ready' && connection.worker_ws_url) return; if ( connection.status === 'cancelled' || @@ -424,6 +438,29 @@ async function untilRevylWorkerReady( } } +/** + * One worker-connection read, or `undefined` when Revyl answered it with a server error: the read + * changes nothing, so the next poll asks again within the same deadline. + */ +async function readWorkerConnection( + client: RevylClient, + runId: string, + deadline: RevylDeadline, + input: RevylReadyInput, +): Promise { + try { + return await runWithinDeadline( + () => client.getWorkerConnection(runId, pollSignal(deadline, input)), + deadline, + input, + ); + } catch (error) { + const status = error instanceof AppError ? error.details?.providerStatus : undefined; + if (typeof status === 'number' && CONNECTION_PENDING_STATUSES.has(status)) return undefined; + throw error; + } +} + /** Fails the moment the readiness budget is spent, whatever a poll that was already sent answers. */ function requireTime(deadline: RevylDeadline, input: RevylReadyInput): void { if (Date.now() < deadline.at) return; @@ -446,6 +483,28 @@ async function sleepBefore(deadline: RevylDeadline, signal?: AbortSignal): Promi ).catch(() => undefined); } +/** + * Refreshes a held session's idle clock on a timer, with a read that changes nothing on the device: + * the worker counts a state read as device use and `health` as not. A failed refresh is not reported, + * since the next one or any command refreshes the clock again; only a holder gone for the whole idle + * timeout loses the device. The timer never keeps the process alive. + */ +export function keepRevylSessionAlive(client: RevylClient, runId: string): () => void { + let refreshing = false; + const timer = setInterval(() => { + if (refreshing) return; + refreshing = true; + void client + .workerAction(runId, 'appearance') + .catch(() => undefined) + .finally(() => { + refreshing = false; + }); + }, REVYL_KEEP_ALIVE_INTERVAL_MS); + timer.unref(); + return () => clearInterval(timer); +} + /** * Ends one Revyl session by the id this runtime issued for it. `/stop` is idempotent, so a repeat * release is safe; every rented session carries that id, so no run-level cancel is needed. diff --git a/packages/provider-revyl/src/revyl-types.ts b/packages/provider-revyl/src/revyl-types.ts index 58f646a192..0b9fe7b49a 100644 --- a/packages/provider-revyl/src/revyl-types.ts +++ b/packages/provider-revyl/src/revyl-types.ts @@ -45,6 +45,8 @@ export type RevylWorkerHealth = Readonly<{ screen_height?: number; /** Set when the worker's `/drag` body accepts `duration_ms`; without it the worker picks the speed. */ supports_explicit_drag_duration?: boolean; + /** Set when `/set_orientation` rotates to a named landscape side and upside down. */ + supports_precise_orientation?: boolean; }>; export type RevylDeviceSessionStopResponse = Readonly<{ diff --git a/packages/provider-revyl/src/runtime-keep-alive.test.ts b/packages/provider-revyl/src/runtime-keep-alive.test.ts new file mode 100644 index 0000000000..ad57d6d574 --- /dev/null +++ b/packages/provider-revyl/src/runtime-keep-alive.test.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import { afterEach, test, vi } from 'vitest'; +import { + revylLease, + startRevylFixtureBackend, + type RevylFixtureBackend, +} from './revyl-backend.fixtures.ts'; +import { REVYL_KEEP_ALIVE_INTERVAL_MS } from './revyl-session.ts'; + +const openBackends: RevylFixtureBackend[] = []; + +afterEach(async () => { + vi.useRealTimers(); + await Promise.all(openBackends.splice(0).map((fixture) => fixture.close())); +}); + +const KEEP_ALIVE = 'GET /api/v1/execution/device-proxy/run-1/appearance'; + +/** Waits until the fixture has recorded `count` keep-alive reads; the read is a real HTTP request. */ +async function keepAlivesReach(fixture: RevylFixtureBackend, count: number): Promise { + await vi.waitFor(() => { + assert.equal(fixture.paths().filter((path) => path === KEEP_ALIVE).length, count); + }); +} + +test('a held session reads appearance on each keep-alive beat, and its release stops the beat', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const fixture = await startRevylFixtureBackend({ + respond: { [KEEP_ALIVE]: { body: { appearance: 'light' } } }, + }); + openBackends.push(fixture); + const runtime = fixture.createRuntime(); + const lease = revylLease('ios'); + await runtime.leaseLifecycle?.allocate?.(lease); + + assert.equal(fixture.paths().includes(KEEP_ALIVE), false, 'no read before the first beat'); + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS); + await keepAlivesReach(fixture, 1); + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS); + await keepAlivesReach(fixture, 2); + + await runtime.leaseLifecycle?.release?.(lease); + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS * 3); + assert.equal(fixture.paths().filter((path) => path === KEEP_ALIVE).length, 2); +}); + +test('a failed keep-alive read leaves the session held and the next beat reads again', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const fixture = await startRevylFixtureBackend({ + respond: { [KEEP_ALIVE]: { status: 501, body: { detail: 'Unsupported on device' } } }, + }); + openBackends.push(fixture); + const runtime = fixture.createRuntime(); + const lease = revylLease('android'); + await runtime.leaseLifecycle?.allocate?.(lease); + + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS); + await keepAlivesReach(fixture, 1); + vi.advanceTimersByTime(REVYL_KEEP_ALIVE_INTERVAL_MS); + await keepAlivesReach(fixture, 2); + const listed = await runtime.deviceInventoryProvider?.({ + leaseProvider: 'revyl', + leaseId: lease.leaseId, + platform: 'android', + }); + assert.equal(listed?.length, 1); + await runtime.leaseLifecycle?.release?.(lease); +}); diff --git a/packages/provider-revyl/src/runtime-transient-reads.test.ts b/packages/provider-revyl/src/runtime-transient-reads.test.ts new file mode 100644 index 0000000000..94eb2ab0a5 --- /dev/null +++ b/packages/provider-revyl/src/runtime-transient-reads.test.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'vitest'; +import { + revylLease, + startRevylFixtureBackend, + type RevylFixtureBackend, +} from './revyl-backend.fixtures.ts'; + +const CONNECTION = 'GET /api/v1/execution/streaming/worker-connection/run-1'; +const openBackends: RevylFixtureBackend[] = []; + +afterEach(async () => { + await Promise.all(openBackends.splice(0).map((fixture) => fixture.close())); +}); + +test('a lease start keeps polling when Revyl answers the worker-connection read with a 500', async () => { + let connectionPolls = 0; + const fixture = await startRevylFixtureBackend({ + respond: { + [CONNECTION]: () => { + connectionPolls += 1; + return connectionPolls === 1 + ? { status: 500, body: { detail: 'Internal server error' } } + : { + body: { + status: 'ready', + workflow_run_id: 'run-1', + worker_ws_url: 'wss://worker.test/ws', + }, + }; + }, + }, + }); + openBackends.push(fixture); + const runtime = fixture.createRuntime({ deviceModel: 'Pixel 7' }); + + const allocation = await runtime.leaseLifecycle?.allocate?.(revylLease('android'), { + initialApp: 'https://apps.test/app.apk', + flags: { device: 'Pixel 7' }, + }); + + assert.ok(allocation); + assert.deepEqual( + fixture.paths().filter((path) => path === CONNECTION), + [CONNECTION, CONNECTION], + ); +}); + +test('a lease start still fails on a worker-connection answer that is not a server error', async () => { + const fixture = await startRevylFixtureBackend({ + respond: { [CONNECTION]: { status: 403, body: { detail: 'Forbidden' } } }, + }); + openBackends.push(fixture); + const runtime = fixture.createRuntime({ deviceModel: 'Pixel 7' }); + + await assert.rejects( + async () => + await runtime.leaseLifecycle?.allocate?.(revylLease('android'), { + initialApp: 'https://apps.test/app.apk', + flags: { device: 'Pixel 7' }, + }), + ); + assert.deepEqual( + fixture.paths().filter((path) => path === CONNECTION), + [CONNECTION], + ); +}); diff --git a/packages/provider-revyl/src/runtime.test.ts b/packages/provider-revyl/src/runtime.test.ts index 2fd8e5c329..cb0d90b334 100644 --- a/packages/provider-revyl/src/runtime.test.ts +++ b/packages/provider-revyl/src/runtime.test.ts @@ -58,7 +58,7 @@ test('a lease start waits for the worker and the device, and reports the rented // The session id is the runtime's own, derived from the lease, so a later process can still // name this session from the lease alone. session_id: revylSessionIdForLease('lease-1'), - idle_timeout_seconds: 1800, + idle_timeout_seconds: 300, app_url: 'https://apps.test/app.zip', device_model: 'iPhone 16', // The lease context's flags outrank what the runtime was built with. diff --git a/packages/provider-revyl/src/runtime.ts b/packages/provider-revyl/src/runtime.ts index bf398afef8..0ad478fd6c 100644 --- a/packages/provider-revyl/src/runtime.ts +++ b/packages/provider-revyl/src/runtime.ts @@ -23,6 +23,7 @@ import { } from './device.ts'; import { createRevylClient, isRevylSessionGone, type RevylClient } from './revyl-client.ts'; import { + keepRevylSessionAlive, REVYL_ALLOCATION_TIMEOUT_MS, revylCallerGaveUp, revylCleanupPending, @@ -230,6 +231,8 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime { function createRevylLeaseDriver( client: RevylClient, ): ProviderLeaseDriver { + /** The idle-clock refresh of each ready session, by session id, ended before its `/stop`. */ + const keepAlives = new Map void>(); return { startTimeoutMs: REVYL_ALLOCATION_TIMEOUT_MS, // A session is created when `start_device` answers, not when it is sent, so the issued id is never @@ -247,9 +250,12 @@ function createRevylLeaseDriver( }); if (started.status === 'failed') return started; const { runId, sessionId } = started.session; + keepAlives.set(sessionId, keepRevylSessionAlive(client, runId)); return { status: 'ready', session: started.session, handle: { runId, sessionId } }; }, stop: async (handle) => { + keepAlives.get(handle.sessionId)?.(); + keepAlives.delete(handle.sessionId); try { await stopRevylSession(client, handle.sessionId); } catch (error) { diff --git a/scripts/capability-matrix/annotations.ts b/scripts/capability-matrix/annotations.ts index c44cc93ca9..e6b45768fe 100644 --- a/scripts/capability-matrix/annotations.ts +++ b/scripts/capability-matrix/annotations.ts @@ -432,6 +432,16 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [ admits: ['setOrientation'], refuses: ['unlockOrientation'], }, + 'revyl-ios': { + text: 'Portrait and landscape-left only; unlock unsupported', + admits: ['setOrientation'], + refuses: ['unlockOrientation'], + }, + 'revyl-android': { + text: 'Set only; unlock unsupported', + admits: ['setOrientation'], + refuses: ['unlockOrientation'], + }, }, }, { @@ -525,6 +535,16 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [ admits: ['setSetting'], refuses: ['readSetting'], }, + 'revyl-ios': { + text: 'Appearance, location coordinates, permission, clear app state, and reset keychain; no reads', + admits: ['setSetting'], + refuses: ['readSetting'], + }, + 'revyl-android': { + text: 'Appearance, location coordinates, permission, and clear app state; no reads', + admits: ['setSetting'], + refuses: ['readSetting'], + }, }, }, { diff --git a/website/docs/docs/capabilities.md b/website/docs/docs/capabilities.md index ce2c99662e..7acb71af5a 100644 --- a/website/docs/docs/capabilities.md +++ b/website/docs/docs/capabilities.md @@ -302,12 +302,12 @@ What a **Yes** does not claim: | --- | --- | --- | --- | --- | --- | --- | --- | --- | | [Back](/docs/commands#navigation) | Yes | Yes | Yes | Yes | Yes | Yes | No | Yes | | [Home](/docs/commands#navigation) | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | -| [Set screen orientation](/docs/commands#navigation) | Set only; unlock unsupported | Set only; unlock unsupported | Set only; unlock unsupported | Set only; unlock unsupported | Set only; unlock unsupported | Yes | No | No | +| [Set screen orientation](/docs/commands#navigation) | Set only; unlock unsupported | Set only; unlock unsupported | Set only; unlock unsupported | Set only; unlock unsupported | Set only; unlock unsupported | Yes | Portrait and landscape-left only; unlock unsupported | Set only; unlock unsupported | | [Phone hardware buttons](/docs/commands#navigation) | Yes | Yes | Yes | Yes | No | Yes | No | No | | [iPhone Action Button](/docs/commands#navigation) | No | No | No | No | Models with an Action Button only | No | No | No | | [Foldable pose](/docs/commands#navigation) | No | No | No | No | No | No | No | No | | [TV remote keys](/docs/commands#tv-targets) | No | No | No | No | No | No | No | No | -| [System and app settings helpers](/docs/commands#settings-helpers) | No | No | No | No | Yes | Yes | No | No | +| [System and app settings helpers](/docs/commands#settings-helpers) | No | No | No | No | Yes | Yes | Appearance, location coordinates, permission, clear app state, and reset keychain; no reads | Appearance, location coordinates, permission, and clear app state; no reads | | [Clipboard read and write](/docs/commands#clipboard) | Yes | Yes | Yes | Yes | Yes | Yes | No | No | | [Push notification simulation](/docs/commands#push-notification-simulation) | No | No | No | No | Yes | No | No | No | | [App event triggers through the app hook](/docs/commands#app-event-triggers-app-hook) | Yes | Yes | Yes | Yes | Yes | Yes | No | No | diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md index cf5ef68458..1f16059940 100644 --- a/website/docs/docs/revyl.md +++ b/website/docs/docs/revyl.md @@ -76,7 +76,9 @@ agent-device disconnect ``` `close` ends the app on the device. `disconnect`, and any daemon shutdown, ends the Revyl session, so -the device is returned. Revyl also releases an idle session on its own after its idle timeout. +the device is returned. While the session is connected, the plugin tells Revyl it is still in use +once a minute, so a pause between commands does not end it. If the process exits without +disconnecting, Revyl releases the session after five idle minutes. ## What works on a Revyl session @@ -95,6 +97,14 @@ A Revyl session runs the commands that reach a device through Revyl's device act bundle identifier or package name, `open` with a deep link or URL, and `close` for the app the session opened. - `home`, and `back` on Android. iOS has no system back button; click the app's own back control. +- `orientation`. An Android emulator rotates to all four sides. An iOS simulator rotates to + `portrait` and `landscape-left` only, and refuses the other two. Neither releases the rotation lock, + so `orientation auto` refuses. +- `settings appearance` (`light`, `dark`, or `toggle`), `settings location set `, + `settings permission`, and `settings clear-app-state`. On iOS, `settings reset-keychain` also + works. `settings location on|off` refuses, because Revyl moves the device's coordinates but cannot + switch location services. `settings permission` refuses `location-always`, `contacts-limited`, and + `--mode limited`. Revyl's iOS simulators refuse `camera` and `notifications`. The plugin refuses every other command with a reason that names the substitute. It does not report a refused command as a success: @@ -102,8 +112,10 @@ report a refused command as a success: - `type` refuses and points at `fill`, because Revyl enters text at a point rather than into the field the platform happens to focus. - `swipe` and `gesture` refuse. Use `scroll`, which plans the path itself and sends one drag. -- `keyboard`, `clipboard`, `settings`, `orientation`, `alert`, `fold`, `telephony`, and `tv-remote` - are not supported. +- `keyboard`, `clipboard`, `alert`, `fold`, `telephony`, and `tv-remote` are not supported. +- The other `settings` refuse: `wifi`, `airplane`, `mobile-data`, `bluetooth`, `animations`, + `text-size`, `faceid`, `touchid`, and `fingerprint`. Revyl's devices refuse airplane mode, and the + worker has no action for the rest. - `reinstall` refuses, as described above. - `uninstall`, `apps`, `push`, `logs`, `network dump`, `artifacts`, and `recordings` are not supported by this version of the plugin.