Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
d1f74bc
test: a holder's rotate of its iOS-simulator lease answers and sends …
leonardoxr Oct 31, 2026
a42ade3
feat(daemon): device.rotate turns a leased simulator through its devi…
leonardoxr Oct 31, 2026
fe1c197
test: a caller rotates a lease it may not touch, or names a bad orien…
leonardoxr Oct 31, 2026
2f1ebec
feat(contract): device.rotate is authorized like device.exec (#1107)
leonardoxr Oct 31, 2026
e54e3f2
test: a holder rotates a lease not on an iOS phone or tablet simulato…
leonardoxr Oct 31, 2026
18acbd7
feat(daemon): device.rotate refuses a lease not on an iOS phone or ta…
leonardoxr Oct 31, 2026
642a392
test: a holder rotates when the helper cannot start or the write fail…
leonardoxr Oct 31, 2026
770e4f0
feat(daemon): device.rotate answers INPUT_UNAVAILABLE with the reason…
leonardoxr Oct 31, 2026
50dac1b
test: an input socket opened after a rotate's helper closed gets a fr…
leonardoxr Oct 31, 2026
22b171d
feat(daemon): one device input per lease, shared by the input module'…
leonardoxr Oct 31, 2026
736d3ba
test: a client program calls client.rotate(leaseId, orientation) and …
leonardoxr Oct 31, 2026
e778c34
feat(client): client.rotate turns a lease's simulator through device.…
leonardoxr Oct 31, 2026
a4d9f18
test: an agent calls POST /v1/leases/{id}/rotate on a worker and thro…
leonardoxr Oct 31, 2026
0dc922c
feat(http): POST /v1/leases/{id}/rotate on a worker and through a gat…
leonardoxr Oct 31, 2026
6f2f973
docs: rotate over HTTP and its two error codes (#1107)
leonardoxr Oct 31, 2026
d8d222b
test: the alias parser maps a spelling to an orientation or the unkno…
leonardoxr Oct 31, 2026
4bae4e7
feat(contract): parseOrientation maps an alias to an orientation or t…
leonardoxr Oct 31, 2026
c6834bc
test: the gateway coordinator forwards device.rotate and names the ca…
leonardoxr Oct 31, 2026
df04c55
test: the front answers orientation on an iOS-simulator lease through…
leonardoxr Oct 31, 2026
b00dbb1
feat(agent-device): the front answers orientation on an iOS-simulator…
leonardoxr Oct 31, 2026
d167a43
test: the front forwards orientation to agent-device off an iOS phone…
leonardoxr Oct 31, 2026
fc86825
feat(agent-device): orientation is forwarded off an iOS phone or tabl…
leonardoxr Oct 31, 2026
eae80be
test: a socket whose write fails closes 1013 while the daemon keeps r…
leonardoxr Oct 31, 2026
aced7b4
test: fold the coordinator's rotate case into the HTTP gateway test t…
leonardoxr Oct 31, 2026
0844848
chore: name how the coordinator's rotate is reached for Fallow (#1107)
leonardoxr Oct 31, 2026
b262854
Merge remote-tracking branch 'origin/task/1107' into task/1109
leonardoxr Oct 31, 2026
428a0ff
test: orientation forwarding is proved for an Android lease on an iPh…
leonardoxr Oct 31, 2026
7aa86a7
fix(gateway): name the caller's lease id in every worker error, and p…
leonardoxr Oct 31, 2026
6382188
docs: list POST /v1/leases/{id}/rotate and device.rotate in the manua…
leonardoxr Oct 31, 2026
941b5ee
Merge remote-tracking branch 'origin/task/1107' into task/1109
leonardoxr Oct 31, 2026
9e60a65
test: a physical iPhone's orientation auto reaches agent-device; orie…
leonardoxr Oct 31, 2026
44ba688
fix(modules): reserve the rotate lease sub-route for the core route (…
V3RON Oct 31, 2026
b90d8f4
test(contract): prove device.rotate's input bounds and strict keys (#…
V3RON Oct 31, 2026
f4f1484
test(gateway): prove gateway.execTimeoutMs bounds a forwarded device.…
V3RON Oct 31, 2026
84bf37d
test(daemon): drop the failed-open case device-rotate's e2e test alre…
V3RON Oct 31, 2026
b8643d1
chore(gateway): drop the Fallow suppression the rotate timeout test m…
V3RON Oct 31, 2026
a65cdee
Merge branch 'task/1107' into task/1109
V3RON Oct 31, 2026
9aff689
Merge remote-tracking branch 'origin/main' into fix-1107
V3RON Oct 31, 2026
283a63e
fix(contract): bump the protocol to 68, since main took 67 (#1107)
V3RON Oct 31, 2026
c07740c
Merge branch 'fix-1107' into fix-1109
V3RON Oct 31, 2026
31765ef
Merge remote-tracking branch 'origin/main' into up-1109
V3RON Oct 31, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions src/agent-device/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ On unless `capabilities.agent-device.enabled` is set false, on a standalone work
| `front/front.ts` | The mount: role check, routes, `/rpc` dispatch by call class |
| `front/request-rules.ts` | Refusals and rewrites before anything is forwarded |
| `front/allocate.ts`, `front/heartbeat.ts`, `front/release.ts` | Lease calls ↔ simlock `lease.*` |
| `front/orientation.ts` | `orientation` on an iOS phone or tablet simulator lease: `device.rotate`, answered unconfirmed; anything else forwarded |
| `front/renewals.ts` | Renews the simlock lease while a command runs |
| `front/front-map.ts` | In-memory leases this front made, and who ended each |
| `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases |
Expand Down Expand Up @@ -76,12 +77,11 @@ Front (`createFront`, prefix `agent-device`):
6. Heartbeat → forwarded with `ttlMs` raised to the ceiling; on success `renewLease`
(`lease.renew` only if it moves the deadline; a gateway list that trails the grant and omits the lease still relays agent-device's reply). agent-device says gone → `lease.release`, reply "ended by simlock".
7. Release → forwarded; on success `lease.release`; map marks it ended by `agent`.
8. Command on a lease → `Renewals.begin`: renew every TTL/3 until the body ends,
capped at `lease.maxTtlMs`. A reply naming `endedLeases` (in `data`, `error.details`, a streamed `type: "response"` line, or a
8. Command on a lease → `Renewals.begin`: renew every TTL/3 until the body ends, capped at `lease.maxTtlMs`. A reply naming `endedLeases` (in `data`, `error.details`, a streamed `type: "response"` line, or a
batch's `data`) → `front/ended.ts` ends each simlock lease this token holds, as a release does.
`orientation` (not a batch step) on an `ios`, not physical lease (an adopted one: physical unknown) whose model is an iPhone or iPad → `device.rotate`, answered with agent-device's unconfirmed reply, `INVALID_ARGS` for an unknown name (an adopted lease forwards it); `ROTATION_UNSUPPORTED`, `UNKNOWN_LEASE` and `FORBIDDEN` forward the command; `WORKER_UNREACHABLE` answers the try-again reply; any other error `COMMAND_FAILED`. Every other lease is forwarded before the name is read.

Host (`AgentDeviceHost.forward`): one proxy per daemon generation. Tags the request, and `authenticate` sets tenant = requester id, overwriting the client's. Rewrites `/v1/agent-device` → `/agent-device`. Download: `Content-Length` > 2 GiB → 413 before
any byte; no length → counted, errors past 2 GiB.
Host (`AgentDeviceHost.forward`): one proxy per daemon generation. Tags the request, and `authenticate` sets tenant = requester id, overwriting the client's. Rewrites `/v1/agent-device` → `/agent-device`. Download: `Content-Length` > 2 GiB → 413 before any byte; no length → counted, errors past 2 GiB.

Lease end: `ReleaseScopeRecord` reads each allocate reply's scope (tenant, run id, …)
through the proxy's upstream fetch. `AgentDeviceLeaseEnd.leaseEnded` waits for a
Expand Down Expand Up @@ -130,8 +130,7 @@ under leasing's signal (`lease.endWaitMs`).
| Renewal tick | TTL / 3 | lease TTL |
| Download cap; `/rpc` body | 2 GiB; 1 MiB | none |

Disk: `<data dir>/agent-device/` and `<data dir>/agent-device-phones/` (agent-device's own files) and the two pid records. Front map,
renewals and release scopes: memory only.
Disk: `<data dir>/agent-device/` and `<data dir>/agent-device-phones/` (agent-device's own files) and the two pid records. Front map, renewals and release scopes: memory only.

Local profile: a standalone worker with HTTP and this module on keeps `<data dir>/agent-device-profile.json` (0600) so an agent on the same Mac connects with `agent-device connect --remote-config <file>` and no token of its own ([ADR 0046](../../docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md)). `definition.ts` declares the file as plain data; the module host writes it at each start, reuses the one `agent`-role token labelled `agent-device on this Mac` (so an agent's saved connection stays valid), revokes other tokens with that label, and deletes the file and revokes the token when HTTP or the module is off. No worker code runs for it.

Expand Down
7 changes: 7 additions & 0 deletions src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,13 @@ describe("the agent-device front, through the whole worker daemon", () => {
"physical",
);
expect(allocatesReceived(rig)).toEqual([]);
if (platform === "ios") {
// why: a physical iPhone has no `device.rotate`, so its `orientation auto` must reach agent-device, not be refused as an unknown name.
await command(rig, "orientation", 1, {}, { positionals: ["auto"] });
expect(rig.phone.rpcRequests("agent_device.command")).toMatchObject([
{ params: { command: "orientation", positionals: ["auto"] } },
]);
}
}
});

Expand Down
1 change: 1 addition & 0 deletions src/agent-device/front/allocate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ async function keepOrRelease(
deadline: grant.lease.ttlDeadline,
identity,
model: grant.device.spec.model,
physical: grant.device.spec.physical === true,
platform: plan.platform,
ttlMs: grant.lease.ttlMs,
...replyFacts(reading.result),
Expand Down
1 change: 1 addition & 0 deletions src/agent-device/front/front-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ interface DeviceFacts {
readonly model?: string;
readonly name?: string;
readonly target?: string;
readonly physical?: boolean;
readonly deviceKey?: string;
// why: an adopted entry was rebuilt after a gateway restart and has no device key until a call names one.
readonly adopted?: boolean;
Expand Down
5 changes: 5 additions & 0 deletions src/agent-device/front/front.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { anyUnreachable, devicesThroughGateway, filterDevices } from "./devices-
import { heartbeat } from "./heartbeat.js";
import type { LinkStatus } from "./host-link.js";
import { releaseEndedLeases } from "./ended.js";
import { answerOrientation, isOrientationCall } from "./orientation.js";
import { release } from "./release.js";
import { checkRequest } from "./request-rules.js";

Expand Down Expand Up @@ -222,6 +223,10 @@ async function forwardCommand(
read: RpcRequest,
leaseId: string | undefined,
): Promise<Response> {
if (leaseId !== undefined && isOrientationCall(read)) {
const answered = await answerOrientation(context, identity, read, leaseId);
if (answered !== undefined) return answered;
}
const isDevices = isDevicesCall(read);
if (isDevices && context.link.readsLeaseHeader) {
return devicesThroughGateway(context, {
Expand Down
280 changes: 280 additions & 0 deletions src/agent-device/front/orientation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
import { describe, expect, it } from "vitest";

import { tokenIdentity } from "../../auth/testing.js";
import { DispatchError } from "../../daemon/dispatch.js";
import type { HttpDispatch } from "../../http/dispatcher-session.js";
import { FakeClock, NoopLogger } from "../../ports/index.js";
import { FRONT_PREFIX } from "../shared/paths.js";
import type { FrontContext } from "./context.js";
import { FrontMap } from "./front-map.js";
import { createFront } from "./front.js";
import type { HostLink } from "./host-link.js";
import { Renewals } from "./renewals.js";

const agent = tokenIdentity("tok_a");
const leaseId = "a".repeat(32);
const ttlMs = 600_000;
const forwardedAnswer = { forwarded: true };

interface Rig {
readonly handle: (command: string, positionals?: readonly string[]) => Promise<Response>;
readonly rotations: unknown[];
readonly forwarded: unknown[];
readonly clock: FakeClock;
}

interface RigOptions {
readonly gateway: boolean;
readonly model: string;
readonly adopted?: boolean;
readonly platform?: "ios" | "android";
readonly physical?: boolean;
readonly owner?: typeof agent;
readonly rotate?: () => Promise<unknown>;
}

function rig(options: RigOptions): Rig {
const clock = new FakeClock(1_000);
const map = new FrontMap(clock);
const rotations: unknown[] = [];
const forwarded: unknown[] = [];
const entry = {
address: "udid-1",
deadline: clock.now() + ttlMs,
identity: options.owner ?? agent,
model: options.model,
platform: options.platform ?? "ios",
...(options.physical === undefined ? {} : { physical: options.physical }),
target: "mobile",
ttlMs,
};
if (!options.adopted) map.add(leaseId, entry);
const link: HostLink = {
adoptable: () => (options.adopted ? [{ ...entry, leaseId, ttlDeadline: entry.deadline }] : []),
forward: async (request) => {
forwarded.push(JSON.parse(await request.text()));
return Response.json({ id: 1, jsonrpc: "2.0", result: { data: forwardedAnswer, ok: true } });
},
readsLeaseHeader: options.gateway,
status: () => Promise.resolve({ platforms: ["ios", "android"], state: "running" }),
};
const dispatch = ((operation: string, input: unknown) => {
if (operation === "device.rotate") {
rotations.push(input);
return (options.rotate ?? (() => Promise.resolve({})))();
}
if (operation === "lease.list") {
return Promise.resolve({
leases: [{ id: leaseId, requesterId: leaseId, ttlDeadline: clock.now() + ttlMs * 10 }],
});
}
return Promise.resolve({});
}) as unknown as HttpDispatch;
const context: FrontContext = {
clock,
dispatch,
link,
logger: new NoopLogger(),
map,
maxRunMs: 3_600_000,
renewals: new Renewals(clock),
};
const mount = createFront(context);
return {
clock,
forwarded,
handle: (command, positionals = []) =>
Promise.resolve(
mount.handle(
new Request(`http://simlock.test${FRONT_PREFIX}/rpc`, {
body: JSON.stringify({
id: 7,
jsonrpc: "2.0",
method: "agent_device.command",
params: { command, meta: { leaseId }, positionals },
}),
headers: { "content-type": "application/json" },
method: "POST",
}),
agent,
),
),
rotations,
};
}

interface Envelope {
readonly id?: unknown;
readonly result?: { readonly ok: boolean; readonly data: Record<string, unknown> };
readonly error?: {
readonly data: {
readonly code: string;
readonly message: string;
readonly details?: { readonly reason: string };
};
};
}

async function answer(response: Response): Promise<Envelope> {
return (await response.json()) as Envelope;
}

function unconfirmed(name: string) {
return {
action: "orientation",
confirmed: false,
message: `Rotation requested: ${name} (unconfirmed)`,
orientation: name,
warning: `Requested ${name}; the device owner reported no resulting orientation, so the rotation is unconfirmed.`,
};
}

const unknownMessage = (input: string) =>
`Unknown orientation ${input}; use portrait, portrait-upside-down, landscape-left or landscape-right`;

const rotated = [
["landscape-left", "landscape_left", "landscape-left"],
["Left", "landscape_left", "landscape-left"],
["right", "landscape_right", "landscape-right"],
["upside-down", "portrait_upside_down", "portrait-upside-down"],
["portrait", "portrait", "portrait"],
] as const;

async function expectRotated(gateway: boolean, model: string, row: (typeof rotated)[number]) {
const [typed, sent, named] = row;
const { handle, rotations, forwarded, clock } = rig({ gateway, model });
const body = await answer(await handle("orientation", [typed]));
const label = `${gateway ? "gateway" : "worker"} ${model} ${typed}`;
expect(body.id, label).toBe(7);
expect(body.result, label).toEqual({ data: unconfirmed(named), ok: true });
expect(rotations, label).toEqual([{ leaseId, orientation: sent }]);
expect(forwarded, label).toEqual([]);
expect(clock.pendingTimerCount, label).toBe(0);
}

async function expectAdoptedRotated() {
const adopted = rig({ adopted: true, gateway: true, model: "iPhone 17 Pro" });
const body = await answer(await adopted.handle("orientation", ["landscape-right"]));
expect(body.result).toEqual({ data: unconfirmed("landscape-right"), ok: true });
expect(adopted.rotations).toEqual([{ leaseId, orientation: "landscape_right" }]);
expect(adopted.forwarded).toEqual([]);
}

async function expectInvalid(typed: readonly string[]) {
const { handle, rotations, forwarded } = rig({ gateway: false, model: "iPad Pro 13-inch (M5)" });
const response = await handle("orientation", typed);
const body = await answer(response);
expect(response.status).toBe(400);
expect(body.error?.data).toEqual({
code: "INVALID_ARGS",
message: unknownMessage(typed[0] ?? ""),
});
expect(rotations).toEqual([]);
expect(forwarded).toEqual([]);
}

interface Failure {
readonly error: Error;
readonly expected: {
readonly code: string;
readonly message: string;
readonly status: number;
readonly details?: { readonly reason: string };
};
}

const failures: readonly Failure[] = [
{
error: new DispatchError("INPUT_UNAVAILABLE", "the input helper could not start", {
leaseId,
reason: "x",
}),
expected: { code: "COMMAND_FAILED", message: "the input helper could not start", status: 502 },
},
{
error: new Error("rotate blew up"),
expected: { code: "COMMAND_FAILED", message: "rotate blew up", status: 502 },
},
{
error: new DispatchError("WORKER_UNREACHABLE", "worker w1 is not connected", {
workerId: "w1",
}),
expected: {
code: "COMMAND_FAILED",
details: { reason: "WORKER_UNREACHABLE" },
message:
"agent-device is not available on this simlock: the worker holding this device is not connected to the gateway; try again",
status: 503,
},
},
];

async function expectFailure({ error, expected }: Failure) {
const { handle, forwarded, clock } = rig({
gateway: true,
model: "iPhone 17 Pro",
rotate: () => Promise.reject(error),
});
const response = await handle("orientation", ["landscape-left"]);
const renewing = expected.status === 503 ? 0 : 2;
expect(clock.pendingTimerCount, `${expected.message} renewal before the body is read`).toBe(
renewing,
);
const body = await answer(response);
const { status, ...data } = expected;
expect(response.status, data.message).toBe(status);
expect(body.error?.data, data.message).toEqual(data);
expect(forwarded, data.message).toEqual([]);
expect(clock.pendingTimerCount, data.message).toBe(0);
}

describe("the agent-device front's orientation command", () => {
it("answers `orientation <name>` on a Simlock iOS-simulator lease with agent-device's unconfirmed reply through device.rotate, without the command reaching agent-device; `auto` or an unknown name is `INVALID_ARGS`, a missing helper `COMMAND_FAILED`, a gone worker the worker-unreachable reply", async () => {
for (const gateway of [true, false]) {
for (const model of ["iPhone 17 Pro", "iPad Pro 13-inch (M5)"]) {
for (const row of rotated) await expectRotated(gateway, model, row);
}
}
await expectAdoptedRotated();
for (const typed of [["auto"], ["sideways"], []]) await expectInvalid(typed);
for (const failure of failures) await expectFailure(failure);
});

it("forwards `orientation <name>` to agent-device when the lease is not on an iOS phone or tablet simulator, or Simlock no longer knows it", async () => {
const cases = [
{ label: "Android emulator", platform: "android", model: "Pixel 8" },
{ label: "Android phone", platform: "android", model: "Pixel 8", physical: true },
{ label: "iPhone", physical: true, model: "iPhone 17 Pro" },
{ label: "Apple TV simulator", model: "Apple TV 4K (3rd generation)" },
{ label: "Android on an iPhone model", platform: "android", model: "iPhone 17 Pro" },
{ label: "another token's lease", owner: tokenIdentity("tok_b"), model: "iPhone 17 Pro" },
] as const;
for (const { label, ...lease } of cases) {
for (const typed of ["landscape-left", "auto"]) {
const { handle, rotations, forwarded } = rig({ gateway: false, ...lease });
const body = await answer(await handle("orientation", [typed]));
expect(body.result?.data, `${label} ${typed}`).toEqual(forwardedAnswer);
expect(forwarded, `${label} ${typed}`).toHaveLength(1);
expect(rotations, `${label} ${typed}`).toEqual([]);
}
}

for (const code of ["UNKNOWN_LEASE", "FORBIDDEN", "ROTATION_UNSUPPORTED"]) {
const { handle, rotations, forwarded } = rig({
gateway: true,
model: "iPhone 17 Pro",
rotate: () => Promise.reject(new DispatchError(code, "not rotatable here")),
});
const body = await answer(await handle("orientation", ["landscape-left"]));
expect(body.result?.data, code).toEqual(forwardedAnswer);
expect(forwarded, code).toHaveLength(1);
expect(rotations, code).toHaveLength(1);
}

const adopted = rig({ adopted: true, gateway: true, model: "iPhone 17 Pro" });
const body = await answer(await adopted.handle("orientation", ["auto"]));
expect(body.result?.data).toEqual(forwardedAnswer);
expect(adopted.forwarded).toHaveLength(1);
expect(adopted.rotations).toEqual([]);
});
});
Loading
Loading