The best way to control Claude Code, Codex and more from any computer or phone

main
ts 291 lines 13.3 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Path from "effect/Path";
9 import * as TestClock from "effect/testing/TestClock";
10
11 import packageJson from "../../package.json" with { type: "json" };
12 import { posixLauncherScript } from "../cloud/pinnedRuntime.ts";
13 import { installCli, isForegroundProcStat, isForegroundPs, offerCliInstall } from "./install.ts";
14
15 const VERSION = packageJson.version;
16
17 /** A standalone runtime in a temp T3 home, started by the npm launcher from an npx cache. */
18 const setup = Effect.gen(function* () {
19 const fs = yield* FileSystem.FileSystem;
20 const path = yield* Path.Path;
21 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-install-" });
22 const runtimeDir = path.join(root, ".t3/runtime");
23 const executable = path.join(runtimeDir, "versions", VERSION, "t3");
24 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
25 yield* fs.writeFileString(executable, "");
26 const npmPackage = path.join(root, ".npm/_npx/abc/node_modules/t3");
27 yield* fs.makeDirectory(path.join(npmPackage, "bin"), { recursive: true });
28 yield* fs.writeFileString(
29 path.join(npmPackage, "package.json"),
30 JSON.stringify({ name: "t3", version: VERSION }),
31 );
32 const binDir = path.join(root, "bin");
33 const provide = <A, E, R>(effect: Effect.Effect<A, E, R>, env: NodeJS.ProcessEnv = {}) =>
34 effect.pipe(
35 Effect.provideService(HostProcess.Platform, "linux"),
36 Effect.provideService(HostProcess.HomeDirectory, root),
37 Effect.provideService(HostProcess.IsExecutable, true),
38 Effect.provideService(HostProcess.ExecutablePath, executable),
39 Effect.provideService(HostProcess.Environment, {
40 PATH: "/usr/bin",
41 SHELL: "/bin/zsh",
42 T3CODE_INSTALL_BIN_DIR: binDir,
43 T3CODE_NPM_LAUNCHER_PATH: path.join(npmPackage, "bin/t3.mjs"),
44 ...env,
45 }),
46 );
47 return { root, npmPackage, runtimeDir, executable, link: path.join(binDir, "t3"), provide };
48 });
49
50 it.layer(NodeServices.layer)("t3 install", (it) => {
51 it.effect("installs the running runtime, records it, and never replaces another t3", () =>
52 Effect.gen(function* () {
53 const fs = yield* FileSystem.FileSystem;
54 const path = yield* Path.Path;
55 const { root, runtimeDir, executable, link, provide } = yield* setup;
56
57 const older = path.join(runtimeDir, "versions/0.0.1/t3");
58 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
59 yield* fs.symlink(older, link);
60 const installed = yield* provide(installCli());
61 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
62 assert.isFalse(installed.onPath);
63 assert.include(installed.pathCommand, "$HOME/bin");
64
65 // A link written through a symlinked T3 home is still ours.
66 const alias = path.join(root, "alias");
67 yield* fs.symlink(path.join(root, ".t3"), alias);
68 yield* fs.remove(link);
69 yield* fs.symlink(path.join(alias, "runtime/versions", VERSION, "t3"), link);
70 const onPath = yield* provide(installCli(), { PATH: `/usr/bin:${path.join(root, "bin")}/` });
71 assert.isTrue(onPath.onPath);
72 // Another t3 earlier on PATH still runs first, so `t3` would not run this one.
73 const otherBin = path.join(root, "other-bin");
74 yield* fs.makeDirectory(otherBin);
75 yield* fs.writeFileString(path.join(otherBin, "t3"), "", { mode: 0o755 });
76 const shadowed = yield* provide(installCli(), {
77 PATH: `${otherBin}:${path.join(root, "bin")}`,
78 });
79 assert.isFalse(shadowed.onPath);
80 assert.equal(shadowed.shadowedBy, path.join(otherBin, "t3"));
81 assert.isUndefined(shadowed.pathCommand);
82 yield* fs.remove(path.join(otherBin, "t3"));
83 yield* fs.makeDirectory(path.join(otherBin, "t3"));
84 const directory = yield* provide(installCli(), {
85 PATH: `${otherBin}:${path.join(root, "bin")}`,
86 });
87 assert.isTrue(directory.onPath);
88 assert.isUndefined(directory.shadowedBy);
89 const recorded = yield* fs.readFileString(path.join(runtimeDir, "launchers"));
90 assert.equal(recorded, `\n${yield* fs.realPath(path.join(root, "bin"))}/t3\n`);
91
92 yield* fs.remove(link);
93 yield* fs.writeFileString(link, "#!/bin/sh\n");
94 const error = yield* provide(installCli()).pipe(Effect.flip);
95 assert.include(error.message, "Another t3 is already at");
96 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\n");
97
98 // Only `<version>/t3` is ours, not another program inside a version.
99 yield* fs.remove(link);
100 yield* fs.symlink(path.join(runtimeDir, "versions/0.0.1/node"), link);
101 const sibling = yield* provide(installCli()).pipe(Effect.flip);
102 assert.include(sibling.message, "Another t3 is already at");
103 // This home's desktop launcher is replaced, as install.sh does.
104 yield* fs.remove(link);
105 yield* fs.symlink(path.join(root, ".t3/bin/t3"), link);
106 yield* provide(installCli());
107 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
108
109 // A script an earlier install wrote is ours too.
110 yield* fs.writeFileString(link, posixLauncherScript(older));
111 yield* provide(installCli());
112 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
113
114 // An empty spot is created exclusively: a file that appears first is kept.
115 yield* fs.remove(link);
116 const racing = installCli().pipe(
117 Effect.provideService(FileSystem.FileSystem, {
118 ...fs,
119 link: (from, to) =>
120 fs
121 .writeFileString(to, "#!/bin/sh\necho raced\n")
122 .pipe(Effect.andThen(fs.link(from, to))),
123 }),
124 );
125 assert.include((yield* provide(racing).pipe(Effect.flip)).message, "Could not write");
126 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho raced\n");
127 yield* fs.remove(link);
128
129 // Windows writes a t3.cmd: only over its own, and only for paths cmd can run.
130 const shim = path.join(root, "bin", "t3.cmd");
131 const windows = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
132 provide(effect.pipe(Effect.provideService(HostProcess.Platform, "win32")));
133 const desktopShim =
134 '@echo off\r\nrem Written by T3 Code\r\n"C:\\T3 Code\\T3 Code.exe" "x" %*\r\n';
135 yield* fs.writeFileString(shim, desktopShim);
136 const foreignShim = yield* windows(installCli()).pipe(Effect.flip);
137 assert.include(foreignShim.message, "Another t3 is already at");
138 assert.equal(yield* fs.readFileString(shim), desktopShim);
139 // A user's wrapper that also runs a managed t3.exe is still theirs.
140 const wrapper = `@echo off\r\nset FOO=1\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`;
141 yield* fs.writeFileString(shim, wrapper);
142 yield* windows(installCli()).pipe(Effect.flip);
143 assert.equal(yield* fs.readFileString(shim), wrapper);
144 // A dangling symlink is not free; writing through it would land outside the bin folder.
145 const elsewhere = path.join(root, "elsewhere.cmd");
146 yield* fs.remove(shim);
147 yield* fs.symlink(elsewhere, shim);
148 yield* windows(installCli()).pipe(Effect.flip);
149 assert.isFalse(yield* fs.exists(elsewhere));
150 yield* fs.remove(shim);
151 yield* fs.writeFileString(
152 shim,
153 `@echo off\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`,
154 );
155 const windowsInstalled = yield* windows(installCli());
156 assert.equal(yield* fs.readFileString(shim), `@echo off\r\n"${executable}" %*`);
157 // A PowerShell command for this window; the saved PATH is left to the user.
158 assert.equal(windowsInstalled.pathCommand, `$env:Path += ';${path.join(root, "bin")}'`);
159 const unrunnable = yield* windows(
160 installCli().pipe(
161 Effect.provideService(
162 HostProcess.ExecutablePath,
163 path.join(runtimeDir, "versions/100%/t3"),
164 ),
165 ),
166 ).pipe(Effect.flip);
167 assert.include(unrunnable.message, "has % or non-ASCII characters");
168 }),
169 );
170
171 it.effect("asks npx users without a t3 command once per minor release and installs on yes", () =>
172 Effect.gen(function* () {
173 const fs = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175 const { root, npmPackage, runtimeDir, executable, link, provide } = yield* setup;
176 let asked = 0;
177 const offer = (
178 answer: boolean | undefined | Effect.Effect<boolean>,
179 options: {
180 readonly args?: ReadonlyArray<string>;
181 readonly env?: NodeJS.ProcessEnv;
182 readonly interactive?: boolean;
183 readonly foreground?: boolean;
184 } = {},
185 ) =>
186 provide(
187 offerCliInstall({
188 args: options.args ?? ["connect"],
189 interactive: options.interactive ?? true,
190 foreground: Effect.succeed(options.foreground ?? true),
191 confirm: Effect.andThen(
192 Effect.sync(() => (asked += 1)),
193 Effect.isEffect(answer) ? answer : Effect.succeed(answer),
194 ),
195 }),
196 options.env,
197 );
198
199 // Scripts, CI, sudo, dumb terminals, background jobs, and help never ask.
200 yield* offer(false, { interactive: false });
201 yield* offer(false, { env: { CI: "true" } });
202 yield* offer(false, { env: { SUDO_USER: "theo" } });
203 yield* offer(false, { env: { TERM: "dumb" } });
204 yield* offer(false, { env: { npm_config_yes: "true" } });
205 yield* offer(false, { args: ["--completions", "zsh"] });
206 yield* offer(false, { foreground: false });
207 yield* offer(false, { args: ["connect", "--help"] });
208 yield* offer(false, { args: ["--log-level", "debug", "install"] });
209 yield* offer(false, { args: ["status", "--json"] });
210 yield* offer(false, { args: ["up", "--yes"] });
211 yield* offer(false, { args: ["status", "--json=true"] });
212 const globalBin = path.join(root, "global-bin");
213 yield* fs.makeDirectory(globalBin);
214 yield* fs.writeFileString(path.join(globalBin, "t3"), "");
215 yield* offer(false, { env: { PATH: globalBin } });
216 assert.equal(asked, 0);
217 assert.isFalse(yield* fs.exists(link));
218
219 // A runner's own .bin on PATH is not an installed t3.
220 const npxBin = path.join(npmPackage, "../.bin");
221 const pnpmBin = path.join(root, ".cache/pnpm/dlx/abc/node_modules/.bin");
222 for (const bin of [npxBin, pnpmBin]) {
223 yield* fs.makeDirectory(bin, { recursive: true });
224 yield* fs.writeFileString(path.join(bin, "t3"), "");
225 }
226 assert.isFalse(yield* offer(undefined, { env: { PATH: `${npxBin}:${pnpmBin}` } }));
227 assert.equal(asked, 1);
228 assert.isFalse(yield* fs.exists(path.join(runtimeDir, "install-prompt-declined")));
229 asked = 0;
230
231 // `service install` is not `t3 install`; it still leaves the command unlinked.
232 yield* offer(false, { args: ["service", "install"] });
233 assert.equal(asked, 1);
234 yield* offer(false);
235 assert.equal(asked, 1);
236 assert.isFalse(yield* fs.exists(link));
237
238 yield* fs.writeFileString(path.join(runtimeDir, "install-prompt-declined"), "0.0\n");
239 yield* offer(true);
240 assert.equal(asked, 2);
241 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
242
243 yield* fs.remove(path.join(runtimeDir, "install-prompt-declined"));
244 yield* offer(true);
245 assert.equal(asked, 2);
246
247 // A yes that cannot install, and no answer at all, also wait for the next minor release.
248 const declined = path.join(runtimeDir, "install-prompt-declined");
249 yield* fs.remove(link);
250 yield* fs.remove(path.join(runtimeDir, "launchers"));
251 yield* fs.writeFileString(link, "#!/bin/sh\necho mine\n");
252 asked = 0;
253 assert.isTrue(yield* offer(true));
254 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho mine\n");
255 assert.equal(
256 (yield* fs.readFileString(declined)).trim(),
257 VERSION.split(".").slice(0, 2).join("."),
258 );
259 yield* offer(true);
260 assert.equal(asked, 1);
261
262 yield* fs.remove(declined);
263 yield* fs.remove(link);
264 const waiting = yield* Deferred.make<void>();
265 const unanswered = yield* offer(
266 Effect.andThen(Deferred.succeed(waiting, undefined), Effect.never),
267 ).pipe(Effect.forkChild);
268 yield* Deferred.await(waiting);
269 yield* TestClock.adjust("30 seconds");
270 assert.isTrue(yield* Fiber.join(unanswered));
271 assert.isTrue(yield* fs.exists(declined));
272 assert.isFalse(yield* fs.exists(link));
273 }),
274 );
275
276 it.effect("reads the terminal's foreground group from /proc and ps", () =>
277 Effect.sync(() => {
278 // The command name can hold spaces and parentheses.
279 const stat = (pgrp: number, tpgid: number) =>
280 `4242 (t3 (serve) x) S 100 ${pgrp} 100 34816 ${tpgid} 4194560 0 0`;
281 assert.isTrue(isForegroundProcStat(stat(4242, 4242)));
282 assert.isFalse(isForegroundProcStat(stat(4242, 4300)));
283 assert.isFalse(isForegroundProcStat(stat(4242, -1)));
284 assert.isFalse(isForegroundProcStat(""));
285 assert.isTrue(isForegroundPs(" 4242 4242\n"));
286 assert.isFalse(isForegroundPs(" 4300 4242\n"));
287 assert.isFalse(isForegroundPs(" -1 4242\n"));
288 assert.isFalse(isForegroundPs(""));
289 }),
290 );
291 });