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

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