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 binDir = path.join(root, "bin");
74 const otherBin = path.join(root, "other-bin");
75 yield* fs.makeDirectory(otherBin);
76 yield* fs.writeFileString(path.join(otherBin, "t3"), "", { mode: 0o755 });
77 const installIn = (cwd: string, PATH: string) =>
78 provide(installCli().pipe(Effect.provideService(HostProcess.WorkingDirectory, cwd)), {
79 PATH,
80 });
81 const assertShadowed = (result: Effect.Success<ReturnType<typeof installCli>>) => {
82 assert.isFalse(result.onPath);
83 assert.equal(result.shadowedBy, path.join(otherBin, "t3"));
84 assert.isUndefined(result.pathCommand);
85 };
86 assertShadowed(yield* provide(installCli(), { PATH: `${otherBin}:${binDir}` }));
87 // Relative and empty entries resolve against the working directory.
88 assertShadowed(yield* installIn(root, `other-bin:${binDir}`));
89 assertShadowed(yield* installIn(otherBin, `:${binDir}`));
90 // An empty PATH is not the working directory.
91 const offPath = yield* installIn(otherBin, "");
92 assert.isUndefined(offPath.shadowedBy);
93 assert.isDefined(offPath.pathCommand);
94 // A symlink to binDir, or a relative entry to it that wins first, is this install.
95 yield* fs.remove(alias);
96 yield* fs.symlink(binDir, alias);
97 for (const pathEnv of [`${alias}:${otherBin}`, `bin:other-bin:${binDir}`]) {
98 const installedOnPath = yield* installIn(root, pathEnv);
99 assert.isTrue(installedOnPath.onPath);
100 assert.isUndefined(installedOnPath.shadowedBy);
101 }
102 yield* fs.remove(alias);
103 yield* fs.remove(path.join(otherBin, "t3"));
104 yield* fs.makeDirectory(path.join(otherBin, "t3"));
105 const directory = yield* provide(installCli(), {
106 PATH: `${otherBin}:${path.join(root, "bin")}`,
107 });
108 assert.isTrue(directory.onPath);
109 assert.isUndefined(directory.shadowedBy);
110 const recorded = yield* fs.readFileString(path.join(runtimeDir, "launchers"));
111 assert.equal(recorded, `\n${yield* fs.realPath(path.join(root, "bin"))}/t3\n`);
112
113 yield* fs.remove(link);
114 yield* fs.writeFileString(link, "#!/bin/sh\n");
115 const error = yield* provide(installCli()).pipe(Effect.flip);
116 assert.include(error.message, "Another t3 is already at");
117 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\n");
118
119 // Only `<version>/t3` is ours, not another program inside a version.
120 yield* fs.remove(link);
121 yield* fs.symlink(path.join(runtimeDir, "versions/0.0.1/node"), link);
122 const sibling = yield* provide(installCli()).pipe(Effect.flip);
123 assert.include(sibling.message, "Another t3 is already at");
124 // This home's desktop launcher is replaced, as install.sh does.
125 yield* fs.remove(link);
126 yield* fs.symlink(path.join(root, ".t3/bin/t3"), link);
127 yield* provide(installCli());
128 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
129
130 // A script an earlier install wrote is ours too.
131 yield* fs.writeFileString(link, posixLauncherScript(older));
132 yield* provide(installCli());
133 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
134
135 // An empty spot is created exclusively: a file that appears first is kept.
136 yield* fs.remove(link);
137 const racing = installCli().pipe(
138 Effect.provideService(FileSystem.FileSystem, {
139 ...fs,
140 link: (from, to) =>
141 fs
142 .writeFileString(to, "#!/bin/sh\necho raced\n")
143 .pipe(Effect.andThen(fs.link(from, to))),
144 }),
145 );
146 assert.include((yield* provide(racing).pipe(Effect.flip)).message, "Could not write");
147 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho raced\n");
148 yield* fs.remove(link);
149
150 // Windows writes a t3.cmd: only over its own, and only for paths cmd can run.
151 const shim = path.join(root, "bin", "t3.cmd");
152 const windows = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
153 provide(effect.pipe(Effect.provideService(HostProcess.Platform, "win32")));
154 const desktopShim =
155 '@echo off\r\nrem Written by T3 Code\r\n"C:\\T3 Code\\T3 Code.exe" "x" %*\r\n';
156 yield* fs.writeFileString(shim, desktopShim);
157 const foreignShim = yield* windows(installCli()).pipe(Effect.flip);
158 assert.include(foreignShim.message, "Another t3 is already at");
159 assert.equal(yield* fs.readFileString(shim), desktopShim);
160 // A user's wrapper that also runs a managed t3.exe is still theirs.
161 const wrapper = `@echo off\r\nset FOO=1\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`;
162 yield* fs.writeFileString(shim, wrapper);
163 yield* windows(installCli()).pipe(Effect.flip);
164 assert.equal(yield* fs.readFileString(shim), wrapper);
165 // A dangling symlink is not free; writing through it would land outside the bin folder.
166 const elsewhere = path.join(root, "elsewhere.cmd");
167 yield* fs.remove(shim);
168 yield* fs.symlink(elsewhere, shim);
169 yield* windows(installCli()).pipe(Effect.flip);
170 assert.isFalse(yield* fs.exists(elsewhere));
171 yield* fs.remove(shim);
172 yield* fs.writeFileString(
173 shim,
174 `@echo off\r\n"${path.join(runtimeDir, "versions/0.0.1/t3.exe")}" %*`,
175 );
176 const windowsInstalled = yield* windows(installCli());
177 assert.equal(yield* fs.readFileString(shim), `@echo off\r\n"${executable}" %*`);
178 // A PowerShell command for this window; the saved PATH is left to the user.
179 assert.equal(windowsInstalled.pathCommand, `$env:Path += ';${path.join(root, "bin")}'`);
180 const unrunnable = yield* windows(
181 installCli().pipe(
182 Effect.provideService(
183 HostProcess.ExecutablePath,
184 path.join(runtimeDir, "versions/100%/t3"),
185 ),
186 ),
187 ).pipe(Effect.flip);
188 assert.include(unrunnable.message, "has % or non-ASCII characters");
189 }),
190 );
191
192 it.effect("asks npx users without a t3 command once per minor release and installs on yes", () =>
193 Effect.gen(function* () {
194 const fs = yield* FileSystem.FileSystem;
195 const path = yield* Path.Path;
196 const { root, npmPackage, runtimeDir, executable, link, provide } = yield* setup;
197 let asked = 0;
198 const offer = (
199 answer: boolean | undefined | Effect.Effect<boolean>,
200 options: {
201 readonly args?: ReadonlyArray<string>;
202 readonly env?: NodeJS.ProcessEnv;
203 readonly interactive?: boolean;
204 readonly foreground?: boolean;
205 } = {},
206 ) =>
207 provide(
208 offerCliInstall({
209 args: options.args ?? ["connect"],
210 interactive: options.interactive ?? true,
211 foreground: Effect.succeed(options.foreground ?? true),
212 confirm: Effect.andThen(
213 Effect.sync(() => (asked += 1)),
214 Effect.isEffect(answer) ? answer : Effect.succeed(answer),
215 ),
216 }),
217 options.env,
218 );
219
220 // Scripts, CI, sudo, dumb terminals, background jobs, and help never ask.
221 yield* offer(false, { interactive: false });
222 yield* offer(false, { env: { CI: "true" } });
223 yield* offer(false, { env: { SUDO_USER: "theo" } });
224 yield* offer(false, { env: { TERM: "dumb" } });
225 yield* offer(false, { env: { npm_config_yes: "true" } });
226 yield* offer(false, { args: ["--completions", "zsh"] });
227 yield* offer(false, { foreground: false });
228 yield* offer(false, { args: ["connect", "--help"] });
229 yield* offer(false, { args: ["--log-level", "debug", "install"] });
230 yield* offer(false, { args: ["status", "--json"] });
231 yield* offer(false, { args: ["up", "--yes"] });
232 yield* offer(false, { args: ["status", "--json=true"] });
233 const globalBin = path.join(root, "global-bin");
234 yield* fs.makeDirectory(globalBin);
235 yield* fs.writeFileString(path.join(globalBin, "t3"), "");
236 yield* fs.chmod(path.join(globalBin, "t3"), 0o755);
237 yield* offer(false, { env: { PATH: globalBin } });
238 assert.equal(asked, 0);
239 assert.isFalse(yield* fs.exists(link));
240
241 // A directory or non-executable file named `t3` on PATH is not an installed t3.
242 const dirBin = path.join(root, "dir-bin");
243 yield* fs.makeDirectory(path.join(dirBin, "t3"), { recursive: true });
244 const nonExecBin = path.join(root, "non-exec-bin");
245 yield* fs.makeDirectory(nonExecBin);
246 yield* fs.writeFileString(path.join(nonExecBin, "t3"), "");
247 assert.isFalse(yield* offer(undefined, { env: { PATH: dirBin } }));
248 assert.equal(asked, 1);
249 assert.isFalse(yield* offer(undefined, { env: { PATH: nonExecBin } }));
250 assert.equal(asked, 2);
251 asked = 0;
252
253 // A runner's own .bin on PATH, even found through a bare launcher record, is not an installed t3.
254 const npxBin = path.join(npmPackage, "../.bin");
255 const pnpmBin = path.join(root, ".cache/pnpm/dlx/abc/node_modules/.bin");
256 for (const bin of [npxBin, pnpmBin]) {
257 yield* fs.makeDirectory(bin, { recursive: true });
258 yield* fs.writeFileString(path.join(bin, "t3"), "");
259 yield* fs.chmod(path.join(bin, "t3"), 0o755);
260 }
261 yield* fs.writeFileString(path.join(runtimeDir, "launchers"), "t3\n");
262 assert.isFalse(yield* offer(undefined, { env: { PATH: `${npxBin}:${pnpmBin}` } }));
263 assert.equal(asked, 1);
264 assert.isFalse(yield* fs.exists(path.join(runtimeDir, "install-prompt-declined")));
265 asked = 0;
266
267 // `service install` is not `t3 install`; it still leaves the command unlinked.
268 yield* offer(false, { args: ["service", "install"] });
269 assert.equal(asked, 1);
270 yield* offer(false);
271 assert.equal(asked, 1);
272 assert.isFalse(yield* fs.exists(link));
273
274 yield* fs.writeFileString(path.join(runtimeDir, "install-prompt-declined"), "0.0\n");
275 yield* offer(true);
276 assert.equal(asked, 2);
277 assert.equal(yield* fs.readFileString(link), posixLauncherScript(executable));
278
279 yield* fs.remove(path.join(runtimeDir, "install-prompt-declined"));
280 yield* offer(true);
281 assert.equal(asked, 2);
282
283 // A yes that cannot install, and no answer at all, also wait for the next minor release.
284 const declined = path.join(runtimeDir, "install-prompt-declined");
285 yield* fs.remove(link);
286 yield* fs.remove(path.join(runtimeDir, "launchers"));
287 yield* fs.writeFileString(link, "#!/bin/sh\necho mine\n");
288 asked = 0;
289 assert.isTrue(yield* offer(true));
290 assert.equal(yield* fs.readFileString(link), "#!/bin/sh\necho mine\n");
291 assert.equal(
292 (yield* fs.readFileString(declined)).trim(),
293 VERSION.split(".").slice(0, 2).join("."),
294 );
295 yield* offer(true);
296 assert.equal(asked, 1);
297
298 yield* fs.remove(declined);
299 yield* fs.remove(link);
300 const waiting = yield* Deferred.make<void>();
301 const unanswered = yield* offer(
302 Effect.andThen(Deferred.succeed(waiting, undefined), Effect.never),
303 ).pipe(Effect.forkChild);
304 yield* Deferred.await(waiting);
305 yield* TestClock.adjust("30 seconds");
306 assert.isTrue(yield* Fiber.join(unanswered));
307 assert.isTrue(yield* fs.exists(declined));
308 assert.isFalse(yield* fs.exists(link));
309 }),
310 );
311
312 it.effect("reads the terminal's foreground group from /proc and ps", () =>
313 Effect.sync(() => {
314 // The command name can hold spaces and parentheses.
315 const stat = (pgrp: number, tpgid: number) =>
316 `4242 (t3 (serve) x) S 100 ${pgrp} 100 34816 ${tpgid} 4194560 0 0`;
317 assert.isTrue(isForegroundProcStat(stat(4242, 4242)));
318 assert.isFalse(isForegroundProcStat(stat(4242, 4300)));
319 assert.isFalse(isForegroundProcStat(stat(4242, -1)));
320 assert.isFalse(isForegroundProcStat(""));
321 assert.isTrue(isForegroundPs(" 4242 4242\n"));
322 assert.isFalse(isForegroundPs(" 4300 4242\n"));
323 assert.isFalse(isForegroundPs(" -1 4242\n"));
324 assert.isFalse(isForegroundPs(""));
325 }),
326 );
327});