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