Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

externalLauncher.test.ts

908 lines34.0 KB

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