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