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

AgentDeviceTarget.test.ts

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