Open History to see the last commit
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 NodeUtil from "node:util";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import { ensureAgentDeviceShim } from "./AgentDeviceShim.ts";
11import {
12 agentDeviceConfigPath,
13 agentDeviceSession,
14 writeAgentDeviceConfig,
15} from "./AgentDeviceTarget.ts";
16
17const exec = NodeUtil.promisify(NodeChildProcess.execFile);
18
19describe("host-bound agent commands", () => {
20 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
21 "runs both desktop hops as Node with a stripped environment, preserving arguments and exit code",
22 () =>
23 Effect.gen(function* () {
24 const fs = yield* FileSystem.FileSystem;
25 const path = yield* Path.Path;
26 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-target-" });
27 const dir = path.join(temp, "quotes '\" $HOME `literal`");
28 yield* fs.makeDirectory(dir);
29 const desktopApp = path.join(dir, "T3 Code");
30 // Dropping Node mode after checking it forces each hop to set it independently.
31 yield* fs.writeFileString(
32 desktopApp,
33 `#!/bin/sh
34if [ "\${ELECTRON_RUN_AS_NODE:-}" != "1" ]; then
35 echo "started the desktop app" >&2
36 exit 134
37fi
38unset ELECTRON_RUN_AS_NODE
39exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@"
40`,
41 );
42 yield* fs.chmod(desktopApp, 0o755);
43 const entryPath = path.join(dir, "cli.mjs");
44 yield* fs.writeFileString(
45 entryPath,
46 "console.log(JSON.stringify(process.argv.slice(2))); process.exitCode = 23;",
47 );
48 const shim = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir }).pipe(
49 Effect.provideService(HostProcess.ExecutablePath, desktopApp),
50 Effect.provideService(HostProcess.IsExecutable, false),
51 );
52 const args = [
53 "snapshot",
54 "--config",
55 path.join(dir, "config.json"),
56 "--session",
57 "a!b!c",
58 "",
59 ];
60 yield* Effect.promise(() =>
61 expect(
62 exec(path.join(shim, "agent-device"), args, {
63 env: { PATH: process.env.PATH ?? "", HOME: temp },
64 }),
65 ).rejects.toMatchObject({ code: 23, stdout: `${JSON.stringify(args)}\n`, stderr: "" }),
66 );
67 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
68 );
69
70 it.effect("runs two hosts concurrently and only updates the reconnected host", () =>
71 Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-target-" });
75 const platform = yield* HostProcess.Platform;
76 const dir = path.join(
77 temp,
78 platform === "win32" ? "paths with spaces" : "quotes '\" $HOME `literal`",
79 );
80 yield* fs.makeDirectory(dir);
81 const entryPath = path.join(dir, "cli.mjs");
82 yield* fs.writeFileString(
83 entryPath,
84 `import { readFileSync } from 'node:fs';
85const args = process.argv.slice(2);
86console.log(readFileSync(args[args.indexOf('--config') + 1], 'utf8'));
87if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
88 );
89 const shim = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir });
90 const files = yield* Effect.forEach(["mini", "android"], (host) =>
91 agentDeviceConfigPath(dir, host, path),
92 );
93 for (const [index, file] of files.entries())
94 yield* writeAgentDeviceConfig(file, {
95 baseUrl: `http://127.0.0.1:${1000 + index}`,
96 token: `token-${index}`,
97 });
98 const invoke = (file: string) =>
99 exec(
100 platform === "win32" ? process.execPath : path.join(shim, "agent-device"),
101 [
102 ...(platform === "win32" ? [path.join(shim, "agent-device-launcher.mjs")] : []),
103 "snapshot",
104 "--config",
105 file,
106 "--session",
107 "test-session",
108 ],
109 { env: { ...process.env, AGENT_DEVICE_DAEMON_BASE_URL: "http://wrong-host" } },
110 ).then((result) => JSON.parse(result.stdout));
111 expect(yield* Effect.promise(() => Promise.all(files.map(invoke)))).toEqual([
112 { daemonBaseUrl: "http://127.0.0.1:1000", daemonAuthToken: "token-0" },
113 { daemonBaseUrl: "http://127.0.0.1:1001", daemonAuthToken: "token-1" },
114 ]);
115 const second = yield* fs.readFileString(files[1]!);
116 yield* writeAgentDeviceConfig(files[0]!, {
117 baseUrl: "http://127.0.0.1:2000",
118 token: "new",
119 });
120 expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");
121 expect(yield* fs.readFileString(files[1]!)).toBe(second);
122 // Hosts with a daemon per device get a file per device, apart from the host's own.
123 const perDevice = yield* Effect.forEach(["udid-1", "udid-2"], (device) =>
124 agentDeviceConfigPath(dir, "eas", path, device),
125 );
126 expect(new Set([...perDevice, yield* agentDeviceConfigPath(dir, "eas", path)]).size).toBe(3);
127 expect(yield* agentDeviceSession("thread", "mini", "same-id")).not.toBe(
128 yield* agentDeviceSession("thread", "android", "same-id"),
129 );
130 for (const args of [
131 ["snapshot"],
132 ["snapshot", "--config", files[0]!],
133 ["snapshot", "--config", "help"],
134 ["snapshot", "--config", files[0]!, "--session"],
135 ]) {
136 yield* Effect.promise(() =>
137 expect(
138 exec(process.execPath, [path.join(shim, "agent-device-launcher.mjs"), ...args]),
139 ).rejects.toThrow("Call device_open first"),
140 );
141 }
142 }).pipe(
143 Effect.scoped,
144 Effect.provideService(HostProcess.IsExecutable, true),
145 Effect.provideService(HostProcess.ExecutablePath, "/packaged/t3"),
146 Effect.provide(NodeServices.layer),
147 ),
148 );
149});