From d1f74bc24d6634c3220fa494ab202e4ae5c8af23 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:50:22 -0300 Subject: [PATCH 01/29] test: a holder's rotate of its iOS-simulator lease answers and sends the helper that orientation (#1107) --- .agents/scripts/protocol-bump-check.mjs | 1 + src/contract/index.ts | 1 + src/contract/operations.ts | 16 +++++ src/contract/orientation.ts | 7 +++ src/daemon/device-rotate.e2e.test.ts | 84 +++++++++++++++++++++++++ src/daemon/dispatcher.ts | 6 ++ src/gateway/dispatcher.ts | 6 ++ 7 files changed, 121 insertions(+) create mode 100644 src/contract/orientation.ts create mode 100644 src/daemon/device-rotate.e2e.test.ts diff --git a/.agents/scripts/protocol-bump-check.mjs b/.agents/scripts/protocol-bump-check.mjs index b45074bc7..da68d4e63 100644 --- a/.agents/scripts/protocol-bump-check.mjs +++ b/.agents/scripts/protocol-bump-check.mjs @@ -14,6 +14,7 @@ const NOT_SHAPES = new Set([ "index.ts", "console-url.ts", "duration.ts", + "orientation.ts", "os-range.ts", "version-order.ts", ]); diff --git a/src/contract/index.ts b/src/contract/index.ts index bc2d913ea..c4ed8d5e1 100644 --- a/src/contract/index.ts +++ b/src/contract/index.ts @@ -2,6 +2,7 @@ export * from "./console-url.js"; export * from "./duration.js"; export * from "./errors.js"; export * from "./operations.js"; +export * from "./orientation.js"; export * from "./os-range.js"; export * from "./protocol.js"; export * from "./pushes.js"; diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 42b9f090b..435b5be4b 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -7,6 +7,7 @@ import { EVENTS_PAGE_WITH_SINCE_MESSAGE, eventsPageWithoutSince, } from "./events-page.js"; +import { INPUT_ORIENTATIONS } from "./orientation.js"; import { parseOsConstraint } from "./os-range.js"; import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; @@ -1074,6 +1075,20 @@ const identityGet = defineOperation({ }), }); +/** + * why: turns a leased iOS phone or tablet simulator, through the lease's device input, whether or not the input module is on. + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const deviceRotate = defineOperation({ + name: "device.rotate", + role: "agent", + effect: "write", + input: z + .object({ leaseId: z.string().min(1).max(256), orientation: z.enum(INPUT_ORIENTATIONS) }) + .strict(), + output: z.object({ leaseId: z.string().max(256), orientation: z.enum(INPUT_ORIENTATIONS) }), +}); + export const OPERATIONS = { "identity.get": identityGet, "catalog.get": catalogGet, @@ -1086,6 +1101,7 @@ export const OPERATIONS = { "lease.get": leaseGet, "driver.passthrough": driverPassthrough, "device.exec": deviceExec, + "device.rotate": deviceRotate, "doctor.run": doctorRun, "lease.release-all": leaseReleaseAll, "list.get": listGet, diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts new file mode 100644 index 000000000..d4cc3829f --- /dev/null +++ b/src/contract/orientation.ts @@ -0,0 +1,7 @@ +// why: the four names a rotate takes over the contract and the input socket's `0x07` frame. +export const INPUT_ORIENTATIONS = [ + "portrait", + "portrait_upside_down", + "landscape_left", + "landscape_right", +] as const; diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts new file mode 100644 index 000000000..e559241a8 --- /dev/null +++ b/src/daemon/device-rotate.e2e.test.ts @@ -0,0 +1,84 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { FakeDriver, FakeInputFactory, fakeDeviceDataTables } from "../core/testing.js"; +import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import type { DispatchSession } from "./dispatch.js"; +import { startDaemon } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +const holder: DispatchSession = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "holder-1", + role: "agent", +}; + +describe("device.rotate", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + ); + }); + + async function worker(options: { + readonly inputModule: boolean; + readonly input: FakeInputFactory; + }) { + const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); + directories.push(dataDirectory); + const daemon = await startDaemon({ + configOverrides: { capabilities: { input: { enabled: options.inputModule } } }, + dataDirectory, + deviceDataTables: fakeDeviceDataTables, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + input: options.input, + knownModels: ["iPhone 15"], + platform: "ios", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + const granted = await daemon.dispatch( + "lease.request", + { model: "iPhone 15", platform: "ios" }, + holder, + ); + return { daemon, leaseId: (granted as { lease: { id: string } }).lease.id }; + } + + it( + "answers a holder's rotate of its iOS-simulator lease and sends the helper that orientation", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const { daemon, leaseId } = await worker({ input, inputModule: false }); + + const answer = await daemon.dispatch( + "device.rotate", + { leaseId, orientation: "landscape_left" }, + holder, + ); + + expect(answer).toEqual({ leaseId, orientation: "landscape_left" }); + expect(input.opened).toHaveLength(1); + expect(input.opened[0]?.sent).toEqual([ + { kind: "orientation", orientation: "landscape_left" }, + ]); + expect(input.opened[0]?.closes).toBe(1); + }, + ); +}); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 46a065717..f0e53343e 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -261,6 +261,7 @@ export class Dispatcher { "lease.get": this.#leaseGet, "driver.passthrough": this.#driverPassthrough, "device.exec": this.#deviceExec, + "device.rotate": this.#deviceRotate, "relay.request": this.#relayRequest, "relay.cancel": this.#relayCancel, "doctor.run": this.#doctorRun, @@ -657,6 +658,11 @@ export class Dispatcher { * so a command that writes a gigabyte costs this process nothing, and a client sees the * first line while the command is still running. */ + #deviceRotate: Handler<"device.rotate"> = async (input) => ({ + leaseId: input.leaseId, + orientation: "portrait", + }); + #deviceExec: Handler<"device.exec"> = async (input, session) => { if (this.options.passthrough === undefined) { throw new DispatchError("INTERNAL", "Tool passthrough is unavailable"); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index b4f41291f..36d51fbd4 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -280,6 +280,7 @@ export class GatewayDispatcher { "lease.cancel": this.#leaseCancel, "lease.release-all": this.#leaseReleaseAll, "device.exec": this.#deviceExec, + "device.rotate": this.#deviceRotate, "relay.request": relayRefused, "relay.cancel": relayRefused, // why: "daemon.stop" is absent for the same reason it is absent from the worker's table: the @@ -730,6 +731,11 @@ export class GatewayDispatcher { return { leaseIds: [...leaseIds] }; }; + #deviceRotate: Handler<"device.rotate"> = async (input) => ({ + leaseId: input.leaseId, + orientation: "portrait", + }); + #deviceExec: Handler<"device.exec"> = async (input, session) => this.options.coordinator.exec( { From a42ade373d49c6767571da627a0d07113c157b39 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:54:12 -0300 Subject: [PATCH 02/29] feat(daemon): device.rotate turns a leased simulator through its device input (#1107) --- src/contract/AGENTS.md | 2 +- src/contract/operations.test.ts | 10 +++++++ src/contract/protocol.ts | 2 +- src/core/fake-device-input.ts | 3 +- src/core/input.ts | 2 +- src/daemon-protocol/index.test.ts | 2 +- src/daemon/AGENTS.md | 2 +- src/daemon/dispatcher.ts | 33 +++++++++++++++++++--- src/daemon/main.ts | 3 ++ src/daemon/server.ts | 2 ++ src/drivers/android/input/device-input.ts | 31 +++++++++++--------- src/drivers/ios/input/device-input.test.ts | 5 ++-- src/drivers/ios/input/device-input.ts | 16 +++++------ src/input/sessions.ts | 2 +- 14 files changed, 80 insertions(+), 35 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index dd79e43dc..1e70704e4 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -57,7 +57,7 @@ Three identities: ## Protocol version -- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 66, max: 66 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 67, max: 67 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 533a1d4a1..bf402ba72 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -49,6 +49,11 @@ const ROLE_MATRIX: ReadonlyArray<{ input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, role: "agent", }, + { + name: "device.rotate", + input: { leaseId: "lease_1", orientation: "landscape_left" }, + role: "agent", + }, { name: "identity.get", input: {}, role: "agent" }, { name: "token.list", input: {}, role: "admin" }, { name: "token.revoke", input: { id: "tok_1" }, role: "admin" }, @@ -138,6 +143,11 @@ const EFFECT_MATRIX: ReadonlyArray<{ input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, effect: "write", }, + { + name: "device.rotate", + input: { leaseId: "lease_1", orientation: "landscape_left" }, + effect: "write", + }, { name: "identity.get", input: {}, effect: "read" }, { name: "token.list", input: {}, effect: "read" }, { name: "token.revoke", input: { id: "tok_1" }, effect: "write" }, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 5d4d09788..b6d73d4d2 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 66, max: 66 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 67, max: 67 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/fake-device-input.ts b/src/core/fake-device-input.ts index 24849529a..b018df012 100644 --- a/src/core/fake-device-input.ts +++ b/src/core/fake-device-input.ts @@ -18,8 +18,9 @@ class FakeDeviceInput implements DeviceInput { this.#config = config; } - send(message: InputMessage): void { + send(message: InputMessage): Promise { this.sent.push(message); + return Promise.resolve(); } onConfig(listener: (config: InputScreenConfig) => void): () => void { diff --git a/src/core/input.ts b/src/core/input.ts index 7fe304b84..ea69da8cb 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -85,7 +85,7 @@ export type InputMessage = // why: what turns messages into taps on one device; one per lease, shared by every socket of it. export interface DeviceInput { - send(message: InputMessage): void; + send(message: InputMessage): Promise; // why: calls the listener with the current screen config at once, then on each change, so a socket // that joins late learns the size as it is now. onConfig(listener: (config: InputScreenConfig) => void): () => void; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 34803f777..64b593c20 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(66); + expect(DAEMON_PROTOCOL_VERSION).toBe(67); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 9292ae23e..20170b255 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -59,7 +59,7 @@ Its stdout lines move the state; a failed line, a non-zero exit or a failed laun 2. **Hello** — first frame must be `hello`, else `HANDSHAKE_REQUIRED` and close. Role: the uplink connection is `admin` by acceptance; otherwise the resolver. Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 66, max: 66 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 67, max: 67 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`. diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index f0e53343e..758e2e6ea 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -34,9 +34,11 @@ import { type WarmPoolReader, type CatalogReader, type PassthroughResolver, + isUnavailableInput, createUsageReader, type UsageReader, } from "../core/index.js"; +import type { ModuleInputs } from "../modules/index.js"; import { type DeviceModeReader, LeaseIdTakenError, @@ -143,6 +145,8 @@ export interface DispatcherOptions { readonly warmKinds?: WarmKindForgetter; readonly enrollment?: Pick; readonly passthrough?: PassthroughResolver; + /** why: the lease's device input, which `device.rotate` writes to; optional so tests that never rotate need none. */ + readonly inputs?: ModuleInputs; readonly processRunner?: ProcessRunner; /** * why: The environment a `device.exec` child starts from, before the driver's own scoping keys are @@ -658,10 +662,31 @@ export class Dispatcher { * so a command that writes a gigabyte costs this process nothing, and a client sees the * first line while the command is still running. */ - #deviceRotate: Handler<"device.rotate"> = async (input) => ({ - leaseId: input.leaseId, - orientation: "portrait", - }); + #deviceRotate: Handler<"device.rotate"> = async (input) => { + if (this.options.inputs === undefined) { + throw new DispatchError("INTERNAL", "Device input is unavailable"); + } + const lease = this.options.registry.snapshot.leases.find( + (candidate) => candidate.id === input.leaseId, + ); + if (lease === undefined) throw new UnknownLeaseError(input.leaseId); + const record = this.options.registry.snapshot.devices.find( + (candidate) => candidate.id === lease.deviceId, + ); + if (record === undefined) throw new UnknownLeaseError(input.leaseId); + const opened = await this.options.inputs.openInput( + record.spec.platform, + toDriverDevice(record), + new AbortController().signal, + ); + if (isUnavailableInput(opened)) throw new Error(opened.unavailable); + try { + await opened.send({ kind: "orientation", orientation: input.orientation }); + } finally { + await opened.close(); + } + return { leaseId: input.leaseId, orientation: input.orientation }; + }; #deviceExec: Handler<"device.exec"> = async (input, session) => { if (this.options.passthrough === undefined) { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 1e4853885..dded5b301 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -665,6 +665,9 @@ async function composeDaemon( logger: logger.child("server"), ...(options.protocolVersion === undefined ? {} : { protocolVersion: options.protocolVersion }), passthrough: core.catalog, + inputs: { + openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), + }, processRunner, execEnv: execBaseEnvironment(process.env), queue: leasing, diff --git a/src/daemon/server.ts b/src/daemon/server.ts index f5e056aaa..0aa1bce23 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -163,6 +163,7 @@ export interface DaemonServerEngineOptions { readonly nuke?: Nuke; readonly warmKinds?: WarmKindForgetter; readonly passthrough?: PassthroughResolver; + readonly inputs?: DispatcherOptions["inputs"]; readonly processRunner?: ProcessRunner; readonly relayTargets?: RelayTargets; readonly relayTwoWayTargets?: TwoWayRelayTargets; @@ -315,6 +316,7 @@ function buildDispatcher( ...(options.nuke === undefined ? {} : { nuke: options.nuke }), ...(options.warmKinds === undefined ? {} : { warmKinds: options.warmKinds }), ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }), + ...(options.inputs === undefined ? {} : { inputs: options.inputs }), ...(options.processRunner === undefined ? {} : { processRunner: options.processRunner }), ...(options.execEnv === undefined ? {} : { execEnv: options.execEnv }), queue: options.queue, diff --git a/src/drivers/android/input/device-input.ts b/src/drivers/android/input/device-input.ts index 1436e2aaa..e736ef8ed 100644 --- a/src/drivers/android/input/device-input.ts +++ b/src/drivers/android/input/device-input.ts @@ -187,34 +187,37 @@ class AndroidDeviceInput implements DeviceInput { // why: a rotation is dropped: scrcpy's only one (ROTATE_DEVICE) toggles between rotations 0 and 1 // through the window manager's rotation lock, so it can name neither upside down nor a landscape side. - send(message: InputMessage): void { + send(message: InputMessage): Promise { const size = this.#config; - if (size === undefined) return; - if (message.kind === "touch") this.#write(touchPacket(message, size)); - else if (message.kind === "scroll") this.#write(scrollPacket(message, size)); - else if (message.kind === "button") this.#press(BUTTON_KEYCODES[message.button]); - else if (message.kind === "key") this.#key(message.type, message.usage); + if (size === undefined) return Promise.resolve(); + if (message.kind === "touch") return this.#write(touchPacket(message, size)); + if (message.kind === "scroll") return this.#write(scrollPacket(message, size)); + if (message.kind === "button") return this.#press(BUTTON_KEYCODES[message.button]); + if (message.kind === "key") return this.#key(message.type, message.usage); + return Promise.resolve(); } - #press(keycode: number): void { - this.#write(keycodePacket("down", keycode, this.#meta)); - this.#write(keycodePacket("up", keycode, this.#meta)); + async #press(keycode: number): Promise { + await Promise.all([ + this.#write(keycodePacket("down", keycode, this.#meta)), + this.#write(keycodePacket("up", keycode, this.#meta)), + ]); } // why: a modifier is held in the meta state of every later key until its `up`; it joins the state // before its own down and leaves it before its own up, as Android's events carry it. - #key(type: "down" | "up", usage: number): void { + #key(type: "down" | "up", usage: number): Promise { const keycode = keycodeOf(usage); - if (keycode === undefined) return; + if (keycode === undefined) return Promise.resolve(); const modifier = modifierOf(usage); if (modifier !== undefined) { this.#meta = type === "down" ? this.#meta | modifier.meta : this.#meta & ~modifier.meta; } - this.#write(keycodePacket(type, keycode, this.#meta)); + return this.#write(keycodePacket(type, keycode, this.#meta)); } - #write(packet: Uint8Array): void { - void this.#stream?.write(packet).catch(() => undefined); + #write(packet: Uint8Array): Promise { + return (this.#stream?.write(packet) ?? Promise.resolve()).catch(() => undefined); } onConfig(listener: (config: InputScreenConfig) => void): () => void { diff --git a/src/drivers/ios/input/device-input.test.ts b/src/drivers/ios/input/device-input.test.ts index 4f3b94a88..c6f7e3d82 100644 --- a/src/drivers/ios/input/device-input.test.ts +++ b/src/drivers/ios/input/device-input.test.ts @@ -222,8 +222,9 @@ describe("iOS device input", () => { const failures: string[] = []; input.onFailed((error) => failures.push(error.message)); broken.launcher.last.writeError = new Error("write EPIPE"); - input.send({ kind: "touch", type: "begin", x: 0.5, y: 0.5 }); - await new Promise((resolve) => setImmediate(resolve)); + await expect(input.send({ kind: "touch", type: "begin", x: 0.5, y: 0.5 })).rejects.toThrow( + "The input helper stopped taking input: write EPIPE", + ); expect(failures).toEqual(["The input helper stopped taking input: write EPIPE"]); expect(broken.launcher.last.stdinClosed).toBe(true); }); diff --git a/src/drivers/ios/input/device-input.ts b/src/drivers/ios/input/device-input.ts index 1ca0ced3a..ea34aad6e 100644 --- a/src/drivers/ios/input/device-input.ts +++ b/src/drivers/ios/input/device-input.ts @@ -172,18 +172,18 @@ class IosDeviceInput implements DeviceInput { this.#config = config; } - send(message: InputMessage): void { + send(message: InputMessage): Promise { if (message.kind === "button") { if (message.button === "home") this.#home(); - return; + return Promise.resolve(); } - if (message.kind === "key" && !this.#keys) return; - this.#child.writeStdin(frameOfMessage(message)).catch((error: unknown) => { - this.#fail( - new Error( - `The input helper stopped taking input: ${error instanceof Error ? error.message : String(error)}`, - ), + if (message.kind === "key" && !this.#keys) return Promise.resolve(); + return this.#child.writeStdin(frameOfMessage(message)).catch((error: unknown) => { + const failure = new Error( + `The input helper stopped taking input: ${error instanceof Error ? error.message : String(error)}`, ); + this.#fail(failure); + throw failure; }); } diff --git a/src/input/sessions.ts b/src/input/sessions.ts index 4e4e933cc..bf03daa30 100644 --- a/src/input/sessions.ts +++ b/src/input/sessions.ts @@ -189,7 +189,7 @@ export function createInputSessions(options: { ); return; } - opened.send(message); + opened.send(message).catch(() => undefined); }); } From fe1c1974d01119ff62f2f7a7c58d480877244005 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:57:26 -0300 Subject: [PATCH 03/29] test: a caller rotates a lease it may not touch, or names a bad orientation, and is refused (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/operations.ts | 6 ++++- src/daemon/device-rotate.e2e.test.ts | 33 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 435b5be4b..6626cd32c 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1084,7 +1084,11 @@ export const deviceRotate = defineOperation({ role: "agent", effect: "write", input: z - .object({ leaseId: z.string().min(1).max(256), orientation: z.enum(INPUT_ORIENTATIONS) }) + .object({ + leaseId: z.string().min(1).max(256), + orientation: z.enum(INPUT_ORIENTATIONS), + requesterId: z.string().min(1).max(256).optional(), + }) .strict(), output: z.object({ leaseId: z.string().max(256), orientation: z.enum(INPUT_ORIENTATIONS) }), }); diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index e559241a8..4594486c7 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -81,4 +81,37 @@ describe("device.rotate", () => { expect(input.opened[0]?.closes).toBe(1); }, ); + + it( + "refuses a caller that rotates a lease it may not touch, or names a bad orientation", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const { daemon, leaseId } = await worker({ input, inputModule: false }); + const other: DispatchSession = { ...holder, principal: "holder-2" }; + const admin: DispatchSession = { ...holder, principal: "gateway-1", role: "admin" }; + const orientation = "landscape_left"; + + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation }, holder), + ).resolves.toEqual({ leaseId, orientation }); + + const refused: readonly (readonly [object, unknown, DispatchSession])[] = [ + [{ name: "UnknownLeaseError" }, { leaseId: "nope", orientation }, holder], + [{ code: "FORBIDDEN" }, { leaseId, orientation }, other], + [{ code: "FORBIDDEN" }, { leaseId, orientation, requesterId: "holder-1" }, holder], + [{ code: "FORBIDDEN" }, { leaseId, orientation, requesterId: "someone-else" }, admin], + [{ code: "BAD_REQUEST" }, { leaseId, orientation: "landscape-left" }, holder], + [{ code: "BAD_REQUEST" }, { leaseId, orientation: "auto" }, holder], + [{ code: "BAD_REQUEST" }, { leaseId, orientation: "" }, holder], + ]; + for (const [expected, body, session] of refused) { + await expect( + daemon.dispatch("device.rotate", body as never, session), + JSON.stringify(body), + ).rejects.toMatchObject(expected); + } + expect(input.opened).toHaveLength(1); + }, + ); }); From 2f1ebec54bb5a9ce3b8a565d89631c0bc3cbc7bb Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 00:57:53 -0300 Subject: [PATCH 04/29] feat(contract): device.rotate is authorized like device.exec (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 2 +- src/contract/operations.ts | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 1e70704e4..6bad06eb6 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -45,7 +45,7 @@ every operation but `daemon.stop`, which `DaemonServer` answers. - `lease.renew`, `lease.release` — `ownsLease`: admin, or `ownerId` = principal. - `lease.cancel` — admin, or the pending request's owner = principal. -- `device.exec` — agent: owns the lease and names no `requesterId`. Admin: the lease's +- `device.exec`, `device.rotate` — agent: owns the lease and names no `requesterId`. Admin: the lease's requester = `requesterId` (default: principal). Three identities: diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 6626cd32c..e4820578b 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -486,16 +486,7 @@ export const deviceExec = defineOperation({ * authorized, the same convention `ownsLease` uses, so the handler's own `UNKNOWN_LEASE` * surfaces instead of a misleading `FORBIDDEN`. */ - authorize: (input, context) => { - if (context.role !== "admin") { - if (input.requesterId !== undefined) return false; - const ownerId = context.ownerId(input.leaseId); - return ownerId === undefined || ownerId === context.principal; - } - const requesterId = input.requesterId ?? context.principal; - const leaseRequesterId = context.leaseRequesterId(input.leaseId); - return leaseRequesterId === undefined || leaseRequesterId === requesterId; - }, + authorize: authorizeOneLeaseCall, }); /** @@ -1075,6 +1066,23 @@ const identityGet = defineOperation({ }), }); +/** + * why: `device.exec`'s and `device.rotate`'s one rule, so a gateway's admin session is held to the lease's requester on both. + */ +function authorizeOneLeaseCall( + input: { readonly leaseId: string; readonly requesterId?: string | undefined }, + context: AuthorizeContext, +): boolean { + if (context.role !== "admin") { + if (input.requesterId !== undefined) return false; + const ownerId = context.ownerId(input.leaseId); + return ownerId === undefined || ownerId === context.principal; + } + const requesterId = input.requesterId ?? context.principal; + const leaseRequesterId = context.leaseRequesterId(input.leaseId); + return leaseRequesterId === undefined || leaseRequesterId === requesterId; +} + /** * why: turns a leased iOS phone or tablet simulator, through the lease's device input, whether or not the input module is on. */ @@ -1091,6 +1099,7 @@ export const deviceRotate = defineOperation({ }) .strict(), output: z.object({ leaseId: z.string().max(256), orientation: z.enum(INPUT_ORIENTATIONS) }), + authorize: authorizeOneLeaseCall, }); export const OPERATIONS = { From e54e3f2f6dbd0f96c285ca2aae4a0b418e52845b Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:00:33 -0300 Subject: [PATCH 05/29] test: a holder rotates a lease not on an iOS phone or tablet simulator and gets ROTATION_UNSUPPORTED naming it (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 117 ++++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 1 deletion(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 4594486c7..10d7092e0 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -31,6 +31,7 @@ describe("device.rotate", () => { async function worker(options: { readonly inputModule: boolean; readonly input: FakeInputFactory; + readonly androidInput?: FakeInputFactory; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); @@ -43,9 +44,24 @@ describe("device.rotate", () => { availableOsVersions: ["18.0"], clock: new SystemClock(), input: options.input, - knownModels: ["iPhone 15"], + knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], + physicalDevices: [ + { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, + { class: "tablet", ids: ["TABLET-1"], model: "iPad Pro", osVersion: "18.0" }, + ], platform: "ios", }), + new FakeDriver({ + availableOsVersions: ["15"], + clock: new SystemClock(), + ...(options.androidInput === undefined ? {} : { input: options.androidInput }), + knownModels: ["Pixel 8"], + physicalDevices: [ + { class: "phone", ids: ["DROID-1"], model: "Pixel 8", osVersion: "15" }, + { class: "tablet", ids: ["DROID-2"], model: "Pixel Tablet", osVersion: "15" }, + ], + platform: "android", + }), ], filesystem: new MemoryFilesystem(), logger: new NoopLogger(), @@ -114,4 +130,103 @@ describe("device.rotate", () => { expect(input.opened).toHaveLength(1); }, ); + + it( + "refuses a holder's rotate of a lease not on an iOS phone or tablet simulator with ROTATION_UNSUPPORTED naming it", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const androidInput = new FakeInputFactory({ + height: 2400, + orientation: "portrait", + width: 1080, + }); + const { daemon } = await worker({ androidInput, input, inputModule: false }); + const admin: DispatchSession = { ...holder, principal: "admin-1", role: "admin" }; + const orientation = "landscape_left"; + + async function lease(principal: string, request: object, enroll?: string) { + const session: DispatchSession = { ...holder, principal }; + if (enroll !== undefined) { + await daemon.dispatch( + "device.add", + { id: enroll, platform: (request as { platform: "ios" | "android" }).platform }, + admin, + ); + } + const granted = await daemon.dispatch("lease.request", request as never, session); + return { id: (granted as { lease: { id: string } }).lease.id, session }; + } + + const cases: readonly (readonly [string, object, string | undefined, string, object])[] = [ + [ + "tv", + { model: "Apple TV 4K", platform: "ios" }, + undefined, + "an Apple TV simulator", + { class: "tv", physical: false, platform: "ios" }, + ], + [ + "unknown family", + { model: "Mystery Box", platform: "ios" }, + undefined, + "a Mystery Box simulator", + { class: "unknown", physical: false, platform: "ios" }, + ], + [ + "emulator", + { model: "Pixel 8", platform: "android" }, + undefined, + "an Android emulator", + { class: "emulator", physical: false, platform: "android" }, + ], + [ + "android phone", + { model: "Pixel 8", physical: true, platform: "android" }, + "DROID-1", + "an Android phone", + { class: "phone", physical: true, platform: "android" }, + ], + [ + "android tablet", + { model: "Pixel Tablet", physical: true, platform: "android" }, + "DROID-2", + "an Android tablet", + { class: "tablet", physical: true, platform: "android" }, + ], + [ + "iphone", + { model: "iPhone 15", physical: true, platform: "ios" }, + "PHONE-1", + "an iPhone", + { class: "phone", physical: true, platform: "ios" }, + ], + [ + "ipad", + { model: "iPad Pro", physical: true, platform: "ios" }, + "TABLET-1", + "an iPad", + { class: "tablet", physical: true, platform: "ios" }, + ], + ]; + for (const [name, request, enroll, phrase, details] of cases) { + const { id, session } = await lease(`holder-${name}`, request, enroll); + await expect( + daemon.dispatch("device.rotate", { leaseId: id, orientation }, session), + name, + ).rejects.toMatchObject({ + code: "ROTATION_UNSUPPORTED", + details: { leaseId: id, ...details }, + message: `Lease ${id} is on ${phrase}; only an iOS simulator can be rotated`, + }); + } + + const ipad = await lease("holder-ipad-simulator", { model: "iPad Pro", platform: "ios" }); + await expect( + daemon.dispatch("device.rotate", { leaseId: ipad.id, orientation }, ipad.session), + ).resolves.toEqual({ leaseId: ipad.id, orientation }); + expect(input.opened).toHaveLength(1); + expect(androidInput.opened).toHaveLength(0); + }, + ); }); From 18acbd706ee6c3b3925a47d8fd7a09fab8cb9b13 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:03:17 -0300 Subject: [PATCH 06/29] feat(daemon): device.rotate refuses a lease not on an iOS phone or tablet simulator (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/errors.ts | 15 ++++++ src/contract/orientation.ts | 20 +++++++ src/daemon/AGENTS.md | 1 + src/daemon/device-rotate.e2e.test.ts | 54 ++++++++++--------- src/daemon/dispatcher.ts | 3 ++ src/daemon/rotation-refusal.ts | 38 +++++++++++++ .../content/docs/docs/reference/errors.mdx | 3 +- 7 files changed, 107 insertions(+), 27 deletions(-) create mode 100644 src/daemon/rotation-refusal.ts diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 9a285ab4e..7e76418c7 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -100,6 +100,13 @@ export interface ErrorDetailsMap { PASSTHROUGH_REFUSED: { readonly tool: string }; UNKNOWN_PASSTHROUGH_TOOL: { readonly tool: string }; EXEC_TIMEOUT: Record; + /** why: `device.rotate` on a lease that is not on an iOS phone or tablet simulator; `class` is the physical class, the simulator's model family, or `emulator`. */ + ROTATION_UNSUPPORTED: { + readonly leaseId: string; + readonly platform: Platform; + readonly physical: boolean; + readonly class: string; + }; DOCTOR_UNAVAILABLE: Record; HISTORY_NOT_KEPT: { readonly oldestTs: number }; HISTORY_UNAVAILABLE: Record; @@ -193,6 +200,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record DOWNLOADS_DISABLED: true, COMPONENT_IN_USE: true, UNKNOWN_LEASE: true, + ROTATION_UNSUPPORTED: true, DEVICE_NOT_ENROLLABLE: true, DEVICE_BUSY: true, UNKNOWN_DEVICE: true, @@ -344,6 +352,13 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry // out of time" outcome (`QUEUE_TIMEOUT`) already uses -- so a script branching on "timed // out" does not need a second number for the second kind of wait. EXEC_TIMEOUT: { code: "EXEC_TIMEOUT", kind: "domain", cliExitCode: 10, httpStatus: 504 }, + // why: a fact about the lease's device, as `RUNTIME_MISSING` is about the host: 422 and 12. + ROTATION_UNSUPPORTED: { + code: "ROTATION_UNSUPPORTED", + kind: "domain", + cliExitCode: 12, + httpStatus: 422, + }, DOWNLOAD_TIMEOUT: { code: "DOWNLOAD_TIMEOUT", kind: "domain", diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index d4cc3829f..03849a8fc 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -5,3 +5,23 @@ export const INPUT_ORIENTATIONS = [ "landscape_left", "landscape_right", ] as const; + +export type ModelFamily = "phone" | "tablet" | "tv" | "watch" | "vision" | "unknown"; + +const MODEL_FAMILY_PREFIXES: readonly (readonly [string, ModelFamily])[] = [ + ["iPhone", "phone"], + ["iPad", "tablet"], + ["Apple TV", "tv"], + ["Apple Watch", "watch"], + ["Apple Vision", "vision"], +]; + +// why: every model the iOS driver lists starts with its product family's name, and the device record keeps only the model. +export function modelFamily(model: string): ModelFamily { + return MODEL_FAMILY_PREFIXES.find(([prefix]) => model.startsWith(prefix))?.[1] ?? "unknown"; +} + +export function isRotatableModel(model: string): boolean { + const family = modelFamily(model); + return family === "phone" || family === "tablet"; +} diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 20170b255..1e869f459 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -25,6 +25,7 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs | `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | | `error-code.ts` | `classifyError`: thrown error → contract code | | `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | +| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | | `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | | `test-relay-support.ts` | Test helpers for relay e2e tests | diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 10d7092e0..71003eb26 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -35,34 +35,35 @@ describe("device.rotate", () => { }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); + const drivers = [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + input: options.input, + knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], + physicalDevices: [ + { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, + { class: "tablet", ids: ["TABLET-1"], model: "iPad Pro", osVersion: "18.0" }, + ], + platform: "ios", + }), + new FakeDriver({ + availableOsVersions: ["15"], + clock: new SystemClock(), + ...(options.androidInput === undefined ? {} : { input: options.androidInput }), + knownModels: ["Pixel 8"], + physicalDevices: [ + { class: "phone", ids: ["DROID-1"], model: "Pixel 8", osVersion: "15" }, + { class: "tablet", ids: ["DROID-2"], model: "Pixel Tablet", osVersion: "15" }, + ], + platform: "android", + }), + ]; const daemon = await startDaemon({ configOverrides: { capabilities: { input: { enabled: options.inputModule } } }, dataDirectory, deviceDataTables: fakeDeviceDataTables, - drivers: [ - new FakeDriver({ - availableOsVersions: ["18.0"], - clock: new SystemClock(), - input: options.input, - knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], - physicalDevices: [ - { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, - { class: "tablet", ids: ["TABLET-1"], model: "iPad Pro", osVersion: "18.0" }, - ], - platform: "ios", - }), - new FakeDriver({ - availableOsVersions: ["15"], - clock: new SystemClock(), - ...(options.androidInput === undefined ? {} : { input: options.androidInput }), - knownModels: ["Pixel 8"], - physicalDevices: [ - { class: "phone", ids: ["DROID-1"], model: "Pixel 8", osVersion: "15" }, - { class: "tablet", ids: ["DROID-2"], model: "Pixel Tablet", osVersion: "15" }, - ], - platform: "android", - }), - ], + drivers, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), version: "1.0.0-e2e", @@ -73,7 +74,7 @@ describe("device.rotate", () => { { model: "iPhone 15", platform: "ios" }, holder, ); - return { daemon, leaseId: (granted as { lease: { id: string } }).lease.id }; + return { daemon, drivers, leaseId: (granted as { lease: { id: string } }).lease.id }; } it( @@ -141,13 +142,14 @@ describe("device.rotate", () => { orientation: "portrait", width: 1080, }); - const { daemon } = await worker({ androidInput, input, inputModule: false }); + const { daemon, drivers } = await worker({ androidInput, input, inputModule: false }); const admin: DispatchSession = { ...holder, principal: "admin-1", role: "admin" }; const orientation = "landscape_left"; async function lease(principal: string, request: object, enroll?: string) { const session: DispatchSession = { ...holder, principal }; if (enroll !== undefined) { + for (const driver of drivers) driver.setPhysicalPresence(enroll, true); await daemon.dispatch( "device.add", { id: enroll, platform: (request as { platform: "ios" | "android" }).platform }, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 758e2e6ea..2e513b0c4 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -39,6 +39,7 @@ import { type UsageReader, } from "../core/index.js"; import type { ModuleInputs } from "../modules/index.js"; +import { rotationRefusal } from "./rotation-refusal.js"; import { type DeviceModeReader, LeaseIdTakenError, @@ -674,6 +675,8 @@ export class Dispatcher { (candidate) => candidate.id === lease.deviceId, ); if (record === undefined) throw new UnknownLeaseError(input.leaseId); + const refusal = rotationRefusal(input.leaseId, record.spec); + if (refusal !== undefined) throw refusal; const opened = await this.options.inputs.openInput( record.spec.platform, toDriverDevice(record), diff --git a/src/daemon/rotation-refusal.ts b/src/daemon/rotation-refusal.ts new file mode 100644 index 000000000..468bb0fff --- /dev/null +++ b/src/daemon/rotation-refusal.ts @@ -0,0 +1,38 @@ +import { isRotatableModel, modelFamily } from "../contract/index.js"; +import type { DeviceSpec } from "../core/index.js"; +import { DispatchError } from "./dispatch.js"; + +const SIMULATOR_NAMES = { + tv: "an Apple TV simulator", + vision: "an Apple Vision simulator", + watch: "an Apple Watch simulator", +} as const; + +function describeTarget(spec: DeviceSpec): { readonly phrase: string; readonly class: string } { + if (spec.physical) { + const phrase = + spec.platform === "android" + ? `an Android ${spec.class}` + : spec.class === "phone" + ? "an iPhone" + : "an iPad"; + return { class: spec.class, phrase }; + } + if (spec.platform === "android") return { class: "emulator", phrase: "an Android emulator" }; + const family = modelFamily(spec.model); + if (family === "tv" || family === "watch" || family === "vision") { + return { class: family, phrase: SIMULATOR_NAMES[family] }; + } + return { class: family, phrase: `a ${spec.model} simulator` }; +} + +/** why: the one place that says which leases `device.rotate` turns, and how a refusal names the device. */ +export function rotationRefusal(leaseId: string, spec: DeviceSpec): DispatchError | undefined { + if (!spec.physical && spec.platform === "ios" && isRotatableModel(spec.model)) return undefined; + const target = describeTarget(spec); + return new DispatchError( + "ROTATION_UNSUPPORTED", + `Lease ${leaseId} is on ${target.phrase}; only an iOS simulator can be rotated`, + { class: target.class, leaseId, physical: spec.physical, platform: spec.platform }, + ); +} diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 8caa70698..97d88469e 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -26,7 +26,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | 2 | `USAGE`, `BAD_REQUEST`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | -| 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | +| 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `ROTATION_UNSUPPORTED`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | | 13 | `REQUESTER_ALREADY_LEASED`, `LEASE_ID_TAKEN` | The request clashes with a lease or request that already exists. | | 14 | — | `simlock lease` without `--detach`: the daemon ended the lease before you did (expiry, an operator's release, or a device that could not be recovered). The `lease-lost` line on stderr gives the reason. | | 15 | — | `simlock component install` with `--worker` or `--all-workers`: at least one worker did not end `installed` or `already-installed`. The result on stdout says which. | @@ -79,6 +79,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | `PASSTHROUGH_REFUSED` | 2 | 422 | Simlock refuses this `simctl`, `adb` or `devicectl` command: a verb that creates, erases or deletes devices or touches every device at once (such as `simctl erase` or `adb kill-server`), a flag that points the tool at another device set or adb server, `simctl` on a physical device, `simctl` or `adb` on a lease of the other platform, a `device.exec` command that names a device other than the lease's (`booted`, another UDID, `adb -s` with another serial, `-e`, `-d`, `-t`, a different `devicectl --device`), or `adb shell` with no command where there is no terminal. | Drop the refused flag or verb, leave the device out of the command, or name the command to run. The message says which. | | `UNKNOWN_PASSTHROUGH_TOOL` | 2 | 422 | A tool Simlock does not wrap. | Use `simctl` or `adb`. | | `EXEC_TIMEOUT` | 10 | 504 | A command run on a device through a gateway ran longer than `exec.timeoutMs` (10 minutes by default) and was stopped. | Split the work, or raise `exec.timeoutMs` on the worker. | +| `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | ## Daemon and connection From 642a3922f5e2f6dad55c5674bcb84d8b4c239c69 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:04:11 -0300 Subject: [PATCH 07/29] test: a holder rotates when the helper cannot start or the write fails and gets INPUT_UNAVAILABLE with the reason (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-input.ts | 7 +++ src/daemon/device-rotate.e2e.test.ts | 74 +++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/core/fake-device-input.ts b/src/core/fake-device-input.ts index b018df012..5e560a4fc 100644 --- a/src/core/fake-device-input.ts +++ b/src/core/fake-device-input.ts @@ -14,11 +14,15 @@ class FakeDeviceInput implements DeviceInput { readonly #failedListeners = new Set<(error: Error) => void>(); #config: InputScreenConfig; + // why: a test sets this to make every write fail, as a helper whose pipe broke does. + sendFailure: Error | undefined; + constructor(config: InputScreenConfig) { this.#config = config; } send(message: InputMessage): Promise { + if (this.sendFailure !== undefined) return Promise.reject(this.sendFailure); this.sent.push(message); return Promise.resolve(); } @@ -57,6 +61,8 @@ export class FakeInputFactory implements DeviceInputFactory { failWith: Error | undefined; // why: a test sets this to hold every open until it resolves, to end a lease while a socket is still opening. gate: Promise | undefined; + // why: a test sets this to make the writes of the inputs it opens next fail. + sendFailure: Error | undefined; opens = 0; constructor(private readonly config: InputScreenConfig) {} @@ -66,6 +72,7 @@ export class FakeInputFactory implements DeviceInputFactory { await this.gate; if (this.failWith !== undefined) throw this.failWith; const input = new FakeDeviceInput(this.config); + input.sendFailure = this.sendFailure; this.opened.push(input); return input; } diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 71003eb26..6e880dc7e 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -30,7 +30,7 @@ describe("device.rotate", () => { async function worker(options: { readonly inputModule: boolean; - readonly input: FakeInputFactory; + readonly input: FakeInputFactory | undefined; readonly androidInput?: FakeInputFactory; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); @@ -39,7 +39,7 @@ describe("device.rotate", () => { new FakeDriver({ availableOsVersions: ["18.0"], clock: new SystemClock(), - input: options.input, + ...(options.input === undefined ? {} : { input: options.input }), knownModels: ["iPhone 15", "iPad Pro", "Apple TV 4K", "Mystery Box"], physicalDevices: [ { class: "phone", ids: ["PHONE-1"], model: "iPhone 15", osVersion: "18.0" }, @@ -231,4 +231,74 @@ describe("device.rotate", () => { expect(androidInput.opened).toHaveLength(0); }, ); + + it( + "refuses a holder's rotate with INPUT_UNAVAILABLE and the reason when the helper cannot start or the write fails", + { timeout: 60_000 }, + async () => { + const screen = { height: 2556, orientation: "portrait", width: 1179 } as const; + const cut = "x".repeat(300); + const cases: readonly (readonly [ + string, + (input: FakeInputFactory) => void, + string, + boolean, + ])[] = [ + ["no factory", () => undefined, "ios devices take no input", false], + [ + "open rejects", + (input) => { + input.failWith = new Error("helper exploded"); + }, + "helper exploded", + true, + ], + [ + "open rejects with a long message", + (input) => { + input.failWith = new Error(cut); + }, + "x".repeat(200), + true, + ], + [ + "open rejects with no message", + (input) => { + input.failWith = new Error(""); + }, + "unknown error", + true, + ], + [ + "write rejects", + (input) => { + input.sendFailure = new Error("pipe closed"); + }, + "pipe closed", + true, + ], + ]; + for (const [name, arrange, reason, hasFactory] of cases) { + const input = new FakeInputFactory(screen); + arrange(input); + const { daemon, leaseId } = await worker({ + input: hasFactory ? input : undefined, + inputModule: false, + }); + + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation: "landscape_left" }, holder), + name, + ).rejects.toMatchObject({ + code: "INPUT_UNAVAILABLE", + details: { leaseId, reason }, + message: `Lease ${leaseId}'s simulator cannot take input: ${reason}`, + }); + expect( + input.opened.map((opened) => opened.closes), + name, + ).toEqual(input.opened.map(() => 1)); + } + }, + ); }); From 770e4f0635fe895a534b4ee9496c3851543f2df4 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:05:07 -0300 Subject: [PATCH 08/29] feat(daemon): device.rotate answers INPUT_UNAVAILABLE with the reason when the helper or the write fails (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/errors.ts | 5 +++ src/daemon/device-rotate.e2e.test.ts | 1 + src/daemon/dispatcher.ts | 34 ++++++++++++++----- .../content/docs/docs/reference/errors.mdx | 3 +- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 7e76418c7..546f96c76 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -107,6 +107,8 @@ export interface ErrorDetailsMap { readonly physical: boolean; readonly class: string; }; + /** why: `device.rotate` could not reach the lease's input helper; `reason` is the driver's text, cut to 200 characters. */ + INPUT_UNAVAILABLE: { readonly leaseId: string; readonly reason: string }; DOCTOR_UNAVAILABLE: Record; HISTORY_NOT_KEPT: { readonly oldestTs: number }; HISTORY_UNAVAILABLE: Record; @@ -201,6 +203,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record COMPONENT_IN_USE: true, UNKNOWN_LEASE: true, ROTATION_UNSUPPORTED: true, + INPUT_UNAVAILABLE: true, DEVICE_NOT_ENROLLABLE: true, DEVICE_BUSY: true, UNKNOWN_DEVICE: true, @@ -359,6 +362,8 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry cliExitCode: 12, httpStatus: 422, }, + // why: the helper that takes the touch is down, like `DOCTOR_UNAVAILABLE`: 503 and 1. + INPUT_UNAVAILABLE: { code: "INPUT_UNAVAILABLE", kind: "domain", cliExitCode: 1, httpStatus: 503 }, DOWNLOAD_TIMEOUT: { code: "DOWNLOAD_TIMEOUT", kind: "domain", diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 6e880dc7e..7f9715631 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -298,6 +298,7 @@ describe("device.rotate", () => { input.opened.map((opened) => opened.closes), name, ).toEqual(input.opened.map(() => 1)); + await daemons.pop()?.stop("test"); } }, ); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 2e513b0c4..7cfb0825b 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -677,16 +677,20 @@ export class Dispatcher { if (record === undefined) throw new UnknownLeaseError(input.leaseId); const refusal = rotationRefusal(input.leaseId, record.spec); if (refusal !== undefined) throw refusal; - const opened = await this.options.inputs.openInput( - record.spec.platform, - toDriverDevice(record), - new AbortController().signal, - ); - if (isUnavailableInput(opened)) throw new Error(opened.unavailable); try { - await opened.send({ kind: "orientation", orientation: input.orientation }); - } finally { - await opened.close(); + const opened = await this.options.inputs.openInput( + record.spec.platform, + toDriverDevice(record), + new AbortController().signal, + ); + if (isUnavailableInput(opened)) throw new Error(opened.unavailable); + try { + await opened.send({ kind: "orientation", orientation: input.orientation }); + } finally { + await opened.close(); + } + } catch (error) { + throw inputUnavailable(input.leaseId, error); } return { leaseId: input.leaseId, orientation: input.orientation }; }; @@ -1135,6 +1139,18 @@ function describeEnrollmentError(error: unknown): unknown { return error; } +const INPUT_REASON_MAX = 200; + +function inputUnavailable(leaseId: string, error: unknown): DispatchError { + const text = error instanceof Error ? error.message : String(error); + const reason = text === "" ? "unknown error" : text.slice(0, INPUT_REASON_MAX); + return new DispatchError( + "INPUT_UNAVAILABLE", + `Lease ${leaseId}'s simulator cannot take input: ${reason}`, + { leaseId, reason }, + ); +} + function unsupportedOnWorker( operation: OperationName, message = `${operation} acts on a gateway's workers, and this daemon is not a gateway`, diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 97d88469e..ffe15b716 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -22,7 +22,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | Exit | Error codes | Meaning | | --- | --- | --- | | 0 | — | Success. For a `simlock lease` that stayed running: the lease ended because you asked. | -| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED` | The command failed. Read the code and the message. | +| 1 | `INTERNAL`, `PROVISION_FAILED`, `UNKNOWN_LEASE`, `FORBIDDEN`, `ADMIN_AUTHENTICATION_FAILED`, `SETUP_MCP_FAILED`, `DAEMON_STARTUP_FAILED`, `DAEMON_CONNECTION_LOST`, `DAEMON_STOPPING`, `DAEMON_UPDATING`, `HANDSHAKE_REQUIRED`, `PROTOCOL_VERSION_UNSUPPORTED`, `WORKER_UNREACHABLE`, `RELAY_TARGET_MISSING`, `ALERT_SEND_FAILED`, `UPDATE_RESOLVE_FAILED`, `HISTORY_UNAVAILABLE`, `DOCTOR_UNAVAILABLE`, `INPUT_UNAVAILABLE`, `NUKE_UNAVAILABLE`, `UNKNOWN_DAEMON_ERROR`, `SERVICE_FAILED`, `CANCELLED` | The command failed. Read the code and the message. | | 2 | `USAGE`, `BAD_REQUEST`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | @@ -80,6 +80,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | `UNKNOWN_PASSTHROUGH_TOOL` | 2 | 422 | A tool Simlock does not wrap. | Use `simctl` or `adb`. | | `EXEC_TIMEOUT` | 10 | 504 | A command run on a device through a gateway ran longer than `exec.timeoutMs` (10 minutes by default) and was stopped. | Split the work, or raise `exec.timeoutMs` on the worker. | | `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | +| `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator could not take the rotation: its input helper did not start within 10 seconds, or writing to it failed. The message ends with the driver's reason, cut to 200 characters. | Run it again. If it repeats, check `simlock daemon logs`. | ## Daemon and connection From 50dac1b5737e6740135ea8d6325bdc92a18b4f82 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:06:33 -0300 Subject: [PATCH 09/29] test: an input socket opened after a rotate's helper closed gets a fresh helper; a socket open during a rotate keeps its helper (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 114 ++++++++++++++++++++++++++- 1 file changed, 112 insertions(+), 2 deletions(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 7f9715631..36a10a00a 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -1,8 +1,10 @@ import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { WebSocket } from "ws"; import { FakeDriver, FakeInputFactory, fakeDeviceDataTables } from "../core/testing.js"; import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; @@ -10,6 +12,15 @@ import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + const holder: DispatchSession = { manageEventSubscription: () => undefined, via: "socket", @@ -21,7 +32,10 @@ describe("device.rotate", () => { const daemons: DaemonServer[] = []; const directories: string[] = []; + const sockets: WebSocket[] = []; + afterEach(async () => { + for (const socket of sockets.splice(0)) socket.terminate(); await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); await Promise.all( directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), @@ -32,6 +46,7 @@ describe("device.rotate", () => { readonly inputModule: boolean; readonly input: FakeInputFactory | undefined; readonly androidInput?: FakeInputFactory; + readonly httpPort?: number; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); @@ -60,7 +75,12 @@ describe("device.rotate", () => { }), ]; const daemon = await startDaemon({ - configOverrides: { capabilities: { input: { enabled: options.inputModule } } }, + configOverrides: { + capabilities: { input: { enabled: options.inputModule } }, + ...(options.httpPort === undefined + ? {} + : { http: { enabled: true, host: "127.0.0.1", port: options.httpPort } }), + }, dataDirectory, deviceDataTables: fakeDeviceDataTables, drivers, @@ -302,4 +322,94 @@ describe("device.rotate", () => { } }, ); + + async function holderWithSocketAccess(input: FakeInputFactory) { + const httpPort = await freeLoopbackPort(); + const { daemon } = await worker({ httpPort, input, inputModule: true }); + const admin: DispatchSession = { ...holder, principal: "operator", role: "admin" }; + const created = await daemon.dispatch( + "token.create", + { label: "holder", role: "agent" }, + admin, + ); + const session: DispatchSession = { ...holder, principal: created.token.id }; + const granted = await daemon.dispatch( + "lease.request", + { model: "iPhone 15", platform: "ios" }, + session, + ); + const leaseId = (granted as { lease: { id: string } }).lease.id; + return { + daemon, + leaseId, + openSocket: async () => { + const socket = new WebSocket( + `ws://127.0.0.1:${String(httpPort)}/v1/leases/${leaseId}/input`, + { + headers: { authorization: `Bearer ${created.secret}` }, + }, + ); + sockets.push(socket); + const messages: number[] = []; + const closed: { code: number | undefined } = { code: undefined }; + socket.on("message", (data) => messages.push((data as Buffer)[0] ?? -1)); + socket.on("close", (code) => { + closed.code = code; + }); + await new Promise((resolve, reject) => { + socket.once("open", () => resolve()); + socket.once("error", reject); + }); + await vi.waitFor(() => expect(messages).toEqual([0x83, 0x82]), { timeout: 10_000 }); + return closed; + }, + session, + }; + } + + it( + "gives an input socket opened after a rotate's helper closed a fresh helper, keeps a socket's helper through a rotate, and answers UNKNOWN_LEASE when the lease is reclaimed while the rotate's helper opens", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const { daemon, leaseId, openSocket, session } = await holderWithSocketAccess(input); + const orientation = "landscape_right"; + + await daemon.dispatch("device.rotate", { leaseId, orientation }, session); + expect(input.opened).toHaveLength(1); + expect(input.opened[0]?.closes).toBe(1); + + const socket = await openSocket(); + expect(input.opened).toHaveLength(2); + expect(input.opened[1]?.closes).toBe(0); + + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation: "portrait" }, session), + ).resolves.toEqual({ leaseId, orientation: "portrait" }); + expect(input.opened).toHaveLength(2); + expect(input.opened[1]?.sent).toEqual([{ kind: "orientation", orientation: "portrait" }]); + expect(input.opened[1]?.closes).toBe(0); + + input.opened[1]?.fail(new Error("pipe closed")); + await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation }, session), + ).resolves.toEqual({ leaseId, orientation }); + expect(input.opened).toHaveLength(3); + expect(input.opened[2]?.sent).toEqual([{ kind: "orientation", orientation }]); + + let open: () => void = () => undefined; + input.gate = new Promise((resolve) => { + open = resolve; + }); + const rotating = daemon.dispatch("device.rotate", { leaseId, orientation }, session); + const outcome = expect(rotating).rejects.toMatchObject({ name: "UnknownLeaseError" }); + await vi.waitFor(() => expect(input.opens).toBe(4), { timeout: 10_000 }); + await daemon.dispatch("lease.release", { leaseId }, session); + open(); + await outcome; + await vi.waitFor(() => expect(input.opened[3]?.closes).toBe(1), { timeout: 10_000 }); + expect(input.opened[3]?.sent).toEqual([]); + }, + ); }); From 22b171d6c0753d8df68c2e2f7441f054527846d7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:08:21 -0300 Subject: [PATCH 10/29] feat(daemon): one device input per lease, shared by the input module's sockets and device.rotate (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/AGENTS.md | 37 +++++++------- src/daemon/dispatcher.ts | 54 +++++++++++--------- src/daemon/lease-inputs.ts | 100 +++++++++++++++++++++++++++++++++++++ src/daemon/main.ts | 14 +++--- src/input/AGENTS.md | 28 +++++------ src/input/sessions.ts | 28 ++++++----- src/input/worker.test.ts | 9 +++- src/modules/AGENTS.md | 10 ++-- src/modules/index.ts | 1 + src/modules/testing.ts | 8 ++- src/modules/types.ts | 14 ++++-- 11 files changed, 216 insertions(+), 87 deletions(-) create mode 100644 src/daemon/lease-inputs.ts diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 1e869f459..1aa936000 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -10,24 +10,25 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Files -| File | Role | -| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | -| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | -| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | -| `dispatcher.ts` | `Dispatcher`: the worker's handlers | -| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | -| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | -| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | -| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | -| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | -| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | -| `error-code.ts` | `classifyError`: thrown error → contract code | -| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | -| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | -| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | -| `test-relay-support.ts` | Test helpers for relay e2e tests | +| File | Role | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | +| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | +| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | +| `dispatcher.ts` | `Dispatcher`: the worker's handlers | +| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | +| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | +| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | +| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | +| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | +| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | +| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | +| `error-code.ts` | `classifyError`: thrown error → contract code | +| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | +| `lease-inputs.ts` | `createLeaseInputs`: the per-lease device input shared by the input module's sockets and `device.rotate`; closed by its last release, its failure or the lease's end | +| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | +| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | +| `test-relay-support.ts` | Test helpers for relay e2e tests | ## Composition (`main.ts`) diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 7cfb0825b..e08a4333b 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -644,25 +644,10 @@ export class Dispatcher { return {}; }; - /** - * why: ADR 0005 §19a: the same command `driver.passthrough` would have handed back, run here - * instead of there. Everything a passthrough already decides is reused verbatim -- which - * flag scopes the tool to this daemon's root, which verbs the driver refuses -- because it - * is the same driver call: `#driverPassthrough` above passes no device, this handler passes - * the lease's device and the lease's platform, and it also spawns the result. - * - * `leaseId` is checked against the registry here so an id that names no lease answers - * `UNKNOWN_LEASE` rather than running a command (`authorize`'s `ownsLease` deliberately lets - * an unknown id through so this handler can say that -- see `roles.ts`). Which device the - * command touches is the driver's answer: it fills the lease's device in where the tool - * expects it and refuses a command that names another (ADR 0047 §1-2); this daemon parses - * none of the arguments. That is the same accident boundary ADR 0001 draws for the local - * wrappers, reached over the wire. - * - * Nothing is buffered: each chunk goes straight to `session.onOutput` as it arrives (§19e), - * so a command that writes a gigabyte costs this process nothing, and a client sees the - * first line while the command is still running. - */ + #leaseIsActive(leaseId: string): boolean { + return this.options.registry.snapshot.leases.some((candidate) => candidate.id === leaseId); + } + #deviceRotate: Handler<"device.rotate"> = async (input) => { if (this.options.inputs === undefined) { throw new DispatchError("INTERNAL", "Device input is unavailable"); @@ -678,23 +663,44 @@ export class Dispatcher { const refusal = rotationRefusal(input.leaseId, record.spec); if (refusal !== undefined) throw refusal; try { - const opened = await this.options.inputs.openInput( + const held = await this.options.inputs.leaseInput( + input.leaseId, record.spec.platform, toDriverDevice(record), - new AbortController().signal, ); - if (isUnavailableInput(opened)) throw new Error(opened.unavailable); try { - await opened.send({ kind: "orientation", orientation: input.orientation }); + if (isUnavailableInput(held.input)) throw new Error(held.input.unavailable); + if (!this.#leaseIsActive(input.leaseId)) throw new UnknownLeaseError(input.leaseId); + await held.input.send({ kind: "orientation", orientation: input.orientation }); } finally { - await opened.close(); + held.release(); } } catch (error) { + if (error instanceof UnknownLeaseError) throw error; throw inputUnavailable(input.leaseId, error); } return { leaseId: input.leaseId, orientation: input.orientation }; }; + /** + * why: ADR 0005 §19a: the same command `driver.passthrough` would have handed back, run here + * instead of there. Everything a passthrough already decides is reused verbatim -- which + * flag scopes the tool to this daemon's root, which verbs the driver refuses -- because it + * is the same driver call: `#driverPassthrough` above passes no device, this handler passes + * the lease's device and the lease's platform, and it also spawns the result. + * + * `leaseId` is checked against the registry here so an id that names no lease answers + * `UNKNOWN_LEASE` rather than running a command (`authorize`'s `ownsLease` deliberately lets + * an unknown id through so this handler can say that -- see `roles.ts`). Which device the + * command touches is the driver's answer: it fills the lease's device in where the tool + * expects it and refuses a command that names another (ADR 0047 §1-2); this daemon parses + * none of the arguments. That is the same accident boundary ADR 0001 draws for the local + * wrappers, reached over the wire. + * + * Nothing is buffered: each chunk goes straight to `session.onOutput` as it arrives (§19e), + * so a command that writes a gigabyte costs this process nothing, and a client sees the + * first line while the command is still running. + */ #deviceExec: Handler<"device.exec"> = async (input, session) => { if (this.options.passthrough === undefined) { throw new DispatchError("INTERNAL", "Tool passthrough is unavailable"); diff --git a/src/daemon/lease-inputs.ts b/src/daemon/lease-inputs.ts new file mode 100644 index 000000000..89ab16c4e --- /dev/null +++ b/src/daemon/lease-inputs.ts @@ -0,0 +1,100 @@ +import { + isUnavailableInput, + type DeviceInput, + type PhysicalDriverDevice, + type UnavailableDeviceInput, + type VirtualDriverDevice, +} from "../core/index.js"; +import type { ModuleInputs, ModuleLeaseEndParticipant } from "../modules/index.js"; +import type { Platform } from "../core/index.js"; + +interface Entry { + readonly opening: Promise; + users: number; + closed: boolean; +} + +export interface LeaseInputs extends ModuleInputs { + readonly leaseEnd: ModuleLeaseEndParticipant; +} + +/** + * why: ADR 0053 §1-6: the daemon keeps one device input per lease, shared by the input module's sockets and `device.rotate`, so two users of one lease never start two controllers on one device. The last user to release closes it; a failure or the lease's end drops it, and the next user opens a fresh one. + */ +export function createLeaseInputs(options: { + readonly openInput: ( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + signal: AbortSignal, + ) => Promise; +}): LeaseInputs { + const entries = new Map(); + + // why: every end of a lease's input -- the last release, its failure, the lease's end -- goes through here, so it closes once, and an input still opening closes when it has opened. + function close(leaseId: string, entry: Entry): void { + if (entry.closed) return; + entry.closed = true; + if (entries.get(leaseId) === entry) entries.delete(leaseId); + void entry.opening + .then((opened) => (isUnavailableInput(opened) ? undefined : opened.close())) + .catch(() => undefined); + } + + function create( + leaseId: string, + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + ): Entry { + const entry: Entry = { + closed: false, + opening: options.openInput(platform, device, new AbortController().signal).then( + (opened) => { + if (isUnavailableInput(opened)) { + if (entries.get(leaseId) === entry) entries.delete(leaseId); + } else { + opened.onFailed(() => close(leaseId, entry)); + } + return opened; + }, + (error: unknown) => { + if (entries.get(leaseId) === entry) entries.delete(leaseId); + throw error; + }, + ), + users: 0, + }; + entries.set(leaseId, entry); + return entry; + } + + return { + leaseEnd: { + leaseEnded: (ended) => { + const entry = entries.get(ended.leaseId); + if (entry !== undefined) close(ended.leaseId, entry); + return Promise.resolve(); + }, + }, + leaseInput: async (leaseId, platform, device) => { + const entry = entries.get(leaseId) ?? create(leaseId, platform, device); + entry.users += 1; + let input: DeviceInput | UnavailableDeviceInput; + try { + input = await entry.opening; + } catch (error) { + entry.users -= 1; + throw error; + } + let released = false; + return { + input, + release: () => { + if (released) return; + released = true; + entry.users -= 1; + if (entry.users === 0) close(leaseId, entry); + }, + }; + }, + }; +} diff --git a/src/daemon/main.ts b/src/daemon/main.ts index dded5b301..3fbe8e510 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -135,6 +135,7 @@ import { WebSocketUplinkListenerFactory, } from "../ports/uplink-websocket.js"; import { classifyError } from "./error-code.js"; +import { createLeaseInputs } from "./lease-inputs.js"; import { createModuleHost, type OptionalModuleDefinition } from "../modules/index.js"; import { optionalModules } from "../module-registry/index.js"; import { DaemonServer } from "./server.js"; @@ -492,6 +493,9 @@ async function composeDaemon( // why: a module's context is built before leasing exists, so `cancelPending` answers only once leasing does. let cancelPendingRequest: ((requesterId: string) => Promise) | undefined; const catalog = new DriverCatalog(drivers); + const leaseInputs = createLeaseInputs({ + openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), + }); const moduleHost = await createModuleHost({ config, defaulted, @@ -516,9 +520,7 @@ async function composeDaemon( processRunner, processSupervisor, registry, - inputs: { - openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), - }, + inputs: leaseInputs, screens: catalog, tcpProbe, }, @@ -536,7 +538,7 @@ async function composeDaemon( describeFailure: describeLeaseRequestFailure, eventBus, idGenerator, - leaseEndParticipants: [...moduleHost.leaseEndParticipants], + leaseEndParticipants: [leaseInputs.leaseEnd, ...moduleHost.leaseEndParticipants], logger, modelPreferences, }); @@ -665,9 +667,7 @@ async function composeDaemon( logger: logger.child("server"), ...(options.protocolVersion === undefined ? {} : { protocolVersion: options.protocolVersion }), passthrough: core.catalog, - inputs: { - openInput: (platform, device, signal) => catalog.openInput(platform, device, signal), - }, + inputs: leaseInputs, processRunner, execEnv: execBaseEnvironment(process.env), queue: leasing, diff --git a/src/input/AGENTS.md b/src/input/AGENTS.md index 478becd14..83d6096ff 100644 --- a/src/input/AGENTS.md +++ b/src/input/AGENTS.md @@ -9,18 +9,18 @@ Off unless `capabilities.input.enabled` (false). Off: nothing loaded, and the `i ## Files -| File | Role | -| ----------------- | ---------------------------------------------------------------------------------------------- | -| `definition.ts` | `inputModule`: name `input`, empty config section, `http` route data, the two loaders | -| `worker.ts` | The worker side from the host's context: capability, hooks, lease route, socket, relay | -| `gateway.ts` | The gateway side: lease route, socket, `beforeDrain` | -| `create.ts` | The two factories; the 426 lease route | -| `worker-link.ts` | Worker: finds the lease in the registry; the socket door and the relay door, both to a session | -| `sessions.ts` | Worker: one device input per lease, its sockets, config, failure, lease end, drain | -| `channel.ts` | Worker: a relay channel as a `LeaseSocket`; heartbeat, `0xF1` close | -| `gateway-link.ts` | Gateway: the relay open, refusals, one bridge per socket, lease-gone wait, drain | -| `framing.ts` | `[len u32][tag u8][payload]` frames, `readFrames`, the `0xF0` and `0xF1` tags | -| `refusal.ts` | The 404, 426 and 503 bodies | +| File | Role | +| ----------------- | ------------------------------------------------------------------------------------------------------- | +| `definition.ts` | `inputModule`: name `input`, empty config section, `http` route data, the two loaders | +| `worker.ts` | The worker side from the host's context: capability, hooks, lease route, socket, relay | +| `gateway.ts` | The gateway side: lease route, socket, `beforeDrain` | +| `create.ts` | The two factories; the 426 lease route | +| `worker-link.ts` | Worker: finds the lease in the registry; the socket door and the relay door, both to a session | +| `sessions.ts` | Worker: one hold on the daemon's device input per lease, its sockets, config, failure, lease end, drain | +| `channel.ts` | Worker: a relay channel as a `LeaseSocket`; heartbeat, `0xF1` close | +| `gateway-link.ts` | Gateway: the relay open, refusals, one bridge per socket, lease-gone wait, drain | +| `framing.ts` | `[len u32][tag u8][payload]` frames, `readFrames`, the `0xF0` and `0xF1` tags | +| `refusal.ts` | The 404, 426 and 503 bodies | ## How it works @@ -31,8 +31,8 @@ lease id; the worker's `relayTwoWay` finds the lease and attaches a `channelSock gateway's accept carries `abandon` (`gateway-link.ts`), which the router calls when the handshake is refused after the relay opened. 1. Worker session (`sessions.ts` `attach`): a lease gone from the registry → close 4001 `lease ended`; a failed - open within 10 s → close 1013; 8 sockets already → close 1013. Else it opens the lease's one device input - (`ctx.inputs.openInput`, shared by every socket) and, once open, sends `0x83` then `0x82`. + open within 10 s → close 1013; 8 sockets already → close 1013. Else it takes the lease's one device input + (`ctx.inputs.leaseInput`, the daemon's, shared by every socket and by `device.rotate`) and, once open, sends `0x83` then `0x82`. 2. `0x82` is the device input's `onConfig` (called at once, then on each change) and goes to every admitted socket. An unavailable device input sends `{"width":1,"height":1,"orientation":"portrait","inputUnavailable":true}` and drops messages. 3. Client messages go through `parseClientMessage` (core): bad JSON, an unknown tag, a position outside 0..1, diff --git a/src/input/sessions.ts b/src/input/sessions.ts index bf03daa30..68c0f1591 100644 --- a/src/input/sessions.ts +++ b/src/input/sessions.ts @@ -10,7 +10,7 @@ import { type InputScreenConfig, type UnavailableDeviceInput, } from "../core/index.js"; -import type { ModuleInputs } from "../modules/index.js"; +import type { LeaseInputHandle, ModuleInputs } from "../modules/index.js"; import type { Clock, LeaseSocket } from "../ports/index.js"; const MAX_SOCKETS_PER_LEASE = 8; @@ -33,6 +33,8 @@ interface LeaseInput { // why: set once the device input has opened, so an end that finds it open closes it at once instead of after a wait. device: DeviceInput | undefined; readonly opening: Promise; + // why: set with `device`; the entry's one hold on the daemon's shared input, given back when the last socket leaves or the input fails. + handle: LeaseInputHandle | undefined; readonly sockets: Set; config: InputScreenConfig | undefined; closed: boolean; @@ -53,11 +55,11 @@ export function createInputSessions(options: { const failedOpens = new Map(); // why: every end of a lease's device input -- its last socket leaving, its own failure -- goes through here, so it closes once. - function release(leaseId: string, entry: LeaseInput, opened: DeviceInput): void { + function release(leaseId: string, entry: LeaseInput): void { if (entry.closed) return; entry.closed = true; if (leases.get(leaseId) === entry) leases.delete(leaseId); - void opened.close(); + entry.handle?.release(); } // why: an unavailable device input has nothing to close, so its entry is dropped at once instead of staying for the daemon's lifetime. @@ -68,14 +70,14 @@ export function createInputSessions(options: { // why: `unlessJoined` is the last socket leaving: a socket that joined while the input was still opening keeps it, so the close that waited for the open drops out. function releaseWhenOpen(leaseId: string, entry: LeaseInput, unlessJoined = false): void { if (entry.device !== undefined) { - release(leaseId, entry, entry.device); + release(leaseId, entry); return; } void entry.opening.then( (opened) => { if (unlessJoined && entry.sockets.size > 0) return; if (isUnavailableInput(opened)) forget(leaseId, entry); - else release(leaseId, entry, opened); + else release(leaseId, entry); }, () => undefined, ); @@ -105,15 +107,17 @@ export function createInputSessions(options: { closed: false, config: undefined, device: undefined, + handle: undefined, opening: options.inputs - .openInput(device.spec.platform, toDriverDevice(device), new AbortController().signal) + .leaseInput(leaseId, device.spec.platform, toDriverDevice(device)) .then( - (opened) => { - if (!isUnavailableInput(opened)) { - entry.device = opened; - wire(leaseId, entry, opened); + (handle) => { + entry.handle = handle; + if (!isUnavailableInput(handle.input)) { + entry.device = handle.input; + wire(leaseId, entry, handle.input); } - return opened; + return handle.input; }, (error: unknown) => { failedOpens.set(leaseId, options.clock.now()); @@ -135,7 +139,7 @@ export function createInputSessions(options: { } }); opened.onFailed(() => { - release(leaseId, entry, opened); + release(leaseId, entry); for (const attached of entry.sockets) attached.socket.close(CLOSE_FAILED, REASON_FAILED); }); } diff --git a/src/input/worker.test.ts b/src/input/worker.test.ts index d29781992..c7ec24388 100644 --- a/src/input/worker.test.ts +++ b/src/input/worker.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import type { DeviceRecord, LeaseRecord } from "../core/index.js"; +import { isUnavailableInput, type DeviceRecord, type LeaseRecord } from "../core/index.js"; import { FakeInputFactory } from "../core/testing.js"; import type { ModuleEndedLease, WorkerModule } from "../modules/index.js"; import { fakeWorkerContext } from "../modules/testing.js"; @@ -32,7 +32,12 @@ async function setup(): Promise<{ const loaded = await inputModule.loadWorker(); const worker = loaded.createWorker({ ...ctx, - inputs: { openInput: () => factory.open() }, + inputs: { + leaseInput: async () => { + const input = await factory.open(); + return { input, release: () => void (isUnavailableInput(input) || input.close()) }; + }, + }, registry, }); return { clock, factory, leases, worker }; diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index fd888657c..057ed9b5b 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -7,11 +7,11 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed ## Files -| File | Role | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `ModuleLease`, `ModuleLeaseHandler` (a module's lease handler, `leaseRoute` on both sides), `ModuleLeaseSocketHandler` (`socket` on both sides: `open` answers a refusal `Response` or an accept that gets the socket), `ModuleInputs` (`WorkerContext.inputs`), `WorkerContext`, the by-shape copies | -| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, collects each module's `mount` and `leaseRoute`, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | -| `testing.ts` | Fake module and context for tests and the conformance suite | +| File | Role | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `types.ts` | `OptionalModuleDefinition` (with optional `http` route data, read only by the OpenAPI document, and optional `localProfile` data), `ModuleTokens`, `ModuleConfig`, `WorkerModule`, `WorkerHooks`, `ModuleLease`, `ModuleLeaseHandler` (a module's lease handler, `leaseRoute` on both sides), `ModuleLeaseSocketHandler` (`socket` on both sides: `open` answers a refusal `Response` or an accept that gets the socket), `ModuleInputs`, `LeaseInputHandle` (`WorkerContext.inputs`: the daemon's per-lease device input, held and released), `WorkerContext`, the by-shape copies | +| `host.ts` | `createModuleHost`: checks names, loads turned-on modules (`role: "worker"` or `"gateway"`), runs hooks, collects each module's `mount` and `leaseRoute`, and on a worker `prepareLocalProfiles` (below); a gateway host runs `beforeDrain` under the same 30 s deadline | +| `testing.ts` | Fake module and context for tests and the conformance suite | ## Rules diff --git a/src/modules/index.ts b/src/modules/index.ts index bb4063d71..3a1ab0c40 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -13,6 +13,7 @@ export type { ModuleFinding, ModuleHttpResponse, ModuleIdentity, + LeaseInputHandle, ModuleInputs, ModuleLease, ModuleLeaseEndParticipant, diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 17766ced7..de83307f9 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -191,7 +191,13 @@ export async function fakeWorkerContext(name: string, config: C): Promise Promise.resolve({ unavailable: "no input in a fake context" }) }, + inputs: { + leaseInput: () => + Promise.resolve({ + input: { unavailable: "no input in a fake context" }, + release: () => undefined, + }), + }, screens: { openScreen: () => Promise.reject(new Error("no screen in a fake context")), screenAvailability: () => Promise.resolve([]), diff --git a/src/modules/types.ts b/src/modules/types.ts index 1a34d940c..46552e01d 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -187,13 +187,19 @@ export interface ModuleScreens { screenAvailability(): Promise; } -// why: the drivers' device input, routed by platform, without handing a module the drivers. +// why: one user's hold on a lease's shared device input; `release` is how the user says it is done, and the last release closes the input. +export interface LeaseInputHandle { + readonly input: DeviceInput | UnavailableDeviceInput; + release(): void; +} + +// why: the daemon's device input per lease, shared by every user of it (the input module's sockets and `device.rotate`), without handing a module the drivers. export interface ModuleInputs { - openInput( + leaseInput( + leaseId: string, platform: Platform, device: VirtualDriverDevice | PhysicalDriverDevice, - signal: AbortSignal, - ): Promise; + ): Promise; } export interface WorkerContext { From 736d3baf467130e48167b12ad49e91625ef585cf Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:10:46 -0300 Subject: [PATCH 11/29] test: a client program calls client.rotate(leaseId, orientation) and gets the op's output (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/admin/index.ts | 2 ++ src/cli/index.test.ts | 1 + src/client/index.ts | 2 ++ src/mcp/test-support.ts | 8 +++++++ src/simlock-client/client.test.ts | 37 +++++++++++++++++++++++++++++++ src/simlock-client/client.ts | 21 ++++++++++++++++++ src/simlock-client/types.ts | 3 +++ 7 files changed, 74 insertions(+) diff --git a/src/admin/index.ts b/src/admin/index.ts index ce9f735a6..16e41ec9f 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -37,6 +37,8 @@ export type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DeviceOutputChunk, ExecOptions, DoctorReport, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 171517b69..aac3b0875 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -8273,6 +8273,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), exec: () => Promise.resolve({ exitCode: 0 }), + rotate: (leaseId, orientation) => Promise.resolve({ leaseId, orientation }), cancelLease: () => Promise.resolve({ result: "not-found" }), renewLease: () => Promise.resolve(grant.lease as LeaseRecord), releaseLease: (input) => Promise.resolve({ leaseId: input.leaseId }), diff --git a/src/client/index.ts b/src/client/index.ts index 5fe7f7ad5..74cbbc2a3 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -25,6 +25,8 @@ export type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DeviceOutputChunk, ExecOptions, DoctorReport, diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 1f5846153..00e291869 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -17,6 +17,7 @@ import { type ExecInput, type ExecOptions, type ExecOutput, + type RotateOutput, type DriverPassthroughInput, type LeaseCancelInput, type LeaseCancelOutput, @@ -78,6 +79,8 @@ export class FakeSimlockClient implements SimlockClient { resolvePassthroughImpl: (input: DriverPassthroughInput) => Promise = notStubbed("resolvePassthrough"); execImpl: (input: ExecInput, options: ExecOptions) => Promise = notStubbed("exec"); + rotateImpl: (leaseId: string, orientation: RotateOutput["orientation"]) => Promise = + notStubbed("rotate"); readonly #leaseLostListeners = new Set<(push: LeaseLostPush) => void>(); readonly #deviceUnhealthyListeners = new Set<(push: DeviceUnhealthyPush) => void>(); @@ -150,6 +153,11 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.execImpl(input, options); } + rotate(leaseId: string, orientation: RotateOutput["orientation"]): Promise { + this.calls.push({ input: { leaseId, orientation }, method: "rotate" }); + return this.#dead ? this.#deadConnection() : this.rotateImpl(leaseId, orientation); + } + onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { this.#leaseLostListeners.add(listener); return () => this.#leaseLostListeners.delete(listener); diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index af32f27c7..8d3a00d4a 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -664,6 +664,43 @@ describe("pushes", () => { expect(onOutput).toHaveBeenCalledTimes(2); }); + it("rotate sends device.rotate for the lease and answers its output, or throws the daemon's typed refusal", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + + const rotated = client.rotate("lease_1", "landscape_left"); + await flushMicrotasks(); + expect(connection.sent.map((frame) => frame.type)).toContain("device.rotate"); + const call = connection.lastSentOf("device.rotate")!; + expect(call.payload).toEqual({ leaseId: "lease_1", orientation: "landscape_left" }); + connection.reply(call.id, { leaseId: "lease_1", orientation: "landscape_left" }); + await expect(rotated).resolves.toEqual({ leaseId: "lease_1", orientation: "landscape_left" }); + + const refused = client.rotate("lease_2", "portrait", { requesterId: "agent-1" }); + await flushMicrotasks(); + const refusedCall = connection.lastSentOf("device.rotate")!; + expect(refusedCall.payload).toEqual({ + leaseId: "lease_2", + orientation: "portrait", + requesterId: "agent-1", + }); + const details = { class: "tv", leaseId: "lease_2", physical: false, platform: "ios" }; + connection.fail( + refusedCall.id, + "ROTATION_UNSUPPORTED", + "Lease lease_2 is on an Apple TV simulator; only an iOS simulator can be rotated", + details, + ); + await expect(refused).rejects.toMatchObject({ + code: "ROTATION_UNSUPPORTED", + details, + kind: "domain", + }); + }); + it("routes a device.exec started push to that call's onStarted, once, before output, and not to another call in flight", async () => { // ADR 0005 §19a: `started` is request-scoped like `output` -- the fact a transport chooses // its response shape on. Round 5 review: the send site and this route could both be deleted diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index b0ea8053d..268e18458 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -51,6 +51,8 @@ import type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DoctorReport, DoctorRunInput, DriverPassthroughInput, @@ -123,6 +125,8 @@ export type { DeviceUnhealthyPush, ExecInput, ExecOutput, + RotateInput, + RotateOutput, DeviceOutputChunk, DoctorReport, DoctorRunInput, @@ -237,6 +241,14 @@ export interface SimlockClient { * line-oriented commands work and full-screen ones do not (§19c). */ exec(input: ExecInput, options?: ExecOptions): Promise; + /** + * why: turns the lease's iOS phone or tablet simulator to `orientation`, whether or not the daemon's input module is on. `requesterId` is for an operator that acts for the lease's requester, as `exec`'s is. + */ + rotate( + leaseId: string, + orientation: RotateInput["orientation"], + options?: { readonly requesterId?: string }, + ): Promise; /** * Reports a lease the *daemon* ended -- an expiry, an operator release, an unrecoverable @@ -429,6 +441,7 @@ function buildDegradedClient( runDoctor: () => rejected(), resolvePassthrough: () => rejected(), exec: () => rejected(), + rotate: () => rejected(), onLeaseLost: () => () => {}, onDeviceUnhealthy: () => () => {}, @@ -623,6 +636,14 @@ class SimlockClientImpl { return this.#parseOutput("device.exec", payload); } + rotate( + _leaseId: string, + _orientation: RotateInput["orientation"], + _options: { readonly requesterId?: string } = {}, + ): Promise { + return Promise.resolve({ leaseId: "", orientation: "portrait" }); + } + onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { this.#leaseLostListeners.add(listener); return () => this.#leaseLostListeners.delete(listener); diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 32b12a7d0..5e13c4771 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -38,6 +38,9 @@ export type DriverPassthroughInput = OpInput<"driver.passthrough">; /** The scoped command `simlock simctl` / `simlock adb` runs; see `passthroughCommandSchema`. */ export type PassthroughCommand = OpOutput<"driver.passthrough">; export type ExecInput = OpInput<"device.exec">; +export type RotateInput = OpInput<"device.rotate">; +/** `{ leaseId, orientation }`: what the lease's simulator was turned to. */ +export type RotateOutput = OpOutput<"device.rotate">; /** `{ exitCode }` -- the output itself arrived as `onOutput` chunks while the command ran * (ADR 0005 §19a). */ export type ExecOutput = OpOutput<"device.exec">; From e778c348c010e19ad4f239be22e22a2afbcb2517 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:11:06 -0300 Subject: [PATCH 12/29] feat(client): client.rotate turns a lease's simulator through device.rotate (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/simlock-client/client.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 268e18458..14ec188e5 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -637,11 +637,11 @@ class SimlockClientImpl { } rotate( - _leaseId: string, - _orientation: RotateInput["orientation"], - _options: { readonly requesterId?: string } = {}, + leaseId: string, + orientation: RotateInput["orientation"], + options: { readonly requesterId?: string } = {}, ): Promise { - return Promise.resolve({ leaseId: "", orientation: "portrait" }); + return this.#call("device.rotate", { leaseId, orientation, ...options }); } onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { From a4d9f18511414e3e2620a9929e0a5cb952fc4d36 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:12:25 -0300 Subject: [PATCH 13/29] test: an agent calls POST /v1/leases/{id}/rotate on a worker and through a gateway (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 157 ++++++++++++++++++++++++++- 1 file changed, 156 insertions(+), 1 deletion(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 36a10a00a..7b02d4611 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -42,11 +42,12 @@ describe("device.rotate", () => { ); }); - async function worker(options: { + async function startWorker(options: { readonly inputModule: boolean; readonly input: FakeInputFactory | undefined; readonly androidInput?: FakeInputFactory; readonly httpPort?: number; + readonly gateway?: { readonly label: string; readonly token: string; readonly url: string }; }) { const dataDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-")); directories.push(dataDirectory); @@ -77,6 +78,7 @@ describe("device.rotate", () => { const daemon = await startDaemon({ configOverrides: { capabilities: { input: { enabled: options.inputModule } }, + ...(options.gateway === undefined ? {} : { gateway: options.gateway }), ...(options.httpPort === undefined ? {} : { http: { enabled: true, host: "127.0.0.1", port: options.httpPort } }), @@ -89,6 +91,11 @@ describe("device.rotate", () => { version: "1.0.0-e2e", }); daemons.push(daemon); + return { daemon, drivers }; + } + + async function worker(options: Parameters[0]) { + const { daemon, drivers } = await startWorker(options); const granted = await daemon.dispatch( "lease.request", { model: "iPhone 15", platform: "ios" }, @@ -412,4 +419,152 @@ describe("device.rotate", () => { expect(input.opened[3]?.sent).toEqual([]); }, ); + async function agentTokens(daemon: DaemonServer, labels: readonly string[]) { + const admin: DispatchSession = { ...holder, principal: "operator", role: "admin" }; + return await Promise.all( + labels.map(async (label) => { + const created = await daemon.dispatch("token.create", { label, role: "agent" }, admin); + return { principal: created.token.id, secret: created.secret }; + }), + ); + } + + async function leaseFor( + daemon: DaemonServer, + principal: string, + request: { readonly model: string; readonly platform: "ios" | "android" }, + ): Promise { + const granted = await daemon.dispatch("lease.request", request, { ...holder, principal }); + return (granted as { lease: { id: string } }).lease.id; + } + + it( + "an agent's POST /v1/leases/{id}/rotate answers 200 with the lease and orientation, or the refusal's status, on a worker and through a gateway", + { timeout: 120_000 }, + async () => { + const screen = { height: 2556, orientation: "portrait", width: 1179 } as const; + + async function exercise( + daemon: DaemonServer, + httpPort: number, + input: FakeInputFactory, + ready: () => Promise, + ) { + const [phone, emulator] = await agentTokens(daemon, ["phone", "emulator"]); + const phoneId = await leaseFor(daemon, phone!.principal, { + model: "iPhone 15", + platform: "ios", + }); + const emulatorId = await leaseFor(daemon, emulator!.principal, { + model: "Pixel 8", + platform: "android", + }); + await ready(); + const rotate = async (leaseId: string, token: string, body: unknown) => { + const url = `http://127.0.0.1:${String(httpPort)}/v1/leases/${leaseId}/rotate`; + const response = await fetch(url, { + body: JSON.stringify(body), + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + method: "POST", + }); + const text = await response.text(); + return { + body: (text.startsWith("{") ? JSON.parse(text) : {}) as { + error?: { code: string; message: string }; + leaseId?: string; + orientation?: string; + }, + status: response.status, + }; + }; + const orientation = "landscape_left"; + + expect(await rotate(phoneId, phone!.secret, { orientation })).toEqual({ + body: { leaseId: phoneId, orientation }, + status: 200, + }); + expect(input.opened[0]?.sent).toEqual([{ kind: "orientation", orientation }]); + + for (const badOrientation of ["landscape-left", "auto", ""]) { + const refused = await rotate(phoneId, phone!.secret, { orientation: badOrientation }); + expect([badOrientation, refused.status, refused.body.error?.code]).toEqual([ + badOrientation, + 400, + "BAD_REQUEST", + ]); + } + expect((await rotate(phoneId, phone!.secret, {})).status).toBe(400); + + const unknown = await rotate("nope", phone!.secret, { orientation }); + expect([unknown.status, unknown.body.error?.code]).toEqual([404, "UNKNOWN_LEASE"]); + const foreign = await rotate(phoneId, emulator!.secret, { orientation }); + expect([foreign.status, foreign.body.error?.code]).toEqual([403, "FORBIDDEN"]); + + const android = await rotate(emulatorId, emulator!.secret, { orientation }); + expect(android.status).toBe(422); + expect(android.body.error).toEqual({ + code: "ROTATION_UNSUPPORTED", + message: `Lease ${emulatorId} is on an Android emulator; only an iOS simulator can be rotated`, + }); + + input.failWith = new Error("helper is gone"); + const missing = await rotate(phoneId, phone!.secret, { orientation }); + expect(missing.status).toBe(503); + expect(missing.body.error).toEqual({ + code: "INPUT_UNAVAILABLE", + message: `Lease ${phoneId}'s simulator cannot take input: helper is gone`, + }); + input.failWith = undefined; + } + + const workerPort = await freeLoopbackPort(); + const workerInput = new FakeInputFactory(screen); + const { daemon: standalone } = await startWorker({ + httpPort: workerPort, + input: workerInput, + inputModule: false, + }); + await exercise(standalone, workerPort, workerInput, () => Promise.resolve()); + await daemons.pop()?.stop("test"); + + const gatewayPort = await freeLoopbackPort(); + const admin: DispatchSession = { ...holder, principal: "operator", role: "admin" }; + const gatewayDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-rotate-gateway-")); + directories.push(gatewayDirectory); + const gateway = await startDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port: gatewayPort } }, + dataDirectory: gatewayDirectory, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + role: "gateway", + version: "1.0.0-e2e", + }); + daemons.push(gateway); + const workerToken = ( + await gateway.dispatch("token.create", { label: "w", role: "worker" }, admin) + ).secret; + const fleetInput = new FakeInputFactory(screen); + await startWorker({ + gateway: { label: "w", token: workerToken, url: `ws://127.0.0.1:${String(gatewayPort)}` }, + input: fleetInput, + inputModule: false, + }); + await vi.waitFor( + async () => { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + expect(workers[0]?.catalog?.length).toBeGreaterThan(0); + }, + { timeout: 10_000 }, + ); + await exercise(gateway, gatewayPort, fleetInput, async () => { + await vi.waitFor( + async () => { + const { leases } = await gateway.dispatch("lease.list", {}, admin); + expect(leases).toHaveLength(2); + }, + { timeout: 10_000 }, + ); + }); + }, + ); }); From 0dc922ca785720001083662f69264d02eeced73a Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:15:14 -0300 Subject: [PATCH 14/29] feat(http): POST /v1/leases/{id}/rotate on a worker and through a gateway (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 8 ++++- src/daemon/server.ts | 2 ++ src/gateway/dispatcher.ts | 10 +++--- src/gateway/fleet-coordinator.ts | 49 ++++++++++++++++++++++++++-- src/http/app.ts | 12 +++++++ src/http/lease-declarations.ts | 22 +++++++++++++ 6 files changed, 96 insertions(+), 7 deletions(-) diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 7b02d4611..1497facc0 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -470,7 +470,7 @@ describe("device.rotate", () => { const text = await response.text(); return { body: (text.startsWith("{") ? JSON.parse(text) : {}) as { - error?: { code: string; message: string }; + error?: Record; leaseId?: string; orientation?: string; }, @@ -503,7 +503,11 @@ describe("device.rotate", () => { const android = await rotate(emulatorId, emulator!.secret, { orientation }); expect(android.status).toBe(422); expect(android.body.error).toEqual({ + class: "emulator", code: "ROTATION_UNSUPPORTED", + leaseId: emulatorId, + physical: false, + platform: "android", message: `Lease ${emulatorId} is on an Android emulator; only an iOS simulator can be rotated`, }); @@ -512,6 +516,8 @@ describe("device.rotate", () => { expect(missing.status).toBe(503); expect(missing.body.error).toEqual({ code: "INPUT_UNAVAILABLE", + leaseId: phoneId, + reason: "helper is gone", message: `Lease ${phoneId}'s simulator cannot take input: helper is gone`, }); input.failWith = undefined; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 0aa1bce23..7440e5771 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1211,6 +1211,8 @@ export class DaemonServer { // why: Unlike `driver.passthrough` above, this one runs the command here -- so it needs the // per-call push wiring `lease.request` needs, and gets it the same way. return this.#execDevice(connection, frame.id, frame.payload); + case "device.rotate": + return this.#dispatcher.dispatch("device.rotate", frame.payload, this.#session(connection)); case "relay.request": return this.#relayRequest(connection, frame.id, frame.payload, relayChannel); case "relay.cancel": diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 36d51fbd4..5c8209f18 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -139,6 +139,7 @@ export interface GatewayDispatcherOptions { | "release" | "releaseAll" | "exec" + | "rotate" | "queueDepth" | "physicalQueueDepth" | "ownerId" @@ -731,10 +732,11 @@ export class GatewayDispatcher { return { leaseIds: [...leaseIds] }; }; - #deviceRotate: Handler<"device.rotate"> = async (input) => ({ - leaseId: input.leaseId, - orientation: "portrait", - }); + #deviceRotate: Handler<"device.rotate"> = async (input, session) => + this.options.coordinator.rotate( + { leaseId: input.leaseId, orientation: input.orientation }, + session, + ); #deviceExec: Handler<"device.exec"> = async (input, session) => this.options.coordinator.exec( diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index b0a037f68..1b7bdc52f 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -43,7 +43,13 @@ * `WORKER_UNREACHABLE` when a target is not reachable *right now*, and nothing more. */ import type { EventBus, EventMap } from "../bus/index.js"; -import type { LeaseGrant, LeaseRecord, SimlockAdminClient } from "../admin/index.js"; +import type { + LeaseGrant, + LeaseRecord, + RotateInput, + RotateOutput, + SimlockAdminClient, +} from "../admin/index.js"; import { isSimlockError, requestedClass, @@ -140,6 +146,11 @@ export interface FleetExecInput { readonly stdin?: string; } +export interface FleetRotateInput { + readonly leaseId: string; + readonly orientation: RotateInput["orientation"]; +} + export interface FleetLeaseCoordinatorOptions { readonly clock: Clock; readonly idGenerator: IdGenerator; @@ -577,6 +588,39 @@ export class FleetLeaseCoordinator { }); } + /** + * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in a refusal; the caller holds the gateway's id, so the refusal names that instead. + */ + async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { + const entry = this.#requireEntry(input.leaseId); + const requesterId = `${this.options.leaseIndex.requesterPrefix}${entry.requesterId}`; + try { + const rotated = await this.#forwardToWorker(entry.workerId, (client) => + this.#withExecTimeout( + client.rotate(entry.workerLeaseId, input.orientation, { requesterId }), + entry.workerId, + () => undefined, + "device.rotate", + ), + ); + return { leaseId: input.leaseId, orientation: rotated.orientation }; + } catch (error) { + throw this.#namedForCaller(error, entry); + } + } + + #namedForCaller(error: unknown, entry: FleetLeaseEntry): unknown { + if (!(error instanceof DispatchError)) return error; + if (error.code !== "ROTATION_UNSUPPORTED" && error.code !== "INPUT_UNAVAILABLE") return error; + const details = + typeof error.details === "object" && error.details !== null ? error.details : {}; + return new DispatchError( + error.code, + error.message.replaceAll(entry.workerLeaseId, entry.gatewayLeaseId), + { ...details, leaseId: entry.gatewayLeaseId }, + ); + } + /** * Races a forwarded `device.exec` against `gateway.execTimeoutMs` (ADR §19e). Before this, * `exec` awaited `client.exec` unbounded -- a worker that never answers at all (the case this @@ -593,6 +637,7 @@ export class FleetLeaseCoordinator { promise: Promise, workerId: string, onTimeout: () => void, + operation = "device.exec", ): Promise { return this.#raceTimeout( promise, @@ -600,7 +645,7 @@ export class FleetLeaseCoordinator { () => new DispatchError( "EXEC_TIMEOUT", - `Worker ${workerId} did not answer device.exec within gateway.execTimeoutMs (${String(this.options.execTimeoutMs)}ms)`, + `Worker ${workerId} did not answer ${operation} within gateway.execTimeoutMs (${String(this.options.execTimeoutMs)}ms)`, ), onTimeout, ); diff --git a/src/http/app.ts b/src/http/app.ts index 10335f28b..37f27d24f 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -48,6 +48,7 @@ import { leaseGetRoute, leaseListRoute, leaseReleaseRoute, + leaseRotateRoute, leaseRenewRoute, leaseRequestCancelRoute, leaseRequestCreateRoute, @@ -597,6 +598,17 @@ export function createHttpApp(deps: HttpGatewayDeps): OpenAPIHono & HttpApp ); }); + app.openapi({ ...leaseRotateRoute, middleware: [agentAuth] }, async (c) => { + const { orientation } = c.req.valid("json"); + // why: dispatched directly, like `exec`, so `device.rotate`'s own authorize answers 403 for another requester's lease and the handler 404 for an unknown one. + const rotated = await deps.dispatch( + "device.rotate", + { leaseId: c.req.valid("param").id, orientation }, + buildHttpSession(c.get("identity")), + ); + return c.json(rotated, 200); + }); + app.openapi({ ...leaseReleaseRoute, middleware: [agentAuth] }, async (c) => { const identity = c.get("identity"); const session = buildHttpSession(identity); diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 4698ebc8b..5f789e1de 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -4,6 +4,7 @@ import { deviceClassSchema, deviceRecordSchema, imageTagSchema, + INPUT_ORIENTATIONS, leaseIdSchema, OPERATIONS, refuseModelWithClass, @@ -160,6 +161,26 @@ export const leaseExecRoute = declareRoute({ errors: { 404: ["UNKNOWN_LEASE"], 501: ["UNSUPPORTED_IN_GATEWAY_MODE"], 504: ["EXEC_TIMEOUT"] }, }); +const rotateBodySchema = z.object({ orientation: z.enum(INPUT_ORIENTATIONS) }).strict(); + +export const leaseRotateRoute = declareRoute({ + method: "post", + path: "/v1/leases/{id}/rotate", + tag: "Leases", + summary: "Rotate the lease's iOS simulator", + role: "agent", + notes: + "Turns an iPhone or iPad simulator, whether or not the input module is on. Answers once the event is written to the simulator's input helper. Any other device answers 422.", + request: { params: leaseParamsSchema, json: rotateBodySchema }, + reply: OPERATIONS["device.rotate"].output, + errors: { + 404: ["UNKNOWN_LEASE"], + 422: ["ROTATION_UNSUPPORTED"], + 503: ["INPUT_UNAVAILABLE", "WORKER_UNREACHABLE"], + 504: ["EXEC_TIMEOUT"], + }, +}); + export const leaseRequestGetRoute = declareRoute({ method: "get", path: "/v1/lease-requests/{id}", @@ -345,6 +366,7 @@ export const LEASE_ROUTES = [ leaseGetRoute, leaseRenewRoute, leaseExecRoute, + leaseRotateRoute, leaseEventsRoute, leaseReleaseRoute, ] as const; From 6f2f9730011f3b75ddfc3e88be10a5897f9a4078 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:15:43 -0300 Subject: [PATCH 15/29] docs: rotate over HTTP and its two error codes (#1107) Co-Authored-By: Claude Sonnet 5.5 --- website/src/content/docs/docs/reference/errors.mdx | 2 +- .../content/docs/docs/using-devices/watching-the-screen.mdx | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index ffe15b716..1933cdfe6 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -80,7 +80,7 @@ Branch on `code`, not on the message: the message wording can change, the code d | `UNKNOWN_PASSTHROUGH_TOOL` | 2 | 422 | A tool Simlock does not wrap. | Use `simctl` or `adb`. | | `EXEC_TIMEOUT` | 10 | 504 | A command run on a device through a gateway ran longer than `exec.timeoutMs` (10 minutes by default) and was stopped. | Split the work, or raise `exec.timeoutMs` on the worker. | | `ROTATION_UNSUPPORTED` | 12 | 422 | The lease is not on an iOS phone or tablet simulator, so `POST /v1/leases/{id}/rotate` has nothing to turn. The message names what it is on: an Apple TV, Apple Watch or Apple Vision simulator, another iOS model, an Android emulator or phone or tablet, an iPhone or an iPad. | Rotate a lease on an iPhone or iPad simulator. | -| `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator could not take the rotation: its input helper did not start within 10 seconds, or writing to it failed. The message ends with the driver's reason, cut to 200 characters. | Run it again. If it repeats, check `simlock daemon logs`. | +| `INPUT_UNAVAILABLE` | 1 | 503 | The lease's simulator cannot take input. For `POST /v1/leases/{id}/rotate`, its input helper did not start within 10 seconds or writing to it failed, and the message ends with the driver's reason, cut to 200 characters. Through a gateway, the same code answers an input socket whose worker has input off. | Run it again. If it repeats, check `simlock daemon logs`. | ## Daemon and connection diff --git a/website/src/content/docs/docs/using-devices/watching-the-screen.mdx b/website/src/content/docs/docs/using-devices/watching-the-screen.mdx index 5a463800a..0806f5366 100644 --- a/website/src/content/docs/docs/using-devices/watching-the-screen.mdx +++ b/website/src/content/docs/docs/using-devices/watching-the-screen.mdx @@ -112,12 +112,16 @@ A lease's holder can open a WebSocket for its lease at `GET /v1/leases//rotate` turns it with no socket. `0x10` is answered `0x90` `{"requestId":7,"ok":false}`. On Android, a tap, swipe, scroll, key or button reaches the device through a second, control-only scrcpy server that Simlock starts for the lease; it shows no picture and changes no device setting. Taps and scrolls land on the screen as it is now, in its current rotation, and Simlock reads the size every 2 seconds, so after an agent rotates the device a tap may use the old size for up to 2 seconds, and the socket then gets a new `0x82`. A scroll sends 1 wheel unit for each 1/16 of the screen, up to 16, at the given position or the screen's centre; a positive `dy` moves the content down and a positive `dx` moves it right. `home`, `app_switcher`, `lock` and `back` are Android's Home, Recents, Power and Back keys. A `0x06` key is a USB HID usage typed as a US keyboard: letters, digits, Enter, Escape, Backspace, Tab, Space, the punctuation row, the arrows and the modifiers (Shift, Ctrl, Alt, Meta) work, and a modifier stays held for the keys after it until its `up`; other usages (function keys, the keypad) are dropped. A `0x07` orientation is dropped; rotate an Android device with agent-device. A dark phone screen is not woken, so a tap on it does nothing. A phone whose adb check is closed gets `inputUnavailable`. On an iOS simulator, a tap, swipe, scroll and `home` work, and so do `0x06` keys on iOS 26 and older runtimes. A tap reaches the simulator through a helper process that Simlock starts for the lease; it shows no picture. `home` brings the home screen forward and sends the app to the background. A scroll is sent as a finger drag. `app_switcher`, `lock` and `back` are dropped. A `0x07` orientation turns the simulator with a device-orientation event, as turning a phone in your hand does; this was checked with Xcode 26.4 and Xcode 27, on iOS 26.4 and iOS 27 runtimes. A screen that does not rotate, such as the iPhone home screen, stays as it is, and nothing tells the client. On an iOS 27 or newer runtime the simulator ignores injected keys, so `0x06` keys are dropped and the `0x82` message carries `"keyboardUnavailable":true`. The `0x82` message always says `"orientation":"portrait"`, after a rotation too, and touch positions stay fractions of the screen in its portrait frame. +### Rotate without a socket + +A lease's holder can also rotate its iPhone or iPad simulator with `POST /v1/leases//rotate` and a body such as `{"orientation":"landscape_left"}`, on a worker or on a gateway, whether or not `capabilities.input.enabled` is on. `orientation` is one of `portrait`, `portrait_upside_down`, `landscape_left` or `landscape_right`; any other spelling answers 400 `BAD_REQUEST`. The call answers `200` with `{"leaseId":"","orientation":"landscape_left"}` once the event is written to the simulator's input helper, and it uses the helper an open input socket already has. Through a gateway, `` is the id you hold. A lease on any other device (an Apple TV, Apple Watch or Apple Vision simulator, an Android emulator or phone, a physical iPhone or iPad) answers 422 `ROTATION_UNSUPPORTED`, and a helper that cannot start or a failed write answers 503 `INPUT_UNAVAILABLE`. A lease that is not the caller's answers 403, and one that does not exist answers 404 `UNKNOWN_LEASE`. A worker that gives no answer within `gateway.execTimeoutMs` answers 504 `EXEC_TIMEOUT`. The JS client calls it as `client.rotate(leaseId, orientation)`. + Up to 8 sockets share one lease's device input. The socket closes with: | Code | Reason | When | From d8d222b69df7de433479d92bc2566705c655544f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:16:08 -0300 Subject: [PATCH 16/29] test: the alias parser maps a spelling to an orientation or the unknown message (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/orientation.test.ts | 33 ++++++++++++++++++++++++++++++++ src/contract/orientation.ts | 10 ++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/contract/orientation.test.ts diff --git a/src/contract/orientation.test.ts b/src/contract/orientation.test.ts new file mode 100644 index 000000000..36f937821 --- /dev/null +++ b/src/contract/orientation.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; + +import { parseOrientation } from "./orientation.js"; + +// why: a parser with many spellings, each a row; it has no surface above it that lists them. +describe("parseOrientation", () => { + it("maps a spelling to an orientation, ignoring case and surrounding space, or to the unknown message", () => { + const accepted: readonly (readonly [string, string])[] = [ + ["landscape_left", "landscape_left"], + ["landscape-left", "landscape_left"], + ["LEFT", "landscape_left"], + [" Left ", "landscape_left"], + ["landscape_right", "landscape_right"], + ["landscape-right", "landscape_right"], + ["right", "landscape_right"], + ["portrait_upside_down", "portrait_upside_down"], + ["portrait-upside-down", "portrait_upside_down"], + ["upside-down", "portrait_upside_down"], + ["portrait", "portrait"], + ["PORTRAIT", "portrait"], + ]; + for (const [spelling, orientation] of accepted) { + expect(parseOrientation(spelling), spelling).toEqual({ ok: true, orientation }); + } + + for (const spelling of ["auto", "landscapeLeft", "", " ", "up", "landscape"]) { + expect(parseOrientation(spelling), JSON.stringify(spelling)).toEqual({ + message: `Unknown orientation ${spelling}; use portrait, portrait-upside-down, landscape-left or landscape-right`, + ok: false, + }); + } + }); +}); diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index 03849a8fc..075037011 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -25,3 +25,13 @@ export function isRotatableModel(model: string): boolean { const family = modelFamily(model); return family === "phone" || family === "tablet"; } + +export type Orientation = (typeof INPUT_ORIENTATIONS)[number]; + +export type OrientationParse = + | { readonly ok: true; readonly orientation: Orientation } + | { readonly ok: false; readonly message: string }; + +export function parseOrientation(_input: string): OrientationParse { + return { message: "", ok: false }; +} From 4bae4e7b0da425f2bb34353c60929831c8f42c9f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:16:44 -0300 Subject: [PATCH 17/29] feat(contract): parseOrientation maps an alias to an orientation or the unknown message (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 1 + src/contract/orientation.ts | 25 +++++++++++++++++++++++-- src/core/input.ts | 10 ++-------- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 6bad06eb6..de97bd144 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -22,6 +22,7 @@ Imported by: daemon, gateway, simlock-client, every frontend, core, leasing, his | `os-range.ts` | OS constraint grammar: parse, `satisfies`, `compareVersions` | | `version-order.ts` | `isNewerVersion(candidate, running)`: the one "newer" rule (semver order) every update surface shares; the console imports it by this path, not the index (the index carries zod) | | `duration.ts` | `parseDurationMs`, for the CLI and HTTP | +| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases the CLI, MCP and agent-device front take), `isRotatableModel`, `modelFamily`; no wire shape | | `relay.ts` | Bounded relay ids, channel ids, headers | | `console-url.ts` | The console address `status.get` reports | diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index 075037011..6a6199180 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -32,6 +32,27 @@ export type OrientationParse = | { readonly ok: true; readonly orientation: Orientation } | { readonly ok: false; readonly message: string }; -export function parseOrientation(_input: string): OrientationParse { - return { message: "", ok: false }; +// why: the CLI, MCP and the agent-device front take these spellings; HTTP and the client take only the four names. +const ALIASES: Readonly> = { + "landscape-left": "landscape_left", + "landscape-right": "landscape_right", + landscape_left: "landscape_left", + landscape_right: "landscape_right", + left: "landscape_left", + portrait: "portrait", + "portrait-upside-down": "portrait_upside_down", + portrait_upside_down: "portrait_upside_down", + right: "landscape_right", + "upside-down": "portrait_upside_down", +}; + +export function parseOrientation(input: string): OrientationParse { + const orientation = Object.hasOwn(ALIASES, input.trim().toLowerCase()) + ? ALIASES[input.trim().toLowerCase()] + : undefined; + if (orientation !== undefined) return { ok: true, orientation }; + return { + message: `Unknown orientation ${input}; use portrait, portrait-upside-down, landscape-left or landscape-right`, + ok: false, + }; } diff --git a/src/core/input.ts b/src/core/input.ts index ea69da8cb..b194329e8 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -1,4 +1,5 @@ import type { PhysicalDriverDevice, VirtualDriverDevice } from "./driver.js"; +import { INPUT_ORIENTATIONS, type Orientation } from "../contract/index.js"; // why: the one table in TypeScript for the input socket's tags, in the messages expo's serve-sim speaks // (ADR 0049 section 3): a client that already speaks them drives a lease with no Simlock-specific code. @@ -32,14 +33,7 @@ export function closeReason(reason: string): string { const INPUT_BUTTONS = ["home", "app_switcher", "lock", "back"] as const; -const INPUT_ORIENTATIONS = [ - "portrait", - "portrait_upside_down", - "landscape_left", - "landscape_right", -] as const; - -export type InputOrientation = (typeof INPUT_ORIENTATIONS)[number]; +export type InputOrientation = Orientation; // why: serve-sim's `0x82` payload, which T3 Code accepts only with a width and height above 0. export interface InputScreenConfig { From c6834bc976bc2242a447c18f0a4ffe5c6d7d0e35 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:17:45 -0300 Subject: [PATCH 18/29] test: the gateway coordinator forwards device.rotate and names the caller's lease id (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/operations.ts | 3 +- src/gateway/fleet-coordinator.test.ts | 45 +++++++++++++++++++++++++++ src/gateway/test-support.ts | 16 ++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index e4820578b..25bf8567f 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -1086,8 +1086,7 @@ function authorizeOneLeaseCall( /** * why: turns a leased iOS phone or tablet simulator, through the lease's device input, whether or not the input module is on. */ -// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. -export const deviceRotate = defineOperation({ +const deviceRotate = defineOperation({ name: "device.rotate", role: "agent", effect: "write", diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 3eb03b612..b0ef8dd73 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1109,6 +1109,51 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); }); + it("forwards device.rotate to the worker's own lease id with the namespaced requester, answers and names the caller's lease id", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + id: "lse_9", + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + }), + kind: "grant", + }); + const grant = await coordinator.request(REQUEST, requestOptions()); + const session = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", + } as const; + + await expect( + coordinator.rotate({ leaseId: grant.lease.id, orientation: "landscape_left" }, session), + ).resolves.toEqual({ leaseId: grant.lease.id, orientation: "landscape_left" }); + expect(client.calls).toContain(`device.rotate:lse_9:${GATEWAY_PREFIX}agent-1`); + + client.rotateErrors.push( + fromWireError( + "ROTATION_UNSUPPORTED", + "Lease lse_9 is on an Apple TV simulator; only an iOS simulator can be rotated", + { class: "tv", leaseId: "lse_9", physical: false, platform: "ios" }, + ), + ); + await expect( + coordinator.rotate({ leaseId: grant.lease.id, orientation: "portrait" }, session), + ).rejects.toMatchObject({ + code: "ROTATION_UNSUPPORTED", + details: { class: "tv", leaseId: grant.lease.id, physical: false, platform: "ios" }, + message: `Lease ${grant.lease.id} is on an Apple TV simulator; only an iOS simulator can be rotated`, + }); + }); + it("announces started from the worker's own push, before any output (ADR §19a)", async () => { const { coordinator, directory, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index abcede425..1a98aed13 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -16,6 +16,7 @@ import type { ExecInput, ExecOptions, ExecOutput, + RotateOutput, LeaseGrant, LeaseRecord, LeaseReleaseInput, @@ -331,6 +332,8 @@ export class ScriptedWorkerClient { * a test sets this to relay that event from inside the call. */ onReleaseLease: ((leaseId: string) => void) | undefined; readonly execQueue: ExecOutcome[] = []; + /** why: a test queues the error the worker's next `device.rotate` throws; an empty queue answers the rotation. */ + readonly rotateErrors: Error[] = []; /** * H4 (round 3 review): the `options` most recently passed to `exec` -- captured before * `execQueue`'s own outcome is even read, so a `"hang"` outcome (whose returned promise never @@ -496,6 +499,19 @@ export class ScriptedWorkerClient { return { exitCode: outcome?.exitCode ?? 0 }; } + // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. + async rotate( + leaseId: string, + orientation: RotateOutput["orientation"], + options: { readonly requesterId?: string } = {}, + ): Promise { + this.calls.push(`device.rotate:${leaseId}:${options.requesterId ?? ""}`); + this.#throwIfFailing(); + const error = this.rotateErrors.shift(); + if (error !== undefined) throw error; + return { leaseId, orientation }; + } + // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. async installComponent( input: ComponentInstallInput, From eae80be7fa10ed131c2b67af7346131f40dfed07 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:26:00 -0300 Subject: [PATCH 19/29] test: a socket whose write fails closes 1013 while the daemon keeps rotating (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/core/fake-device-input.ts | 7 +++++-- src/daemon/device-rotate.e2e.test.ts | 12 +++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/core/fake-device-input.ts b/src/core/fake-device-input.ts index 5e560a4fc..2a0d033d3 100644 --- a/src/core/fake-device-input.ts +++ b/src/core/fake-device-input.ts @@ -14,7 +14,7 @@ class FakeDeviceInput implements DeviceInput { readonly #failedListeners = new Set<(error: Error) => void>(); #config: InputScreenConfig; - // why: a test sets this to make every write fail, as a helper whose pipe broke does. + // why: a test sets this to make every write fail and the input report it through `onFailed`, as a helper whose pipe broke does. sendFailure: Error | undefined; constructor(config: InputScreenConfig) { @@ -22,7 +22,10 @@ class FakeDeviceInput implements DeviceInput { } send(message: InputMessage): Promise { - if (this.sendFailure !== undefined) return Promise.reject(this.sendFailure); + if (this.sendFailure !== undefined) { + this.fail(this.sendFailure); + return Promise.reject(this.sendFailure); + } this.sent.push(message); return Promise.resolve(); } diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 1497facc0..7a98bcca9 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -260,7 +260,7 @@ describe("device.rotate", () => { ); it( - "refuses a holder's rotate with INPUT_UNAVAILABLE and the reason when the helper cannot start or the write fails", + "refuses a holder's rotate with INPUT_UNAVAILABLE and the reason when the helper cannot start or the write fails, and closes a socket whose write fails 1013 while the daemon keeps running", { timeout: 60_000 }, async () => { const screen = { height: 2556, orientation: "portrait", width: 1179 } as const; @@ -327,6 +327,16 @@ describe("device.rotate", () => { ).toEqual(input.opened.map(() => 1)); await daemons.pop()?.stop("test"); } + + const failing = new FakeInputFactory(screen); + failing.sendFailure = new Error("pipe closed"); + const { daemon, leaseId, openSocket, session } = await holderWithSocketAccess(failing); + const socket = await openSocket(); + sockets.at(-1)?.send(Buffer.concat([Buffer.from([0x04]), Buffer.from('{"button":"lock"}')])); + await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation: "portrait" }, session), + ).rejects.toMatchObject({ code: "INPUT_UNAVAILABLE", details: { reason: "pipe closed" } }); }, ); From aced7b4bf160bf3839846e001151e8de73463940 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:26:59 -0300 Subject: [PATCH 20/29] test: fold the coordinator's rotate case into the HTTP gateway test that proves it (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/fleet-coordinator.test.ts | 45 --------------------------- src/gateway/test-support.ts | 16 ---------- 2 files changed, 61 deletions(-) diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index b0ef8dd73..3eb03b612 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1109,51 +1109,6 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); }); - it("forwards device.rotate to the worker's own lease id with the namespaced requester, answers and names the caller's lease id", async () => { - const { coordinator, directory, workers } = harness(); - const client = new ScriptedWorkerClient(); - directory.add("wrk_a", client); - connectWorker(workers, "wrk_a"); - client.requestLeaseQueue.push({ - grant: grantFixture({ - lease: { - ...grantFixture().lease, - id: "lse_9", - ownerId: "agent-1", - requesterId: `${GATEWAY_PREFIX}agent-1`, - }, - }), - kind: "grant", - }); - const grant = await coordinator.request(REQUEST, requestOptions()); - const session = { - manageEventSubscription: () => undefined, - via: "socket", - principal: "agent-1", - role: "agent", - } as const; - - await expect( - coordinator.rotate({ leaseId: grant.lease.id, orientation: "landscape_left" }, session), - ).resolves.toEqual({ leaseId: grant.lease.id, orientation: "landscape_left" }); - expect(client.calls).toContain(`device.rotate:lse_9:${GATEWAY_PREFIX}agent-1`); - - client.rotateErrors.push( - fromWireError( - "ROTATION_UNSUPPORTED", - "Lease lse_9 is on an Apple TV simulator; only an iOS simulator can be rotated", - { class: "tv", leaseId: "lse_9", physical: false, platform: "ios" }, - ), - ); - await expect( - coordinator.rotate({ leaseId: grant.lease.id, orientation: "portrait" }, session), - ).rejects.toMatchObject({ - code: "ROTATION_UNSUPPORTED", - details: { class: "tv", leaseId: grant.lease.id, physical: false, platform: "ios" }, - message: `Lease ${grant.lease.id} is on an Apple TV simulator; only an iOS simulator can be rotated`, - }); - }); - it("announces started from the worker's own push, before any output (ADR §19a)", async () => { const { coordinator, directory, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 1a98aed13..abcede425 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -16,7 +16,6 @@ import type { ExecInput, ExecOptions, ExecOutput, - RotateOutput, LeaseGrant, LeaseRecord, LeaseReleaseInput, @@ -332,8 +331,6 @@ export class ScriptedWorkerClient { * a test sets this to relay that event from inside the call. */ onReleaseLease: ((leaseId: string) => void) | undefined; readonly execQueue: ExecOutcome[] = []; - /** why: a test queues the error the worker's next `device.rotate` throws; an empty queue answers the rotation. */ - readonly rotateErrors: Error[] = []; /** * H4 (round 3 review): the `options` most recently passed to `exec` -- captured before * `execQueue`'s own outcome is even read, so a `"hang"` outcome (whose returned promise never @@ -499,19 +496,6 @@ export class ScriptedWorkerClient { return { exitCode: outcome?.exitCode ?? 0 }; } - // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. - async rotate( - leaseId: string, - orientation: RotateOutput["orientation"], - options: { readonly requesterId?: string } = {}, - ): Promise { - this.calls.push(`device.rotate:${leaseId}:${options.requesterId ?? ""}`); - this.#throwIfFailing(); - const error = this.rotateErrors.shift(); - if (error !== undefined) throw error; - return { leaseId, orientation }; - } - // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. async installComponent( input: ComponentInstallInput, From 0844848f7624cff1678d944129c572dea15b8bd9 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 01:27:31 -0300 Subject: [PATCH 21/29] chore: name how the coordinator's rotate is reached for Fallow (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/fleet-coordinator.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 1b7bdc52f..eacae88a2 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -591,6 +591,7 @@ export class FleetLeaseCoordinator { /** * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in a refusal; the caller holds the gateway's id, so the refusal names that instead. */ + // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option. async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { const entry = this.#requireEntry(input.leaseId); const requesterId = `${this.options.leaseIndex.requesterPrefix}${entry.requesterId}`; From 7aa86a7886633d86cf4dabec6fc6ba5b2e495a81 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:10:32 -0300 Subject: [PATCH 22/29] fix(gateway): name the caller's lease id in every worker error, and prove rotate's cases (#1107) The coordinator rewrote the worker's lease id only for two codes and with a substring replace; it now maps every coded error's details.leaseId and replaces the id only as a whole token. The rotate e2e test sends all four orientation names, covers a rejected open and a failed shared input, and no longer waits on the daemon's real host-load probe on Linux; the registry's lease-end close and failure drop get a unit test. Co-Authored-By: Claude Sonnet 5.5 --- src/daemon/device-rotate.e2e.test.ts | 102 ++++++++++++++++++++------- src/daemon/lease-inputs.test.ts | 60 ++++++++++++++++ src/gateway/fleet-coordinator.ts | 27 +++++-- 3 files changed, 157 insertions(+), 32 deletions(-) create mode 100644 src/daemon/lease-inputs.test.ts diff --git a/src/daemon/device-rotate.e2e.test.ts b/src/daemon/device-rotate.e2e.test.ts index 7a98bcca9..02f122958 100644 --- a/src/daemon/device-rotate.e2e.test.ts +++ b/src/daemon/device-rotate.e2e.test.ts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { WebSocket } from "ws"; import { FakeDriver, FakeInputFactory, fakeDeviceDataTables } from "../core/testing.js"; -import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import { FakeSystemStats, MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -88,6 +88,7 @@ describe("device.rotate", () => { drivers, filesystem: new MemoryFilesystem(), logger: new NoopLogger(), + systemStats: new FakeSystemStats({ cpuCount: 16, totalRamBytes: 64 * 1024 ** 3 }), version: "1.0.0-e2e", }); daemons.push(daemon); @@ -105,24 +106,28 @@ describe("device.rotate", () => { } it( - "answers a holder's rotate of its iOS-simulator lease and sends the helper that orientation", + "answers a holder's rotate of its iOS-simulator lease to each of the four orientation names and sends the helper that orientation", { timeout: 60_000 }, async () => { const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); const { daemon, leaseId } = await worker({ input, inputModule: false }); - const answer = await daemon.dispatch( - "device.rotate", - { leaseId, orientation: "landscape_left" }, - holder, - ); - - expect(answer).toEqual({ leaseId, orientation: "landscape_left" }); - expect(input.opened).toHaveLength(1); - expect(input.opened[0]?.sent).toEqual([ - { kind: "orientation", orientation: "landscape_left" }, - ]); - expect(input.opened[0]?.closes).toBe(1); + const names = [ + "landscape_left", + "portrait_upside_down", + "landscape_right", + "portrait", + ] as const; + for (const [index, orientation] of names.entries()) { + const answer = await daemon.dispatch("device.rotate", { leaseId, orientation }, holder); + + expect(answer, orientation).toEqual({ leaseId, orientation }); + expect(input.opened, orientation).toHaveLength(index + 1); + expect(input.opened[index]?.sent, orientation).toEqual([ + { kind: "orientation", orientation }, + ]); + expect(input.opened[index]?.closes, orientation).toBe(1); + } }, ); @@ -385,13 +390,23 @@ describe("device.rotate", () => { } it( - "gives an input socket opened after a rotate's helper closed a fresh helper, keeps a socket's helper through a rotate, and answers UNKNOWN_LEASE when the lease is reclaimed while the rotate's helper opens", + "gives a rotate after a failed open, an input socket opened after a rotate's helper closed, and a rotate after the shared helper failed a fresh helper, keeps a socket's helper through a rotate, and answers UNKNOWN_LEASE when the lease is reclaimed while the rotate's helper opens", { timeout: 60_000 }, async () => { const input = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); const { daemon, leaseId, openSocket, session } = await holderWithSocketAccess(input); const orientation = "landscape_right"; + input.failWith = new Error("helper exploded"); + await expect( + daemon.dispatch("device.rotate", { leaseId, orientation }, session), + ).rejects.toMatchObject({ + code: "INPUT_UNAVAILABLE", + details: { reason: "helper exploded" }, + }); + input.failWith = undefined; + expect(input.opened).toHaveLength(0); + await daemon.dispatch("device.rotate", { leaseId, orientation }, session); expect(input.opened).toHaveLength(1); expect(input.opened[0]?.closes).toBe(1); @@ -408,12 +423,13 @@ describe("device.rotate", () => { expect(input.opened[1]?.closes).toBe(0); input.opened[1]?.fail(new Error("pipe closed")); - await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); await expect( daemon.dispatch("device.rotate", { leaseId, orientation }, session), ).resolves.toEqual({ leaseId, orientation }); expect(input.opened).toHaveLength(3); + expect(input.opened[1]?.sent).toEqual([{ kind: "orientation", orientation: "portrait" }]); expect(input.opened[2]?.sent).toEqual([{ kind: "orientation", orientation }]); + await vi.waitFor(() => expect(socket.code).toBe(1013), { timeout: 10_000 }); let open: () => void = () => undefined; input.gate = new Promise((resolve) => { @@ -421,7 +437,7 @@ describe("device.rotate", () => { }); const rotating = daemon.dispatch("device.rotate", { leaseId, orientation }, session); const outcome = expect(rotating).rejects.toMatchObject({ name: "UnknownLeaseError" }); - await vi.waitFor(() => expect(input.opens).toBe(4), { timeout: 10_000 }); + await vi.waitFor(() => expect(input.opens).toBe(5), { timeout: 10_000 }); await daemon.dispatch("lease.release", { leaseId }, session); open(); await outcome; @@ -459,6 +475,7 @@ describe("device.rotate", () => { httpPort: number, input: FakeInputFactory, ready: () => Promise, + reclaimOnWorker?: (leaseId: string) => Promise, ) { const [phone, emulator] = await agentTokens(daemon, ["phone", "emulator"]); const phoneId = await leaseFor(daemon, phone!.principal, { @@ -531,6 +548,21 @@ describe("device.rotate", () => { message: `Lease ${phoneId}'s simulator cannot take input: helper is gone`, }); input.failWith = undefined; + + if (reclaimOnWorker !== undefined) { + let open: () => void = () => undefined; + input.gate = new Promise((resolve) => { + open = resolve; + }); + const opensBefore = input.opens; + const rotating = rotate(phoneId, phone!.secret, { orientation }); + await vi.waitFor(() => expect(input.opens).toBe(opensBefore + 1), { timeout: 10_000 }); + await reclaimOnWorker(phoneId); + open(); + const gone = await rotating; + expect([gone.status, gone.body.error?.code]).toEqual([404, "UNKNOWN_LEASE"]); + expect(gone.body.error?.message).toBe(`Unknown lease: ${phoneId}`); + } } const workerPort = await freeLoopbackPort(); @@ -560,7 +592,7 @@ describe("device.rotate", () => { await gateway.dispatch("token.create", { label: "w", role: "worker" }, admin) ).secret; const fleetInput = new FakeInputFactory(screen); - await startWorker({ + const { daemon: fleetWorker } = await startWorker({ gateway: { label: "w", token: workerToken, url: `ws://127.0.0.1:${String(gatewayPort)}` }, input: fleetInput, inputModule: false, @@ -572,15 +604,31 @@ describe("device.rotate", () => { }, { timeout: 10_000 }, ); - await exercise(gateway, gatewayPort, fleetInput, async () => { - await vi.waitFor( - async () => { - const { leases } = await gateway.dispatch("lease.list", {}, admin); - expect(leases).toHaveLength(2); - }, - { timeout: 10_000 }, - ); - }); + await exercise( + gateway, + gatewayPort, + fleetInput, + async () => { + await vi.waitFor( + async () => { + const { leases } = await gateway.dispatch("lease.list", {}, admin); + expect(leases).toHaveLength(2); + }, + { timeout: 10_000 }, + ); + }, + async (leaseId) => { + const { leases } = await gateway.dispatch("lease.list", {}, admin); + const owner = leases.find((lease) => lease.id === leaseId)?.requesterId; + const held = await fleetWorker.dispatch("lease.list", {}, admin); + const workerLease = held.leases.find((lease) => lease.requesterId.endsWith(owner ?? "")); + await fleetWorker.dispatch( + "lease.release", + { leaseId: workerLease?.id ?? "", requesterId: workerLease?.requesterId ?? "" }, + admin, + ); + }, + ); }, ); }); diff --git a/src/daemon/lease-inputs.test.ts b/src/daemon/lease-inputs.test.ts new file mode 100644 index 000000000..304eb74e2 --- /dev/null +++ b/src/daemon/lease-inputs.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; + +import { FakeInputFactory } from "../core/testing.js"; +import { createLeaseInputs } from "./lease-inputs.js"; + +const device = { id: "device-1", platform: "ios" } as never; +const ended = { + deviceId: "device-1", + leaseId: "lease-1", + ownerId: "owner-1", + platform: "ios", + reason: "explicit", +} as const; + +// why: the surface cannot force a user that holds the input past its lease's end: the input module and `device.rotate` both release at once, so only the registry's own lease-end participant is left to close it. +describe("createLeaseInputs", () => { + it("closes the input of a lease whose user never releases it when the lease ends, and gives the next user of that lease a fresh one", async () => { + const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const inputs = createLeaseInputs({ openInput: () => factory.open() }); + await inputs.leaseInput("lease-1", "ios", device); + await inputs.leaseInput("lease-1", "ios", device); + expect(factory.opened).toHaveLength(1); + expect(factory.opened[0]?.closes).toBe(0); + + await inputs.leaseEnd.leaseEnded(ended, new AbortController().signal); + await Promise.resolve(); + + expect(factory.opened[0]?.closes).toBe(1); + await inputs.leaseInput("lease-1", "ios", device); + expect(factory.opened).toHaveLength(2); + }); + + it("drops an input that failed while another user still holds it, so the next user opens a fresh one", async () => { + const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const inputs = createLeaseInputs({ openInput: () => factory.open() }); + await inputs.leaseInput("lease-1", "ios", device); + await inputs.leaseInput("lease-1", "ios", device); + + factory.opened[0]?.fail(new Error("pipe closed")); + await Promise.resolve(); + + expect(factory.opened[0]?.closes).toBe(1); + const fresh = await inputs.leaseInput("lease-1", "ios", device); + expect(factory.opened).toHaveLength(2); + expect(fresh.input).toBe(factory.opened[1]); + }); + + it("opens a fresh input for the next user after an open rejected", async () => { + const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); + const inputs = createLeaseInputs({ openInput: () => factory.open() }); + factory.failWith = new Error("helper exploded"); + await expect(inputs.leaseInput("lease-1", "ios", device)).rejects.toThrow("helper exploded"); + factory.failWith = undefined; + + await inputs.leaseInput("lease-1", "ios", device); + + expect(factory.opens).toBe(2); + expect(factory.opened).toHaveLength(1); + }); +}); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index eacae88a2..212a155f0 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -589,7 +589,7 @@ export class FleetLeaseCoordinator { } /** - * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in a refusal; the caller holds the gateway's id, so the refusal names that instead. + * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in any coded error; the caller holds the gateway's id, so the error names that instead. */ // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option. async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { @@ -612,13 +612,15 @@ export class FleetLeaseCoordinator { #namedForCaller(error: unknown, entry: FleetLeaseEntry): unknown { if (!(error instanceof DispatchError)) return error; - if (error.code !== "ROTATION_UNSUPPORTED" && error.code !== "INPUT_UNAVAILABLE") return error; const details = - typeof error.details === "object" && error.details !== null ? error.details : {}; + typeof error.details === "object" && error.details !== null ? error.details : undefined; + const names = (details as { leaseId?: unknown } | undefined)?.leaseId === entry.workerLeaseId; + const message = replaceWholeId(error.message, entry.workerLeaseId, entry.gatewayLeaseId); + if (!names && message === error.message) return error; return new DispatchError( error.code, - error.message.replaceAll(entry.workerLeaseId, entry.gatewayLeaseId), - { ...details, leaseId: entry.gatewayLeaseId }, + message, + names ? { ...details, leaseId: entry.gatewayLeaseId } : error.details, ); } @@ -1597,3 +1599,18 @@ function routable(waiter: FleetWaiter): RoutableRequest { ...(waiter.options.requires === undefined ? {} : { requires: waiter.options.requires }), }; } + +// why: a lease id is replaced only as a whole token, so a short id inside a longer word or id is left alone. +function replaceWholeId(text: string, id: string, replacement: string): string { + const isIdCharacter = (character: string | undefined): boolean => + character !== undefined && /[\w-]/.test(character); + let result = ""; + let from = 0; + for (let at = text.indexOf(id); at !== -1; at = text.indexOf(id, from)) { + const end = at + id.length; + const whole = !isIdCharacter(text[at - 1]) && !isIdCharacter(text[end]); + result += text.slice(from, at) + (whole ? replacement : id); + from = end; + } + return result + text.slice(from); +} From 638218804376c0ad364482b40ac4ef6f2a5579c1 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 02:10:38 -0300 Subject: [PATCH 23/29] docs: list POST /v1/leases/{id}/rotate and device.rotate in the manuals, and reword the orientation claims (#1107) Co-Authored-By: Claude Sonnet 5.5 --- src/contract/AGENTS.md | 4 ++-- src/contract/orientation.ts | 2 +- src/daemon/AGENTS.md | 40 ++++++++++++++++++------------------- src/http/AGENTS.md | 1 + 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index de97bd144..748f8abf8 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -22,7 +22,7 @@ Imported by: daemon, gateway, simlock-client, every frontend, core, leasing, his | `os-range.ts` | OS constraint grammar: parse, `satisfies`, `compareVersions` | | `version-order.ts` | `isNewerVersion(candidate, running)`: the one "newer" rule (semver order) every update surface shares; the console imports it by this path, not the index (the index carries zod) | | `duration.ts` | `parseDurationMs`, for the CLI and HTTP | -| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases the CLI, MCP and agent-device front take), `isRotatableModel`, `modelFamily`; no wire shape | +| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases a spelling maps to an orientation or the unknown message), `isRotatableModel`, `modelFamily`; no wire shape | | `relay.ts` | Bounded relay ids, channel ids, headers | | `console-url.ts` | The console address `status.get` reports | @@ -34,7 +34,7 @@ park on readiness (all but `status.get`) → handler → parse output. every operation but `daemon.stop`, which `DaemonServer` answers. - `agent`: `catalog.get`, `status.get`, `component.list`, `lease.request`, `lease.cancel`, - `lease.renew`, `lease.release`, `lease.list`, `lease.get`, `driver.passthrough`, `device.exec`, + `lease.renew`, `lease.release`, `lease.list`, `lease.get`, `driver.passthrough`, `device.exec`, `device.rotate`, `doctor.run` without `fix` or `purgeOrphans`. - `admin`: every other operation (`list.get`, `config.get`, `inbox.get`, `daemon.stop`, `events.*`, `token.*`, `worker.*`, `component.install`, `device.add`, `relay.request`, ...). diff --git a/src/contract/orientation.ts b/src/contract/orientation.ts index 6a6199180..050470e1c 100644 --- a/src/contract/orientation.ts +++ b/src/contract/orientation.ts @@ -32,7 +32,7 @@ export type OrientationParse = | { readonly ok: true; readonly orientation: Orientation } | { readonly ok: false; readonly message: string }; -// why: the CLI, MCP and the agent-device front take these spellings; HTTP and the client take only the four names. +// why: the spellings `parseOrientation` accepts for a caller that takes more than the four names; HTTP and the client take only the four names. const ALIASES: Readonly> = { "landscape-left": "landscape_left", "landscape-right": "landscape_right", diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 1aa936000..2862c26f0 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -10,25 +10,24 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Files -| File | Role | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | -| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | -| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | -| `dispatcher.ts` | `Dispatcher`: the worker's handlers | -| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | -| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | -| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | -| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | -| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | -| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | -| `error-code.ts` | `classifyError`: thrown error → contract code | -| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | -| `lease-inputs.ts` | `createLeaseInputs`: the per-lease device input shared by the input module's sockets and `device.rotate`; closed by its last release, its failure or the lease's end | -| `rotation-refusal.ts` | `rotationRefusal`: `device.rotate`'s `ROTATION_UNSUPPORTED`, with how it names the device | -| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | -| `test-relay-support.ts` | Test helpers for relay e2e tests | +| File | Role | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `main.ts` | Composition root; worker or gateway; driver discovery; log sinks | +| `server.ts` | `DaemonServer`: framing, `hello`, sessions, pushes, readiness, stop | +| `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | +| `dispatcher.ts` | `Dispatcher`: the worker's handlers | +| `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | +| `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | +| `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | +| `openapi.ts` | `openApiDocument`, `writeOpenApiDocument`: the HTTP API document from the module registry; run by `pnpm openapi` | +| `update-coordinator.ts` | `createUpdateCoordinator`: `daemon.update`'s state (`waiting`, `installing`), the updater launch, `status.get`'s update fields | +| `version-check.ts` | `startVersionCheck`: npm's `latest` Simlock version, read at start and every 24 h (`update.check`); `status.get`'s `latestVersion`, both roles | +| `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | +| `error-code.ts` | `classifyError`: thrown error → contract code | +| `enrollment-wake.ts` | `wakingQueueAfter`: wakes the queue after `device.add`/`device.remove` | +| `lease-inputs.ts` | `createLeaseInputs`: the per-lease device input shared by the input module's sockets and `device.rotate`, closed by its last release, failure or the lease's end; `rotation-refusal.ts`: `rotationRefusal`, `device.rotate`'s `ROTATION_UNSUPPORTED` | +| `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | +| `test-relay-support.ts` | Test helpers for relay e2e tests | ## Composition (`main.ts`) @@ -147,6 +146,5 @@ Security model: cooperative identity, not a hostile-process boundary. - The claim comes before any write to `admin.token` and before converge. - On a worker, no request but `hello`, `status.get` and `daemon.stop` runs before converge ends. -- `daemon.stop` releases nothing. Leases persist with their deadlines. -- A closed connection ends no lease and kills no command. +- `daemon.stop` releases nothing; leases persist with their deadlines. A closed connection ends no lease and kills no command. - `daemon.started` is emitted only after converge, and never after `daemon.stopping`. diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 562159c42..c167cf8e1 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -96,6 +96,7 @@ A route with a `socket` handler also takes a WebSocket upgrade: `app.leaseSocket - `POST /v1/update` (optional body `{version, force}`, strict) → `daemon.update`: 202 when the call began the update (`started`), 200 when it followed one or found nothing to do (`upToDate`). The route declares both (`alsoStatus`). The role check is the dispatcher's; on a gateway it updates the gateway itself, with no lease wait. - `POST /v1/workers/{id}/update` (optional body `{version, force}`, strict) → `worker.update`: the same 202 and 200; `UNKNOWN_WORKER` 404, `WORKER_NOT_CONNECTED` 409, and a worker daemon answers 501. - `GET /v1/leases/{id}/events` — the lease's notices; ends on `lease_lost`. +- `POST /v1/leases/{id}/rotate` (body `{orientation}`, one of the four names, strict) → `device.rotate`: 200 with `{leaseId, orientation}`; `ROTATION_UNSUPPORTED` 422, `INPUT_UNAVAILABLE` 503, 403 for another requester's lease, 404 for an unknown one (`src/http/lease-declarations.ts`, `src/http/app.ts`). - `POST /v1/leases/{id}/exec` → `device.exec`. The stream opens on `onStarted`; a failure before that is a plain error response. Events: `output`, then `exit` or `error`. - `POST /v1/components/install` → `component.install`, or `worker.install-component` with From 44ba6888021dbf88e75daef56cb9454060ff4bb8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sat, 31 Oct 2026 22:01:20 +0100 Subject: [PATCH 24/29] fix(modules): reserve the rotate lease sub-route for the core route (#1107) --- src/daemon/optional-modules.test.ts | 4 ++-- src/modules/AGENTS.md | 2 +- src/modules/host.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/daemon/optional-modules.test.ts b/src/daemon/optional-modules.test.ts index 17a519b52..f54fc353e 100644 --- a/src/daemon/optional-modules.test.ts +++ b/src/daemon/optional-modules.test.ts @@ -279,8 +279,8 @@ describe("optional modules: HTTP routes", () => { ); }); - it("a module named like a core lease sub-route (renew, exec) fails the start, and POST /v1/leases/{id}/renew still renews", async () => { - for (const name of ["renew", "exec"]) { + it("a module named like a core lease sub-route (renew, exec, rotate) fails the start, and POST /v1/leases/{id}/renew still renews", async () => { + for (const name of ["renew", "exec", "rotate"]) { await expect(start({ modules: definitions(fakeModule({ name })) })).rejects.toThrow(name); } diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index 057ed9b5b..7bf092557 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -16,7 +16,7 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed ## Rules - A module is on only under `capabilities..enabled`; off, nothing of it is loaded and its capability reads `off`. `enabled` defaults to false; a definition with `enabledByDefault: "standalone-worker"` gets true on a worker with no `gateway.url` when no layer sets it. The loader reports those names (`loadConfigWithDefaults`), and the host hands the module `ctx.enabledByDefault`. -- Names: the capability name pattern, unique, not a core route segment or a core lease sub-route (`renew`, `exec`), at most 16 capabilities. +- Names: the capability name pattern, unique, not a core route segment or a core lease sub-route (`renew`, `exec`, `rotate`), at most 16 capabilities. - Creating starts nothing. A start that fails before the socket is claimed drops created modules; after it, the normal stop runs their stop hooks. - Hooks are direct calls. `afterSocketClaimed` is not awaited; `beforeDrain` and `beforeDriversDispose` share one 30 s budget per step; a throw is logged and the step goes on. - A definition with `localProfile` has a file in the data directory that the worker host keeps for local agents: `prepareLocalProfiles` (awaited by `daemon/main.ts` after the socket claim and before HTTP starts) writes it with one `agent` token labelled `localProfile.tokenLabel` when `http.enabled` and the module are on, and deletes it and revokes labelled tokens otherwise, for an off module too. A failure logs one `warn` and the start goes on. diff --git a/src/modules/host.ts b/src/modules/host.ts index 6bca07453..792c02f88 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -111,7 +111,7 @@ function targetsByName( } // why: a module's lease route is `/v1/leases/:id/`; these are the sub-routes the HTTP app registers itself, and a module may not take one. -const CORE_LEASE_SUBROUTES: readonly string[] = ["exec", "renew"]; +const CORE_LEASE_SUBROUTES: readonly string[] = ["exec", "renew", "rotate"]; type StopHook = "beforeDrain" | "beforeDriversDispose"; From b90d8f4c1f4e983b994609475aa185939d521604 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sat, 31 Oct 2026 22:02:23 +0100 Subject: [PATCH 25/29] test(contract): prove device.rotate's input bounds and strict keys (#1107) --- src/contract/operations.test.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index bf402ba72..118530201 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -1159,6 +1159,36 @@ describe("operation input/output round trips", () => { expect(OPERATIONS["device.exec"].output.parse({ exitCode: 0 })).toEqual({ exitCode: 0 }); }); + it("device.rotate: accepts a leaseId and requesterId of 1 to 256 characters and each orientation, and refuses an empty or 257-character one, another orientation or an unknown key", () => { + const parse = (input: object) => OPERATIONS["device.rotate"].input.parse(input); + const base = { leaseId: "lse_1", orientation: "portrait" }; + + for (const orientation of [ + "portrait", + "portrait_upside_down", + "landscape_left", + "landscape_right", + ]) { + expect(parse({ ...base, orientation })).toEqual({ ...base, orientation }); + } + expect(parse({ ...base, leaseId: "x".repeat(256), requesterId: "y".repeat(256) })).toEqual({ + ...base, + leaseId: "x".repeat(256), + requesterId: "y".repeat(256), + }); + + for (const refused of [ + { ...base, leaseId: "" }, + { ...base, leaseId: "x".repeat(257) }, + { ...base, requesterId: "" }, + { ...base, requesterId: "y".repeat(257) }, + { ...base, orientation: "upside_down" }, + { ...base, angle: 90 }, + ]) { + expect(() => parse(refused)).toThrow(); + } + }); + it("the output push carries a frame id, a stream, and a chunk", () => { expect(PUSH_SCHEMAS.output.parse({ chunk: "hello", requestId: 7, stream: "stdout" })).toEqual({ chunk: "hello", From f4f14845dfe9fa5407d0fc836a33ea62811e43ef Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sat, 31 Oct 2026 22:03:53 +0100 Subject: [PATCH 26/29] test(gateway): prove gateway.execTimeoutMs bounds a forwarded device.rotate (#1107) --- src/gateway/fleet-coordinator.test.ts | 33 +++++++++++++++++++++++++++ src/gateway/test-support.ts | 14 ++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 3eb03b612..88000c898 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1301,6 +1301,39 @@ describe("FleetLeaseCoordinator dispatch", () => { expect((error as DispatchError).code).toBe("EXEC_TIMEOUT"); }); + it("times out a forwarded device.rotate after gateway.execTimeoutMs when the worker never answers", async () => { + const { clock, coordinator, directory, workers } = harness({ execTimeoutMs: 5_000 }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request(REQUEST, requestOptions()); + client.hangingCalls.add("device.rotate"); + + const rotation = coordinator.rotate( + { leaseId: grant.lease.id, orientation: "landscape_left" }, + { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent-1", + role: "agent", + }, + ); + const rotationState = promiseState(rotation); + const rejection = rotation.catch((error: unknown) => error); + await tick(); + clock.advance(4_999); + await tick(); + expect(rotationState.state).toBe("pending"); + + clock.advance(1); + await tick(); + expect(rotationState.state).toBe("rejected"); + const error = await rejection; + expect(error).toBeInstanceOf(DispatchError); + expect((error as DispatchError).code).toBe("EXEC_TIMEOUT"); + }); + it("stops relaying a worker's device.exec output once gateway.execTimeoutMs has already rejected the call (H4, round 3 review)", async () => { const { clock, coordinator, directory, workers } = harness({ execTimeoutMs: 5_000 }); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index abcede425..a1d52f428 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -24,6 +24,8 @@ import type { LeaseRequestInput, InstallComponentOptions, RequestLeaseOptions, + RotateInput, + RotateOutput, StatusGetOutput, } from "../admin/index.js"; import type { GatewayWorkerClient } from "./worker-client.js"; @@ -496,6 +498,18 @@ export class ScriptedWorkerClient { return { exitCode: outcome?.exitCode ?? 0 }; } + // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. + async rotate( + leaseId: string, + orientation: RotateInput["orientation"], + options: { readonly requesterId?: string } = {}, + ): Promise { + this.calls.push(`device.rotate:${options.requesterId ?? ""}`); + if (this.hangingCalls.has("device.rotate")) return new Promise(() => {}); + this.#throwIfFailing(); + return { leaseId, orientation }; + } + // fallow-ignore-next-line unused-class-member -- reached through the GatewayWorkerClient that asClient() casts this double to. async installComponent( input: ComponentInstallInput, From 84bf37df0bfb5c8ab83bfea1577c5862b6816370 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sat, 31 Oct 2026 22:04:05 +0100 Subject: [PATCH 27/29] test(daemon): drop the failed-open case device-rotate's e2e test already proves (#1107) --- src/daemon/lease-inputs.test.ts | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/daemon/lease-inputs.test.ts b/src/daemon/lease-inputs.test.ts index 304eb74e2..ea9032cd3 100644 --- a/src/daemon/lease-inputs.test.ts +++ b/src/daemon/lease-inputs.test.ts @@ -44,17 +44,4 @@ describe("createLeaseInputs", () => { expect(factory.opened).toHaveLength(2); expect(fresh.input).toBe(factory.opened[1]); }); - - it("opens a fresh input for the next user after an open rejected", async () => { - const factory = new FakeInputFactory({ height: 2556, orientation: "portrait", width: 1179 }); - const inputs = createLeaseInputs({ openInput: () => factory.open() }); - factory.failWith = new Error("helper exploded"); - await expect(inputs.leaseInput("lease-1", "ios", device)).rejects.toThrow("helper exploded"); - factory.failWith = undefined; - - await inputs.leaseInput("lease-1", "ios", device); - - expect(factory.opens).toBe(2); - expect(factory.opened).toHaveLength(1); - }); }); From b8643d12342bcbb22404b2c6cb1459aba5823ac9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sat, 31 Oct 2026 22:05:57 +0100 Subject: [PATCH 28/29] chore(gateway): drop the Fallow suppression the rotate timeout test made stale (#1107) --- src/gateway/fleet-coordinator.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 212a155f0..cdbd01478 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -591,7 +591,6 @@ export class FleetLeaseCoordinator { /** * why: `device.rotate` forwarded to the worker that owns the lease, with the lease's own namespaced requester, bounded by `gateway.execTimeoutMs` like `exec`. A worker names the lease by its own id in any coded error; the caller holds the gateway's id, so the error names that instead. */ - // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option. async rotate(input: FleetRotateInput, _session: DispatchSession): Promise { const entry = this.#requireEntry(input.leaseId); const requesterId = `${this.options.leaseIndex.requesterPrefix}${entry.requesterId}`; From 283a63e59c849fce34d5cbdd4176f40dda6eeb1f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sat, 31 Oct 2026 22:12:58 +0100 Subject: [PATCH 29/29] fix(contract): bump the protocol to 68, since main took 67 (#1107) --- src/contract/AGENTS.md | 2 +- src/contract/protocol.ts | 2 +- src/daemon-protocol/index.test.ts | 2 +- src/daemon/AGENTS.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 748f8abf8..52ed801be 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -58,7 +58,7 @@ Three identities: ## Protocol version -- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 67, max: 67 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. +- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 68, max: 68 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`. - Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index b6d73d4d2..13ff9417e 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 67, max: 67 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 68, max: 68 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 64b593c20..02e4f3a67 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(67); + expect(DAEMON_PROTOCOL_VERSION).toBe(68); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 2862c26f0..3423d89cc 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -60,7 +60,7 @@ Its stdout lines move the state; a failed line, a non-zero exit or a failed laun 2. **Hello** — first frame must be `hello`, else `HANDSHAKE_REQUIRED` and close. Role: the uplink connection is `admin` by acceptance; otherwise the resolver. Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` - is `{ min: 67, max: 67 }` (`src/contract/protocol.ts`). No overlap → the + is `{ min: 68, max: 68 }` (`src/contract/protocol.ts`). No overlap → the connection stays open, and every request but `daemon.stop` gets `PROTOCOL_VERSION_UNSUPPORTED`. 4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`.