Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentDeviceShim.ts

317 lines11.8 KB

1// @effect-diagnostics globalJsonInEffect:off - JSON string literals embed paths safely into generated JavaScript.
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import { resolveNodeExecutable } from "@t3tools/shared/nodeRuntime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7​
8const SHIM_DIR = "device/bin";
9const TARGETS_DIR = "device/targets";
10const STALE_RUNTIME =
11 "This agent-device command is out of date because T3 Code moved or updated its runtime. Call device_open again for a fresh one.";
12​
13const quoteShell = (value: string) => "'" + value.replaceAll("'", "'\"'\"'") + "'";
14​
15/** agent-device 0.21.41's flags that take a value, so the launcher can find the command past them. */
16const VALUE_FLAGS: ReadonlyArray<string> = [
17 "--activity",
18 "--all",
19 "--android-device-allowlist",
20 "--app",
21 "--appium-version",
22 "--artifact",
23 "--artifacts-dir",
24 "--aws-app-arn",
25 "--aws-device-arn",
26 "--aws-interaction-mode",
27 "--aws-project-arn",
28 "--aws-region",
29 "-b",
30 "--baseline",
31 "--bearer-token",
32 "--bundle-url",
33 "--button",
34 "--config",
35 "--count",
36 "--crop-on",
37 "--custom-network",
38 "-d",
39 "--daemon-auth-token",
40 "--daemon-base-url",
41 "--daemon-server-mode",
42 "--daemon-transport",
43 "--delay-ms",
44 "--depth",
45 "--device",
46 "--device-baseline",
47 "--device-mode",
48 "--device-orientation",
49 "--dsym",
50 "--duration-ms",
51 "-e",
52 "--env",
53 "--fps",
54 "--from",
55 "--geo-location",
56 "--github-actions-artifact",
57 "--header",
58 "--hold-ms",
59 "--host",
60 "--image-tag",
61 "--in-app",
62 "--include",
63 "--interval-ms",
64 "--ios-simulator-device-set",
65 "--ios-xctest-derived-data-path",
66 "--ios-xctest-env-dir",
67 "--ios-xctestrun-file",
68 "--jitter-px",
69 "--keyframes",
70 "--kind",
71 "--language",
72 "--launch-args",
73 "--launch-console",
74 "--launch-url",
75 "--lease-backend",
76 "--lease-id",
77 "--level",
78 "--listen-host",
79 "--locale",
80 "--max-passes",
81 "--max-steps",
82 "--metro-host",
83 "--metro-kind",
84 "--metro-port",
85 "--network-profile",
86 "--on-error",
87 "--os",
88 "--os-version",
89 "--out",
90 "--pattern",
91 "--pause-ms",
92 "--pick",
93 "--pixel-density",
94 "--pixels",
95 "--plan-digest",
96 "--platform",
97 "--pointer-count",
98 "--port",
99 "--probe-timeout-ms",
100 "--project-root",
101 "--provider",
102 "--provider-app",
103 "--provider-appium-version",
104 "--provider-build",
105 "--provider-custom-network",
106 "--provider-device-orientation",
107 "--provider-device-type",
108 "--provider-geo-location",
109 "--provider-language",
110 "--provider-locale",
111 "--provider-network-hosts",
112 "--provider-network-profile",
113 "--provider-os-version",
114 "--provider-project",
115 "--provider-session",
116 "--provider-session-name",
117 "--provider-timezone",
118 "--proxy-base-url",
119 "--public-base-url",
120 "--public-origin",
121 "--quality",
122 "--record-as",
123 "--remote-config",
124 "--reporter",
125 "--report-junit",
126 "--retention-ms",
127 "--retries",
128 "--run-id",
129 "--runtime-file",
130 "-s",
131 "--scale",
132 "--scope",
133 "--search-path",
134 "--serial",
135 "--session",
136 "--session-isolation",
137 "--session-lock",
138 "--settle-quiet",
139 "--shard-all",
140 "--shard-split",
141 "--startup-timeout-ms",
142 "--state-dir",
143 "--status-host",
144 "--steps",
145 "--steps-file",
146 "--surface",
147 "--system",
148 "--target",
149 "--target-app",
150 "--template",
151 "--tenant",
152 "--threshold",
153 "--timeout",
154 "--timezone",
155 "--udid",
156 "--until",
157 "--wait",
158];
159​
160// Help gets no bound flags (agent-device reads --config even for help); only args before `--` are flags.
161// agent-device 0.21.31 refuses some bound flags per command; connect/disconnect/auth/daemon would
162// replace T3's connection; device status reads this machine's claims. It reports a sandboxed shell and a
163// dropped tunnel alike, so check first, at --daemon-base-url if given, as agent-device prefers it.
164const launcherSource = (node: string, entryPath: string, boundArgs: ReadonlyArray<string>) =>
165 `import { spawn } from "node:child_process";
166import { existsSync, readFileSync } from "node:fs";
167import { connect } from "node:net";
168const entry = ${JSON.stringify(entryPath)};
169const bound = ${JSON.stringify(boundArgs)};
170const refused = new Map([["cdp", ["--platform", "--udid", "--config", "--session"]], ["connection", ["--platform", "--udid"]]]);
171const managed = ["connect", "disconnect", "auth", "daemon"];
172const args = process.argv.slice(2);
173const end = args.indexOf("--");
174const options = end < 0 ? args : args.slice(0, end);
175const valued = new Set(${JSON.stringify(VALUE_FLAGS)});
176let name = "";
177for (let index = 0; index < args.length; index++) {
178 const arg = args[index];
179 if (arg === "--") { name = args[index + 1] ?? ""; break; }
180 if (!arg.startsWith("-")) { name = arg; break; }
181 if (!arg.includes("=") && valued.has(arg)) index++;
183const informational = args.length === 0 || ["help", "--help", "-h", "--version", "version"].includes(args[0]) || options.includes("--help") || options.includes("-h");
184if (!informational && managed.includes(name)) {
185 console.error("T3 Code manages this command's connection to the device, so \`" + name + "\` is not available through it.");
186 process.exit(1);
188if (!informational && name === "device") {
189 console.error("\`device status\` reads this machine's device claims, not those on the device's host, so it is not available through this command. Quote the DEVICE_IN_USE error instead.");
190 process.exit(1);
192const skip = refused.get(name) ?? [];
193if (!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]);
194const command = end < 0 ? options : [...options, ...args.slice(end)];
195const 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("--")); };
196if (!informational && !skip.includes("--session") && !(hasValue("--config") && hasValue("--session"))) {
197 console.error("Call device_open first and run the agent-device command it returns.");
198 process.exit(1);
200if (!existsSync(entry)) {
201 console.error(${JSON.stringify(STALE_RUNTIME)});
202 process.exit(1);
204const valueOf = flag => { const inline = options.find(arg => arg.startsWith(flag + "=")); if (inline) return inline.slice(flag.length + 1); const index = options.indexOf(flag); return index >= 0 ? options[index + 1] : undefined; };
205const endpoint = () => { try { const url = new URL(valueOf("--daemon-base-url") ?? JSON.parse(readFileSync(valueOf("--config"), "utf8")).daemonBaseUrl); return ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) && url.port ? url : undefined; } catch { return undefined; } };
206const local = informational || refused.has(name) ? undefined : endpoint();
207if (local) {
208 const failure = await new Promise(resolve => {
209 const socket = connect({ host: local.hostname.replace(/^\\[|\\]$/g, ""), port: Number(local.port) });
210 socket.setTimeout(3000, () => { socket.destroy(); resolve("ETIMEDOUT"); });
211 socket.once("connect", () => { socket.destroy(); resolve(undefined); });
212 socket.once("error", error => resolve(error.code ?? "ERROR"));
213 });
214 if (failure === "EPERM" || failure === "EACCES") {
215 console.error("This shell cannot reach T3 Code's device connection at " + local.host + " (connect " + failure + "): a network sandbox is blocking localhost. Run this command again with network access, outside the sandbox.");
216 process.exit(1);
217 }
218 if (failure) {
219 console.error("T3 Code's device connection at " + local.host + " is not reachable from this shell (connect " + failure + "). Call device_open again to reconnect; if that succeeds and this repeats, this shell runs in a network sandbox, so run the command with network access, outside the sandbox.");
220 process.exit(1);
221 }
223const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };
224delete env.AGENT_DEVICE_DAEMON_BASE_URL;
225delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
226delete env.AGENT_DEVICE_CONFIG;
227const child = spawn(${JSON.stringify(node)}, [entry, ...command], { stdio: "inherit", env });
228child.on("error", error => { console.error(error.message); process.exitCode = 1; });
229child.on("exit", code => { process.exitCode = code ?? 1; });
230`;
231​
232/** Writes a launcher into `dir` and returns the executable agents run. */
233const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (input: {
234 readonly dir: string;
235 readonly entryPath: string;
236 readonly boundArgs: ReadonlyArray<string>;
237}) {
238 const fs = yield* FileSystem.FileSystem;
239 const path = yield* Path.Path;
240 const platform = yield* HostProcess.Platform;
241 const node = yield* resolveNodeExecutable("Device automation");
242 yield* fs.makeDirectory(input.dir, { recursive: true });
243 const launcherPath = path.join(input.dir, "agent-device-launcher.mjs");
244 yield* fs.writeFileString(launcherPath, launcherSource(node, input.entryPath, input.boundArgs));
245 if (platform === "win32") {
246 const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nif not exist "${node}" (echo ${STALE_RUNTIME} 1>&2 & exit /b 1)\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"${node}" "${launcherPath}" %*\r\n`;
247 const scriptPath = path.join(input.dir, "agent-device.cmd");
248 yield* fs.writeFileString(scriptPath, script);
249 return scriptPath;
250 }
251 const script = `#!/bin/sh\n[ -x ${quoteShell(node)} ] || { echo ${quoteShell(STALE_RUNTIME)} >&2; exit 1; }\nexport ELECTRON_RUN_AS_NODE=1\nexec ${quoteShell(node)} ${quoteShell(launcherPath)} "$@"\n`;
252 const scriptPath = path.join(input.dir, "agent-device");
253 yield* fs.writeFileString(scriptPath, script);
254 yield* fs.chmod(scriptPath, 0o755);
255 return scriptPath;
256});
257​
258/** The unbound launcher: every call needs the device's target flags. */
259export const ensureAgentDeviceShim = Effect.fn("AgentDeviceShim.ensure")(function* (input: {
260 readonly entryPath: string;
261 readonly stateDir: string;
262}) {
263 const path = yield* Path.Path;
264 const shimDir = path.join(input.stateDir, SHIM_DIR);
265 yield* writeLauncher({ dir: shimDir, entryPath: input.entryPath, boundArgs: [] });
266 return shimDir;
267});
268​
269/**
270 * A launcher for one agent-device session with its target flags built in, so
271 * agents pass none, and a shell that does not word-split a variable cannot mangle them.
272 */
273export const bindAgentDeviceLauncher = Effect.fn("AgentDeviceShim.bind")(function* (input: {
274 readonly entryPath: string;
275 readonly stateDir: string;
276 readonly session: string;
277 readonly targetArgs: ReadonlyArray<string>;
278}) {
279 const path = yield* Path.Path;
280 return yield* writeLauncher({
281 dir: path.join(input.stateDir, TARGETS_DIR, input.session),
282 entryPath: input.entryPath,
283 boundArgs: input.targetArgs,
284 });
285});
286​
287/** Removes the bound launchers of agent-device sessions not in `live`. */
288export const pruneAgentDeviceLaunchers = Effect.fn("AgentDeviceShim.prune")(function* (input: {
289 readonly stateDir: string;
290 readonly live: ReadonlySet<string>;
291}) {
292 const fs = yield* FileSystem.FileSystem;
293 const path = yield* Path.Path;
294 const dir = path.join(input.stateDir, TARGETS_DIR);
295 const sessions = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
296 yield* Effect.forEach(
297 sessions.filter((session) => !input.live.has(session)),
298 (session) => fs.remove(path.join(dir, session), { recursive: true, force: true }),
299 { discard: true },
300 ).pipe(Effect.ignore);
301});
302​
303export type AgentDeviceCloseOutcome = "closed" | "no-session" | "failed" | "timed-out";
304​
305/** What a launcher's `close` did; only a failure or timeout can leave the device claimed. */
306export const agentDeviceCloseOutcome = (result: {
307 readonly code: number | null;
308 readonly stderr: string;
309 readonly timedOut: boolean;
310}): AgentDeviceCloseOutcome =>
311 result.timedOut
312 ? "timed-out"
313 : result.code === 0
314 ? "closed"
315 : result.stderr.includes("SESSION_NOT_FOUND")
316 ? "no-session"
317 : "failed";