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

AgentDeviceTarget.test.ts

480 lines19.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - exercises concurrent real CLI subprocesses.
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import { describe, expect, it } from "@effect/vitest";
4import * as NodeChildProcess from "node:child_process";
5import * as NodeNet from "node:net";
6import * as NodeUtil from "node:util";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11import {
12 agentDeviceCloseOutcome,
13 bindAgentDeviceLauncher,
14 ensureAgentDeviceShim,
15 pruneAgentDeviceLaunchers,
16} from "./AgentDeviceShim.ts";
17import {
18 agentDeviceConfigPath,
19 agentDeviceSession,
20 writeAgentDeviceConfig,
21} from "./AgentDeviceTarget.ts";
22​
23const exec = NodeUtil.promisify(NodeChildProcess.execFile);
24​
25/** A loopback port that accepts connections until the scope closes, like T3's device connection. */
26const listeningPort = Effect.acquireRelease(
27 Effect.promise(
28 () =>
29 new Promise<NodeNet.Server>((resolve) => {
30 const server = NodeNet.createServer((socket) => socket.destroy());
31 server.listen(0, "127.0.0.1", () => resolve(server));
32 }),
33 ),
34 (server) => Effect.promise(() => new Promise<void>((resolve) => server.close(() => resolve()))),
35).pipe(Effect.map((server) => (server.address() as NodeNet.AddressInfo).port));
36​
37describe("host-bound agent commands", () => {
38 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
39 "runs both desktop hops as Node with a stripped environment, preserving arguments and exit code",
40 () =>
41 Effect.gen(function* () {
42 const fs = yield* FileSystem.FileSystem;
43 const path = yield* Path.Path;
44 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-target-" });
45 const dir = path.join(temp, "quotes '\" $HOME `literal`");
46 yield* fs.makeDirectory(dir);
47 const desktopApp = path.join(dir, "T3 Code");
48 // Dropping Node mode after checking it forces each hop to set it independently.
49 yield* fs.writeFileString(
50 desktopApp,
51 `#!/bin/sh
52if [ "\${ELECTRON_RUN_AS_NODE:-}" != "1" ]; then
53 echo "started the desktop app" >&2
54 exit 134
55fi
56unset ELECTRON_RUN_AS_NODE
57exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@"
58`,
59 );
60 yield* fs.chmod(desktopApp, 0o755);
61 const entryPath = path.join(dir, "cli.mjs");
62 yield* fs.writeFileString(
63 entryPath,
64 "console.log(JSON.stringify(process.argv.slice(2))); process.exitCode = 23;",
65 );
66 const shim = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir }).pipe(
67 Effect.provideService(HostProcess.ExecutablePath, desktopApp),
68 Effect.provideService(HostProcess.IsExecutable, false),
69 );
70 const args = [
71 "snapshot",
72 "--config",
73 path.join(dir, "config.json"),
74 "--session",
75 "a!b!c",
76 "",
77 ];
78 yield* Effect.promise(() =>
79 expect(
80 exec(path.join(shim, "agent-device"), args, {
81 env: { PATH: process.env.PATH ?? "", HOME: temp },
82 }),
83 ).rejects.toMatchObject({ code: 23, stdout: `${JSON.stringify(args)}\n`, stderr: "" }),
84 );
85 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
86 );
87​
88 it.effect("binds one device's flags into its launcher and leaves help alone", () =>
89 Effect.gen(function* () {
90 const fs = yield* FileSystem.FileSystem;
91 const path = yield* Path.Path;
92 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-bound-" });
93 const entryPath = path.join(dir, "cli.mjs");
94 yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));");
95 const target = [
96 "--platform",
97 "ios",
98 "--udid",
99 "UDID-1",
100 "--config",
101 "/h.json",
102 "--session",
103 "t3-a",
104 ];
105 const command = yield* bindAgentDeviceLauncher({
106 entryPath,
107 stateDir: dir,
108 session: "t3-a",
109 targetArgs: target,
110 });
111 const shared = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir });
112 const launch = (launcher: string, args: ReadonlyArray<string>) =>
113 exec(process.execPath, [path.join(launcher, "agent-device-launcher.mjs"), ...args]).then(
114 (result) => JSON.parse(result.stdout),
115 );
116 const bound = path.dirname(command);
117 expect(yield* Effect.promise(() => launch(bound, ["snapshot", "-i"]))).toEqual([
118 "snapshot",
119 "-i",
120 ...target,
121 ]);
122 // A flag the agent passes itself wins over the bound one.
123 expect(yield* Effect.promise(() => launch(bound, ["open", "--session", "mine"]))).toEqual([
124 "open",
125 "--session",
126 "mine",
127 "--platform",
128 "ios",
129 "--udid",
130 "UDID-1",
131 "--config",
132 "/h.json",
133 ]);
134 expect(yield* Effect.promise(() => launch(bound, ["snapshot", "--session=mine"]))).toEqual([
135 "snapshot",
136 "--session=mine",
137 "--platform",
138 "ios",
139 "--udid",
140 "UDID-1",
141 "--config",
142 "/h.json",
143 ]);
144 // After `--` everything is text: no help, no overrides, and bound flags go before it.
145 for (const text of [["--help"], ["literal text", "--session", "mine"]]) {
146 expect(yield* Effect.promise(() => launch(bound, ["fill", "@e5", "--", ...text]))).toEqual([
147 "fill",
148 "@e5",
149 ...target,
150 "--",
151 ...text,
152 ]);
153 }
154 expect(
155 yield* Effect.promise(() =>
156 launch(shared, ["snapshot", "--config=/h.json", "--session=t3-a"]),
157 ),
158 ).toEqual(["snapshot", "--config=/h.json", "--session=t3-a"]);
159 yield* Effect.promise(() =>
160 expect(
161 launch(shared, ["fill", "@e5", "--", "--config", "/h.json", "--session", "t3-a"]),
162 ).rejects.toThrow("Call device_open first"),
163 );
164 for (const args of [["help", "gesture"], ["open", "--help"], ["record", "-h"], []]) {
165 expect(yield* Effect.promise(() => launch(bound, args))).toEqual(args);
166 expect(yield* Effect.promise(() => launch(shared, args))).toEqual(args);
167 }
168 yield* fs.remove(entryPath);
169 yield* Effect.promise(() =>
170 expect(launch(bound, ["snapshot"])).rejects.toThrow("Call device_open again"),
171 );
172 }).pipe(
173 Effect.scoped,
174 Effect.provideService(HostProcess.IsExecutable, false),
175 Effect.provideService(HostProcess.ExecutablePath, process.execPath),
176 Effect.provide(NodeServices.layer),
177 ),
178 );
179​
180 it.effect("passes each command only the bound flags agent-device accepts for it", () =>
181 Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-commands-" });
185 const entryPath = path.join(dir, "cli.mjs");
186 yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));");
187 const command = yield* bindAgentDeviceLauncher({
188 entryPath,
189 stateDir: dir,
190 session: "t3-a",
191 targetArgs: [
192 "--platform",
193 "ios",
194 "--udid",
195 "UDID-1",
196 "--config",
197 "/h.json",
198 "--session",
199 "t3-a",
200 ],
201 });
202 const launch = (args: ReadonlyArray<string>) =>
203 exec(process.execPath, [
204 path.join(path.dirname(command), "agent-device-launcher.mjs"),
205 ...args,
206 ]).then((result) => JSON.parse(result.stdout));
207 // agent-device 0.21.31 rejects these flags with "unknown option" or "not supported for command".
208 const cdp = ["cdp", "target", "list", "--url", "http://127.0.0.1:8081"];
209 expect(yield* Effect.promise(() => launch(cdp))).toEqual(cdp);
210 expect(yield* Effect.promise(() => launch(["connection"]))).toEqual([
211 "connection",
212 "--config",
213 "/h.json",
214 "--session",
215 "t3-a",
216 ]);
217 // The command is found past leading flags and their values, in either form.
218 for (const config of [["--config", "/o.json"], ["--config=/o.json"]]) {
219 expect(yield* Effect.promise(() => launch([...config, "connection"]))).toEqual([
220 ...config,
221 "connection",
222 "--session",
223 "t3-a",
224 ]);
225 // device status reads claims on the machine it runs on, which is not the device's host.
226 yield* Effect.promise(() =>
227 expect(launch([...config, "device", "status"])).rejects.toThrow(
228 "`device status` reads this machine's device claims, not those on the device's host",
229 ),
230 );
231 }
232 expect(yield* Effect.promise(() => launch(["--json", ...cdp]))).toEqual(["--json", ...cdp]);
233 for (const managed of [
234 ["connect"],
235 ["disconnect"],
236 ["auth", "status"],
237 ["daemon", "stop"],
238 ["--config", "/o.json", "auth", "status"],
239 ["--", "connect"],
240 ]) {
241 yield* Effect.promise(() =>
242 expect(launch(managed)).rejects.toThrow(
243 `T3 Code manages this command's connection to the device, so \`${managed.find((arg) => ["connect", "disconnect", "auth", "daemon"].includes(arg))}\` is not available through it.`,
244 ),
245 );
246 }
247 }).pipe(
248 Effect.scoped,
249 Effect.provideService(HostProcess.IsExecutable, false),
250 Effect.provideService(HostProcess.ExecutablePath, process.execPath),
251 Effect.provide(NodeServices.layer),
252 ),
253 );
254​
255 it("tells a released session from a close that failed or timed out", () => {
256 const result = (code: number | null, stderr = "", timedOut = false) => ({
257 stdout: "",
258 stderr,
259 code,
260 timedOut,
261 });
262 expect(agentDeviceCloseOutcome(result(0))).toBe("closed");
263 // A session that never ran `open` has nothing to release.
264 expect(
265 agentDeviceCloseOutcome(
266 result(1, "Error (SESSION_NOT_FOUND): No active session. Run open first."),
267 ),
268 ).toBe("no-session");
269 expect(
270 agentDeviceCloseOutcome(result(1, "Error (COMMAND_FAILED): Remote daemon is unavailable")),
271 ).toBe("failed");
272 expect(agentDeviceCloseOutcome(result(null, "", true))).toBe("timed-out");
273 });
274​
275 it.live("stops before agent-device when T3's device connection is down", () =>
276 Effect.gen(function* () {
277 const fs = yield* FileSystem.FileSystem;
278 const path = yield* Path.Path;
279 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-endpoint-" });
280 const entryPath = path.join(dir, "cli.mjs");
281 yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));");
282 const configPath = path.join(dir, "host.json");
283 // A port that was just free: nothing listens on it, so a connect is refused.
284 const port = yield* Effect.promise(
285 () =>
286 new Promise<number>((resolve) => {
287 const server = NodeNet.createServer();
288 server.listen(0, "127.0.0.1", () => {
289 const address = server.address() as NodeNet.AddressInfo;
290 server.close(() => resolve(address.port));
291 });
292 }),
293 );
294 yield* writeAgentDeviceConfig(configPath, {
295 baseUrl: `http://127.0.0.1:${port}`,
296 token: "secret",
297 });
298 const command = yield* bindAgentDeviceLauncher({
299 entryPath,
300 stateDir: dir,
301 session: "t3-a",
302 targetArgs: ["--config", configPath, "--session", "t3-a"],
303 });
304 const launch = (args: ReadonlyArray<string>) =>
305 exec(process.execPath, [
306 path.join(path.dirname(command), "agent-device-launcher.mjs"),
307 ...args,
308 ]);
309 yield* Effect.promise(() =>
310 expect(launch(["screenshot", "/tmp/shot.png"])).rejects.toMatchObject({
311 code: 1,
312 stdout: "",
313 stderr: `T3 Code's device connection at 127.0.0.1:${port} is not reachable from this shell (connect ECONNREFUSED). 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.\n`,
314 }),
315 );
316 // An explicit --daemon-base-url wins over the config, as it does in agent-device.
317 const override = `http://127.0.0.1:${yield* listeningPort}`;
318 for (const flag of [["--daemon-base-url", override], [`--daemon-base-url=${override}`]]) {
319 expect(
320 JSON.parse(
321 (yield* Effect.promise(() => launch(["screenshot", "/tmp/shot.png", ...flag]))).stdout,
322 ),
323 ).toEqual([
324 "screenshot",
325 "/tmp/shot.png",
326 ...flag,
327 "--config",
328 configPath,
329 "--session",
330 "t3-a",
331 ]);
332 }
333 // cdp talks to Metro, not to T3's connection, so it still runs.
334 expect(
335 JSON.parse((yield* Effect.promise(() => launch(["cdp", "target", "list"]))).stdout),
336 ).toEqual(["cdp", "target", "list"]);
337 }).pipe(
338 Effect.scoped,
339 Effect.provideService(HostProcess.IsExecutable, false),
340 Effect.provideService(HostProcess.ExecutablePath, process.execPath),
341 Effect.provide(NodeServices.layer),
342 ),
343 );
344​
345 it.effect("prunes the launchers of ended sessions and keeps the shared one", () =>
346 Effect.gen(function* () {
347 const fs = yield* FileSystem.FileSystem;
348 const path = yield* Path.Path;
349 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-prune-" });
350 const entryPath = path.join(stateDir, "cli.mjs");
351 const shared = yield* ensureAgentDeviceShim({ entryPath, stateDir });
352 const bind = (session: string) =>
353 bindAgentDeviceLauncher({ entryPath, stateDir, session, targetArgs: [] });
354 const kept = yield* bind("t3-open");
355 const ended = yield* bind("t3-closed");
356 yield* pruneAgentDeviceLaunchers({ stateDir, live: new Set(["t3-open"]) });
357 expect(yield* fs.exists(kept)).toBe(true);
358 expect(yield* fs.exists(path.dirname(ended))).toBe(false);
359 expect(yield* fs.exists(shared)).toBe(true);
360 yield* pruneAgentDeviceLaunchers({ stateDir, live: new Set() });
361 expect(yield* fs.readDirectory(path.join(stateDir, "device", "targets"))).toEqual([]);
362 }).pipe(
363 Effect.scoped,
364 Effect.provideService(HostProcess.IsExecutable, false),
365 Effect.provideService(HostProcess.ExecutablePath, process.execPath),
366 Effect.provide(NodeServices.layer),
367 ),
368 );
369​
370 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
371 "tells the agent to reopen the device when the runtime it was bound to is gone",
372 () =>
373 Effect.gen(function* () {
374 const fs = yield* FileSystem.FileSystem;
375 const path = yield* Path.Path;
376 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-stale-" });
377 const runtime = path.join(dir, "old-node");
378 yield* fs.writeFileString(runtime, "#!/bin/sh\nexit 0\n");
379 yield* fs.chmod(runtime, 0o755);
380 const command = yield* bindAgentDeviceLauncher({
381 entryPath: path.join(dir, "cli.mjs"),
382 stateDir: dir,
383 session: "t3-a",
384 targetArgs: ["--config", "/h.json", "--session", "t3-a"],
385 }).pipe(Effect.provideService(HostProcess.ExecutablePath, runtime));
386 yield* fs.remove(runtime);
387 yield* Effect.promise(() =>
388 expect(exec(command, ["snapshot"])).rejects.toMatchObject({
389 code: 1,
390 stderr: expect.stringContaining("Call device_open again"),
391 }),
392 );
393 }).pipe(
394 Effect.scoped,
395 Effect.provideService(HostProcess.IsExecutable, false),
396 Effect.provide(NodeServices.layer),
397 ),
398 );
399​
400 it.effect("runs two hosts concurrently and only updates the reconnected host", () =>
401 Effect.gen(function* () {
402 const fs = yield* FileSystem.FileSystem;
403 const path = yield* Path.Path;
404 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-target-" });
405 const platform = yield* HostProcess.Platform;
406 const dir = path.join(
407 temp,
408 platform === "win32" ? "paths with spaces" : "quotes '\" $HOME `literal`",
409 );
410 yield* fs.makeDirectory(dir);
411 const entryPath = path.join(dir, "cli.mjs");
412 yield* fs.writeFileString(
413 entryPath,
414 `import { readFileSync } from 'node:fs';
415const args = process.argv.slice(2);
416console.log(readFileSync(args[args.indexOf('--config') + 1], 'utf8'));
417if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
418 );
419 const shim = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir });
420 const files = yield* Effect.forEach(["mini", "android"], (host) =>
421 agentDeviceConfigPath(dir, host, path),
422 );
423 const ports = [yield* listeningPort, yield* listeningPort, yield* listeningPort];
424 for (const [index, file] of files.entries())
425 yield* writeAgentDeviceConfig(file, {
426 baseUrl: `http://127.0.0.1:${ports[index]}`,
427 token: `token-${index}`,
428 });
429 const invoke = (file: string) =>
430 exec(
431 platform === "win32" ? process.execPath : path.join(shim, "agent-device"),
432 [
433 ...(platform === "win32" ? [path.join(shim, "agent-device-launcher.mjs")] : []),
434 "snapshot",
435 "--config",
436 file,
437 "--session",
438 "test-session",
439 ],
440 { env: { ...process.env, AGENT_DEVICE_DAEMON_BASE_URL: "http://wrong-host" } },
441 ).then((result) => JSON.parse(result.stdout));
442 expect(yield* Effect.promise(() => Promise.all(files.map(invoke)))).toEqual([
443 { daemonBaseUrl: `http://127.0.0.1:${ports[0]}`, daemonAuthToken: "token-0" },
444 { daemonBaseUrl: `http://127.0.0.1:${ports[1]}`, daemonAuthToken: "token-1" },
445 ]);
446 const second = yield* fs.readFileString(files[1]!);
447 yield* writeAgentDeviceConfig(files[0]!, {
448 baseUrl: `http://127.0.0.1:${ports[2]}`,
449 token: "new",
450 });
451 expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");
452 expect(yield* fs.readFileString(files[1]!)).toBe(second);
453 // Hosts with a daemon per device get a file per device, apart from the host's own.
454 const perDevice = yield* Effect.forEach(["udid-1", "udid-2"], (device) =>
455 agentDeviceConfigPath(dir, "eas", path, device),
456 );
457 expect(new Set([...perDevice, yield* agentDeviceConfigPath(dir, "eas", path)]).size).toBe(3);
458 expect(yield* agentDeviceSession("thread", "mini", "same-id")).not.toBe(
459 yield* agentDeviceSession("thread", "android", "same-id"),
460 );
461 for (const args of [
462 ["snapshot"],
463 ["snapshot", "--config", files[0]!],
464 ["snapshot", "--config", "help"],
465 ["snapshot", "--config", files[0]!, "--session"],
466 ]) {
467 yield* Effect.promise(() =>
468 expect(
469 exec(process.execPath, [path.join(shim, "agent-device-launcher.mjs"), ...args]),
470 ).rejects.toThrow("Call device_open first"),
471 );
472 }
473 }).pipe(
474 Effect.scoped,
475 Effect.provideService(HostProcess.IsExecutable, true),
476 Effect.provideService(HostProcess.ExecutablePath, "/packaged/t3"),
477 Effect.provide(NodeServices.layer),
478 ),
479 );
480});