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