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

externalLauncher.test.ts

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