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 entryPath,
98 });
99 const invoke = (file: string) =>
100 exec(
101 platform === "win32" ? process.execPath : path.join(shim, "agent-device"),
102 [
103 ...(platform === "win32" ? [path.join(shim, "agent-device-launcher.mjs")] : []),
104 "snapshot",
105 "--config",
106 file,
107 "--session",
108 "test-session",
109 ],
110 { env: { ...process.env, AGENT_DEVICE_DAEMON_BASE_URL: "http://wrong-host" } },
111 ).then((result) => JSON.parse(result.stdout));
112 expect(yield* Effect.promise(() => Promise.all(files.map(invoke)))).toEqual([
113 { daemonBaseUrl: "http://127.0.0.1:1000", daemonAuthToken: "token-0" },
114 { daemonBaseUrl: "http://127.0.0.1:1001", daemonAuthToken: "token-1" },
115 ]);
116 const second = yield* fs.readFileString(files[1]!);
117 yield* writeAgentDeviceConfig(files[0]!, {
118 baseUrl: "http://127.0.0.1:2000",
119 token: "new",
120 entryPath,
121 });
122 expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");
123 expect(yield* fs.readFileString(files[1]!)).toBe(second);
124 expect(yield* agentDeviceSession("thread", "mini", "same-id")).not.toBe(
125 yield* agentDeviceSession("thread", "android", "same-id"),
126 );
127 for (const args of [
128 ["snapshot"],
129 ["snapshot", "--config", files[0]!],
130 ["snapshot", "--config", "help"],
131 ["snapshot", "--config", files[0]!, "--session"],
132 ]) {
133 yield* Effect.promise(() =>
134 expect(
135 exec(process.execPath, [path.join(shim, "agent-device-launcher.mjs"), ...args]),
136 ).rejects.toThrow("Call device_open first"),
137 );
138 }
139 }).pipe(
140 Effect.scoped,
141 Effect.provideService(HostProcess.IsExecutable, true),
142 Effect.provideService(HostProcess.ExecutablePath, "/packaged/t3"),
143 Effect.provide(NodeServices.layer),
144 ),
145 );
146});