@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,459 lines 56.4 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - the Windows launch smoke tests use filesystem notifications to observe real PowerShell launches.
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, it } from "@effect/vitest";
4 import * as ConfigProvider from "effect/ConfigProvider";
5 import * as Deferred from "effect/Deferred";
6 import * as Cause from "effect/Cause";
7 import * as Effect from "effect/Effect";
8 import * as TestClock from "effect/testing/TestClock";
9 import * as Exit from "effect/Exit";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Layer from "effect/Layer";
12 import * as Path from "effect/Path";
13 import * as Option from "effect/Option";
14 import * as PlatformError from "effect/PlatformError";
15 import * as Sink from "effect/Sink";
16 import * as Stream from "effect/Stream";
17 import { ChildProcess, ChildProcessSpawner } from "effect/process";
18
19 import { EDITORS } from "@t3tools/contracts";
20 import { resolveEditorCommand } from "@t3tools/shared/editor";
21 import * as HostProcess from "@t3tools/shared/HostProcess";
22 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
23 import * as ExternalLauncher from "./externalLauncher.ts";
24 import { WindowsVerbatimSpawn } from "./windowsVerbatimSpawn.ts";
25
26 // Windows drive letters break mocked POSIX PATH splitting; these tests also require /bin/sh stubs.
27 const windowsHost = HostProcess.Platform.defaultValue() === "win32";
28
29 interface MockSpawnResult {
30 readonly spawnError?: PlatformError.PlatformError;
31 readonly exitCode?: number;
32 readonly stdout?: string;
33 readonly stall?: boolean;
34 }
35
36 function makeMockDetachedHandle(input: MockSpawnResult & { readonly onUnref?: () => void } = {}) {
37 return ChildProcessSpawner.makeHandle({
38 pid: ChildProcessSpawner.ProcessId(1),
39 exitCode: input.stall
40 ? Effect.never
41 : Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
42 isRunning: Effect.succeed(true),
43 kill: () => Effect.void,
44 unref: Effect.sync(() => {
45 input.onUnref?.();
46 return Effect.void;
47 }),
48 stdin: Sink.drain,
49 stdout:
50 input.stdout === undefined
51 ? Stream.empty
52 : Stream.make(new TextEncoder().encode(input.stdout)),
53 stderr: Stream.empty,
54 all: Stream.empty,
55 getInputFd: () => Sink.drain,
56 getOutputFd: () => Stream.empty,
57 });
58 }
59
60 const layerTest = (input: {
61 readonly platform: NodeJS.Platform;
62 readonly env?: Record<string, string>;
63 readonly path?: Path.Path;
64 readonly resolveExecutable?: (command: string) => string | undefined;
65 readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
66 readonly onUnref?: () => void;
67 readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined;
68 }) => {
69 const layerSpawner = Layer.succeed(
70 ChildProcessSpawner.ChildProcessSpawner,
71 ChildProcessSpawner.make((command) =>
72 Effect.gen(function* () {
73 assert.equal(ChildProcess.isStandardCommand(command), true);
74 if (!ChildProcess.isStandardCommand(command)) {
75 throw new Error("Expected a standard command");
76 }
77 input.onSpawn?.(command);
78 const result = input.spawnResult?.(command);
79 if (result?.spawnError) return yield* result.spawnError;
80 return makeMockDetachedHandle({
81 ...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }),
82 ...result,
83 });
84 }),
85 ),
86 );
87
88 return Layer.mergeAll(
89 ExternalLauncher.layer.pipe(
90 Layer.provide(
91 Layer.mergeAll(
92 NodeServices.layer,
93 layerSpawner,
94 input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty,
95 ),
96 ),
97 ),
98 Layer.succeed(HostProcess.Platform, input.platform),
99 Layer.succeed(
100 SpawnExecutableResolution,
101 (command) => input.resolveExecutable?.(command) ?? command,
102 ),
103 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
104 );
105 };
106
107 // macOS command lookup cannot search a Windows drive-letter PATH.
108 it.effect.skipIf(windowsHost)("opens home-relative targets using the server home directory", () =>
109 Effect.gen(function* () {
110 const fs = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const bin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-app-open-" });
113 for (const name of ["open", "code", "idea"]) {
114 yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
115 yield* fs.chmod(path.join(bin, name), 0o755);
116 }
117 const spawned: ChildProcess.StandardCommand[] = [];
118 yield* Effect.gen(function* () {
119 const launcher = yield* ExternalLauncher.ExternalLauncher;
120 for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app", "/tmp/a:12"]) {
121 yield* launcher.launchEditor({ editor: "file-manager", cwd, position: { line: 5 } });
122 }
123 yield* launcher.launchEditor({ editor: "vscode", cwd: "~/notes/todo.md:3" });
124 yield* launcher.launchEditor({
125 editor: "idea",
126 cwd: "~/notes/todo.md:3",
127 projectRoot: "~/notes",
128 });
129 }).pipe(
130 Effect.provide(
131 layerTest({
132 platform: "darwin",
133 env: { PATH: bin },
134 onSpawn: (command) => spawned.push(command),
135 }),
136 ),
137 Effect.provideService(HostProcess.HomeDirectory, "/Users/server"),
138 );
139 assert.deepEqual(
140 spawned.map((command) => command.args),
141 [
142 ["/Users/server/Applications/My App.app"],
143 ["/Applications/My App.app"],
144 ["/tmp/a:12"],
145 ["--goto", "/Users/server/notes/todo.md:3"],
146 ["/Users/server/notes", "--line", "3", "/Users/server/notes/todo.md"],
147 ],
148 );
149 }).pipe(Effect.provide(NodeServices.layer)),
150 );
151
152 it.effect.skipIf(windowsHost)(
153 "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE",
154 () =>
155 Effect.gen(function* () {
156 const fileSystem = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
159 const codePath = path.join(binDir, "code");
160 yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n");
161 yield* fileSystem.chmod(codePath, 0o755);
162
163 const spawned: ChildProcess.StandardCommand[] = [];
164 yield* Effect.gen(function* () {
165 const launcher = yield* ExternalLauncher.ExternalLauncher;
166 yield* launcher.launchBrowser("https://example.com");
167 yield* launcher.launchEditor({ editor: "vscode", cwd: "/workspace" });
168 }).pipe(
169 Effect.provide(
170 layerTest({
171 platform: "linux",
172 env: { PATH: binDir, DISPLAY: ":0" },
173 onSpawn: (command) => spawned.push(command),
174 }),
175 ),
176 Effect.provideService(HostProcess.Environment, {
177 PATH: binDir,
178 DISPLAY: ":0",
179 ELECTRON_RUN_AS_NODE: "1",
180 }),
181 );
182
183 assert.deepEqual(
184 spawned.map((command) => ({
185 command: command.command,
186 env: command.options.env,
187 extendEnv: command.options.extendEnv,
188 })),
189 ["xdg-open", "code"].map((command) => ({
190 command,
191 env: { PATH: binDir, DISPLAY: ":0" },
192 extendEnv: false,
193 })),
194 );
195 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
196 );
197
198 // A project opened from T3 must not replace the editor's last active window.
199 it.effect.skipIf(windowsHost)(
200 "opens a project folder in a new VS Code window and a file in the existing one",
201 () =>
202 Effect.gen(function* () {
203 const fileSystem = yield* FileSystem.FileSystem;
204 const path = yield* Path.Path;
205 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
206 const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-project-" });
207 for (const name of ["code", "zeditor", "idea"]) {
208 const executable = path.join(binDir, name);
209 yield* fileSystem.writeFileString(executable, "#!/bin/sh\n");
210 yield* fileSystem.chmod(executable, 0o755);
211 }
212 const colonProject = path.join(project, "build:2026");
213 yield* fileSystem.makeDirectory(colonProject);
214 const file = `${path.join(project, "file.ts")}:3:7`;
215 const exactFile = path.join(project, "a:12");
216 yield* fileSystem.writeFileString(exactFile, "exact");
217 yield* fileSystem.makeDirectory(`${exactFile}:1:1`);
218 const positionedFile = path.join(project, "position.txt");
219 yield* fileSystem.writeFileString(positionedFile, "position");
220 yield* fileSystem.writeFileString(`${positionedFile}:7`, "collision");
221
222 const spawned: ChildProcess.StandardCommand[] = [];
223 yield* Effect.gen(function* () {
224 const launcher = yield* ExternalLauncher.ExternalLauncher;
225 yield* launcher.launchEditor({ editor: "vscode", cwd: project });
226 yield* launcher.launchEditor({ editor: "vscode", cwd: file });
227 yield* launcher.launchEditor({ editor: "vscode", cwd: colonProject });
228 for (const position of [{}, { line: 5 }]) {
229 yield* launcher.launchEditor({ editor: "vscode", cwd: exactFile, position });
230 }
231
232 yield* launcher.launchEditor({ editor: "zed", cwd: exactFile, position: {} });
233 yield* launcher.launchEditor({
234 editor: "zed",
235 cwd: positionedFile,
236 position: { line: 5, column: 3 },
237 });
238 yield* launcher.launchEditor({ editor: "zed", cwd: positionedFile, position: { line: 7 } });
239 yield* launcher.launchEditor({
240 editor: "vscode",
241 cwd: `${project}/exponent:1e3`,
242 position: { line: 5 },
243 });
244 yield* launcher.launchEditor({
245 editor: "idea",
246 cwd: exactFile,
247 position: { line: 5, column: 3 },
248 });
249 }).pipe(
250 Effect.provide(
251 layerTest({
252 platform: "linux",
253 env: { PATH: binDir, DISPLAY: ":0" },
254 onSpawn: (command) => spawned.push(command),
255 }),
256 ),
257 Effect.provideService(HostProcess.Environment, { PATH: binDir, DISPLAY: ":0" }),
258 );
259
260 assert.deepEqual(
261 spawned.map((command) => command.args),
262 [
263 ["--new-window", project],
264 ["--goto", file],
265 ["--new-window", colonProject],
266 [exactFile],
267 [exactFile],
268 [exactFile],
269 [`${positionedFile}:5:3`],
270 [positionedFile],
271 [`${project}/exponent:1e3`],
272 ["--line", "5", "--column", "2", exactFile],
273 ],
274 );
275 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
276 );
277
278 // Windows drive letters cannot resolve the POSIX editor stub.
279 it.effect.skipIf(windowsHost)(
280 "a Linux editor launch without a display takes the desktop session's display from the systemd user manager",
281 () =>
282 Effect.gen(function* () {
283 const fileSystem = yield* FileSystem.FileSystem;
284 const path = yield* Path.Path;
285 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
286 const codiumPath = path.join(binDir, "codium");
287 yield* fileSystem.writeFileString(codiumPath, "#!/bin/sh\n");
288 yield* fileSystem.chmod(codiumPath, 0o755);
289
290 const launchEnv = (sessionManager: MockSpawnResult) =>
291 Effect.gen(function* () {
292 const spawned: ChildProcess.StandardCommand[] = [];
293 yield* Effect.gen(function* () {
294 const launcher = yield* ExternalLauncher.ExternalLauncher;
295 yield* launcher.launchEditor({ editor: "vscodium", cwd: "/workspace" });
296 yield* launcher.launchBrowser("https://example.com");
297 }).pipe(
298 Effect.provide(
299 layerTest({
300 platform: "linux",
301 env: { PATH: binDir },
302 onSpawn: (command) => spawned.push(command),
303 spawnResult: (command) =>
304 command.command === "busctl" ? sessionManager : undefined,
305 }),
306 ),
307 Effect.provideService(HostProcess.Environment, { PATH: binDir }),
308 );
309 // Only editors borrow the session display; a browser must not open on that screen.
310 assert.deepEqual(spawned.find((command) => command.command === "xdg-open")?.options.env, {
311 PATH: binDir,
312 });
313 return spawned.find((command) => command.command === "codium")?.options.env;
314 });
315
316 assert.deepEqual(
317 yield* launchEnv({
318 stdout: JSON.stringify({
319 type: "as",
320 data: [
321 "DISPLAY=:0",
322 "HOME=/home/user",
323 "WAYLAND_DISPLAY=wayland-1",
324 "XAUTHORITY=/home/user/auth files/cookie",
325 ],
326 }),
327 }),
328 {
329 PATH: binDir,
330 DISPLAY: ":0",
331 WAYLAND_DISPLAY: "wayland-1",
332 // Raw, not the $'...' quoting `systemctl show-environment` would print.
333 XAUTHORITY: "/home/user/auth files/cookie",
334 },
335 );
336 assert.deepEqual(yield* launchEnv({ stdout: "invalid JSON" }), { PATH: binDir });
337 assert.deepEqual(yield* launchEnv({ stdout: '{"data":[42]}' }), { PATH: binDir });
338 assert.deepEqual(
339 yield* launchEnv({
340 spawnError: PlatformError.systemError({
341 _tag: "NotFound",
342 module: "ChildProcess",
343 method: "spawn",
344 }),
345 }),
346 { PATH: binDir },
347 );
348 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
349 );
350
351 // Windows drive letters cannot resolve the POSIX xdg stubs.
352 it.effect.skipIf(windowsHost)(
353 "a Linux server without a display offers and opens the file manager on the desktop session's display",
354 () =>
355 Effect.gen(function* () {
356 const fileSystem = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
359 for (const name of ["xdg-open", "xdg-mime"]) {
360 const filePath = path.join(binDir, name);
361 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
362 yield* fileSystem.chmod(filePath, 0o755);
363 }
364
365 const fileManager = (sessionEnv: ReadonlyArray<string>) =>
366 Effect.gen(function* () {
367 const spawned: ChildProcess.StandardCommand[] = [];
368 const result = yield* Effect.gen(function* () {
369 const launcher = yield* ExternalLauncher.ExternalLauncher;
370 const editors = yield* launcher.resolveAvailableEditors();
371 const kind = yield* launcher.resolveFileManagerRevealKind();
372 const opened = yield* launcher
373 .launchEditor({ editor: "file-manager", cwd: "/workspace" })
374 .pipe(Effect.exit);
375 return { offered: editors.includes("file-manager"), kind, opened };
376 }).pipe(
377 Effect.provide(
378 layerTest({
379 platform: "linux",
380 env: { PATH: binDir },
381 onSpawn: (command) => spawned.push(command),
382 spawnResult: (command) =>
383 command.command === "busctl"
384 ? { stdout: JSON.stringify({ type: "as", data: sessionEnv }) }
385 : command.command === "xdg-mime"
386 ? { stdout: "org.kde.dolphin.desktop\n" }
387 : undefined,
388 }),
389 ),
390 Effect.provideService(HostProcess.Environment, { PATH: binDir }),
391 );
392 const open = spawned.find((command) => command.command === "xdg-open");
393 return { ...result, open: open && { args: open.args, env: open.options.env } };
394 });
395
396 const session = yield* fileManager(["DISPLAY=:0", "HOME=/home/user"]);
397 assert.equal(session.offered, true);
398 assert.equal(session.kind, "files");
399 assert.equal(Exit.isSuccess(session.opened), true);
400 assert.deepEqual(session.open, {
401 args: ["/workspace"],
402 env: { PATH: binDir, DISPLAY: ":0" },
403 });
404
405 // No one is logged in to a desktop, so there is no screen to open it on.
406 const headless = yield* fileManager(["HOME=/home/user"]);
407 assert.equal(headless.offered, false);
408 assert.equal(headless.kind, undefined);
409 assert.equal(Exit.isFailure(headless.opened), true);
410 assert.equal(headless.open, undefined);
411 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
412 );
413
414 it.effect("launches an installed editor with platform-safe arguments", () =>
415 Effect.gen(function* () {
416 const fileSystem = yield* FileSystem.FileSystem;
417 const path = yield* Path.Path;
418 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
419 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
420
421 let spawned: ChildProcess.StandardCommand | undefined;
422 yield* Effect.gen(function* () {
423 const launcher = yield* ExternalLauncher.ExternalLauncher;
424 yield* launcher.launchEditor({
425 editor: "vscode",
426 cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
427 });
428 }).pipe(
429 Effect.provide(
430 layerTest({
431 platform: "win32",
432 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
433 resolveExecutable: (command) =>
434 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
435 onSpawn: (command) => {
436 spawned = command;
437 },
438 }),
439 ),
440 );
441
442 assert.ok(spawned);
443 assert.equal(
444 spawned.command,
445 [
446 '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"',
447 '^"--goto^"',
448 '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
449 ].join(" "),
450 );
451 assert.deepEqual(spawned.args, []);
452 assert.equal(spawned.options.shell, true);
453 assert.equal(spawned.options.detached, true);
454 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
455 );
456
457 const wslpathSpawner = (out: string | undefined) =>
458 Layer.succeed(
459 ChildProcessSpawner.ChildProcessSpawner,
460 ChildProcessSpawner.make((command) =>
461 Effect.sync(() => {
462 if (!ChildProcess.isStandardCommand(command)) {
463 throw new Error("Expected a standard command");
464 }
465 assert.equal(command.command, "wslpath");
466 return makeMockDetachedHandle(
467 out === undefined ? { exitCode: 1 } : { exitCode: 0, stdout: `${out}\n` },
468 );
469 }),
470 ),
471 );
472
473 it.effect.each([
474 // wslpath is mount-aware: a drive remapped in /etc/wsl.conf keeps its real letter.
475 { target: "/mnt/d/project", wslpath: "E:\\project", expected: "E:\\project" },
476 // wslpath missing or failing falls back to the hand-built UNC path.
477 {
478 target: "/home/user/repo",
479 wslpath: undefined,
480 expected: "\\\\wsl.localhost\\Ubuntu-24.04\\home\\user\\repo",
481 },
482 { target: "/", wslpath: undefined, expected: "\\\\wsl.localhost\\Ubuntu-24.04" },
483 ])("resolveWslFileManagerPath resolves $target to $expected", ({ target, wslpath, expected }) =>
484 Effect.gen(function* () {
485 const result = yield* ExternalLauncher.resolveWslFileManagerPath(target, "Ubuntu-24.04");
486 assert.equal(result, expected);
487 }).pipe(Effect.provide(wslpathSpawner(wslpath))),
488 );
489
490 it.live.skipIf(!windowsHost)("opens Windows folders through the default shell handler", () =>
491 Effect.gen(function* () {
492 let spawned: ChildProcess.StandardCommand | undefined;
493 yield* Effect.gen(function* () {
494 const launcher = yield* ExternalLauncher.ExternalLauncher;
495 yield* launcher.launchEditor({
496 editor: "file-manager",
497 cwd: "C:/workspace [draft]/author's ‘left’ ‚low‛ $media/’; Write-Output injected; #",
498 });
499 }).pipe(
500 Effect.provide(
501 layerTest({
502 platform: "win32",
503 env: { PATH: "C:\\Windows", PATHEXT: ".EXE" },
504 onSpawn: (command) => {
505 spawned = command;
506 },
507 }),
508 ),
509 );
510 assert.ok(spawned);
511 assert.equal(spawned.options.detached, false);
512 const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le");
513 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
514 const output = yield* spawner.string(
515 ChildProcess.make(spawned.command, [
516 ...spawned.args.slice(0, -1),
517 Buffer.from(
518 `[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); function Invoke-Item { param($LiteralPath) Write-Output $LiteralPath }; ${source}`,
519 "utf16le",
520 ).toString("base64"),
521 ]),
522 );
523 assert.equal(
524 output.trim(),
525 "C:\\workspace [draft]\\author's ‘left’ ‚low‛ $media\\’; Write-Output injected; #",
526 );
527 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
528 );
529
530 for (const [replacement, verb, handler, target, expected] of [
531 ["none", "none", "", "C:/repo/file.txt", 'explorer.exe /select,"C:\\repo\\file.txt"'],
532 ["Directory", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"],
533 ["Folder", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"],
534 [
535 "Folder",
536 "open",
537 '"C:\\Windows\\explorer.exe"',
538 "C:/repo/file.txt",
539 'explorer.exe /select,"C:\\repo\\file.txt"',
540 ],
541 [
542 "Folder",
543 "open",
544 "ExplorerDelegate",
545 "C:/repo/file.txt",
546 'explorer.exe /select,"C:\\repo\\file.txt"',
547 ],
548 [
549 "Drive",
550 "openindopus",
551 "dopusrt.exe",
552 "C:/repo/file.txt",
553 'explorer.exe /select,"C:\\repo\\file.txt"',
554 ],
555 ["Drive", "openindopus", "dopusrt.exe", "C:/file.txt", "shell:C:\\"],
556 ] as const) {
557 it.live.skipIf(!windowsHost)(
558 `reveals ${target} with ${replacement}/${verb} handled by ${handler}`,
559 () =>
560 Effect.gen(function* () {
561 let spawned: ChildProcess.StandardCommand | undefined;
562 yield* Effect.gen(function* () {
563 const launcher = yield* ExternalLauncher.ExternalLauncher;
564 yield* launcher.launchEditor({
565 editor: "file-manager",
566 cwd: target,
567 reveal: true,
568 });
569 }).pipe(
570 Effect.provide(
571 layerTest({
572 platform: "win32",
573 env: { PATH: "C:\\Windows", PATHEXT: ".EXE" },
574 onSpawn: (command) => {
575 spawned = command;
576 },
577 }),
578 ),
579 );
580 assert.ok(spawned);
581 const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le");
582 const stubs = `function Get-ItemProperty { param($LiteralPath, $ErrorAction) @{ '(default)' = if ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell') { '${verb}' } elseif ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell\\${verb}\\command') { '${handler}' } else { 'none' }; DelegateExecute = if ('${handler}' -eq 'ExplorerDelegate') { '{11dbb47c-a525-400b-9e80-a54615a090c0}' } else { '' } } }; function Invoke-Item { param($LiteralPath) Write-Output "shell:$LiteralPath" }; function Start-Process { param($FilePath, $ArgumentList) Write-Output "$FilePath $ArgumentList" }; `;
583 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
584 const output = yield* spawner.string(
585 ChildProcess.make(spawned.command, [
586 ...spawned.args.slice(0, -1),
587 Buffer.from(stubs + source, "utf16le").toString("base64"),
588 ]),
589 );
590 assert.equal(output.trim(), expected);
591 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
592 );
593 }
594
595 it.effect.skipIf(windowsHost)(
596 "reveals a WSL file in Windows File Explorer through its UNC path",
597 () =>
598 Effect.gen(function* () {
599 const fileSystem = yield* FileSystem.FileSystem;
600 const path = yield* Path.Path;
601 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
602 for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) {
603 const filePath = path.join(binDir, name);
604 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
605 yield* fileSystem.chmod(filePath, 0o755);
606 }
607
608 let spawned: ChildProcess.StandardCommand | undefined;
609 const result = yield* Effect.gen(function* () {
610 const launcher = yield* ExternalLauncher.ExternalLauncher;
611 const kind = yield* launcher.resolveFileManagerRevealKind();
612 const editors = yield* launcher.resolveAvailableEditors();
613 yield* launcher.launchEditor({
614 editor: "file-manager",
615 cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4",
616 reveal: true,
617 });
618 return { kind, editors };
619 }).pipe(
620 Effect.provide(
621 layerTest({
622 platform: "linux",
623 env: {
624 PATH: binDir,
625 WSL_DISTRO_NAME: "Ubuntu-24.04",
626 WSL_INTEROP: "/run/WSL/1_interop",
627 },
628 onSpawn: (command) => {
629 spawned = command;
630 },
631 }),
632 ),
633 );
634
635 assert.equal(result.kind, "file-explorer");
636 assert.equal(result.editors.includes("file-manager"), true);
637 assert.ok(spawned);
638 assert.equal(spawned.command, "powershell.exe");
639 assert.equal(spawned.options.detached, true);
640 const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? "");
641 const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
642 assert.include(decodedCommand, "'Directory', 'Folder'");
643 assert.include(
644 decodedCommand,
645 "Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media'",
646 );
647 assert.include(
648 decodedCommand,
649 "'\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media\\clip|draft.mp4'",
650 );
651 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
652 );
653
654 const STOCK_FOLDER_VERB =
655 "\r\nHKEY_CLASSES_ROOT\\Directory\\shell\r\n (Default) REG_SZ none\r\n\r\n";
656
657 it.effect.each([
658 ["selects the file with Explorer on stock Windows", { stdout: STOCK_FOLDER_VERB }, true],
659 [
660 "keeps the PowerShell reveal for a replacement file manager",
661 { stdout: " (Default) REG_SZ open\r\n" },
662 false,
663 ],
664 ["keeps the PowerShell reveal when the registry lookup fails", { exitCode: 1 }, false],
665 ] as const)("%s", ([, registry, native]) =>
666 Effect.gen(function* () {
667 const fileSystem = yield* FileSystem.FileSystem;
668 const path = yield* Path.Path;
669 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
670 yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), "");
671 const spawned: ChildProcess.StandardCommand[] = [];
672 const verbatim: Array<readonly [string, ReadonlyArray<string>]> = [];
673 const exit = yield* Effect.gen(function* () {
674 const launcher = yield* ExternalLauncher.ExternalLauncher;
675 return yield* launcher
676 .launchEditor({
677 editor: "file-manager",
678 cwd: "C:/Users/t3/my project/a,b.ts",
679 reveal: true,
680 })
681 .pipe(Effect.exit);
682 }).pipe(
683 Effect.provideService(WindowsVerbatimSpawn, (command, args) =>
684 Effect.sync(() => verbatim.push([command, args])),
685 ),
686 Effect.provide(
687 layerTest({
688 platform: "win32",
689 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" },
690 onSpawn: (command) => spawned.push(command),
691 spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined),
692 }),
693 ),
694 );
695
696 assert.deepEqual(
697 spawned.map((command) => command.command),
698 ["C:\\Windows\\System32\\reg.exe"],
699 );
700 if (native) {
701 assert.isTrue(Exit.isSuccess(exit));
702 assert.deepEqual(verbatim, [
703 ["C:\\Windows\\explorer.exe", ['/select,"C:\\Users\\t3\\my project\\a,b.ts"']],
704 ]);
705 } else {
706 assert.deepEqual(verbatim, []);
707 // The PowerShell launch is reached; this host has no powershell.exe to run it.
708 assert.isTrue(Exit.isFailure(exit));
709 if (Exit.isFailure(exit)) {
710 const error = Cause.squash(exit.cause);
711 assert.instanceOf(error, ExternalLauncher.ExternalLauncherCommandNotFoundError);
712 assert.equal(
713 (error as ExternalLauncher.ExternalLauncherCommandNotFoundError).command,
714 "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
715 );
716 }
717 }
718 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
719 );
720
721 for (const wsl of [false, true]) {
722 it.effect.skipIf(windowsHost)(
723 "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"),
724 () =>
725 Effect.gen(function* () {
726 const fileSystem = yield* FileSystem.FileSystem;
727 const path = yield* Path.Path;
728 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
729 for (const name of ["xdg-open", "xdg-mime", "gdbus", ...(wsl ? ["explorer.exe"] : [])]) {
730 const filePath = path.join(binDir, name);
731 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
732 yield* fileSystem.chmod(filePath, 0o755);
733 }
734 const target = "/workspace/media/a 'quoted' \"clip\" #100% ? é\\name.mp4";
735 const spawnedCommands: ChildProcess.StandardCommand[] = [];
736 yield* Effect.gen(function* () {
737 const launcher = yield* ExternalLauncher.ExternalLauncher;
738 yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true });
739 }).pipe(
740 Effect.provide(
741 layerTest({
742 platform: "linux",
743 env: {
744 PATH: binDir,
745 WAYLAND_DISPLAY: "wayland-1",
746 ...(wsl
747 ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" }
748 : {}),
749 },
750 onSpawn: (command) => spawnedCommands.push(command),
751 spawnResult: (command) =>
752 command.command === "xdg-mime"
753 ? { stdout: "com.thisisgm.flea.desktop\n" }
754 : undefined,
755 }),
756 ),
757 );
758
759 const reveal = spawnedCommands.find((command) => command.command === "gdbus");
760 assert.ok(reveal);
761 assert.deepEqual(reveal.args, [
762 "call",
763 "--session",
764 "--dest",
765 "org.freedesktop.FileManager1",
766 "--object-path",
767 "/org/freedesktop/FileManager1",
768 "--method",
769 "org.freedesktop.FileManager1.ShowItems",
770 "[\"file:///workspace/media/a%20'quoted'%20%22clip%22%20%23100%25%20%3F%20%C3%A9%5Cname.mp4\"]",
771 "",
772 ]);
773 assert.deepEqual(
774 spawnedCommands.filter((command) => command.command !== "xdg-mime"),
775 [reveal],
776 );
777 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
778 );
779 }
780
781 for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12:4"]) {
782 it.effect.skipIf(windowsHost)(
783 `opens ${cwd} with the macOS Zed bundle when another zed is on PATH`,
784 () =>
785 Effect.gen(function* () {
786 const fs = yield* FileSystem.FileSystem;
787 const path = yield* Path.Path;
788 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-collision-" });
789 const executable = path.join(home, "Applications/Zed.app/Contents/MacOS/cli");
790 const binDir = path.join(home, "zfs/bin");
791 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
792 yield* fs.makeDirectory(binDir, { recursive: true });
793 for (const command of [executable, path.join(binDir, "zed")]) {
794 yield* fs.writeFileString(command, "#!/bin/sh\n");
795 yield* fs.chmod(command, 0o755);
796 }
797
798 let spawned: ChildProcess.StandardCommand | undefined;
799 yield* Effect.gen(function* () {
800 const launcher = yield* ExternalLauncher.ExternalLauncher;
801 assert.include(yield* launcher.resolveAvailableEditors(), "zed");
802 yield* launcher.launchEditor({ editor: "zed", cwd });
803 }).pipe(
804 Effect.provide(
805 layerTest({
806 platform: "darwin",
807 env: { HOME: home, PATH: binDir },
808 onSpawn: (command) => {
809 spawned = command;
810 },
811 }),
812 ),
813 );
814 assert.ok(spawned);
815 assert.equal(spawned.command, executable);
816 assert.deepEqual(spawned.args, [cwd]);
817 assert.equal(spawned.options.shell, false);
818 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
819 );
820 }
821
822 for (const { layout, pathNames, fallbackNames, expected } of [
823 { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" },
824 {
825 layout: "mixed locations",
826 pathNames: ["zed"],
827 fallbackNames: ["zeditor"],
828 expected: "fallback",
829 },
830 {
831 layout: "fallback directory",
832 pathNames: [],
833 fallbackNames: ["zed", "zeditor"],
834 expected: "fallback",
835 },
836 ]) {
837 it.effect.skipIf(windowsHost)(`prefers the Zed editor on Linux with ${layout}`, () =>
838 Effect.gen(function* () {
839 const fs = yield* FileSystem.FileSystem;
840 const path = yield* Path.Path;
841 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-linux-" });
842 const binDir = path.join(home, "bin");
843 const fallbackDir = path.join(home, ".local/bin");
844 for (const [dir, names] of [
845 [binDir, pathNames],
846 [fallbackDir, fallbackNames],
847 ] as const) {
848 yield* fs.makeDirectory(dir, { recursive: true });
849 for (const name of names) {
850 yield* fs.writeFileString(path.join(dir, name), "#!/bin/sh\n");
851 yield* fs.chmod(path.join(dir, name), 0o755);
852 }
853 }
854
855 let spawned: ChildProcess.StandardCommand | undefined;
856 yield* Effect.gen(function* () {
857 const launcher = yield* ExternalLauncher.ExternalLauncher;
858 assert.include(yield* launcher.resolveAvailableEditors(), "zed");
859 yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" });
860 }).pipe(
861 Effect.provide(
862 layerTest({
863 platform: "linux",
864 env: { HOME: home, PATH: binDir },
865 onSpawn: (command) => {
866 spawned = command;
867 },
868 }),
869 ),
870 );
871 assert.ok(spawned);
872 assert.equal(
873 spawned.command,
874 expected === "fallback" ? path.join(fallbackDir, "zeditor") : expected,
875 );
876 assert.deepEqual(spawned.args, ["/workspace"]);
877 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
878 );
879 }
880
881 // Linux editor discovery also probes fixed system directories; tests point them at a temp
882 // directory so an editor installed on the host cannot satisfy the lookup.
883 const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({
884 ...path,
885 join: (...parts) =>
886 path.join(
887 ...parts.map((part) =>
888 ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part,
889 ),
890 ),
891 });
892
893 it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directory", () =>
894 Effect.gen(function* () {
895 const fs = yield* FileSystem.FileSystem;
896 const path = yield* Path.Path;
897 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-fallback-" });
898 const localBin = path.join(home, ".local/bin");
899 const systemBin = path.join(home, "system-bin");
900 for (const [dir, name] of [
901 [localBin, "zed"],
902 [systemBin, "zeditor"],
903 ] as const) {
904 yield* fs.makeDirectory(dir, { recursive: true });
905 const executable = path.join(dir, name);
906 yield* fs.writeFileString(executable, "#!/bin/sh\necho 'Zed 0.200.0'\n");
907 yield* fs.chmod(executable, 0o755);
908 }
909 const editor = EDITORS.find((editor) => editor.id === "zed")!;
910 const resolve = resolveEditorCommand(editor, { HOME: home, PATH: "" }).pipe(
911 Effect.provideService(HostProcess.Platform, "linux"),
912 Effect.provideService(Path.Path, withSystemBin(path, systemBin)),
913 );
914 assert.deepEqual(
915 yield* resolve,
916 Option.some({ command: path.join(systemBin, "zeditor"), baseArgs: [] }),
917 );
918 yield* fs.remove(path.join(systemBin, "zeditor"));
919 assert.deepEqual(
920 yield* resolve,
921 Option.some({ command: path.join(localBin, "zed"), baseArgs: [] }),
922 );
923 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
924 );
925
926 it.effect.skipIf(windowsHost)("does not offer the OpenZFS zed daemon as Zed on Linux", () =>
927 Effect.gen(function* () {
928 const fs = yield* FileSystem.FileSystem;
929 const path = yield* Path.Path;
930 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-" });
931 const binDir = path.join(home, "bin");
932 const systemBin = path.join(home, "system-bin");
933 yield* fs.makeDirectory(binDir, { recursive: true });
934 yield* fs.makeDirectory(systemBin, { recursive: true });
935 const zfsZed = path.join(binDir, "zed");
936 // OpenZFS zed only takes short options: `--version` is rejected with usage on stderr.
937 yield* fs.writeFileString(
938 zfsZed,
939 "#!/bin/sh\necho \"Invalid option '--'\" >&2\necho 'Usage: zed [OPTION]...' >&2\nexit 1\n",
940 );
941 yield* fs.chmod(zfsZed, 0o755);
942 const editor = EDITORS.find((editor) => editor.id === "zed")!;
943 const laterBin = path.join(home, "later-bin");
944 const resolveOn = (platform: NodeJS.Platform) =>
945 resolveEditorCommand(editor, { HOME: home, PATH: `${binDir}:${laterBin}` }).pipe(
946 Effect.provideService(HostProcess.Platform, platform),
947 Effect.provideService(Path.Path, withSystemBin(path, systemBin)),
948 );
949 assert.deepEqual(yield* resolveOn("linux"), Option.none());
950 assert.deepEqual(yield* resolveOn("darwin"), Option.none());
951
952 const zedEditor = path.join(home, ".local/bin/zed");
953 yield* fs.makeDirectory(path.dirname(zedEditor), { recursive: true });
954 yield* fs.writeFileString(zedEditor, "#!/bin/sh\necho 'Zed 0.200.0'\n");
955 yield* fs.chmod(zedEditor, 0o755);
956 assert.deepEqual(yield* resolveOn("linux"), Option.some({ command: zedEditor, baseArgs: [] }));
957
958 yield* fs.remove(zedEditor);
959 const laterZed = path.join(laterBin, "zed");
960 yield* fs.makeDirectory(laterBin, { recursive: true });
961 yield* fs.writeFileString(laterZed, "#!/bin/sh\necho 'Zed 0.200.0'\n");
962 yield* fs.chmod(laterZed, 0o755);
963 for (const platform of ["linux", "darwin"] as const) {
964 assert.deepEqual(
965 yield* resolveOn(platform),
966 Option.some({ command: laterZed, baseArgs: [] }),
967 );
968 }
969 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
970 );
971
972 it.effect.skipIf(windowsHost)("does not open Zed with the OpenZFS zed daemon on Linux", () =>
973 Effect.gen(function* () {
974 const fs = yield* FileSystem.FileSystem;
975 const path = yield* Path.Path;
976 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-launch-" });
977 const binDir = path.join(home, "bin");
978 const systemBin = path.join(home, "system-bin");
979 yield* fs.makeDirectory(binDir, { recursive: true });
980 yield* fs.writeFileString(path.join(binDir, "zed"), "#!/bin/sh\nexit 1\n");
981 yield* fs.chmod(path.join(binDir, "zed"), 0o755);
982
983 const spawned: ChildProcess.StandardCommand[] = [];
984 const exit = yield* Effect.gen(function* () {
985 const launcher = yield* ExternalLauncher.ExternalLauncher;
986 return yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" }).pipe(Effect.exit);
987 }).pipe(
988 Effect.provide(
989 layerTest({
990 platform: "linux",
991 env: { HOME: home, PATH: binDir, DISPLAY: ":0" },
992 path: withSystemBin(path, systemBin),
993 onSpawn: (command) => spawned.push(command),
994 spawnResult: (command) => (command.args[0] === "--version" ? { exitCode: 1 } : undefined),
995 }),
996 ),
997 );
998 assert.isTrue(Exit.isFailure(exit));
999 if (Exit.isFailure(exit)) {
1000 assert.instanceOf(
1001 Cause.squash(exit.cause),
1002 ExternalLauncher.ExternalLauncherCommandNotFoundError,
1003 );
1004 }
1005 assert.deepEqual(
1006 spawned.map((command) => command.args),
1007 [["--version"]],
1008 );
1009 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1010 );
1011
1012 it.effect.each([
1013 { editor: "webstorm", installPath: "Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm" },
1014 { editor: "idea", installPath: "Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea" },
1015 ] as const)(
1016 "discovers and launches $editor from a versioned macOS bundle",
1017 ({ editor, installPath }) =>
1018 Effect.gen(function* () {
1019 const fs = yield* FileSystem.FileSystem;
1020 const path = yield* Path.Path;
1021 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-versioned-" });
1022 const executable = path.join(home, installPath);
1023 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
1024 yield* fs.writeFileString(executable, "#!/bin/sh\n");
1025 yield* fs.chmod(executable, 0o755);
1026
1027 let spawned: ChildProcess.StandardCommand | undefined;
1028 yield* Effect.gen(function* () {
1029 const launcher = yield* ExternalLauncher.ExternalLauncher;
1030 assert.include(yield* launcher.resolveAvailableEditors(), editor);
1031 yield* launcher.launchEditor({
1032 editor,
1033 cwd: "/workspace with spaces/file.ts:12:4",
1034 projectRoot: "/workspace with spaces",
1035 });
1036 }).pipe(
1037 Effect.provide(
1038 layerTest({
1039 platform: "darwin",
1040 env: { HOME: home, PATH: path.join(home, "empty") },
1041 onSpawn: (command) => {
1042 spawned = command;
1043 },
1044 }),
1045 ),
1046 );
1047
1048 assert.ok(spawned);
1049 assert.equal(spawned.command, executable);
1050 assert.deepEqual(spawned.args, [
1051 "/workspace with spaces",
1052 "--line",
1053 "12",
1054 "--column",
1055 "3",
1056 "/workspace with spaces/file.ts",
1057 ]);
1058 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1059 );
1060
1061 it.effect("matches macOS bundles on the name boundary only", () =>
1062 Effect.gen(function* () {
1063 const fs = yield* FileSystem.FileSystem;
1064 const path = yield* Path.Path;
1065 const unrelatedHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-unrelated-" });
1066 const unrelated = path.join(
1067 unrelatedHome,
1068 "Applications/WebStormHelper.app/Contents/MacOS/webstorm",
1069 );
1070 yield* fs.makeDirectory(path.dirname(unrelated), { recursive: true });
1071 yield* fs.writeFileString(unrelated, "#!/bin/sh\n");
1072 yield* fs.chmod(unrelated, 0o755);
1073
1074 const editorsFor = (home: string) =>
1075 Effect.gen(function* () {
1076 const launcher = yield* ExternalLauncher.ExternalLauncher;
1077 return yield* launcher.resolveAvailableEditors();
1078 }).pipe(
1079 Effect.provide(
1080 layerTest({ platform: "darwin", env: { HOME: home, PATH: path.join(home, "bin") } }),
1081 ),
1082 );
1083
1084 assert.notInclude(yield* editorsFor(unrelatedHome), "webstorm");
1085
1086 const exactHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-exact-" });
1087 const exact = path.join(exactHome, "Applications/WebStorm.app/Contents/MacOS/webstorm");
1088 yield* fs.makeDirectory(path.dirname(exact), { recursive: true });
1089 yield* fs.writeFileString(exact, "#!/bin/sh\n");
1090 yield* fs.chmod(exact, 0o755);
1091
1092 assert.include(yield* editorsFor(exactHome), "webstorm");
1093 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1094 );
1095
1096 it.effect("keeps the macOS VS Code Insiders bundle out of stable VS Code", () =>
1097 Effect.gen(function* () {
1098 const fs = yield* FileSystem.FileSystem;
1099 const path = yield* Path.Path;
1100 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-insiders-" });
1101 // The real Insiders bundle ships both `code-insiders` and `code`.
1102 const bin = path.join(
1103 home,
1104 "Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin",
1105 );
1106 yield* fs.makeDirectory(bin, { recursive: true });
1107 for (const name of ["code", "code-insiders"]) {
1108 yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
1109 yield* fs.chmod(path.join(bin, name), 0o755);
1110 }
1111
1112 let spawned: ChildProcess.StandardCommand | undefined;
1113 const editors = yield* Effect.gen(function* () {
1114 const launcher = yield* ExternalLauncher.ExternalLauncher;
1115 const available = yield* launcher.resolveAvailableEditors();
1116 yield* launcher.launchEditor({ editor: "vscode-insiders", cwd: "/workspace/file.ts" });
1117 return available;
1118 }).pipe(
1119 Effect.provide(
1120 layerTest({
1121 platform: "darwin",
1122 env: { HOME: home, PATH: path.join(home, "empty") },
1123 onSpawn: (command) => {
1124 spawned = command;
1125 },
1126 }),
1127 ),
1128 );
1129
1130 assert.notInclude(editors, "vscode");
1131 assert.include(editors, "vscode-insiders");
1132 assert.equal(spawned?.command, path.join(bin, "code-insiders"));
1133 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1134 );
1135
1136 it.effect.each([
1137 {
1138 platform: "darwin",
1139 scripts: "Library/Application Support/JetBrains/Toolbox/scripts",
1140 suffix: "",
1141 },
1142 { platform: "linux", scripts: ".local/share/JetBrains/Toolbox/scripts", suffix: "" },
1143 { platform: "win32", scripts: "JetBrains/Toolbox/scripts", suffix: ".cmd" },
1144 {
1145 platform: "win32",
1146 scripts: "JetBrains/Toolbox/scripts",
1147 suffix: ".cmd",
1148 install: "Programs/IntelliJ IDEA/bin/idea64.exe",
1149 },
1150 ] as const)(
1151 "discovers a numbered JetBrains Toolbox script on $platform",
1152 ({ platform, scripts, suffix, ...row }) =>
1153 Effect.gen(function* () {
1154 const fs = yield* FileSystem.FileSystem;
1155 const path = yield* Path.Path;
1156 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-toolbox-numbered-" });
1157 const dir = path.join(home, scripts);
1158 yield* fs.makeDirectory(dir, { recursive: true });
1159 for (const name of ["idea10", "idea2"]) {
1160 yield* fs.writeFileString(path.join(dir, `${name}${suffix}`), "#!/bin/sh\n");
1161 yield* fs.chmod(path.join(dir, `${name}${suffix}`), 0o755);
1162 }
1163 const install = "install" in row ? path.join(home, row.install) : undefined;
1164 if (install) {
1165 yield* fs.makeDirectory(path.dirname(install), { recursive: true });
1166 yield* fs.writeFileString(install, "");
1167 }
1168
1169 const editor = EDITORS.find((editor) => editor.id === "idea")!;
1170 const resolved = yield* resolveEditorCommand(editor, {
1171 HOME: home,
1172 LOCALAPPDATA: home,
1173 PATH: path.join(home, "empty"),
1174 PATHEXT: ".COM;.EXE;.BAT;.CMD",
1175 }).pipe(
1176 Effect.provideService(HostProcess.Platform, platform),
1177 // Keep IDEs installed on the host out of system locations such as /Applications.
1178 Effect.provideService(FileSystem.FileSystem, {
1179 ...fs,
1180 stat: (file) =>
1181 fs.stat(file.startsWith(`${home}${path.sep}`) ? file : path.join(home, "missing")),
1182 }),
1183 );
1184
1185 assert.deepEqual(
1186 resolved,
1187 Option.some({ command: install ?? path.join(dir, `idea2${suffix}`), baseArgs: [] }),
1188 );
1189 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1190 );
1191
1192 for (const { platform, installPath, onPath } of [
1193 { platform: "darwin", installPath: ".local/bin/agy", onPath: true },
1194 { platform: "linux", installPath: ".local/bin/agy", onPath: false },
1195 { platform: "win32", installPath: "agy/bin/agy.cmd", onPath: true },
1196 ] as const) {
1197 it.effect.skipIf(windowsHost && platform !== "win32")(
1198 `does not report the agy CLI as the Antigravity IDE on ${platform}`,
1199 () =>
1200 Effect.gen(function* () {
1201 const fs = yield* FileSystem.FileSystem;
1202 const path = yield* Path.Path;
1203 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cli-" });
1204 const executable = path.join(home, installPath);
1205 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
1206 yield* fs.writeFileString(executable, "#!/bin/sh\n");
1207 yield* fs.chmod(executable, 0o755);
1208 const editors = yield* Effect.gen(function* () {
1209 const launcher = yield* ExternalLauncher.ExternalLauncher;
1210 return yield* launcher.resolveAvailableEditors();
1211 }).pipe(
1212 Effect.provide(
1213 layerTest({
1214 platform,
1215 env: {
1216 HOME: home,
1217 LOCALAPPDATA: home,
1218 PATH: onPath ? path.dirname(executable) : path.join(home, "empty"),
1219 PATHEXT: ".COM;.EXE;.BAT;.CMD",
1220 },
1221 }),
1222 ),
1223 );
1224 assert.notInclude(editors, "antigravity");
1225 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1226 );
1227 }
1228
1229 it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launchers first", () =>
1230 Effect.gen(function* () {
1231 const fs = yield* FileSystem.FileSystem;
1232 const path = yield* Path.Path;
1233 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-priority-" });
1234 const executable = path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/code");
1235 const env = { HOME: home, PATH: path.join(home, "bin") };
1236 const discover = Effect.gen(function* () {
1237 const launcher = yield* ExternalLauncher.ExternalLauncher;
1238 return yield* launcher.resolveAvailableEditors();
1239 });
1240 const before = yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env })));
1241 yield* fs.makeDirectory(executable, { recursive: true });
1242 assert.deepEqual(
1243 yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
1244 before,
1245 );
1246 yield* fs.remove(executable, { recursive: true });
1247 yield* fs.writeFileString(executable, "#!/bin/sh\n");
1248 yield* fs.chmod(executable, 0o644);
1249 assert.deepEqual(
1250 yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
1251 before,
1252 );
1253 yield* fs.chmod(executable, 0o755);
1254 yield* fs.makeDirectory(env.PATH);
1255 yield* fs.writeFileString(path.join(env.PATH, "cursor"), "#!/bin/sh\n");
1256 yield* fs.chmod(path.join(env.PATH, "cursor"), 0o755);
1257 let spawned: ChildProcess.StandardCommand | undefined;
1258 yield* Effect.gen(function* () {
1259 const launcher = yield* ExternalLauncher.ExternalLauncher;
1260 yield* launcher.launchEditor({ editor: "cursor", cwd: "/workspace" });
1261 }).pipe(
1262 Effect.provide(
1263 layerTest({
1264 platform: "darwin",
1265 env: { ...env, PATH: `${env.PATH}:/usr/bin` },
1266 onSpawn: (command) => {
1267 spawned = command;
1268 },
1269 }),
1270 ),
1271 );
1272 assert.equal(spawned?.command, "cursor");
1273 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1274 );
1275
1276 it.effect(
1277 "memoizes editor discovery and refreshes in the background after the cache window",
1278 () => {
1279 let statCalls = 0;
1280 const rescanned = Deferred.makeUnsafe<void>();
1281 let initialScanDone = false;
1282 const fileInfo = { type: "File" } as FileSystem.File.Info;
1283 const layerLauncher = ExternalLauncher.layer.pipe(
1284 Layer.provide(
1285 Layer.mergeAll(
1286 FileSystem.layerNoop({
1287 stat: () =>
1288 Effect.sync(() => {
1289 statCalls += 1;
1290 return fileInfo;
1291 }).pipe(
1292 Effect.tap(() =>
1293 initialScanDone ? Deferred.succeed(rescanned, undefined) : Effect.void,
1294 ),
1295 ),
1296 }),
1297 Path.layer,
1298 Layer.succeed(
1299 ChildProcessSpawner.ChildProcessSpawner,
1300 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
1301 ),
1302 ),
1303 ),
1304 );
1305
1306 return Effect.gen(function* () {
1307 const launcher = yield* ExternalLauncher.ExternalLauncher;
1308
1309 const first = yield* launcher.resolveAvailableEditors();
1310 assert.equal(first.includes("vscode"), true);
1311 const statCallsAfterFirstScan = statCalls;
1312 initialScanDone = true;
1313 assert.isAbove(statCallsAfterFirstScan, 0);
1314
1315 // Past the shared command-resolution cache TTL (30s) but within the
1316 // discovery cache window: the memoized set is reused without any scan.
1317 yield* TestClock.adjust("31 seconds");
1318 const second = yield* launcher.resolveAvailableEditors();
1319 assert.deepEqual([...second], [...first]);
1320 assert.equal(statCalls, statCallsAfterFirstScan);
1321
1322 // Past the discovery cache window the next call still answers from the
1323 // memoized set and rescans in the background.
1324 yield* TestClock.adjust("30 seconds");
1325 const third = yield* launcher.resolveAvailableEditors();
1326 assert.deepEqual([...third], [...first]);
1327 yield* Deferred.await(rescanned);
1328 assert.isAbove(statCalls, statCallsAfterFirstScan);
1329 }).pipe(
1330 Effect.provide(
1331 Layer.mergeAll(
1332 layerLauncher,
1333 Layer.succeed(HostProcess.Platform, "win32"),
1334 ConfigProvider.layer(
1335 ConfigProvider.fromEnv({
1336 env: {
1337 PATH: "C:\\t3-editor-discovery-cache-test",
1338 PATHEXT: ".COM;.EXE;.BAT;.CMD",
1339 },
1340 }),
1341 ),
1342 TestClock.layer(),
1343 ),
1344 ),
1345 );
1346 },
1347 );
1348
1349 it.effect.each(["Zed Nightly", "Zed Preview"])(
1350 "launches stable Zed on Windows when %s comes first on PATH",
1351 (channel) =>
1352 Effect.gen(function* () {
1353 const fs = yield* FileSystem.FileSystem;
1354 const path = yield* Path.Path;
1355 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-channels-" });
1356 // A user folder naming Zed and a channel does not mark either install.
1357 const programs = path.join(root, "Users", "zedpreview", "Programs");
1358 const prereleaseBin = path.join(programs, channel, "bin");
1359 const stableBin = path.join(programs, "Zed", "bin");
1360 for (const dir of [prereleaseBin, stableBin]) {
1361 yield* fs.makeDirectory(dir, { recursive: true });
1362 yield* fs.writeFileString(path.join(dir, "zed.EXE"), "");
1363 }
1364 const env = { PATH: `${prereleaseBin};${stableBin}`, PATHEXT: ".COM;.EXE;.BAT;.CMD" };
1365
1366 const launchZed = Effect.gen(function* () {
1367 let spawned: ChildProcess.StandardCommand | undefined;
1368 yield* Effect.gen(function* () {
1369 const launcher = yield* ExternalLauncher.ExternalLauncher;
1370 yield* launcher.launchEditor({ editor: "zed", cwd: "C:\\workspace" });
1371 }).pipe(
1372 Effect.provide(
1373 layerTest({
1374 platform: "win32",
1375 env,
1376 onSpawn: (command) => {
1377 spawned = command;
1378 },
1379 }),
1380 ),
1381 );
1382 assert.ok(spawned);
1383 return spawned;
1384 });
1385
1386 const stable = yield* launchZed;
1387 assert.equal(stable.command, path.join(stableBin, "zed.EXE"));
1388 assert.deepEqual(stable.args, ["C:\\workspace"]);
1389
1390 env.PATH = `${stableBin};${prereleaseBin}`;
1391 assert.equal((yield* launchZed).command, "zed");
1392
1393 env.PATH = `${prereleaseBin};${stableBin}`;
1394 // With only the prerelease install left, it still opens by name.
1395 yield* fs.remove(path.join(stableBin, "zed.EXE"));
1396 assert.equal((yield* launchZed).command, "zed");
1397 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1398 );
1399
1400 const launchWindowsShimEditor = (cwd: string) =>
1401 Effect.gen(function* () {
1402 const fileSystem = yield* FileSystem.FileSystem;
1403 const path = yield* Path.Path;
1404 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
1405 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
1406 let spawned: ChildProcess.StandardCommand | undefined;
1407 const exit = yield* Effect.gen(function* () {
1408 const launcher = yield* ExternalLauncher.ExternalLauncher;
1409 return yield* launcher.launchEditor({ editor: "vscode", cwd }).pipe(Effect.exit);
1410 }).pipe(
1411 Effect.provide(
1412 layerTest({
1413 platform: "win32",
1414 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
1415 resolveExecutable: (command) =>
1416 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
1417 onSpawn: (command) => {
1418 spawned = command;
1419 },
1420 }),
1421 ),
1422 );
1423 return { exit, spawned };
1424 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
1425
1426 it.effect.each([
1427 ["CRLF", "C:\\workspace\\file.ts\r\ncalc.exe"],
1428 ["LF", "C:\\workspace\\file.ts\ncalc.exe"],
1429 ["double quote", 'C:\\workspace\\file.ts" & calc.exe & "'],
1430 ] as const)("does not start a Windows command shim for a path with a $0", ([, cwd]) =>
1431 Effect.gen(function* () {
1432 const { exit, spawned } = yield* launchWindowsShimEditor(cwd);
1433 assert.equal(spawned, undefined);
1434 assert.isTrue(Exit.isFailure(exit));
1435 if (Exit.isFailure(exit)) {
1436 assert.instanceOf(
1437 Cause.squash(exit.cause),
1438 ExternalLauncher.ExternalLauncherUnsupportedTargetError,
1439 );
1440 }
1441 }),
1442 );
1443
1444 it.effect("starts a Windows command shim for unicode paths with cmd metacharacters", () =>
1445 Effect.gen(function* () {
1446 const { exit, spawned } = yield* launchWindowsShimEditor(
1447 "C:\\Users\\jö\\R&D (100%)\\naïve ^file!.ts:3:7",
1448 );
1449 assert.isTrue(Exit.isSuccess(exit));
1450 assert.ok(spawned);
1451 assert.equal(spawned.options.shell, true);
1452 assert.deepEqual(spawned.args, []);
1453 assert.isTrue(
1454 spawned.command.endsWith(
1455 ' ^"--goto^" ^"C:\\Users\\jö\\R^&D^ ^(100^%^)\\naïve^ ^^file^!.ts:3:7^"',
1456 ),
1457 );
1458 }),
1459 );