Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12import * as DesktopCliCommand from "./DesktopCliCommand.ts";
13import * as DesktopCliShim from "./DesktopCliShim.ts";
14import * as DesktopEnvironment from "./DesktopEnvironment.ts";
15
16const environmentFor = (
17 path: Path.Path,
18 input: { home: string; baseDir: string; platform?: NodeJS.Platform; isPackaged?: boolean },
19) =>
20 DesktopEnvironment.DesktopEnvironment.of({
21 path,
22 platform: input.platform ?? "linux",
23 isPackaged: input.isPackaged ?? true,
24 homeDirectory: input.home,
25 baseDir: input.baseDir,
26 stateDir: path.join(input.baseDir, "userdata"),
27 desktopSettingsPath: path.join(input.baseDir, "userdata", "desktop-settings.json"),
28 serverRoot: "/opt/T3 Code/resources/app.asar",
29 appImagePath: Option.none(),
30 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
31
32const commandIn = (
33 input: {
34 home: string;
35 baseDir?: string;
36 platform?: NodeJS.Platform;
37 isPackaged?: boolean;
38 env?: NodeJS.ProcessEnv;
39 },
40 spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"],
41) =>
42 Effect.gen(function* () {
43 const path = yield* Path.Path;
44 const fs = yield* FileSystem.FileSystem;
45 const baseDir = input.baseDir ?? path.join(input.home, ".t3");
46 yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true });
47 const make = DesktopCliCommand.make.pipe(
48 Effect.provideService(
49 DesktopEnvironment.DesktopEnvironment,
50 environmentFor(path, { ...input, baseDir }),
51 ),
52 Effect.provideService(HostProcess.Environment, input.env ?? { PATH: "", SHELL: "/bin/zsh" }),
53 );
54 return yield* spawner
55 ? make.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner))
56 : make;
57 });
58
59/** `inherited` stands in for the app's own environment, which `extendEnv` passes on. */
60const fakePowerShell = (initial: string, inherited: Record<string, string> = {}) => {
61 const registry = { path: initial, failReads: false, writes: 0 };
62 const spawner = ChildProcessSpawner.make((command) =>
63 Effect.sync(() => {
64 const { options } = command as unknown as {
65 readonly options: { readonly env?: Record<string, string>; readonly extendEnv?: boolean };
66 };
67 const env = { ...(options.extendEnv ? inherited : {}), ...options.env };
68 let exitCode = 0;
69 let stdout = "";
70 if (env.T3_SET === "1") {
71 registry.path = env.T3_PATH ?? "";
72 registry.writes += 1;
73 } else if (registry.failReads) {
74 exitCode = 1;
75 } else {
76 stdout = Buffer.from(registry.path, "utf8").toString("base64");
77 }
78 return ChildProcessSpawner.makeHandle({
79 pid: ChildProcessSpawner.ProcessId(1),
80 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
81 exitStatus: Effect.succeed({
82 _tag: "Exited",
83 code: ChildProcessSpawner.ExitCode(exitCode),
84 }),
85 isRunning: Effect.succeed(false),
86 kill: () => Effect.void,
87 unref: Effect.succeed(Effect.void),
88 stdin: Sink.drain,
89 stdout: Stream.make(new TextEncoder().encode(stdout)),
90 stderr: Stream.empty,
91 all: Stream.empty,
92 getInputFd: () => Sink.drain,
93 getOutputFd: () => Stream.empty,
94 });
95 }),
96 );
97 return { registry, spawner };
98};
99
100it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
101 it.effect("links the launcher onto PATH and removes only that link", () =>
102 Effect.gen(function* () {
103 const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
104 const fs = yield* FileSystem.FileSystem;
105 const path = yield* Path.Path;
106 const home = yield* fs.makeTempDirectoryScoped();
107 const command = yield* commandIn({ home, env });
108 const link = path.join(home, ".local", "bin", "t3");
109
110 expect(yield* command.state).toEqual({
111 supported: true,
112 installedPath: null,
113 onPath: false,
114 launcherPath: null,
115 });
116 yield* command.installOnFirstLaunch;
117 expect((yield* command.state).installedPath).toBe(link);
118 const installed = yield* command.install;
119 expect(installed.installedPath).toBe(link);
120 expect(installed.launcherPath).toBe(path.join(home, ".t3", "bin", "t3"));
121 expect(installed.pathSetup).toEqual({ file: "~/.zshrc", added: false });
122 expect(yield* fs.readLink(link)).toBe(path.join(home, ".t3", "bin", "t3"));
123 expect((yield* command.install).installedPath).toBe(link);
124
125 // Add to PATH appends one line, once, and keeps a final line with no newline intact.
126 const zshrc = path.join(home, ".zshrc");
127 yield* fs.writeFileString(zshrc, "# mine");
128 // A folder already on PATH needs nothing.
129 env.PATH = path.join(home, ".local", "bin");
130 yield* command.addToPath;
131 expect(yield* fs.readFileString(zshrc)).toBe("# mine");
132 env.PATH = "";
133 yield* Effect.all([command.addToPath, command.addToPath], { concurrency: "unbounded" });
134 expect((yield* command.addToPath).pathSetup).toEqual({ file: "~/.zshrc", added: true });
135 expect(yield* fs.readFileString(zshrc)).toBe(
136 '# mine\n# Added by T3 Code\nexport PATH="$PATH:$HOME/.local/bin"\n',
137 );
138
139 expect((yield* command.uninstall).installedPath).toBeNull();
140 expect(yield* fs.exists(link)).toBe(false);
141 expect(yield* fs.exists(path.join(home, ".t3", "bin", "t3"))).toBe(true);
142 // Removed stays removed: first launch never installs again.
143 yield* command.installOnFirstLaunch;
144 expect(yield* fs.exists(link)).toBe(false);
145
146 // Also when first launch was put off (no shell PATH yet) and the user removed it meanwhile.
147 const laterHome = yield* fs.makeTempDirectoryScoped();
148 const later = yield* commandIn({ home: laterHome, env });
149 yield* later.install;
150 yield* later.uninstall;
151 yield* later.installOnFirstLaunch;
152 expect(yield* fs.exists(path.join(laterHome, ".local", "bin", "t3"))).toBe(false);
153
154 // An app that ran before left its settings or launcher. Its user may have removed t3 or
155 // chosen another, so first launch leaves it to Settings, where Install still works.
156 for (const left of ["userdata/desktop-settings.json", "bin/t3"]) {
157 const upgradedHome = yield* fs.makeTempDirectoryScoped();
158 const leftFile = path.join(upgradedHome, ".t3", left);
159 yield* fs.makeDirectory(path.dirname(leftFile), { recursive: true });
160 yield* fs.writeFileString(leftFile, `#!/bin/sh\n# ${DesktopCliShim.MARKER}\n`);
161 const upgraded = yield* commandIn({ home: upgradedHome, env });
162 yield* upgraded.installOnFirstLaunch;
163 const upgradedLink = path.join(upgradedHome, ".local", "bin", "t3");
164 expect(yield* fs.exists(upgradedLink)).toBe(false);
165 expect((yield* upgraded.install).installedPath).toBe(upgradedLink);
166 }
167 }),
168 );
169
170 it.effect("never replaces or removes a t3 it did not create", () =>
171 Effect.gen(function* () {
172 const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
173 const fs = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175 const home = yield* fs.makeTempDirectoryScoped();
176 const command = yield* commandIn({ home, env });
177 const theirs = path.join(home, ".local", "bin", "t3");
178 yield* fs.makeDirectory(path.dirname(theirs), { recursive: true });
179 yield* fs.writeFileString(theirs, "npm's t3\n");
180 yield* fs.makeDirectory(path.join(home, "bin"), { recursive: true });
181 yield* fs.symlink(path.join(home, "gone"), path.join(home, "bin", "t3"));
182
183 const error = yield* Effect.flip(command.install);
184 expect(error.message).toContain("Another t3 command is already in");
185 yield* command.uninstall;
186 expect(yield* fs.readFileString(theirs)).toBe("npm's t3\n");
187 expect(yield* fs.readLink(path.join(home, "bin", "t3"))).toBe(path.join(home, "gone"));
188
189 // A fresh install beside someone else's t3 (even off PATH or a dangling link) adds no second
190 // t3 in ~/bin.
191 for (const dangling of [false, true]) {
192 const besideHome = yield* fs.makeTempDirectoryScoped();
193 const other = path.join(besideHome, ".local", "bin", "t3");
194 yield* fs.makeDirectory(path.dirname(other), { recursive: true });
195 yield* dangling
196 ? fs.symlink(path.join(besideHome, "gone"), other)
197 : fs.writeFileString(other, "npm's t3\n");
198 yield* (yield* commandIn({ home: besideHome })).installOnFirstLaunch;
199 expect(yield* fs.exists(path.join(besideHome, "bin", "t3"))).toBe(false);
200 }
201
202 const launcher = path.join(home, ".t3", "bin", "t3");
203 yield* fs.writeFileString(launcher, "npm's t3\n");
204 env.PATH = path.dirname(launcher);
205 expect(yield* command.state).toMatchObject({ onPath: false, shadowedBy: launcher });
206 expect((yield* Effect.flip(command.install)).message).toContain("Could not set up");
207 yield* command.uninstall;
208 expect(yield* fs.readFileString(launcher)).toBe("npm's t3\n");
209 }),
210 );
211
212 it.effect("finds and removes a link left by a previous T3 home", () =>
213 Effect.gen(function* () {
214 const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
215 const fs = yield* FileSystem.FileSystem;
216 const path = yield* Path.Path;
217 const home = yield* fs.makeTempDirectoryScoped();
218 const before = yield* commandIn({ home, baseDir: path.join(home, "old-t3"), env });
219 const link = (yield* before.install).installedPath;
220
221 const after = yield* commandIn({ home, baseDir: path.join(home, "new-t3"), env });
222 // A first launch leaves another home's command alone; only Install takes it over.
223 yield* after.installOnFirstLaunch;
224 expect(yield* fs.readLink(link!)).toBe(path.join(home, "old-t3", "bin", "t3"));
225 // On PATH, it runs the other home's launcher. Settings offers Install (not Remove, and not
226 // "another t3 runs first"), which updates that link in place.
227 env.PATH = path.dirname(link!);
228 expect(yield* after.state).toMatchObject({ installedPath: null, onPath: false });
229 expect((yield* after.state).shadowedBy).toBeUndefined();
230 env.PATH = "";
231 // Off PATH, Add to PATH would expose the other home's command, not this one.
232 expect((yield* after.state).pathSetup).toBeUndefined();
233 yield* Effect.flip(after.addToPath);
234 expect(yield* fs.exists(path.join(home, ".zshrc"))).toBe(false);
235 // Behind another t3 the install fails, and the old link still works.
236 const shadow = path.join(home, "shadow");
237 yield* fs.makeDirectory(shadow);
238 yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 });
239 env.PATH = shadow;
240 yield* Effect.flip(after.install);
241 expect(yield* fs.readLink(link!)).toBe(path.join(home, "old-t3", "bin", "t3"));
242 // Install takes it over, also with its folder first on PATH.
243 env.PATH = path.dirname(link!);
244 expect((yield* after.install).installedPath).toBe(link);
245 expect(yield* fs.readLink(link!)).toBe(path.join(home, "new-t3", "bin", "t3"));
246 env.PATH = "";
247 yield* after.uninstall;
248 expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
249 expect(yield* fs.exists(path.join(home, "bin", "t3"))).toBe(false);
250
251 // A folder already on PATH wins, even written with a trailing slash.
252 env.PATH = `${path.join(home, "bin")}/`;
253 expect((yield* after.install).installedPath).toBe(path.join(home, "bin", "t3"));
254
255 // An old link of ours is updated where it is, not moved to a folder that may be off PATH.
256 yield* fs.writeFileString(path.join(home, "bin", "t3.staging"), "mine");
257 yield* fs.remove(path.join(home, "bin", "t3"));
258 yield* fs.symlink(path.join(home, "old-t3", "bin", "t3"), path.join(home, "bin", "t3"));
259 env.PATH = "";
260 expect((yield* after.install).installedPath).toBe(path.join(home, "bin", "t3"));
261 expect(yield* fs.readLink(path.join(home, "bin", "t3"))).toBe(
262 path.join(home, "new-t3", "bin", "t3"),
263 );
264 expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
265 expect(yield* fs.readFileString(path.join(home, "bin", "t3.staging"))).toBe("mine");
266 }),
267 );
268
269 it.effect("refuses to install behind another t3 that runs first", () =>
270 Effect.gen(function* () {
271 const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
272 const fs = yield* FileSystem.FileSystem;
273 const path = yield* Path.Path;
274 const home = yield* fs.makeTempDirectoryScoped();
275 const shadow = path.join(home, "shadow");
276 yield* fs.makeDirectory(shadow);
277 yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 });
278 env.PATH = [shadow, `${path.join(home, ".local", "bin")}/`].join(":");
279
280 const command = yield* commandIn({ home, env });
281 const theirs = path.join(shadow, "t3");
282 expect((yield* command.state).shadowedBy).toBe(theirs);
283 const error = yield* Effect.flip(command.install);
284 expect(error.message).toContain(theirs);
285 yield* command.installOnFirstLaunch;
286 expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
287 expect(yield* fs.readFileString(theirs)).toBe("#!/bin/sh\n");
288
289 // Its folder is already on PATH behind theirs; adding it again would change which t3 runs.
290 yield* fs.makeDirectory(path.join(home, ".local", "bin"), { recursive: true });
291 yield* fs.symlink(
292 path.join(home, ".t3", "bin", "t3"),
293 path.join(home, ".local", "bin", "t3"),
294 );
295 const behind = yield* command.state;
296 expect(behind.installedPath).toBe(path.join(home, ".local", "bin", "t3"));
297 expect(behind.pathSetup).toBeUndefined();
298 // Off PATH behind theirs, adding the folder would still put ours first.
299 env.PATH = shadow;
300 expect((yield* command.state).pathSetup).toBeUndefined();
301 yield* Effect.flip(command.addToPath);
302 expect(yield* fs.exists(path.join(home, ".zshrc"))).toBe(false);
303 env.PATH = [shadow, `${path.join(home, ".local", "bin")}/`].join(":");
304 yield* fs.remove(path.join(home, ".local", "bin", "t3"));
305
306 // A first-launch install that failed is not retried behind the user's back.
307 yield* fs.remove(theirs);
308 yield* command.installOnFirstLaunch;
309 expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
310 const installed = yield* command.install;
311 expect(installed).toMatchObject({
312 onPath: true,
313 installedPath: path.join(home, ".local", "bin", "t3"),
314 });
315 expect(installed.shadowedBy).toBeUndefined();
316 }),
317 );
318
319 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
320 "skips a t3 directory or a file this user cannot execute",
321 () =>
322 Effect.gen(function* () {
323 const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
324 const fs = yield* FileSystem.FileSystem;
325 const path = yield* Path.Path;
326 const home = yield* fs.makeTempDirectoryScoped();
327 const folder = path.join(home, "folder");
328 const plain = path.join(home, "plain");
329 const shadow = path.join(home, "shadow");
330 yield* fs.makeDirectory(path.join(folder, "t3"), { recursive: true });
331 yield* fs.makeDirectory(plain);
332 yield* fs.writeFileString(path.join(plain, "t3"), "notes\n");
333 // Root can execute mode 0o601; other users must honor the owner permissions.
334 yield* fs.chmod(path.join(plain, "t3"), process.getuid?.() === 0 ? 0o600 : 0o601);
335 yield* fs.makeDirectory(shadow);
336 yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 });
337 env.PATH = [folder, plain, shadow, path.join(home, ".local", "bin")].join(":");
338
339 const command = yield* commandIn({ home, env });
340 expect((yield* command.state).shadowedBy).toBe(path.join(shadow, "t3"));
341
342 const error = yield* Effect.flip(command.install);
343 expect(error.message).toContain(path.join(shadow, "t3"));
344
345 yield* fs.remove(shadow, { recursive: true });
346 expect(yield* command.install).toMatchObject({
347 onPath: true,
348 installedPath: path.join(home, ".local", "bin", "t3"),
349 });
350 }),
351 );
352
353 it.effect("does not treat its own launcher as another t3 when its folder is first on PATH", () =>
354 Effect.gen(function* () {
355 const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
356 const fs = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const home = yield* fs.makeTempDirectoryScoped();
359 const launcher = path.join(home, ".t3", "bin", "t3");
360 env.PATH = [path.dirname(launcher), path.join(home, ".local", "bin")].join(":");
361
362 const command = yield* commandIn({ home, env });
363 const installed = yield* command.install;
364
365 expect(yield* fs.exists(launcher)).toBe(true);
366 expect(installed).toMatchObject({
367 onPath: true,
368 installedPath: path.join(home, ".local", "bin", "t3"),
369 });
370 expect(installed.shadowedBy).toBeUndefined();
371 expect(yield* command.state).toEqual(installed);
372
373 const removed = yield* command.uninstall;
374 expect(removed.installedPath).toBeNull();
375 expect(removed.onPath).toBe(true);
376 expect(yield* command.state).toEqual(removed);
377 expect(yield* fs.exists(installed.installedPath!)).toBe(false);
378 expect(yield* fs.exists(launcher)).toBe(true);
379 }),
380 );
381
382 it.effect("leaves the Windows PATH alone when it cannot be read", () =>
383 Effect.gen(function* () {
384 const fs = yield* FileSystem.FileSystem;
385 const home = yield* fs.makeTempDirectoryScoped();
386 const userPath = "C:\\Users\\Me\\npm;%USERPROFILE%\\tools";
387 const { registry, spawner } = fakePowerShell(userPath);
388 const command = yield* commandIn({ home, platform: "win32" }, spawner);
389
390 registry.failReads = true;
391 const error = yield* Effect.flip(command.install);
392 expect(error.message).toContain("left unchanged");
393 expect(registry).toMatchObject({ path: userPath, writes: 0 });
394
395 registry.failReads = false;
396 const launcherDir = DesktopCliShim.launcherPath(
397 environmentFor(yield* Path.Path, { home, baseDir: `${home}/.t3`, platform: "win32" }),
398 ).replace(/[\\/]t3\.cmd$/, "");
399 yield* command.install;
400 expect(registry.path).toBe(`${userPath};${launcherDir}`);
401 yield* command.uninstall;
402 expect(registry.path).toBe(userPath);
403
404 // A `;` in the folder would split it into two PATH entries, so nothing is written.
405 const split = fakePowerShell(userPath);
406 const semicolon = yield* commandIn(
407 { home, baseDir: `${home}\\T3;Home`, platform: "win32" },
408 split.spawner,
409 );
410 expect((yield* Effect.flip(semicolon.install)).message).toContain('has a ";"');
411 expect(split.registry).toMatchObject({ path: userPath, writes: 0 });
412
413 // An inherited T3_SET=1 never turns a read into a write of the whole PATH.
414 const inherited = fakePowerShell(userPath, { T3_SET: "1", T3_PATH: "C:\\other" });
415 const reader = yield* commandIn({ home, platform: "win32" }, inherited.spawner);
416 yield* reader.install;
417 expect(inherited.registry).toMatchObject({ path: `${userPath};${launcherDir}`, writes: 1 });
418 }),
419 );
420
421 it.effect("does not claim or remove a Windows PATH entry the user added", () =>
422 Effect.gen(function* () {
423 const fs = yield* FileSystem.FileSystem;
424 const path = yield* Path.Path;
425 const home = yield* fs.makeTempDirectoryScoped();
426 const launcherDir = path.dirname(
427 DesktopCliShim.launcherPath(
428 environmentFor(path, { home, baseDir: path.join(home, ".t3"), platform: "win32" }),
429 ),
430 );
431 const userPath = `C:\\Tools;${launcherDir}`;
432 const { registry, spawner } = fakePowerShell(userPath);
433 const command = yield* commandIn({ home, platform: "win32" }, spawner);
434
435 expect((yield* command.state).installedPath).toBeNull();
436 yield* command.uninstall;
437 expect(registry.path).toBe(userPath);
438
439 // A fresh install beside a standalone t3.cmd (from `t3 install`), even off PATH, leaves
440 // PATH alone.
441 const besideHome = yield* fs.makeTempDirectoryScoped();
442 yield* fs.makeDirectory(path.join(besideHome, ".local", "bin"), { recursive: true });
443 yield* fs.writeFileString(path.join(besideHome, ".local", "bin", "t3.cmd"), "@echo off\r\n");
444 const beside = fakePowerShell("C:\\Tools");
445 yield* (yield* commandIn({ home: besideHome, platform: "win32" }, beside.spawner))
446 .installOnFirstLaunch;
447 expect(beside.registry).toMatchObject({ path: "C:\\Tools", writes: 0 });
448 }),
449 );
450});