Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the Windows launch smoke tests use filesystem notifications to observe real PowerShell launches.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Deferred from "effect/Deferred";
6import * as Cause from "effect/Cause";
7import * as Effect from "effect/Effect";
8import * as TestClock from "effect/testing/TestClock";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Option from "effect/Option";
15import * as PlatformError from "effect/PlatformError";
16import * as Sink from "effect/Sink";
17import * as Stream from "effect/Stream";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19
20import { EDITORS } from "@t3tools/contracts";
21import { resolveEditorCommand } from "@t3tools/shared/editor";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { SpawnExecutableResolution } from "@t3tools/shared/shell";
24import * as ExternalLauncher from "./externalLauncher.ts";
25
26// Windows drive letters break mocked POSIX PATH splitting; these tests also require /bin/sh stubs.
27const windowsHost = HostProcess.Platform.defaultValue() === "win32";
28
29interface MockSpawnResult {
30 readonly spawnError?: PlatformError.PlatformError;
31 readonly exitCode?: number;
32 readonly stdout?: string;
33 readonly stall?: boolean;
34}
35
36function 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
60const layerTest = (input: {
61 readonly platform: NodeJS.Platform;
62 readonly env?: Record<string, string>;
63 readonly resolveExecutable?: (command: string) => string | undefined;
64 readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
65 readonly onUnref?: () => void;
66 readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined;
67}) => {
68 const layerSpawner = Layer.succeed(
69 ChildProcessSpawner.ChildProcessSpawner,
70 ChildProcessSpawner.make((command) =>
71 Effect.gen(function* () {
72 assert.equal(ChildProcess.isStandardCommand(command), true);
73 if (!ChildProcess.isStandardCommand(command)) {
74 throw new Error("Expected a standard command");
75 }
76 input.onSpawn?.(command);
77 const result = input.spawnResult?.(command);
78 if (result?.spawnError) return yield* result.spawnError;
79 return makeMockDetachedHandle({
80 ...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }),
81 ...result,
82 });
83 }),
84 ),
85 );
86
87 return Layer.mergeAll(
88 ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, layerSpawner))),
89 Layer.succeed(HostProcess.Platform, input.platform),
90 Layer.succeed(
91 SpawnExecutableResolution,
92 (command) => input.resolveExecutable?.(command) ?? command,
93 ),
94 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
95 );
96};
97
98// macOS command lookup cannot search a Windows drive-letter PATH.
99it.effect.skipIf(windowsHost)(
100 "opens home-relative app bundles using the server home directory",
101 () =>
102 Effect.gen(function* () {
103 const fs = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const bin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-app-open-" });
106 yield* fs.writeFileString(path.join(bin, "open"), "#!/bin/sh\n");
107 yield* fs.chmod(path.join(bin, "open"), 0o755);
108 const spawned: ChildProcess.StandardCommand[] = [];
109 yield* Effect.gen(function* () {
110 const launcher = yield* ExternalLauncher.ExternalLauncher;
111 for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app"]) {
112 yield* launcher.launchEditor({ editor: "file-manager", cwd });
113 }
114 }).pipe(
115 Effect.provide(
116 layerTest({
117 platform: "darwin",
118 env: { PATH: bin },
119 onSpawn: (command) => spawned.push(command),
120 }),
121 ),
122 Effect.provideService(HostProcess.HomeDirectory, "/Users/server"),
123 );
124 assert.deepEqual(
125 spawned.map((command) => command.args),
126 [["/Users/server/Applications/My App.app"], ["/Applications/My App.app"]],
127 );
128 }).pipe(Effect.provide(NodeServices.layer)),
129);
130
131it.effect.skipIf(windowsHost)(
132 "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE",
133 () =>
134 Effect.gen(function* () {
135 const fileSystem = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
138 const codePath = path.join(binDir, "code");
139 yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n");
140 yield* fileSystem.chmod(codePath, 0o755);
141
142 const spawned: ChildProcess.StandardCommand[] = [];
143 yield* Effect.gen(function* () {
144 const launcher = yield* ExternalLauncher.ExternalLauncher;
145 yield* launcher.launchBrowser("https://example.com");
146 yield* launcher.launchEditor({ editor: "vscode", cwd: "/workspace" });
147 }).pipe(
148 Effect.provide(
149 layerTest({
150 platform: "linux",
151 env: { PATH: binDir, DISPLAY: ":0" },
152 onSpawn: (command) => spawned.push(command),
153 }),
154 ),
155 Effect.provideService(HostProcess.Environment, {
156 PATH: binDir,
157 DISPLAY: ":0",
158 ELECTRON_RUN_AS_NODE: "1",
159 }),
160 );
161
162 assert.deepEqual(
163 spawned.map((command) => ({
164 command: command.command,
165 env: command.options.env,
166 extendEnv: command.options.extendEnv,
167 })),
168 ["xdg-open", "code"].map((command) => ({
169 command,
170 env: { PATH: binDir, DISPLAY: ":0" },
171 extendEnv: false,
172 })),
173 );
174 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
175);
176
177// Windows drive letters cannot resolve the POSIX editor stub.
178it.effect.skipIf(windowsHost)(
179 "a Linux editor launch without a display takes the desktop session's display from the systemd user manager",
180 () =>
181 Effect.gen(function* () {
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
185 const codiumPath = path.join(binDir, "codium");
186 yield* fileSystem.writeFileString(codiumPath, "#!/bin/sh\n");
187 yield* fileSystem.chmod(codiumPath, 0o755);
188
189 const launchEnv = (sessionManager: MockSpawnResult) =>
190 Effect.gen(function* () {
191 const spawned: ChildProcess.StandardCommand[] = [];
192 yield* Effect.gen(function* () {
193 const launcher = yield* ExternalLauncher.ExternalLauncher;
194 yield* launcher.launchEditor({ editor: "vscodium", cwd: "/workspace" });
195 yield* launcher.launchBrowser("https://example.com");
196 }).pipe(
197 Effect.provide(
198 layerTest({
199 platform: "linux",
200 env: { PATH: binDir },
201 onSpawn: (command) => spawned.push(command),
202 spawnResult: (command) =>
203 command.command === "busctl" ? sessionManager : undefined,
204 }),
205 ),
206 Effect.provideService(HostProcess.Environment, { PATH: binDir }),
207 );
208 // Only editors borrow the session display; a browser must not open on that screen.
209 assert.deepEqual(spawned.find((command) => command.command === "xdg-open")?.options.env, {
210 PATH: binDir,
211 });
212 return spawned.find((command) => command.command === "codium")?.options.env;
213 });
214
215 assert.deepEqual(
216 yield* launchEnv({
217 stdout: JSON.stringify({
218 type: "as",
219 data: [
220 "DISPLAY=:0",
221 "HOME=/home/user",
222 "WAYLAND_DISPLAY=wayland-1",
223 "XAUTHORITY=/home/user/auth files/cookie",
224 ],
225 }),
226 }),
227 {
228 PATH: binDir,
229 DISPLAY: ":0",
230 WAYLAND_DISPLAY: "wayland-1",
231 // Raw, not the $'...' quoting `systemctl show-environment` would print.
232 XAUTHORITY: "/home/user/auth files/cookie",
233 },
234 );
235 assert.deepEqual(yield* launchEnv({ stdout: "invalid JSON" }), { PATH: binDir });
236 assert.deepEqual(yield* launchEnv({ stdout: '{"data":[42]}' }), { PATH: binDir });
237 assert.deepEqual(
238 yield* launchEnv({
239 spawnError: PlatformError.systemError({
240 _tag: "NotFound",
241 module: "ChildProcess",
242 method: "spawn",
243 }),
244 }),
245 { PATH: binDir },
246 );
247 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
248);
249
250it.effect("launches an installed editor with platform-safe arguments", () =>
251 Effect.gen(function* () {
252 const fileSystem = yield* FileSystem.FileSystem;
253 const path = yield* Path.Path;
254 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
255 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
256
257 let spawned: ChildProcess.StandardCommand | undefined;
258 yield* Effect.gen(function* () {
259 const launcher = yield* ExternalLauncher.ExternalLauncher;
260 yield* launcher.launchEditor({
261 editor: "vscode",
262 cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
263 });
264 }).pipe(
265 Effect.provide(
266 layerTest({
267 platform: "win32",
268 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
269 resolveExecutable: (command) =>
270 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
271 onSpawn: (command) => {
272 spawned = command;
273 },
274 }),
275 ),
276 );
277
278 assert.ok(spawned);
279 assert.equal(
280 spawned.command,
281 [
282 '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"',
283 '^"--goto^"',
284 '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
285 ].join(" "),
286 );
287 assert.deepEqual(spawned.args, []);
288 assert.equal(spawned.options.shell, true);
289 assert.equal(spawned.options.detached, true);
290 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
291);
292
293it.effect.skipIf(windowsHost)(
294 "reveals a WSL file in Windows File Explorer through its UNC path",
295 () =>
296 Effect.gen(function* () {
297 const fileSystem = yield* FileSystem.FileSystem;
298 const path = yield* Path.Path;
299 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
300 for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) {
301 const filePath = path.join(binDir, name);
302 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
303 yield* fileSystem.chmod(filePath, 0o755);
304 }
305
306 let spawned: ChildProcess.StandardCommand | undefined;
307 const result = yield* Effect.gen(function* () {
308 const launcher = yield* ExternalLauncher.ExternalLauncher;
309 const kind = yield* launcher.resolveFileManagerRevealKind();
310 const editors = yield* launcher.resolveAvailableEditors();
311 yield* launcher.launchEditor({
312 editor: "file-manager",
313 cwd: "/home/t3/workspace [draft]/author's $media/clip|draft.mp4",
314 reveal: true,
315 });
316 return { kind, editors };
317 }).pipe(
318 Effect.provide(
319 layerTest({
320 platform: "linux",
321 env: {
322 PATH: binDir,
323 WSL_DISTRO_NAME: "Ubuntu-24.04",
324 WSL_INTEROP: "/run/WSL/1_interop",
325 },
326 onSpawn: (command) => {
327 spawned = command;
328 },
329 }),
330 ),
331 );
332
333 assert.equal(result.kind, "file-explorer");
334 assert.equal(result.editors.includes("file-manager"), true);
335 assert.ok(spawned);
336 assert.equal(spawned.command, "powershell.exe");
337 assert.equal(spawned.options.detached, true);
338 const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? "");
339 const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
340 assert.equal(
341 decodedCommand,
342 "$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media' } else { Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media\\clip|draft.mp4' + '\"') }",
343 );
344 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
345);
346
347for (const wsl of [false, true]) {
348 it.effect.skipIf(windowsHost)(
349 "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"),
350 () =>
351 Effect.gen(function* () {
352 const fileSystem = yield* FileSystem.FileSystem;
353 const path = yield* Path.Path;
354 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
355 for (const name of ["xdg-open", "xdg-mime", "gdbus", ...(wsl ? ["explorer.exe"] : [])]) {
356 const filePath = path.join(binDir, name);
357 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
358 yield* fileSystem.chmod(filePath, 0o755);
359 }
360 const target = "/workspace/media/a 'quoted' \"clip\" #100% ? é\\name.mp4";
361 const spawnedCommands: ChildProcess.StandardCommand[] = [];
362 yield* Effect.gen(function* () {
363 const launcher = yield* ExternalLauncher.ExternalLauncher;
364 yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true });
365 }).pipe(
366 Effect.provide(
367 layerTest({
368 platform: "linux",
369 env: {
370 PATH: binDir,
371 WAYLAND_DISPLAY: "wayland-1",
372 ...(wsl
373 ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" }
374 : {}),
375 },
376 onSpawn: (command) => spawnedCommands.push(command),
377 spawnResult: (command) =>
378 command.command === "xdg-mime"
379 ? { stdout: "com.thisisgm.flea.desktop\n" }
380 : undefined,
381 }),
382 ),
383 );
384
385 const reveal = spawnedCommands.find((command) => command.command === "gdbus");
386 assert.ok(reveal);
387 assert.deepEqual(reveal.args, [
388 "call",
389 "--session",
390 "--dest",
391 "org.freedesktop.FileManager1",
392 "--object-path",
393 "/org/freedesktop/FileManager1",
394 "--method",
395 "org.freedesktop.FileManager1.ShowItems",
396 "[\"file:///workspace/media/a%20'quoted'%20%22clip%22%20%23100%25%20%3F%20%C3%A9%5Cname.mp4\"]",
397 "",
398 ]);
399 assert.deepEqual(
400 spawnedCommands.filter((command) => command.command !== "xdg-mime"),
401 [reveal],
402 );
403 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
404 );
405}
406
407for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12:4"]) {
408 it.effect.skipIf(windowsHost)(
409 `opens ${cwd} with the macOS Zed bundle when another zed is on PATH`,
410 () =>
411 Effect.gen(function* () {
412 const fs = yield* FileSystem.FileSystem;
413 const path = yield* Path.Path;
414 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-collision-" });
415 const executable = path.join(home, "Applications/Zed.app/Contents/MacOS/cli");
416 const binDir = path.join(home, "zfs/bin");
417 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
418 yield* fs.makeDirectory(binDir, { recursive: true });
419 for (const command of [executable, path.join(binDir, "zed")]) {
420 yield* fs.writeFileString(command, "#!/bin/sh\n");
421 yield* fs.chmod(command, 0o755);
422 }
423
424 let spawned: ChildProcess.StandardCommand | undefined;
425 yield* Effect.gen(function* () {
426 const launcher = yield* ExternalLauncher.ExternalLauncher;
427 assert.include(yield* launcher.resolveAvailableEditors(), "zed");
428 yield* launcher.launchEditor({ editor: "zed", cwd });
429 }).pipe(
430 Effect.provide(
431 layerTest({
432 platform: "darwin",
433 env: { HOME: home, PATH: binDir },
434 onSpawn: (command) => {
435 spawned = command;
436 },
437 }),
438 ),
439 );
440 assert.ok(spawned);
441 assert.equal(spawned.command, executable);
442 assert.deepEqual(spawned.args, [cwd]);
443 assert.equal(spawned.options.shell, false);
444 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
445 );
446}
447
448for (const { layout, pathNames, fallbackNames, expected } of [
449 { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" },
450 {
451 layout: "mixed locations",
452 pathNames: ["zed"],
453 fallbackNames: ["zeditor"],
454 expected: "fallback",
455 },
456 {
457 layout: "fallback directory",
458 pathNames: [],
459 fallbackNames: ["zed", "zeditor"],
460 expected: "fallback",
461 },
462]) {
463 it.effect.skipIf(windowsHost)(`prefers the Zed editor on Linux with ${layout}`, () =>
464 Effect.gen(function* () {
465 const fs = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-linux-" });
468 const binDir = path.join(home, "bin");
469 const fallbackDir = path.join(home, ".local/bin");
470 for (const [dir, names] of [
471 [binDir, pathNames],
472 [fallbackDir, fallbackNames],
473 ] as const) {
474 yield* fs.makeDirectory(dir, { recursive: true });
475 for (const name of names) {
476 yield* fs.writeFileString(path.join(dir, name), "#!/bin/sh\n");
477 yield* fs.chmod(path.join(dir, name), 0o755);
478 }
479 }
480
481 let spawned: ChildProcess.StandardCommand | undefined;
482 yield* Effect.gen(function* () {
483 const launcher = yield* ExternalLauncher.ExternalLauncher;
484 assert.include(yield* launcher.resolveAvailableEditors(), "zed");
485 yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" });
486 }).pipe(
487 Effect.provide(
488 layerTest({
489 platform: "linux",
490 env: { HOME: home, PATH: binDir },
491 onSpawn: (command) => {
492 spawned = command;
493 },
494 }),
495 ),
496 );
497 assert.ok(spawned);
498 assert.equal(
499 spawned.command,
500 expected === "fallback" ? path.join(fallbackDir, "zeditor") : expected,
501 );
502 assert.deepEqual(spawned.args, ["/workspace"]);
503 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
504 );
505}
506
507it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directory", () =>
508 Effect.gen(function* () {
509 const fs = yield* FileSystem.FileSystem;
510 const path = yield* Path.Path;
511 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-fallback-" });
512 const localBin = path.join(home, ".local/bin");
513 const systemBin = path.join(home, "system-bin");
514 for (const [dir, name] of [
515 [localBin, "zed"],
516 [systemBin, "zeditor"],
517 ] as const) {
518 yield* fs.makeDirectory(dir, { recursive: true });
519 const executable = path.join(dir, name);
520 yield* fs.writeFileString(executable, "#!/bin/sh\necho 'Zed 0.200.0'\n");
521 yield* fs.chmod(executable, 0o755);
522 }
523 const editor = EDITORS.find((editor) => editor.id === "zed")!;
524 const resolve = resolveEditorCommand(editor, { HOME: home, PATH: "" }).pipe(
525 Effect.provideService(HostProcess.Platform, "linux"),
526 Effect.provideService(Path.Path, {
527 ...path,
528 join: (...parts) =>
529 path.join(
530 ...parts.map((part) =>
531 ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part,
532 ),
533 ),
534 }),
535 );
536 assert.deepEqual(
537 yield* resolve,
538 Option.some({ command: path.join(systemBin, "zeditor"), baseArgs: [] }),
539 );
540 yield* fs.remove(path.join(systemBin, "zeditor"));
541 assert.deepEqual(
542 yield* resolve,
543 Option.some({ command: path.join(localBin, "zed"), baseArgs: [] }),
544 );
545 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
546);
547
548it.effect.skipIf(windowsHost)("does not offer the OpenZFS zed daemon as Zed on Linux", () =>
549 Effect.gen(function* () {
550 const fs = yield* FileSystem.FileSystem;
551 const path = yield* Path.Path;
552 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-" });
553 const binDir = path.join(home, "bin");
554 const systemBin = path.join(home, "system-bin");
555 yield* fs.makeDirectory(binDir, { recursive: true });
556 yield* fs.makeDirectory(systemBin, { recursive: true });
557 const zfsZed = path.join(binDir, "zed");
558 // OpenZFS zed only takes short options: `--version` is rejected with usage on stderr.
559 yield* fs.writeFileString(
560 zfsZed,
561 "#!/bin/sh\necho \"Invalid option '--'\" >&2\necho 'Usage: zed [OPTION]...' >&2\nexit 1\n",
562 );
563 yield* fs.chmod(zfsZed, 0o755);
564 const editor = EDITORS.find((editor) => editor.id === "zed")!;
565 const resolve = resolveEditorCommand(editor, { HOME: home, PATH: binDir }).pipe(
566 Effect.provideService(HostProcess.Platform, "linux"),
567 Effect.provideService(Path.Path, {
568 ...path,
569 join: (...parts) =>
570 path.join(
571 ...parts.map((part) =>
572 ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part,
573 ),
574 ),
575 }),
576 );
577 assert.deepEqual(yield* resolve, Option.none());
578
579 const zedEditor = path.join(home, ".local/bin/zed");
580 yield* fs.makeDirectory(path.dirname(zedEditor), { recursive: true });
581 yield* fs.writeFileString(zedEditor, "#!/bin/sh\necho 'Zed 0.200.0'\n");
582 yield* fs.chmod(zedEditor, 0o755);
583 assert.deepEqual(yield* resolve, Option.some({ command: zedEditor, baseArgs: [] }));
584 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
585);
586
587it.effect.skipIf(windowsHost)("does not open Zed with the OpenZFS zed daemon on Linux", () =>
588 Effect.gen(function* () {
589 const fs = yield* FileSystem.FileSystem;
590 const path = yield* Path.Path;
591 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-launch-" });
592 const binDir = path.join(home, "bin");
593 yield* fs.makeDirectory(binDir, { recursive: true });
594 yield* fs.writeFileString(path.join(binDir, "zed"), "#!/bin/sh\nexit 1\n");
595 yield* fs.chmod(path.join(binDir, "zed"), 0o755);
596
597 const spawned: ChildProcess.StandardCommand[] = [];
598 const exit = yield* Effect.gen(function* () {
599 const launcher = yield* ExternalLauncher.ExternalLauncher;
600 return yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" }).pipe(Effect.exit);
601 }).pipe(
602 Effect.provide(
603 layerTest({
604 platform: "linux",
605 env: { HOME: home, PATH: binDir },
606 onSpawn: (command) => spawned.push(command),
607 spawnResult: (command) => (command.args[0] === "--version" ? { exitCode: 1 } : undefined),
608 }),
609 ),
610 );
611 assert.isTrue(Exit.isFailure(exit));
612 if (Exit.isFailure(exit)) {
613 assert.instanceOf(
614 Cause.squash(exit.cause),
615 ExternalLauncher.ExternalLauncherCommandNotFoundError,
616 );
617 }
618 assert.deepEqual(
619 spawned.map((command) => command.args),
620 [["--version"]],
621 );
622 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
623);
624
625it.effect.each([
626 { editor: "webstorm", installPath: "Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm" },
627 { editor: "idea", installPath: "Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea" },
628] as const)(
629 "discovers and launches $editor from a versioned macOS bundle",
630 ({ editor, installPath }) =>
631 Effect.gen(function* () {
632 const fs = yield* FileSystem.FileSystem;
633 const path = yield* Path.Path;
634 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-versioned-" });
635 const executable = path.join(home, installPath);
636 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
637 yield* fs.writeFileString(executable, "#!/bin/sh\n");
638 yield* fs.chmod(executable, 0o755);
639
640 let spawned: ChildProcess.StandardCommand | undefined;
641 yield* Effect.gen(function* () {
642 const launcher = yield* ExternalLauncher.ExternalLauncher;
643 assert.include(yield* launcher.resolveAvailableEditors(), editor);
644 yield* launcher.launchEditor({ editor, cwd: "/workspace with spaces/file.ts:12:4" });
645 }).pipe(
646 Effect.provide(
647 layerTest({
648 platform: "darwin",
649 env: { HOME: home, PATH: path.join(home, "empty") },
650 onSpawn: (command) => {
651 spawned = command;
652 },
653 }),
654 ),
655 );
656
657 assert.ok(spawned);
658 assert.equal(spawned.command, executable);
659 assert.deepEqual(spawned.args, [
660 "--line",
661 "12",
662 "--column",
663 "3",
664 "/workspace with spaces/file.ts",
665 ]);
666 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
667);
668
669it.effect("matches macOS bundles on the name boundary only", () =>
670 Effect.gen(function* () {
671 const fs = yield* FileSystem.FileSystem;
672 const path = yield* Path.Path;
673 const unrelatedHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-unrelated-" });
674 const unrelated = path.join(
675 unrelatedHome,
676 "Applications/WebStormHelper.app/Contents/MacOS/webstorm",
677 );
678 yield* fs.makeDirectory(path.dirname(unrelated), { recursive: true });
679 yield* fs.writeFileString(unrelated, "#!/bin/sh\n");
680 yield* fs.chmod(unrelated, 0o755);
681
682 const editorsFor = (home: string) =>
683 Effect.gen(function* () {
684 const launcher = yield* ExternalLauncher.ExternalLauncher;
685 return yield* launcher.resolveAvailableEditors();
686 }).pipe(
687 Effect.provide(
688 layerTest({ platform: "darwin", env: { HOME: home, PATH: path.join(home, "bin") } }),
689 ),
690 );
691
692 assert.notInclude(yield* editorsFor(unrelatedHome), "webstorm");
693
694 const exactHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-exact-" });
695 const exact = path.join(exactHome, "Applications/WebStorm.app/Contents/MacOS/webstorm");
696 yield* fs.makeDirectory(path.dirname(exact), { recursive: true });
697 yield* fs.writeFileString(exact, "#!/bin/sh\n");
698 yield* fs.chmod(exact, 0o755);
699
700 assert.include(yield* editorsFor(exactHome), "webstorm");
701 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
702);
703
704it.effect("keeps the macOS VS Code Insiders bundle out of stable VS Code", () =>
705 Effect.gen(function* () {
706 const fs = yield* FileSystem.FileSystem;
707 const path = yield* Path.Path;
708 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-insiders-" });
709 // The real Insiders bundle ships both `code-insiders` and `code`.
710 const bin = path.join(
711 home,
712 "Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin",
713 );
714 yield* fs.makeDirectory(bin, { recursive: true });
715 for (const name of ["code", "code-insiders"]) {
716 yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
717 yield* fs.chmod(path.join(bin, name), 0o755);
718 }
719
720 let spawned: ChildProcess.StandardCommand | undefined;
721 const editors = yield* Effect.gen(function* () {
722 const launcher = yield* ExternalLauncher.ExternalLauncher;
723 const available = yield* launcher.resolveAvailableEditors();
724 yield* launcher.launchEditor({ editor: "vscode-insiders", cwd: "/workspace/file.ts" });
725 return available;
726 }).pipe(
727 Effect.provide(
728 layerTest({
729 platform: "darwin",
730 env: { HOME: home, PATH: path.join(home, "empty") },
731 onSpawn: (command) => {
732 spawned = command;
733 },
734 }),
735 ),
736 );
737
738 assert.notInclude(editors, "vscode");
739 assert.include(editors, "vscode-insiders");
740 assert.equal(spawned?.command, path.join(bin, "code-insiders"));
741 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
742);
743
744for (const { platform, installPath, onPath } of [
745 { platform: "darwin", installPath: ".local/bin/agy", onPath: true },
746 { platform: "linux", installPath: ".local/bin/agy", onPath: false },
747 { platform: "win32", installPath: "agy/bin/agy.cmd", onPath: true },
748] as const) {
749 it.effect.skipIf(windowsHost && platform !== "win32")(
750 `does not report the agy CLI as the Antigravity IDE on ${platform}`,
751 () =>
752 Effect.gen(function* () {
753 const fs = yield* FileSystem.FileSystem;
754 const path = yield* Path.Path;
755 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cli-" });
756 const executable = path.join(home, installPath);
757 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
758 yield* fs.writeFileString(executable, "#!/bin/sh\n");
759 yield* fs.chmod(executable, 0o755);
760 const editors = yield* Effect.gen(function* () {
761 const launcher = yield* ExternalLauncher.ExternalLauncher;
762 return yield* launcher.resolveAvailableEditors();
763 }).pipe(
764 Effect.provide(
765 layerTest({
766 platform,
767 env: {
768 HOME: home,
769 LOCALAPPDATA: home,
770 PATH: onPath ? path.dirname(executable) : path.join(home, "empty"),
771 PATHEXT: ".COM;.EXE;.BAT;.CMD",
772 },
773 }),
774 ),
775 );
776 assert.notInclude(editors, "antigravity");
777 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
778 );
779}
780
781it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launchers first", () =>
782 Effect.gen(function* () {
783 const fs = yield* FileSystem.FileSystem;
784 const path = yield* Path.Path;
785 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-priority-" });
786 const executable = path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/code");
787 const env = { HOME: home, PATH: path.join(home, "bin") };
788 const discover = Effect.gen(function* () {
789 const launcher = yield* ExternalLauncher.ExternalLauncher;
790 return yield* launcher.resolveAvailableEditors();
791 });
792 const before = yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env })));
793 yield* fs.makeDirectory(executable, { recursive: true });
794 assert.deepEqual(
795 yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
796 before,
797 );
798 yield* fs.remove(executable, { recursive: true });
799 yield* fs.writeFileString(executable, "#!/bin/sh\n");
800 yield* fs.chmod(executable, 0o644);
801 assert.deepEqual(
802 yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
803 before,
804 );
805 yield* fs.chmod(executable, 0o755);
806 yield* fs.makeDirectory(env.PATH);
807 yield* fs.writeFileString(path.join(env.PATH, "cursor"), "#!/bin/sh\n");
808 yield* fs.chmod(path.join(env.PATH, "cursor"), 0o755);
809 let spawned: ChildProcess.StandardCommand | undefined;
810 yield* Effect.gen(function* () {
811 const launcher = yield* ExternalLauncher.ExternalLauncher;
812 yield* launcher.launchEditor({ editor: "cursor", cwd: "/workspace" });
813 }).pipe(
814 Effect.provide(
815 layerTest({
816 platform: "darwin",
817 env: { ...env, PATH: `${env.PATH}:/usr/bin` },
818 onSpawn: (command) => {
819 spawned = command;
820 },
821 }),
822 ),
823 );
824 assert.equal(spawned?.command, "cursor");
825 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
826);
827
828it.effect(
829 "memoizes editor discovery and refreshes in the background after the cache window",
830 () => {
831 let statCalls = 0;
832 const rescanned = Deferred.makeUnsafe<void>();
833 let initialScanDone = false;
834 const fileInfo = { type: "File" } as FileSystem.File.Info;
835 const layerLauncher = ExternalLauncher.layer.pipe(
836 Layer.provide(
837 Layer.mergeAll(
838 FileSystem.layerNoop({
839 stat: () =>
840 Effect.sync(() => {
841 statCalls += 1;
842 return fileInfo;
843 }).pipe(
844 Effect.tap(() =>
845 initialScanDone ? Deferred.succeed(rescanned, undefined) : Effect.void,
846 ),
847 ),
848 }),
849 Path.layer,
850 Layer.succeed(
851 ChildProcessSpawner.ChildProcessSpawner,
852 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
853 ),
854 ),
855 ),
856 );
857
858 return Effect.gen(function* () {
859 const launcher = yield* ExternalLauncher.ExternalLauncher;
860
861 const first = yield* launcher.resolveAvailableEditors();
862 assert.equal(first.includes("vscode"), true);
863 const statCallsAfterFirstScan = statCalls;
864 initialScanDone = true;
865 assert.isAbove(statCallsAfterFirstScan, 0);
866
867 // Past the shared command-resolution cache TTL (30s) but within the
868 // discovery cache window: the memoized set is reused without any scan.
869 yield* TestClock.adjust("31 seconds");
870 const second = yield* launcher.resolveAvailableEditors();
871 assert.deepEqual([...second], [...first]);
872 assert.equal(statCalls, statCallsAfterFirstScan);
873
874 // Past the discovery cache window the next call still answers from the
875 // memoized set and rescans in the background.
876 yield* TestClock.adjust("30 seconds");
877 const third = yield* launcher.resolveAvailableEditors();
878 assert.deepEqual([...third], [...first]);
879 yield* Deferred.await(rescanned);
880 assert.isAbove(statCalls, statCallsAfterFirstScan);
881 }).pipe(
882 Effect.provide(
883 Layer.mergeAll(
884 layerLauncher,
885 Layer.succeed(HostProcess.Platform, "win32"),
886 ConfigProvider.layer(
887 ConfigProvider.fromEnv({
888 env: {
889 PATH: "C:\\t3-editor-discovery-cache-test",
890 PATHEXT: ".COM;.EXE;.BAT;.CMD",
891 },
892 }),
893 ),
894 TestClock.layer(),
895 ),
896 ),
897 );
898 },
899);
900
901it.effect("keeps scanning after the caller is interrupted and shares that scan", () => {
902 const fileInfo = { type: "File" } as FileSystem.File.Info;
903 const release = Deferred.makeUnsafe<void>();
904 let parkedStats = 0;
905 const layerLauncher = ExternalLauncher.layer.pipe(
906 Layer.provide(
907 Layer.mergeAll(
908 FileSystem.layerNoop({
909 stat: () =>
910 Effect.gen(function* () {
911 if (!Deferred.isDoneUnsafe(release)) {
912 parkedStats += 1;
913 yield* Deferred.await(release);
914 }
915 return fileInfo;
916 }),
917 }),
918 Path.layer,
919 Layer.succeed(
920 ChildProcessSpawner.ChildProcessSpawner,
921 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
922 ),
923 ),
924 ),
925 );
926
927 return Effect.gen(function* () {
928 const launcher = yield* ExternalLauncher.ExternalLauncher;
929
930 const interrupted = yield* Effect.forkChild(launcher.resolveAvailableEditors());
931 yield* Effect.yieldNow;
932 yield* Fiber.interrupt(interrupted);
933
934 const next = yield* Effect.forkChild(launcher.resolveAvailableEditors());
935 yield* Effect.yieldNow;
936 assert.equal(parkedStats, 1);
937
938 yield* Deferred.succeed(release, undefined);
939 const editors = yield* Fiber.join(next);
940 assert.equal(editors.includes("vscode"), true);
941 }).pipe(
942 Effect.provide(
943 Layer.mergeAll(
944 layerLauncher,
945 Layer.succeed(HostProcess.Platform, "win32"),
946 ConfigProvider.layer(
947 ConfigProvider.fromEnv({
948 env: {
949 PATH: "C:\\t3-editor-discovery-interrupt-test",
950 PATHEXT: ".COM;.EXE;.BAT;.CMD",
951 },
952 }),
953 ),
954 ),
955 ),
956 );
957});
958
959const launchWindowsShimEditor = (cwd: string) =>
960 Effect.gen(function* () {
961 const fileSystem = yield* FileSystem.FileSystem;
962 const path = yield* Path.Path;
963 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
964 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
965 let spawned: ChildProcess.StandardCommand | undefined;
966 const exit = yield* Effect.gen(function* () {
967 const launcher = yield* ExternalLauncher.ExternalLauncher;
968 return yield* launcher.launchEditor({ editor: "vscode", cwd }).pipe(Effect.exit);
969 }).pipe(
970 Effect.provide(
971 layerTest({
972 platform: "win32",
973 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
974 resolveExecutable: (command) =>
975 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
976 onSpawn: (command) => {
977 spawned = command;
978 },
979 }),
980 ),
981 );
982 return { exit, spawned };
983 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
984
985it.effect.each([
986 ["CRLF", "C:\\workspace\\file.ts\r\ncalc.exe"],
987 ["LF", "C:\\workspace\\file.ts\ncalc.exe"],
988 ["double quote", 'C:\\workspace\\file.ts" & calc.exe & "'],
989] as const)("does not start a Windows command shim for a path with a $0", ([, cwd]) =>
990 Effect.gen(function* () {
991 const { exit, spawned } = yield* launchWindowsShimEditor(cwd);
992 assert.equal(spawned, undefined);
993 assert.isTrue(Exit.isFailure(exit));
994 if (Exit.isFailure(exit)) {
995 assert.instanceOf(
996 Cause.squash(exit.cause),
997 ExternalLauncher.ExternalLauncherUnsupportedTargetError,
998 );
999 }
1000 }),
1001);
1002
1003it.effect("starts a Windows command shim for unicode paths with cmd metacharacters", () =>
1004 Effect.gen(function* () {
1005 const { exit, spawned } = yield* launchWindowsShimEditor(
1006 "C:\\Users\\jö\\R&D (100%)\\naïve ^file!.ts:3:7",
1007 );
1008 assert.isTrue(Exit.isSuccess(exit));
1009 assert.ok(spawned);
1010 assert.equal(spawned.options.shell, true);
1011 assert.deepEqual(spawned.args, []);
1012 assert.isTrue(
1013 spawned.command.endsWith(
1014 ' ^"--goto^" ^"C:\\Users\\jö\\R^&D^ ^(100^%^)\\naïve^ ^^file^!.ts:3:7^"',
1015 ),
1016 );
1017 }),
1018);