diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index f43f7a31c..e01a7dee2 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -22,6 +22,7 @@ On unless `capabilities.agent-device.enabled` is set false, on a standalone work | `front/front.ts` | The mount: role check, routes, `/rpc` dispatch by call class | | `front/request-rules.ts` | Refusals and rewrites before anything is forwarded | | `front/allocate.ts`, `front/heartbeat.ts`, `front/release.ts` | Lease calls ↔ simlock `lease.*` | +| `front/orientation.ts` | `orientation` on an iOS phone or tablet simulator lease: `device.rotate`, answered unconfirmed; anything else forwarded | | `front/renewals.ts` | Renews the simlock lease while a command runs | | `front/front-map.ts` | In-memory leases this front made, and who ended each | | `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases | @@ -76,12 +77,11 @@ Front (`createFront`, prefix `agent-device`): 6. Heartbeat → forwarded with `ttlMs` raised to the ceiling; on success `renewLease` (`lease.renew` only if it moves the deadline; a gateway list that trails the grant and omits the lease still relays agent-device's reply). agent-device says gone → `lease.release`, reply "ended by simlock". 7. Release → forwarded; on success `lease.release`; map marks it ended by `agent`. -8. Command on a lease → `Renewals.begin`: renew every TTL/3 until the body ends, - capped at `lease.maxTtlMs`. A reply naming `endedLeases` (in `data`, `error.details`, a streamed `type: "response"` line, or a +8. Command on a lease → `Renewals.begin`: renew every TTL/3 until the body ends, capped at `lease.maxTtlMs`. A reply naming `endedLeases` (in `data`, `error.details`, a streamed `type: "response"` line, or a batch's `data`) → `front/ended.ts` ends each simlock lease this token holds, as a release does. + `orientation` (not a batch step) on an `ios`, not physical lease (an adopted one: physical unknown) whose model is an iPhone or iPad → `device.rotate`, answered with agent-device's unconfirmed reply, `INVALID_ARGS` for an unknown name (an adopted lease forwards it); `ROTATION_UNSUPPORTED`, `UNKNOWN_LEASE` and `FORBIDDEN` forward the command; `WORKER_UNREACHABLE` answers the try-again reply; any other error `COMMAND_FAILED`. Every other lease is forwarded before the name is read. -Host (`AgentDeviceHost.forward`): one proxy per daemon generation. Tags the request, and `authenticate` sets tenant = requester id, overwriting the client's. Rewrites `/v1/agent-device` → `/agent-device`. Download: `Content-Length` > 2 GiB → 413 before -any byte; no length → counted, errors past 2 GiB. +Host (`AgentDeviceHost.forward`): one proxy per daemon generation. Tags the request, and `authenticate` sets tenant = requester id, overwriting the client's. Rewrites `/v1/agent-device` → `/agent-device`. Download: `Content-Length` > 2 GiB → 413 before any byte; no length → counted, errors past 2 GiB. Lease end: `ReleaseScopeRecord` reads each allocate reply's scope (tenant, run id, …) through the proxy's upstream fetch. `AgentDeviceLeaseEnd.leaseEnded` waits for a @@ -130,8 +130,7 @@ under leasing's signal (`lease.endWaitMs`). | Renewal tick | TTL / 3 | lease TTL | | Download cap; `/rpc` body | 2 GiB; 1 MiB | none | -Disk: `/agent-device/` and `/agent-device-phones/` (agent-device's own files) and the two pid records. Front map, -renewals and release scopes: memory only. +Disk: `/agent-device/` and `/agent-device-phones/` (agent-device's own files) and the two pid records. Front map, renewals and release scopes: memory only. Local profile: a standalone worker with HTTP and this module on keeps `/agent-device-profile.json` (0600) so an agent on the same Mac connects with `agent-device connect --remote-config ` and no token of its own ([ADR 0046](../../docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md)). `definition.ts` declares the file as plain data; the module host writes it at each start, reuses the one `agent`-role token labelled `agent-device on this Mac` (so an agent's saved connection stays valid), revokes other tokens with that label, and deletes the file and revokes the token when HTTP or the module is off. No worker code runs for it. diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 19982dcce..624f92154 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -888,6 +888,13 @@ describe("the agent-device front, through the whole worker daemon", () => { "physical", ); expect(allocatesReceived(rig)).toEqual([]); + if (platform === "ios") { + // why: a physical iPhone has no `device.rotate`, so its `orientation auto` must reach agent-device, not be refused as an unknown name. + await command(rig, "orientation", 1, {}, { positionals: ["auto"] }); + expect(rig.phone.rpcRequests("agent_device.command")).toMatchObject([ + { params: { command: "orientation", positionals: ["auto"] } }, + ]); + } } }); diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index aac048b09..e91c115ce 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -355,6 +355,7 @@ async function keepOrRelease( deadline: grant.lease.ttlDeadline, identity, model: grant.device.spec.model, + physical: grant.device.spec.physical === true, platform: plan.platform, ttlMs: grant.lease.ttlMs, ...replyFacts(reading.result), diff --git a/src/agent-device/front/front-map.ts b/src/agent-device/front/front-map.ts index 087c675b5..a463898e9 100644 --- a/src/agent-device/front/front-map.ts +++ b/src/agent-device/front/front-map.ts @@ -8,6 +8,7 @@ interface DeviceFacts { readonly model?: string; readonly name?: string; readonly target?: string; + readonly physical?: boolean; readonly deviceKey?: string; // why: an adopted entry was rebuilt after a gateway restart and has no device key until a call names one. readonly adopted?: boolean; diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index ba14f59fe..3dd508dd6 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -27,6 +27,7 @@ import { anyUnreachable, devicesThroughGateway, filterDevices } from "./devices- import { heartbeat } from "./heartbeat.js"; import type { LinkStatus } from "./host-link.js"; import { releaseEndedLeases } from "./ended.js"; +import { answerOrientation, isOrientationCall } from "./orientation.js"; import { release } from "./release.js"; import { checkRequest } from "./request-rules.js"; @@ -222,6 +223,10 @@ async function forwardCommand( read: RpcRequest, leaseId: string | undefined, ): Promise { + if (leaseId !== undefined && isOrientationCall(read)) { + const answered = await answerOrientation(context, identity, read, leaseId); + if (answered !== undefined) return answered; + } const isDevices = isDevicesCall(read); if (isDevices && context.link.readsLeaseHeader) { return devicesThroughGateway(context, { diff --git a/src/agent-device/front/orientation.test.ts b/src/agent-device/front/orientation.test.ts new file mode 100644 index 000000000..469c0fbdf --- /dev/null +++ b/src/agent-device/front/orientation.test.ts @@ -0,0 +1,280 @@ +import { describe, expect, it } from "vitest"; + +import { tokenIdentity } from "../../auth/testing.js"; +import { DispatchError } from "../../daemon/dispatch.js"; +import type { HttpDispatch } from "../../http/dispatcher-session.js"; +import { FakeClock, NoopLogger } from "../../ports/index.js"; +import { FRONT_PREFIX } from "../shared/paths.js"; +import type { FrontContext } from "./context.js"; +import { FrontMap } from "./front-map.js"; +import { createFront } from "./front.js"; +import type { HostLink } from "./host-link.js"; +import { Renewals } from "./renewals.js"; + +const agent = tokenIdentity("tok_a"); +const leaseId = "a".repeat(32); +const ttlMs = 600_000; +const forwardedAnswer = { forwarded: true }; + +interface Rig { + readonly handle: (command: string, positionals?: readonly string[]) => Promise; + readonly rotations: unknown[]; + readonly forwarded: unknown[]; + readonly clock: FakeClock; +} + +interface RigOptions { + readonly gateway: boolean; + readonly model: string; + readonly adopted?: boolean; + readonly platform?: "ios" | "android"; + readonly physical?: boolean; + readonly owner?: typeof agent; + readonly rotate?: () => Promise; +} + +function rig(options: RigOptions): Rig { + const clock = new FakeClock(1_000); + const map = new FrontMap(clock); + const rotations: unknown[] = []; + const forwarded: unknown[] = []; + const entry = { + address: "udid-1", + deadline: clock.now() + ttlMs, + identity: options.owner ?? agent, + model: options.model, + platform: options.platform ?? "ios", + ...(options.physical === undefined ? {} : { physical: options.physical }), + target: "mobile", + ttlMs, + }; + if (!options.adopted) map.add(leaseId, entry); + const link: HostLink = { + adoptable: () => (options.adopted ? [{ ...entry, leaseId, ttlDeadline: entry.deadline }] : []), + forward: async (request) => { + forwarded.push(JSON.parse(await request.text())); + return Response.json({ id: 1, jsonrpc: "2.0", result: { data: forwardedAnswer, ok: true } }); + }, + readsLeaseHeader: options.gateway, + status: () => Promise.resolve({ platforms: ["ios", "android"], state: "running" }), + }; + const dispatch = ((operation: string, input: unknown) => { + if (operation === "device.rotate") { + rotations.push(input); + return (options.rotate ?? (() => Promise.resolve({})))(); + } + if (operation === "lease.list") { + return Promise.resolve({ + leases: [{ id: leaseId, requesterId: leaseId, ttlDeadline: clock.now() + ttlMs * 10 }], + }); + } + return Promise.resolve({}); + }) as unknown as HttpDispatch; + const context: FrontContext = { + clock, + dispatch, + link, + logger: new NoopLogger(), + map, + maxRunMs: 3_600_000, + renewals: new Renewals(clock), + }; + const mount = createFront(context); + return { + clock, + forwarded, + handle: (command, positionals = []) => + Promise.resolve( + mount.handle( + new Request(`http://simlock.test${FRONT_PREFIX}/rpc`, { + body: JSON.stringify({ + id: 7, + jsonrpc: "2.0", + method: "agent_device.command", + params: { command, meta: { leaseId }, positionals }, + }), + headers: { "content-type": "application/json" }, + method: "POST", + }), + agent, + ), + ), + rotations, + }; +} + +interface Envelope { + readonly id?: unknown; + readonly result?: { readonly ok: boolean; readonly data: Record }; + readonly error?: { + readonly data: { + readonly code: string; + readonly message: string; + readonly details?: { readonly reason: string }; + }; + }; +} + +async function answer(response: Response): Promise { + return (await response.json()) as Envelope; +} + +function unconfirmed(name: string) { + return { + action: "orientation", + confirmed: false, + message: `Rotation requested: ${name} (unconfirmed)`, + orientation: name, + warning: `Requested ${name}; the device owner reported no resulting orientation, so the rotation is unconfirmed.`, + }; +} + +const unknownMessage = (input: string) => + `Unknown orientation ${input}; use portrait, portrait-upside-down, landscape-left or landscape-right`; + +const rotated = [ + ["landscape-left", "landscape_left", "landscape-left"], + ["Left", "landscape_left", "landscape-left"], + ["right", "landscape_right", "landscape-right"], + ["upside-down", "portrait_upside_down", "portrait-upside-down"], + ["portrait", "portrait", "portrait"], +] as const; + +async function expectRotated(gateway: boolean, model: string, row: (typeof rotated)[number]) { + const [typed, sent, named] = row; + const { handle, rotations, forwarded, clock } = rig({ gateway, model }); + const body = await answer(await handle("orientation", [typed])); + const label = `${gateway ? "gateway" : "worker"} ${model} ${typed}`; + expect(body.id, label).toBe(7); + expect(body.result, label).toEqual({ data: unconfirmed(named), ok: true }); + expect(rotations, label).toEqual([{ leaseId, orientation: sent }]); + expect(forwarded, label).toEqual([]); + expect(clock.pendingTimerCount, label).toBe(0); +} + +async function expectAdoptedRotated() { + const adopted = rig({ adopted: true, gateway: true, model: "iPhone 17 Pro" }); + const body = await answer(await adopted.handle("orientation", ["landscape-right"])); + expect(body.result).toEqual({ data: unconfirmed("landscape-right"), ok: true }); + expect(adopted.rotations).toEqual([{ leaseId, orientation: "landscape_right" }]); + expect(adopted.forwarded).toEqual([]); +} + +async function expectInvalid(typed: readonly string[]) { + const { handle, rotations, forwarded } = rig({ gateway: false, model: "iPad Pro 13-inch (M5)" }); + const response = await handle("orientation", typed); + const body = await answer(response); + expect(response.status).toBe(400); + expect(body.error?.data).toEqual({ + code: "INVALID_ARGS", + message: unknownMessage(typed[0] ?? ""), + }); + expect(rotations).toEqual([]); + expect(forwarded).toEqual([]); +} + +interface Failure { + readonly error: Error; + readonly expected: { + readonly code: string; + readonly message: string; + readonly status: number; + readonly details?: { readonly reason: string }; + }; +} + +const failures: readonly Failure[] = [ + { + error: new DispatchError("INPUT_UNAVAILABLE", "the input helper could not start", { + leaseId, + reason: "x", + }), + expected: { code: "COMMAND_FAILED", message: "the input helper could not start", status: 502 }, + }, + { + error: new Error("rotate blew up"), + expected: { code: "COMMAND_FAILED", message: "rotate blew up", status: 502 }, + }, + { + error: new DispatchError("WORKER_UNREACHABLE", "worker w1 is not connected", { + workerId: "w1", + }), + expected: { + code: "COMMAND_FAILED", + details: { reason: "WORKER_UNREACHABLE" }, + message: + "agent-device is not available on this simlock: the worker holding this device is not connected to the gateway; try again", + status: 503, + }, + }, +]; + +async function expectFailure({ error, expected }: Failure) { + const { handle, forwarded, clock } = rig({ + gateway: true, + model: "iPhone 17 Pro", + rotate: () => Promise.reject(error), + }); + const response = await handle("orientation", ["landscape-left"]); + const renewing = expected.status === 503 ? 0 : 2; + expect(clock.pendingTimerCount, `${expected.message} renewal before the body is read`).toBe( + renewing, + ); + const body = await answer(response); + const { status, ...data } = expected; + expect(response.status, data.message).toBe(status); + expect(body.error?.data, data.message).toEqual(data); + expect(forwarded, data.message).toEqual([]); + expect(clock.pendingTimerCount, data.message).toBe(0); +} + +describe("the agent-device front's orientation command", () => { + it("answers `orientation ` on a Simlock iOS-simulator lease with agent-device's unconfirmed reply through device.rotate, without the command reaching agent-device; `auto` or an unknown name is `INVALID_ARGS`, a missing helper `COMMAND_FAILED`, a gone worker the worker-unreachable reply", async () => { + for (const gateway of [true, false]) { + for (const model of ["iPhone 17 Pro", "iPad Pro 13-inch (M5)"]) { + for (const row of rotated) await expectRotated(gateway, model, row); + } + } + await expectAdoptedRotated(); + for (const typed of [["auto"], ["sideways"], []]) await expectInvalid(typed); + for (const failure of failures) await expectFailure(failure); + }); + + it("forwards `orientation ` to agent-device when the lease is not on an iOS phone or tablet simulator, or Simlock no longer knows it", async () => { + const cases = [ + { label: "Android emulator", platform: "android", model: "Pixel 8" }, + { label: "Android phone", platform: "android", model: "Pixel 8", physical: true }, + { label: "iPhone", physical: true, model: "iPhone 17 Pro" }, + { label: "Apple TV simulator", model: "Apple TV 4K (3rd generation)" }, + { label: "Android on an iPhone model", platform: "android", model: "iPhone 17 Pro" }, + { label: "another token's lease", owner: tokenIdentity("tok_b"), model: "iPhone 17 Pro" }, + ] as const; + for (const { label, ...lease } of cases) { + for (const typed of ["landscape-left", "auto"]) { + const { handle, rotations, forwarded } = rig({ gateway: false, ...lease }); + const body = await answer(await handle("orientation", [typed])); + expect(body.result?.data, `${label} ${typed}`).toEqual(forwardedAnswer); + expect(forwarded, `${label} ${typed}`).toHaveLength(1); + expect(rotations, `${label} ${typed}`).toEqual([]); + } + } + + for (const code of ["UNKNOWN_LEASE", "FORBIDDEN", "ROTATION_UNSUPPORTED"]) { + const { handle, rotations, forwarded } = rig({ + gateway: true, + model: "iPhone 17 Pro", + rotate: () => Promise.reject(new DispatchError(code, "not rotatable here")), + }); + const body = await answer(await handle("orientation", ["landscape-left"])); + expect(body.result?.data, code).toEqual(forwardedAnswer); + expect(forwarded, code).toHaveLength(1); + expect(rotations, code).toHaveLength(1); + } + + const adopted = rig({ adopted: true, gateway: true, model: "iPhone 17 Pro" }); + const body = await answer(await adopted.handle("orientation", ["auto"])); + expect(body.result?.data).toEqual(forwardedAnswer); + expect(adopted.forwarded).toHaveLength(1); + expect(adopted.rotations).toEqual([]); + }); +}); diff --git a/src/agent-device/front/orientation.ts b/src/agent-device/front/orientation.ts new file mode 100644 index 000000000..61eec798d --- /dev/null +++ b/src/agent-device/front/orientation.ts @@ -0,0 +1,90 @@ +import type { Identity } from "../../auth/index.js"; +import { isRotatableModel, parseOrientation } from "../../contract/index.js"; +import { buildHttpSession } from "../../http/dispatcher-session.js"; +import { mapError } from "../../http/errors.js"; +import { + failure, + frontReply, + markUnreachableAnswer, + refusal, + successReply, + workerUnreachable, +} from "../shared/replies.js"; +import type { RpcRead } from "../shared/rpc.js"; +import { asRecord, commandName } from "../shared/selectors.js"; +import type { FrontContext } from "./context.js"; + +// why: these say the lease is not one Simlock can rotate (or no longer knows), so agent-device answers as it does for any other lease. +const FORWARDED_CODES: ReadonlySet = new Set([ + "ROTATION_UNSUPPORTED", + "UNKNOWN_LEASE", + "FORBIDDEN", +]); + +type RpcRequest = RpcRead & { readonly kind: "request" }; + +export function isOrientationCall(read: RpcRequest): boolean { + return commandName(asRecord(read.params)?.["command"]) === "orientation"; +} + +function typedName(read: RpcRequest): string { + const positionals = asRecord(read.params)?.["positionals"]; + const first: unknown = Array.isArray(positionals) ? positionals[0] : undefined; + return typeof first === "string" ? first : ""; +} + +// why: agent-device spells the two compound names with hyphens, and echoes the one it was asked for. +function agentDeviceName(orientation: string): string { + return orientation.replaceAll("_", "-"); +} + +function unconfirmed(name: string) { + return { + action: "orientation", + confirmed: false, + message: `Rotation requested: ${name} (unconfirmed)`, + orientation: name, + warning: `Requested ${name}; the device owner reported no resulting orientation, so the rotation is unconfirmed.`, + }; +} + +/** + * why: agent-device's own rotation goes through its XCTest runner, which leaves taps missing; on an iOS phone or tablet simulator Simlock's input helper turns it instead. Undefined means the command is agent-device's to answer. + */ +export async function answerOrientation( + context: FrontContext, + identity: Identity, + read: RpcRequest, + leaseId: string, +): Promise { + const held = context.map.get(leaseId); + if ( + held === undefined || + held.identity.principal !== identity.principal || + held.platform !== "ios" || + held.physical === true || + held.model === undefined || + !isRotatableModel(held.model) + ) { + return undefined; + } + const typed = typedName(read); + const parsed = parseOrientation(typed); + if (!parsed.ok) + return held.adopted === true ? undefined : frontReply(refusal(parsed.message), read); + try { + await context.dispatch( + "device.rotate", + { leaseId, orientation: parsed.orientation }, + buildHttpSession(identity), + ); + } catch (error) { + const code = mapError(error).code; + if (FORWARDED_CODES.has(code)) return undefined; + if (code === "WORKER_UNREACHABLE") { + return markUnreachableAnswer(frontReply(workerUnreachable(), read)); + } + return frontReply(failure(error instanceof Error ? error.message : String(error)), read); + } + return successReply(unconfirmed(agentDeviceName(parsed.orientation)), read); +} diff --git a/src/agent-device/shared/replies.ts b/src/agent-device/shared/replies.ts index 77eee0d64..b93529e96 100644 --- a/src/agent-device/shared/replies.ts +++ b/src/agent-device/shared/replies.ts @@ -56,6 +56,10 @@ export function failure(message: string, status = 502): FrontReply { return { code: "COMMAND_FAILED", message, status }; } +export function successReply(data: unknown, rpc: { readonly id: unknown }): Response { + return Response.json({ id: rpc.id, jsonrpc: "2.0", result: { data, ok: true } }); +} + export function frontReply(reply: FrontReply, rpc: { readonly id: unknown } | undefined): Response { if (rpc === undefined) { return Response.json( diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index 67597db12..d868687a0 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -101,6 +101,7 @@ When several agents use agent-device on one machine, each sets its own `AGENT_DE - **`close` gives the device back.** Simlock ends the lease and wipes the device for the next agent. - **`install` sends the app from your machine.** The path is on the agent's machine, and agent-device uploads it. A path on the worker is refused with `refused: send the app from your machine as an upload`. - **`devices` lists only your devices**, and an empty list before `open`. +- **`orientation` on an iPhone or iPad simulator goes through Simlock.** `agent-device orientation landscape-left` turns the simulator with Simlock's input helper, not agent-device's own rotation, and replies `Rotation requested: landscape-left (unconfirmed)`: the rotation was requested and nothing confirms the result. `portrait`, `portrait-upside-down`, `landscape-left` and `landscape-right` work, with the aliases `upside-down`, `left` and `right`; `auto` or any other name is refused with `Unknown orientation ; use portrait, portrait-upside-down, landscape-left or landscape-right`. A helper that cannot start fails the command with Simlock's `INPUT_UNAVAILABLE` message. On any other lease (Android, a physical iPhone or iPad, an Apple TV simulator) the command goes to agent-device as usual, and so does `orientation` as a step of a `batch`. ## On the same Mac