Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
168 changes: 103 additions & 65 deletions apps/server/src/device/AgentDeviceShim.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,72 +32,110 @@ const listeningPort = Effect.acquireRelease(
).pipe(Effect.map((server) => (server.address() as NodeNet.AddressInfo).port));

describe.skipIf(process.platform === "win32")("agent-device launcher", () => {
it.live("binds one device's flags, lets the agent's own flags win, and leaves help alone", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-launcher-" });
const port = yield* listeningPort;
const entryPath = path.join(dir, "cli.mjs");
yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));");
const config = agentDeviceConfigPath(path, dir);
yield* writeAgentDeviceConfig(config, { baseUrl: `http://127.0.0.1:${port}`, token: "t" });
const target = [
"--platform",
"ios",
"--udid",
"UDID-1",
"--config",
config,
"--session",
"tl-a",
];
const command = yield* bindAgentDeviceLauncher({
stateDir: dir,
threadId: "thread-1",
deviceId: "UDID-1",
node: process.execPath,
entryPath,
targetArgs: target,
});
expect(command).toBe(
path.join(agentDeviceLaunchersDir(path, dir), "thread-1", "UDID-1", "agent-device"),
);
const launch = (args: ReadonlyArray<string>) =>
exec(command, [...args]).then((result) => JSON.parse(result.stdout));
it.live(
"binds one device's flags, refuses override flags, strips Android --serial on cdp, and leaves help alone",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-launcher-" });
const port = yield* listeningPort;
const entryPath = path.join(dir, "cli.mjs");
yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));");
const config = agentDeviceConfigPath(path, dir);
yield* writeAgentDeviceConfig(config, { baseUrl: `http://127.0.0.1:${port}`, token: "t" });
const target = [
"--platform",
"ios",
"--udid",
"UDID-1",
"--config",
config,
"--session",
"tl-a",
];
const command = yield* bindAgentDeviceLauncher({
stateDir: dir,
threadId: "thread-1",
deviceId: "UDID-1",
node: process.execPath,
entryPath,
targetArgs: target,
});
expect(command).toBe(
path.join(agentDeviceLaunchersDir(path, dir), "thread-1", "UDID-1", "agent-device"),
);
const launch = (args: ReadonlyArray<string>) =>
exec(command, [...args]).then((result) => JSON.parse(result.stdout));

expect(yield* Effect.promise(() => launch(["snapshot", "-i"]))).toEqual([
"snapshot",
"-i",
...target,
]);
expect(yield* Effect.promise(() => launch(["open", "--session", "mine"]))).toEqual([
"open",
"--session",
"mine",
...target.slice(0, 6),
]);
// After `--` everything is text, and bound flags go before it.
expect(yield* Effect.promise(() => launch(["fill", "@e5", "--", "--help"]))).toEqual([
"fill",
"@e5",
...target,
"--",
"--help",
]);
for (const args of [["help", "gesture"], ["open", "--help"], []]) {
expect(yield* Effect.promise(() => launch(args))).toEqual(args);
}
// Commands that would replace Threadlines' connection are refused.
yield* Effect.promise(() =>
expect(launch(["daemon", "stop"])).rejects.toThrow("Threadlines manages this command"),
);
// A runtime that moved since device_open names the fix.
yield* fs.remove(entryPath);
yield* Effect.promise(() =>
expect(launch(["snapshot"])).rejects.toThrow("Call device_open again"),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
expect(yield* Effect.promise(() => launch(["snapshot", "-i"]))).toEqual([
"snapshot",
"-i",
...target,
]);
// Override flags are refused so every session stays one Threadlines ends.
for (const args of [
["open", "--session", "mine"],
["open", "-s", "mine"],
["snapshot", "--udid=OTHER"],
["snapshot", "--daemon-base-url", "http://127.0.0.1:9999"],
]) {
yield* Effect.promise(() =>
expect(launch(args)).rejects.toThrow("bound to one device and its session"),
);
}
// Positional `-h` on text commands is text, not help.
expect(yield* Effect.promise(() => launch(["fill", "@e5", "-h"]))).toEqual([
"fill",
"@e5",
"-h",
...target,
]);
// Android `cdp` strips `--serial` as well as `--platform`/`--config`/`--session`.
const androidCommand = yield* bindAgentDeviceLauncher({
stateDir: dir,
threadId: "thread-1",
deviceId: "emulator-5554",
node: process.execPath,
entryPath,
targetArgs: [
"--platform",
"android",
"--serial",
"emulator-5554",
"--config",
config,
"--session",
"tl-b",
],
});
const launchAndroid = (args: ReadonlyArray<string>) =>
exec(androidCommand, [...args]).then((result) => JSON.parse(result.stdout));
expect(yield* Effect.promise(() => launchAndroid(["cdp", "list"]))).toEqual([
"cdp",
"list",
]);
// After `--` everything is text, and bound flags go before it.
expect(yield* Effect.promise(() => launch(["fill", "@e5", "--", "--help"]))).toEqual([
"fill",
"@e5",
...target,
"--",
"--help",
]);
for (const args of [["help", "gesture"], ["open", "--help"], []]) {
expect(yield* Effect.promise(() => launch(args))).toEqual(args);
}
// Commands that would replace Threadlines' connection are refused.
yield* Effect.promise(() =>
expect(launch(["daemon", "stop"])).rejects.toThrow("Threadlines manages this command"),
);
// A runtime that moved since device_open names the fix.
yield* fs.remove(entryPath);
yield* Effect.promise(() =>
expect(launch(["snapshot"])).rejects.toThrow("Call device_open again"),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.live("says the device connection is down before running agent-device", () =>
Expand Down
51 changes: 43 additions & 8 deletions apps/server/src/device/AgentDeviceShim.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @effect-diagnostics globalJsonInEffect:off - JSON string literals embed paths safely into generated JavaScript.
// @effect-diagnostics nodeBuiltinImport:off - sha256 digest for non-plain device ids.
/**
* The `agent-device` launcher `device_open` hands an agent
* (docs/design/devices.md). One per thread and device, at
Expand All @@ -9,10 +10,13 @@
* would replace Threadlines' connection, and checks the connection first so a
* sandboxed shell and a dead daemon get different messages.
*/
import { createHash } from "node:crypto";

import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

import { writeFileStringAtomically } from "../atomicWrite.ts";
import { deviceStateDir } from "./DeviceToolchain.ts";

const STALE_RUNTIME =
Expand Down Expand Up @@ -169,7 +173,7 @@ import { existsSync, readFileSync } from "node:fs";
import { connect } from "node:net";
const entry = ${JSON.stringify(entryPath)};
const bound = ${JSON.stringify(boundArgs)};
const refused = new Map([["cdp", ["--platform", "--udid", "--config", "--session"]], ["connection", ["--platform", "--udid"]]]);
const refused = new Map([["cdp", ["--platform", "--udid", "--serial", "--config", "--session"]], ["connection", ["--platform", "--udid", "--serial"]]]);
const managed = ["connect", "disconnect", "auth", "daemon"];
const args = process.argv.slice(2);
const end = args.indexOf("--");
Expand All @@ -182,7 +186,14 @@ for (let index = 0; index < args.length; index++) {
if (!arg.startsWith("-")) { name = arg; break; }
if (!arg.includes("=") && valued.has(arg)) index++;
}
const informational = args.length === 0 || ["help", "--help", "-h", "--version", "version"].includes(args[0]) || options.includes("--help") || options.includes("-h");
const textCommands = new Set(["fill", "type"]);
let hasHelpFlag = false;
for (let index = 0; index < options.length; index++) {
const arg = options[index];
if (arg === "--help" || (arg === "-h" && !textCommands.has(name))) { hasHelpFlag = true; break; }
if (!arg.includes("=") && valued.has(arg)) index++;
}
const informational = args.length === 0 || ["help", "--help", "-h", "--version", "version"].includes(args[0]) || hasHelpFlag;
if (!informational && managed.includes(name)) {
console.error("Threadlines manages this command's connection to the device, so \`" + name + "\` is not available through it.");
process.exit(1);
Expand All @@ -192,6 +203,22 @@ if (!informational && name === "device") {
process.exit(1);
}
const skip = refused.get(name) ?? [];
// Its device, session and daemon are bound: an agent's own would open a session Threadlines cannot end.
const locked = new Set([...bound.filter((_, index) => index % 2 === 0), "--device", "-d", "--serial", "--udid", "--platform", "--session", "-s", "--config", "--daemon-base-url", "--daemon-auth-token", "--state-dir"]);
let overridden;
if (bound.length > 0 && !informational) {
for (let index = 0; index < options.length; index++) {
const arg = options[index];
const eq = arg.indexOf("=");
const flag = eq > 0 ? arg.slice(0, eq) : arg;
if (locked.has(flag)) { overridden = flag; break; }
if (eq < 0 && valued.has(arg)) index++;
}
}
if (overridden) {
console.error("This command is bound to one device and its session, so it takes no " + overridden + ". Leave it out, or call device_open for another device.");
process.exit(1);
}
if (!informational) for (let index = 0; index + 1 < bound.length; index += 2) if (!skip.includes(bound[index]) && !options.some(arg => arg === bound[index] || arg.startsWith(bound[index] + "="))) options.push(bound[index], bound[index + 1]);
const command = end < 0 ? options : [...options, ...args.slice(end)];
const hasValue = flag => { const index = options.indexOf(flag); return options.some(arg => arg.startsWith(flag + "=") && arg.length > flag.length + 1) || (index >= 0 && !!options[index + 1] && !options[index + 1].startsWith("--")); };
Expand Down Expand Up @@ -227,10 +254,13 @@ delete env.AGENT_DEVICE_DAEMON_BASE_URL;
delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
delete env.AGENT_DEVICE_CONFIG;
const child = spawn(${JSON.stringify(node)}, [entry, ...command], { stdio: "inherit", env });
for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => { if (!child.killed) child.kill(signal); });
child.on("error", error => { console.error(error.message); process.exitCode = 1; });
child.on("exit", code => { process.exitCode = code ?? 1; });
`;

const escapeCmd = (value: string) => value.replaceAll("%", "%%");

/** Writes a launcher into `dir` and returns the executable agents run. */
const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (input: {
readonly dir: string;
Expand All @@ -243,27 +273,32 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu
const node = input.node;
yield* fs.makeDirectory(input.dir, { recursive: true });
const launcherPath = path.join(input.dir, "agent-device-launcher.mjs");
yield* fs.writeFileString(launcherPath, launcherSource(node, input.entryPath, input.boundArgs));
yield* writeFileStringAtomically({
filePath: launcherPath,
contents: launcherSource(node, input.entryPath, input.boundArgs),
});
if (process.platform === "win32") {
const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nif not exist "${node}" (echo ${STALE_RUNTIME} 1>&2 & exit /b 1)\r\n"${node}" "${launcherPath}" %*\r\n`;
const safeNode = escapeCmd(node);
const safeLauncher = escapeCmd(launcherPath);
const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nif not exist "${safeNode}" (echo ${STALE_RUNTIME} 1>&2 & exit /b 1)\r\n"${safeNode}" "${safeLauncher}" %*\r\n`;
const scriptPath = path.join(input.dir, "agent-device.cmd");
yield* fs.writeFileString(scriptPath, script);
yield* writeFileStringAtomically({ filePath: scriptPath, contents: script });
return scriptPath;
}
const script = `#!/bin/sh\n[ -x ${quoteShell(node)} ] || { echo ${quoteShell(STALE_RUNTIME)} >&2; exit 1; }\nexec ${quoteShell(node)} ${quoteShell(launcherPath)} "$@"\n`;
const scriptPath = path.join(input.dir, "agent-device");
yield* fs.writeFileString(scriptPath, script);
yield* writeFileStringAtomically({ filePath: scriptPath, contents: script });
yield* fs.chmod(scriptPath, 0o755);
return scriptPath;
});

const SAFE_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/;

/** A path segment for an id: the id itself when it is plain, else a digest of it. */
/** A path segment for an id: the id itself when it is plain, else a sha256 digest of it. */
const segment = (id: string) =>
SAFE_SEGMENT.test(id) && id !== "." && id !== ".."
? id
: `x-${Buffer.from(id).toString("base64url").slice(0, 96)}`;
: `x-${createHash("sha256").update(id).digest("hex").slice(0, 24)}`;

/** `<stateDir>/device/bin`. */
export const agentDeviceLaunchersDir = (path: Path.Path, stateDir: string) =>
Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/device/DeviceActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,36 @@ describe("runDeviceAction", () => {
expect(calls.map((call) => call.args.at(-1))).toEqual(permissions);
}),
);

it.effect("shakes an iOS simulator via notifyutil", () =>
Effect.gen(function* () {
const { ready, calls } = makeReady();
yield* runDeviceAction(ready, "ios", { type: "shake", deviceId: udid });
expect(calls).toEqual([
{
command: "xcrun",
args: ["simctl", "spawn", udid, "notifyutil", "-p", "com.apple.UIKit.simulatorShake"],
},
]);
}),
);

it.effect("rejects Android permission reset as unsupported instead of revoking", () =>
Effect.gen(function* () {
const { ready, calls } = makeReady();
const error = yield* Effect.flip(
runDeviceAction(ready, "android", {
type: "setPermission",
deviceId: "emulator-5554",
appId: "com.example.app",
permission: "camera",
decision: "reset",
}),
);
expect(error._tag).toBe("DeviceActionUnavailableError");
expect(calls).toEqual([]);
}),
);
});

describe("readDeviceDetail", () => {
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/device/DeviceActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const IOS_ACTIONS: ReadonlySet<DeviceActionType> = new Set([
"openUrl",
"launchApp",
"terminateApp",
"shake",
"sendPush",
]);

Expand Down Expand Up @@ -315,6 +316,13 @@ const runIos = Effect.fn("DeviceActions.runIos")(function* (
return;
}
case "shake":
yield* simctl(
run,
udid,
["spawn", "notifyutil", "-p", "com.apple.UIKit.simulatorShake"],
"shake",
);
return;
case "setOrientation":
return yield* new DeviceActionUnavailableError({
operation: input.type,
Expand Down Expand Up @@ -433,6 +441,13 @@ const runAndroid = Effect.fn("DeviceActions.runAndroid")(function* (
// The emulator cannot clear location; keep the fix and refresh the reading.
return;
case "setPermission": {
if (input.decision === "reset") {
return yield* new DeviceActionUnavailableError({
operation: "permission",
platform: "android",
reason: "unsupported",
});
}
const permissions = ANDROID_PERMISSIONS[input.permission];
if (!permissions) {
return yield* new DeviceActionUnavailableError({
Expand Down
Loading
Loading