Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
5be571e
test: a lease holder runs exec with stdinFile and the command reads t…
V3RON Nov 6, 2026
0b23ca7
feat(exec): exec pipes a lease file named by stdinFile to the command…
V3RON Nov 6, 2026
821b3fb
test: stdin and stdinFile together are refused with BAD_REQUEST over …
V3RON Nov 6, 2026
ec5d6b8
feat(exec): exec refuses stdin and stdinFile together (#1357)
V3RON Nov 6, 2026
c47948c
test: stdinFile cases: 9 MiB, empty, other case, null, bad name, unkn…
V3RON Nov 6, 2026
5cf78f1
feat(exec): a stdinFile that names no file answers UNKNOWN_FILE befor…
V3RON Nov 6, 2026
3432029
test: a read error of the input stream rejects inputFailed with the b…
V3RON Nov 6, 2026
3f97670
feat(ports): a streamed child's input stream is piped with backpressu…
V3RON Nov 6, 2026
5424fca
test: a stdinFile that cannot be read to its end stops the command an…
V3RON Nov 6, 2026
ecb23f5
feat(exec): a stdinFile that cannot be read to its end stops the comm…
V3RON Nov 6, 2026
6e8dc30
feat(mcp): run_on_device takes no stdinFile (#1357)
V3RON Nov 6, 2026
b457994
feat(exec): every exec runs with the lease folder as its working fold…
V3RON Nov 6, 2026
42c8eab
test: through a gateway, exec with stdinFile reaches the lease's work…
V3RON Nov 6, 2026
a954d2d
feat(gateway): exec forwards stdinFile to the lease's worker (#1357)
V3RON Nov 6, 2026
b22a37f
test(e2e): a lease's uploaded 70 MB file is pushed to a real emulator…
V3RON Nov 6, 2026
699051a
docs(exec): stdinFile and the lease folder as the working folder (#1357)
V3RON Nov 6, 2026
cb6ce24
chore: run the full push hooks on the finished change (#1357)
V3RON Nov 6, 2026
b1a60cd
docs(lease-files): the folder-level test comment names who calls fold…
V3RON Nov 6, 2026
b42ac9e
refactor(exec): the spawn of an exec is its own method and the test l…
V3RON Nov 6, 2026
efd952b
Merge remote-tracking branch 'origin/task/1356' into HEAD
V3RON Nov 6, 2026
2f4d99b
test(e2e): the fake tool's reported working folder is part of the exp…
V3RON Nov 6, 2026
1c78001
fix(daemon): device.exec answers 404 for an ended lease, a vanished f…
V3RON Nov 6, 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
13 changes: 9 additions & 4 deletions docs/internal/flows/device-exec.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Modules: [daemon](../../../src/daemon/AGENTS.md), [gateway](../../../src/gateway/AGENTS.md).
Contract: `src/contract/operations.ts` `deviceExec` — role `agent`, effect `write`.
Input (strict): `{ leaseId, tool, args, stdin?, requesterId? }`. Output: `{ exitCode }`.
Input (strict): `{ leaseId, tool, args, stdin?, stdinFile?, requesterId? }`. Output: `{ exitCode }`.
Runs the command on the machine that owns the device and streams its output back.

## Callers
Expand Down Expand Up @@ -36,9 +36,14 @@ Runs the command on the machine that owns the device and streams its output back
another device (ADR 0047), see "Resolution per platform".
5. Env — `execBaseEnvironment(process.env)` (`src/daemon/exec-env.ts`, the allowlisted
keys, read once at start) + the command's `env`, minus its `unsetEnv`.
6. Spawn — `ProcessRunner.spawnStreaming`, pipes only. `stdin` (at most 8 MiB
of characters, refused `BAD_REQUEST` by the contract before any dispatcher
forwards or spawns) is written once, then closed.
6. Spawn — `ProcessRunner.spawnStreaming`, pipes only, with the lease's folder
(`LeaseFiles.folderOf`) as `cwd`. `stdin` (at most 8 MiB of characters, refused
`BAD_REQUEST` by the contract before any dispatcher forwards or spawns) is written
once, then closed. `stdinFile` instead names a file of that folder, opened first
(`UNKNOWN_FILE` before anything starts) and piped as `inputStream`; both together
are `BAD_REQUEST`, checked by the worker's dispatcher. A read failure rejects the
handle's `inputFailed`: the command is stopped as a timeout stops it and the
stream ends with `STDIN_FILE_FAILED`. A gateway forwards `stdinFile` unchanged.
7. `started` push the moment the process exists, then one `output` push per chunk
(`{ requestId, stream, chunk }`). The push write is awaited before the child is
read again: a slow reader slows the command. Nothing is buffered; no size cap.
Expand Down
92 changes: 92 additions & 0 deletions e2e/device-exec.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { realpath } from "node:fs/promises";
import { createServer } from "node:net";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";

import { waitFor, withDaemon, type TestEnv } from "./helpers/index.js";
Expand Down Expand Up @@ -181,6 +183,7 @@ describe("device.exec over HTTP", () => {
// device root is prepended and the driver's environment reached the child's own process.
expect(JSON.parse(chunksOf(frames, "stdout"))).toEqual({
argv: ["/fake/ios", "list", "devices", "--fake-exec-stderr=a warning", "--fake-exec-exit=3"],
cwd: expect.any(String),
platform: "ios",
});
expect(chunksOf(frames, "stderr")).toBe("a warning");
Expand All @@ -200,6 +203,95 @@ describe("device.exec over HTTP", () => {
await env.cli(["release", leaseId]);
});

it("runs exec with stdinFile and the command reads the file's bytes, then end of input", async () => {
const { baseUrl, env, exec, lease, token } = await fleet();
const auth = await token("agent");
const leaseId = await lease({ device: "iPhone 16", os: "18.4", platform: "ios" }, auth);
const upload = async (name: string, body: string): Promise<void> => {
const uploaded = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/${name}`, {
body,
headers: { ...auth, "content-type": "application/octet-stream" },
method: "PUT",
});
expect(uploaded.status).toBe(201);
};
const nineMiB = "0123456789abcdef".repeat(9 * 65_536);
await upload("fixture.txt", "stored payload");
await upload("big.bin", nineMiB);
await upload("empty.bin", "");

const reads = [
{ name: "fixture.txt", stdin: "stored payload" },
{ name: "big.bin", stdin: nineMiB },
{ name: "empty.bin", stdin: "" },
{ name: "FIXTURE.TXT", stdin: "stored payload" },
];
for (const { name, stdin } of reads) {
const response = await exec(
leaseId,
{ args: ["list", "--fake-exec-echo-stdin"], stdinFile: name, tool: "simctl" },
auth,
);
expect(response.status).toBe(200);
const frames = await readSse(response);
expect(frames.at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" });
expect((JSON.parse(chunksOf(frames, "stdout")) as { stdin: string }).stdin === stdin).toBe(
true,
);
}
const none = await exec(
leaseId,
{ args: ["list"], stdin: null, stdinFile: null, tool: "simctl" },
auth,
);
expect(none.status).toBe(200);
expect((await readSse(none)).at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" });

const refusals = [
{ body: { stdinFile: ".hidden" }, code: "BAD_REQUEST", status: 400 },
{ body: { stdinFile: "missing.tar" }, code: "UNKNOWN_FILE", status: 404 },
{ body: { stdin: "x", stdinFile: "fixture.txt" }, code: "BAD_REQUEST", status: 400 },
];
for (const { body, code, status } of refusals) {
const refused = await exec(leaseId, { args: ["list"], tool: "simctl", ...body }, auth);
expect(refused.status).toBe(status);
expect(await errorCodeOf(refused)).toBe(code);
}

await env.cli(["release", leaseId]);
});

it("runs every exec with the lease's folder as its working folder", async () => {
const { baseUrl, env, exec, lease, token } = await fleet();
const auth = await token("agent");
const leaseId = await lease({ device: "iPhone 16", os: "18.4", platform: "ios" }, auth);
const report = async (args: string[]): Promise<{ cwd: string; fileSize?: number }> => {
const response = await exec(leaseId, { args, tool: "simctl" }, auth);
expect(response.status).toBe(200);
const frames = await readSse(response);
expect(frames.at(-1)).toEqual({ data: { exitCode: 0 }, event: "exit" });
return JSON.parse(chunksOf(frames, "stdout")) as { cwd: string; fileSize?: number };
};

// why: no file was uploaded yet, so this shows the folder is made for the command.
const first = await report(["list"]);
expect(dirname(await realpath(first.cwd))).toBe(
join(await realpath(env.dataDirectory), "lease-files"),
);

const uploaded = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/fixture.bin`, {
body: "x".repeat(1234),
headers: { ...auth, "content-type": "application/octet-stream" },
method: "PUT",
});
expect(uploaded.status).toBe(201);
const second = await report(["list", "--fake-exec-read-file=fixture.bin"]);
expect(second.fileSize).toBe(1234);
expect(await realpath(second.cwd)).toBe(await realpath(first.cwd));

await env.cli(["release", leaseId]);
});

it("refuses through the fake driver's own mirrored list, and never runs what it refuses", async () => {
// The fake driver's refusal rules are its own mirror of the real Android/iOS drivers'
// (see `e2e/fake-driver/fake-driver.ts`'s own comment on `passthrough`), kept deliberately
Expand Down
5 changes: 5 additions & 0 deletions e2e/fake-driver/fake-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,13 @@ const PASSTHROUGH_PROGRAM =
// running while the route has to decide what to answer.
"const sleepMs = Number(flag('--fake-exec-sleep') ?? 0);" +
"if (sleepMs > 0) setTimeout(() => {}, sleepMs);" +
// why: `device.exec` runs every command in the lease's folder: `cwd` shows where, and
// `--fake-exec-read-file=<name>` shows that a relative name finds a file stored there.
"const readFile = flag('--fake-exec-read-file');" +
"const report = (stdin) => process.stdout.write(JSON.stringify({" +
"argv," +
"cwd: process.cwd()," +
"...(readFile === undefined ? {} : { fileSize: require('node:fs').readFileSync(readFile).length })," +
"platform: process.env.SIMLOCK_FAKE_PASSTHROUGH_PLATFORM ?? null," +
"...(stdin === undefined ? {} : { stdin })," +
"}));" +
Expand Down
2 changes: 2 additions & 0 deletions e2e/gateway-smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ describe("gateway smoke", () => {
"--fake-exec-exit=3",
"--fake-exec-echo-stdin",
],
// why: `device.exec` runs in the lease's folder on the worker, which lives under lease-files.
cwd: expect.stringContaining("lease-files"),
platform: "android",
stdin: "",
});
Expand Down
3 changes: 3 additions & 0 deletions e2e/lease-environment-passthrough.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ describe("reaching a leased device", () => {
expect(passthrough.code).toBe(7);
expect(JSON.parse(passthrough.stdout)).toEqual({
argv: [`/fake/${platform}`, ...args],
// why: the fake reports its working folder; a worker's passthrough keeps the CLI's own,
// so only that a folder was reported is asserted here.
cwd: expect.any(String),
platform,
});
},
Expand Down
134 changes: 134 additions & 0 deletions e2e/slow-android-lease-files.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";

import { DEVICE_READY_MS, waitFor, withHttpDaemon } from "./helpers/index.js";

const ANDROID_HOME =
process.env.ANDROID_HOME ??
process.env.ANDROID_SDK_ROOT ??
join(homedir(), "Library/Android/sdk");
const hasAndroidSdk =
existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb"));

const FILE_BYTES = 70_000_000;

interface SseFrame {
readonly event: string;
readonly data: unknown;
}

async function readSse(response: Response): Promise<SseFrame[]> {
const frames: SseFrame[] = [];
for (const raw of (await response.text()).split("\n\n")) {
if (raw.trim() === "" || raw.startsWith(":")) continue;
let event: string | undefined;
let data = "";
for (const line of raw.split("\n")) {
if (line.startsWith("event:")) event = line.slice(6).trim();
else if (line.startsWith("data:")) data += line.slice(5).trim();
}
if (event !== undefined) frames.push({ data: JSON.parse(data) as unknown, event });
}
return frames;
}

// why: only a real emulator proves that the folder a lease's upload went to is the folder `adb push` reads from, and that `adb pull` leaves a file the GET route serves, at a size no fake pipe is asked to carry.
describe.skipIf(!hasAndroidSdk)(
"a lease's files on a real emulator",
{ tags: ["slow", "android"] },
() => {
it(
"pushes an uploaded 70 MB file to the emulator with adb push, reads its size back with adb shell wc -c, and pulls it into a file a GET returns byte for byte",
{ timeout: 600_000 },
async () => {
const { env, port } = await withHttpDaemon((httpPort) => ({
configOverrides: {
http: { enabled: true, host: "127.0.0.1", port: httpPort },
idle: { shutdownAfterMs: 300_000 },
warmPool: { learn: false },
},
driver: "real",
}));
const baseUrl = `http://127.0.0.1:${String(port)}`;
try {
const created = await env.cli(["token", "create", "--role", "agent"]);
expect(created.code, created.stderr).toBe(0);
const auth = {
authorization: `Bearer ${(created.json as { secret: string }).secret}`,
"content-type": "application/json",
};
const requested = await fetch(`${baseUrl}/v1/lease-requests`, {
body: JSON.stringify({ device: "Pixel 9", platform: "android" }),
headers: auth,
method: "POST",
});
expect(requested.status).toBe(201);
const requestId = ((await requested.json()) as { request: { id: string } }).request.id;
let leaseId = "";
await waitFor(
async () => {
const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, {
headers: auth,
});
const view = (await polled.json()) as {
request: { state: string; lease?: { id: string } };
};
leaseId = view.request.lease?.id ?? "";
return view.request.state === "granted";
},
{ label: "the lease request is granted", timeout: DEVICE_READY_MS },
);

const bytes = Buffer.alloc(FILE_BYTES);
for (let at = 0; at < FILE_BYTES; at += 1) bytes[at] = at % 251;
const uploaded = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/fixture.bin`, {
body: bytes,
headers: { ...auth, "content-type": "application/octet-stream" },
method: "PUT",
});
expect(uploaded.status).toBe(201);

const run = async (args: string[]): Promise<{ exitCode: number; stdout: string }> => {
const response = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, {
body: JSON.stringify({ args, tool: "adb" }),
headers: auth,
method: "POST",
});
expect(response.status).toBe(200);
const frames = await readSse(response);
const exit = frames.find((frame) => frame.event === "exit");
return {
exitCode: (exit?.data as { exitCode: number } | undefined)?.exitCode ?? -1,
stdout: frames
.filter((frame) => frame.event === "output")
.map((frame) => frame.data as { stream: string; chunk: string })
.filter((chunk) => chunk.stream === "stdout")
.map((chunk) => chunk.chunk)
.join(""),
};
};

expect((await run(["push", "fixture.bin", "/data/local/tmp/fixture.bin"])).exitCode).toBe(
0,
);
const size = await run(["shell", "wc", "-c", "/data/local/tmp/fixture.bin"]);
expect(size.exitCode).toBe(0);
expect(size.stdout).toContain(String(FILE_BYTES));
expect((await run(["pull", "/data/local/tmp/fixture.bin", "back.bin"])).exitCode).toBe(0);

const back = await fetch(`${baseUrl}/v1/leases/${leaseId}/files/back.bin`, {
headers: auth,
});
expect(back.status).toBe(200);
expect(Buffer.from(await back.arrayBuffer()).equals(bytes)).toBe(true);
} finally {
await env
.cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 })
.catch(() => undefined);
}
},
);
},
);
4 changes: 4 additions & 0 deletions src/contract/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ export interface ErrorDetailsMap {
PASSTHROUGH_REFUSED: { readonly tool: string };
UNKNOWN_PASSTHROUGH_TOOL: { readonly tool: string };
EXEC_TIMEOUT: Record<string, never>;
/** why: ADR 0067 §5: the lease file named by `stdinFile` could not be read to its end after `bytesRead` bytes, and the command was stopped. */
STDIN_FILE_FAILED: { readonly name: string; readonly bytesRead: number };
/** 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;
Expand Down Expand Up @@ -229,6 +231,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record<CodeWithDeclaredDetails, true>
FILE_TOO_LARGE: true,
LEASE_FILES_FULL: true,
UNKNOWN_FILE: true,
STDIN_FILE_FAILED: true,
UPLOAD_STALLED: true,
FILE_BUSY: true,
LICENSE_NOT_ACCEPTED: true,
Expand Down Expand Up @@ -368,6 +371,7 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry
FILE_TOO_LARGE: { code: "FILE_TOO_LARGE", kind: "domain", cliExitCode: 1, httpStatus: 413 },
LEASE_FILES_FULL: { code: "LEASE_FILES_FULL", kind: "domain", cliExitCode: 1, httpStatus: 413 },
UNKNOWN_FILE: { code: "UNKNOWN_FILE", kind: "domain", cliExitCode: 1, httpStatus: 404 },
STDIN_FILE_FAILED: { code: "STDIN_FILE_FAILED", kind: "domain", cliExitCode: 1, httpStatus: 500 },
UPLOAD_STALLED: { code: "UPLOAD_STALLED", kind: "domain", cliExitCode: 1, httpStatus: 408 },
FILE_BUSY: { code: "FILE_BUSY", kind: "domain", cliExitCode: 1, httpStatus: 409 },
// why: a lease's tunnel socket refuses with these (ADR 0054 section 7), so every surface reports them alike.
Expand Down
10 changes: 10 additions & 0 deletions src/contract/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,9 @@ export const driverPassthrough = defineOperation({
output: passthroughCommandSchema,
});

/** why: the File name rule of a lease's files (1 to 128 characters), shared by the upload routes and exec's `stdinFile`. */
export const LEASE_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;

// why: the daemon parses a request as one string, so unbounded stdin exhausts the heap (#1242).
export const EXEC_STDIN_MAX_LENGTH = 8_388_608;

Expand All @@ -496,6 +499,12 @@ export const EXEC_STDIN_MAX_LENGTH = 8_388_608;
* `PASSTHROUGH_REFUSED` a lifecycle verb gets. Locally, where the CLI hands the tool its own
* terminal, it stays allowed and interactive.
*
* Every command runs with the lease's folder on the worker as its working folder (ADR 0067 §5),
* so a relative path names a file the holder uploaded. `stdinFile` names such a file to pipe to
* the command's stdin instead of `stdin`; the two together are `BAD_REQUEST`, checked by the
* worker's dispatcher, not here, because `.omit()` cannot build `run_on_device`'s input from an
* object carrying a refinement.
*
* `stdin` is a **one-shot string**, not a stream: it is written to the child's stdin and the
* pipe is then closed. ADR §19c is explicit that there is no pseudo-terminal here, so
* line-oriented commands (`adb shell getprop`, `simctl spawn`) work and full-screen or
Expand All @@ -522,6 +531,7 @@ export const deviceExec = defineOperation({
tool: z.string().min(1),
args: z.array(z.string()),
stdin: z.string().max(EXEC_STDIN_MAX_LENGTH).optional(),
stdinFile: z.string().regex(LEASE_FILE_NAME_PATTERN).optional(),
/**
* why: Who this command is being run *for* -- the requester the lease is attributed to (ADR
* 0003 §4), not the connection's principal. Read **only on an admin session**, where it
Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: 81, max: 81 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 82, max: 82 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down
Loading
Loading