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

externalLauncher.test.ts

1,326 lines50.8 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 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";
24import { WindowsVerbatimSpawn } from "./windowsVerbatimSpawn.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 path?: Path.Path;
64 readonly resolveExecutable?: (command: string) => string | undefined;
65 readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
66 readonly onUnref?: () => void;
67 readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined;
68}) => {
69 const layerSpawner = Layer.succeed(
70 ChildProcessSpawner.ChildProcessSpawner,
71 ChildProcessSpawner.make((command) =>
72 Effect.gen(function* () {
73 assert.equal(ChildProcess.isStandardCommand(command), true);
74 if (!ChildProcess.isStandardCommand(command)) {
75 throw new Error("Expected a standard command");
76 }
77 input.onSpawn?.(command);
78 const result = input.spawnResult?.(command);
79 if (result?.spawnError) return yield* result.spawnError;
80 return makeMockDetachedHandle({
81 ...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }),
82 ...result,
83 });
84 }),
85 ),
86 );
87​
88 return Layer.mergeAll(
89 ExternalLauncher.layer.pipe(
90 Layer.provide(
91 Layer.mergeAll(
92 NodeServices.layer,
93 layerSpawner,
94 input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty,
95 ),
96 ),
97 ),
98 Layer.succeed(HostProcess.Platform, input.platform),
99 Layer.succeed(
100 SpawnExecutableResolution,
101 (command) => input.resolveExecutable?.(command) ?? command,
102 ),
103 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
104 );
105};
106​
107// macOS command lookup cannot search a Windows drive-letter PATH.
108it.effect.skipIf(windowsHost)("opens home-relative targets using the server home directory", () =>
109 Effect.gen(function* () {
110 const fs = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const bin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-app-open-" });
113 for (const name of ["open", "code", "idea"]) {
114 yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
115 yield* fs.chmod(path.join(bin, name), 0o755);
116 }
117 const spawned: ChildProcess.StandardCommand[] = [];
118 yield* Effect.gen(function* () {
119 const launcher = yield* ExternalLauncher.ExternalLauncher;
120 for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app"]) {
121 yield* launcher.launchEditor({ editor: "file-manager", cwd });
122 }
123 yield* launcher.launchEditor({ editor: "vscode", cwd: "~/notes/todo.md:3" });
124 yield* launcher.launchEditor({
125 editor: "idea",
126 cwd: "~/notes/todo.md:3",
127 projectRoot: "~/notes",
128 });
129 }).pipe(
130 Effect.provide(
131 layerTest({
132 platform: "darwin",
133 env: { PATH: bin },
134 onSpawn: (command) => spawned.push(command),
135 }),
136 ),
137 Effect.provideService(HostProcess.HomeDirectory, "/Users/server"),
138 );
139 assert.deepEqual(
140 spawned.map((command) => command.args),
141 [
142 ["/Users/server/Applications/My App.app"],
143 ["/Applications/My App.app"],
144 ["--goto", "/Users/server/notes/todo.md:3"],
145 ["/Users/server/notes", "--line", "3", "/Users/server/notes/todo.md"],
146 ],
147 );
148 }).pipe(Effect.provide(NodeServices.layer)),
149);
150​
151it.effect.skipIf(windowsHost)(
152 "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE",
153 () =>
154 Effect.gen(function* () {
155 const fileSystem = yield* FileSystem.FileSystem;
156 const path = yield* Path.Path;
157 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
158 const codePath = path.join(binDir, "code");
159 yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n");
160 yield* fileSystem.chmod(codePath, 0o755);
161​
162 const spawned: ChildProcess.StandardCommand[] = [];
163 yield* Effect.gen(function* () {
164 const launcher = yield* ExternalLauncher.ExternalLauncher;
165 yield* launcher.launchBrowser("https://example.com");
166 yield* launcher.launchEditor({ editor: "vscode", cwd: "/workspace" });
167 }).pipe(
168 Effect.provide(
169 layerTest({
170 platform: "linux",
171 env: { PATH: binDir, DISPLAY: ":0" },
172 onSpawn: (command) => spawned.push(command),
173 }),
174 ),
175 Effect.provideService(HostProcess.Environment, {
176 PATH: binDir,
177 DISPLAY: ":0",
178 ELECTRON_RUN_AS_NODE: "1",
179 }),
180 );
181​
182 assert.deepEqual(
183 spawned.map((command) => ({
184 command: command.command,
185 env: command.options.env,
186 extendEnv: command.options.extendEnv,
187 })),
188 ["xdg-open", "code"].map((command) => ({
189 command,
190 env: { PATH: binDir, DISPLAY: ":0" },
191 extendEnv: false,
192 })),
193 );
194 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
195);
196​
197// A project opened from T3 must not replace the editor's last active window.
198it.effect.skipIf(windowsHost)(
199 "opens a project folder in a new VS Code window and a file in the existing one",
200 () =>
201 Effect.gen(function* () {
202 const fileSystem = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
205 const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-project-" });
206 const codePath = path.join(binDir, "code");
207 yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n");
208 yield* fileSystem.chmod(codePath, 0o755);
209 const colonProject = path.join(project, "build:2026");
210 yield* fileSystem.makeDirectory(colonProject);
211 const file = `${path.join(project, "file.ts")}:3:7`;
212​
213 const spawned: ChildProcess.StandardCommand[] = [];
214 yield* Effect.gen(function* () {
215 const launcher = yield* ExternalLauncher.ExternalLauncher;
216 yield* launcher.launchEditor({ editor: "vscode", cwd: project });
217 yield* launcher.launchEditor({ editor: "vscode", cwd: file });
218 yield* launcher.launchEditor({ editor: "vscode", cwd: colonProject });
219 }).pipe(
220 Effect.provide(
221 layerTest({
222 platform: "linux",
223 env: { PATH: binDir, DISPLAY: ":0" },
224 onSpawn: (command) => spawned.push(command),
225 }),
226 ),
227 Effect.provideService(HostProcess.Environment, { PATH: binDir, DISPLAY: ":0" }),
228 );
229​
230 assert.deepEqual(
231 spawned.map((command) => command.args),
232 [
233 ["--new-window", project],
234 ["--goto", file],
235 ["--new-window", colonProject],
236 ],
237 );
238 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
239);
240​
241// Windows drive letters cannot resolve the POSIX editor stub.
242it.effect.skipIf(windowsHost)(
243 "a Linux editor launch without a display takes the desktop session's display from the systemd user manager",
244 () =>
245 Effect.gen(function* () {
246 const fileSystem = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
249 const codiumPath = path.join(binDir, "codium");
250 yield* fileSystem.writeFileString(codiumPath, "#!/bin/sh\n");
251 yield* fileSystem.chmod(codiumPath, 0o755);
252​
253 const launchEnv = (sessionManager: MockSpawnResult) =>
254 Effect.gen(function* () {
255 const spawned: ChildProcess.StandardCommand[] = [];
256 yield* Effect.gen(function* () {
257 const launcher = yield* ExternalLauncher.ExternalLauncher;
258 yield* launcher.launchEditor({ editor: "vscodium", cwd: "/workspace" });
259 yield* launcher.launchBrowser("https://example.com");
260 }).pipe(
261 Effect.provide(
262 layerTest({
263 platform: "linux",
264 env: { PATH: binDir },
265 onSpawn: (command) => spawned.push(command),
266 spawnResult: (command) =>
267 command.command === "busctl" ? sessionManager : undefined,
268 }),
269 ),
270 Effect.provideService(HostProcess.Environment, { PATH: binDir }),
271 );
272 // Only editors borrow the session display; a browser must not open on that screen.
273 assert.deepEqual(spawned.find((command) => command.command === "xdg-open")?.options.env, {
274 PATH: binDir,
275 });
276 return spawned.find((command) => command.command === "codium")?.options.env;
277 });
278​
279 assert.deepEqual(
280 yield* launchEnv({
281 stdout: JSON.stringify({
282 type: "as",
283 data: [
284 "DISPLAY=:0",
285 "HOME=/home/user",
286 "WAYLAND_DISPLAY=wayland-1",
287 "XAUTHORITY=/home/user/auth files/cookie",
288 ],
289 }),
290 }),
291 {
292 PATH: binDir,
293 DISPLAY: ":0",
294 WAYLAND_DISPLAY: "wayland-1",
295 // Raw, not the $'...' quoting `systemctl show-environment` would print.
296 XAUTHORITY: "/home/user/auth files/cookie",
297 },
298 );
299 assert.deepEqual(yield* launchEnv({ stdout: "invalid JSON" }), { PATH: binDir });
300 assert.deepEqual(yield* launchEnv({ stdout: '{"data":[42]}' }), { PATH: binDir });
301 assert.deepEqual(
302 yield* launchEnv({
303 spawnError: PlatformError.systemError({
304 _tag: "NotFound",
305 module: "ChildProcess",
306 method: "spawn",
307 }),
308 }),
309 { PATH: binDir },
310 );
311 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
312);
313​
314it.effect("launches an installed editor with platform-safe arguments", () =>
315 Effect.gen(function* () {
316 const fileSystem = yield* FileSystem.FileSystem;
317 const path = yield* Path.Path;
318 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
319 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
320​
321 let spawned: ChildProcess.StandardCommand | undefined;
322 yield* Effect.gen(function* () {
323 const launcher = yield* ExternalLauncher.ExternalLauncher;
324 yield* launcher.launchEditor({
325 editor: "vscode",
326 cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
327 });
328 }).pipe(
329 Effect.provide(
330 layerTest({
331 platform: "win32",
332 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
333 resolveExecutable: (command) =>
334 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
335 onSpawn: (command) => {
336 spawned = command;
337 },
338 }),
339 ),
340 );
341​
342 assert.ok(spawned);
343 assert.equal(
344 spawned.command,
345 [
346 '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"',
347 '^"--goto^"',
348 '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
349 ].join(" "),
350 );
351 assert.deepEqual(spawned.args, []);
352 assert.equal(spawned.options.shell, true);
353 assert.equal(spawned.options.detached, true);
354 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
355);
356​
357it.live.skipIf(!windowsHost)("opens Windows folders through the default shell handler", () =>
358 Effect.gen(function* () {
359 let spawned: ChildProcess.StandardCommand | undefined;
360 yield* Effect.gen(function* () {
361 const launcher = yield* ExternalLauncher.ExternalLauncher;
362 yield* launcher.launchEditor({
363 editor: "file-manager",
364 cwd: "C:/workspace [draft]/author's ‘left’ ‚low‛ $media/’; Write-Output injected; #",
365 });
366 }).pipe(
367 Effect.provide(
368 layerTest({
369 platform: "win32",
370 env: { PATH: "C:\\Windows", PATHEXT: ".EXE" },
371 onSpawn: (command) => {
372 spawned = command;
373 },
374 }),
375 ),
376 );
377 assert.ok(spawned);
378 assert.equal(spawned.options.detached, false);
379 const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le");
380 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
381 const output = yield* spawner.string(
382 ChildProcess.make(spawned.command, [
383 ...spawned.args.slice(0, -1),
384 Buffer.from(
385 `[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); function Invoke-Item { param($LiteralPath) Write-Output $LiteralPath }; ${source}`,
386 "utf16le",
387 ).toString("base64"),
388 ]),
389 );
390 assert.equal(
391 output.trim(),
392 "C:\\workspace [draft]\\author's ‘left’ ‚low‛ $media\\’; Write-Output injected; #",
393 );
394 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
395);
396​
397for (const [replacement, verb, handler, target, expected] of [
398 ["none", "none", "", "C:/repo/file.txt", 'explorer.exe /select,"C:\\repo\\file.txt"'],
399 ["Directory", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"],
400 ["Folder", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"],
401 [
402 "Folder",
403 "open",
404 '"C:\\Windows\\explorer.exe"',
405 "C:/repo/file.txt",
406 'explorer.exe /select,"C:\\repo\\file.txt"',
407 ],
408 [
409 "Folder",
410 "open",
411 "ExplorerDelegate",
412 "C:/repo/file.txt",
413 'explorer.exe /select,"C:\\repo\\file.txt"',
414 ],
415 [
416 "Drive",
417 "openindopus",
418 "dopusrt.exe",
419 "C:/repo/file.txt",
420 'explorer.exe /select,"C:\\repo\\file.txt"',
421 ],
422 ["Drive", "openindopus", "dopusrt.exe", "C:/file.txt", "shell:C:\\"],
423] as const) {
424 it.live.skipIf(!windowsHost)(
425 `reveals ${target} with ${replacement}/${verb} handled by ${handler}`,
426 () =>
427 Effect.gen(function* () {
428 let spawned: ChildProcess.StandardCommand | undefined;
429 yield* Effect.gen(function* () {
430 const launcher = yield* ExternalLauncher.ExternalLauncher;
431 yield* launcher.launchEditor({
432 editor: "file-manager",
433 cwd: target,
434 reveal: true,
435 });
436 }).pipe(
437 Effect.provide(
438 layerTest({
439 platform: "win32",
440 env: { PATH: "C:\\Windows", PATHEXT: ".EXE" },
441 onSpawn: (command) => {
442 spawned = command;
443 },
444 }),
445 ),
446 );
447 assert.ok(spawned);
448 const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le");
449 const stubs = `function Get-ItemProperty { param($LiteralPath, $ErrorAction) @{ '(default)' = if ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell') { '${verb}' } elseif ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell\\${verb}\\command') { '${handler}' } else { 'none' }; DelegateExecute = if ('${handler}' -eq 'ExplorerDelegate') { '{11dbb47c-a525-400b-9e80-a54615a090c0}' } else { '' } } }; function Invoke-Item { param($LiteralPath) Write-Output "shell:$LiteralPath" }; function Start-Process { param($FilePath, $ArgumentList) Write-Output "$FilePath $ArgumentList" }; `;
450 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
451 const output = yield* spawner.string(
452 ChildProcess.make(spawned.command, [
453 ...spawned.args.slice(0, -1),
454 Buffer.from(stubs + source, "utf16le").toString("base64"),
455 ]),
456 );
457 assert.equal(output.trim(), expected);
458 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
459 );
461​
462it.effect.skipIf(windowsHost)(
463 "reveals a WSL file in Windows File Explorer through its UNC path",
464 () =>
465 Effect.gen(function* () {
466 const fileSystem = yield* FileSystem.FileSystem;
467 const path = yield* Path.Path;
468 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
469 for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) {
470 const filePath = path.join(binDir, name);
471 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
472 yield* fileSystem.chmod(filePath, 0o755);
473 }
474​
475 let spawned: ChildProcess.StandardCommand | undefined;
476 const result = yield* Effect.gen(function* () {
477 const launcher = yield* ExternalLauncher.ExternalLauncher;
478 const kind = yield* launcher.resolveFileManagerRevealKind();
479 const editors = yield* launcher.resolveAvailableEditors();
480 yield* launcher.launchEditor({
481 editor: "file-manager",
482 cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4",
483 reveal: true,
484 });
485 return { kind, editors };
486 }).pipe(
487 Effect.provide(
488 layerTest({
489 platform: "linux",
490 env: {
491 PATH: binDir,
492 WSL_DISTRO_NAME: "Ubuntu-24.04",
493 WSL_INTEROP: "/run/WSL/1_interop",
494 },
495 onSpawn: (command) => {
496 spawned = command;
497 },
498 }),
499 ),
500 );
501​
502 assert.equal(result.kind, "file-explorer");
503 assert.equal(result.editors.includes("file-manager"), true);
504 assert.ok(spawned);
505 assert.equal(spawned.command, "powershell.exe");
506 assert.equal(spawned.options.detached, true);
507 const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? "");
508 const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
509 assert.include(decodedCommand, "'Directory', 'Folder'");
510 assert.include(
511 decodedCommand,
512 "Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media'",
513 );
514 assert.include(
515 decodedCommand,
516 "'\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media\\clip|draft.mp4'",
517 );
518 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
519);
520​
521const STOCK_FOLDER_VERB =
522 "\r\nHKEY_CLASSES_ROOT\\Directory\\shell\r\n (Default) REG_SZ none\r\n\r\n";
523​
524it.effect.each([
525 ["selects the file with Explorer on stock Windows", { stdout: STOCK_FOLDER_VERB }, true],
526 [
527 "keeps the PowerShell reveal for a replacement file manager",
528 { stdout: " (Default) REG_SZ open\r\n" },
529 false,
530 ],
531 ["keeps the PowerShell reveal when the registry lookup fails", { exitCode: 1 }, false],
532] as const)("%s", ([, registry, native]) =>
533 Effect.gen(function* () {
534 const fileSystem = yield* FileSystem.FileSystem;
535 const path = yield* Path.Path;
536 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
537 yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), "");
538 const spawned: ChildProcess.StandardCommand[] = [];
539 const verbatim: Array<readonly [string, ReadonlyArray<string>]> = [];
540 const exit = yield* Effect.gen(function* () {
541 const launcher = yield* ExternalLauncher.ExternalLauncher;
542 return yield* launcher
543 .launchEditor({
544 editor: "file-manager",
545 cwd: "C:/Users/t3/my project/a,b.ts",
546 reveal: true,
547 })
548 .pipe(Effect.exit);
549 }).pipe(
550 Effect.provideService(WindowsVerbatimSpawn, (command, args) =>
551 Effect.sync(() => verbatim.push([command, args])),
552 ),
553 Effect.provide(
554 layerTest({
555 platform: "win32",
556 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" },
557 onSpawn: (command) => spawned.push(command),
558 spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined),
559 }),
560 ),
561 );
562​
563 assert.deepEqual(
564 spawned.map((command) => command.command),
565 ["C:\\Windows\\System32\\reg.exe"],
566 );
567 if (native) {
568 assert.isTrue(Exit.isSuccess(exit));
569 assert.deepEqual(verbatim, [
570 ["C:\\Windows\\explorer.exe", ['/select,"C:\\Users\\t3\\my project\\a,b.ts"']],
571 ]);
572 } else {
573 assert.deepEqual(verbatim, []);
574 // The PowerShell launch is reached; this host has no powershell.exe to run it.
575 assert.isTrue(Exit.isFailure(exit));
576 if (Exit.isFailure(exit)) {
577 const error = Cause.squash(exit.cause);
578 assert.instanceOf(error, ExternalLauncher.ExternalLauncherCommandNotFoundError);
579 assert.equal(
580 (error as ExternalLauncher.ExternalLauncherCommandNotFoundError).command,
581 "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
582 );
583 }
584 }
585 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
586);
587​
588for (const wsl of [false, true]) {
589 it.effect.skipIf(windowsHost)(
590 "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"),
591 () =>
592 Effect.gen(function* () {
593 const fileSystem = yield* FileSystem.FileSystem;
594 const path = yield* Path.Path;
595 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
596 for (const name of ["xdg-open", "xdg-mime", "gdbus", ...(wsl ? ["explorer.exe"] : [])]) {
597 const filePath = path.join(binDir, name);
598 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
599 yield* fileSystem.chmod(filePath, 0o755);
600 }
601 const target = "/workspace/media/a 'quoted' \"clip\" #100% ? é\\name.mp4";
602 const spawnedCommands: ChildProcess.StandardCommand[] = [];
603 yield* Effect.gen(function* () {
604 const launcher = yield* ExternalLauncher.ExternalLauncher;
605 yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true });
606 }).pipe(
607 Effect.provide(
608 layerTest({
609 platform: "linux",
610 env: {
611 PATH: binDir,
612 WAYLAND_DISPLAY: "wayland-1",
613 ...(wsl
614 ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" }
615 : {}),
616 },
617 onSpawn: (command) => spawnedCommands.push(command),
618 spawnResult: (command) =>
619 command.command === "xdg-mime"
620 ? { stdout: "com.thisisgm.flea.desktop\n" }
621 : undefined,
622 }),
623 ),
624 );
625​
626 const reveal = spawnedCommands.find((command) => command.command === "gdbus");
627 assert.ok(reveal);
628 assert.deepEqual(reveal.args, [
629 "call",
630 "--session",
631 "--dest",
632 "org.freedesktop.FileManager1",
633 "--object-path",
634 "/org/freedesktop/FileManager1",
635 "--method",
636 "org.freedesktop.FileManager1.ShowItems",
637 "[\"file:///workspace/media/a%20'quoted'%20%22clip%22%20%23100%25%20%3F%20%C3%A9%5Cname.mp4\"]",
638 "",
639 ]);
640 assert.deepEqual(
641 spawnedCommands.filter((command) => command.command !== "xdg-mime"),
642 [reveal],
643 );
644 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
645 );
647​
648for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12:4"]) {
649 it.effect.skipIf(windowsHost)(
650 `opens ${cwd} with the macOS Zed bundle when another zed is on PATH`,
651 () =>
652 Effect.gen(function* () {
653 const fs = yield* FileSystem.FileSystem;
654 const path = yield* Path.Path;
655 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-collision-" });
656 const executable = path.join(home, "Applications/Zed.app/Contents/MacOS/cli");
657 const binDir = path.join(home, "zfs/bin");
658 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
659 yield* fs.makeDirectory(binDir, { recursive: true });
660 for (const command of [executable, path.join(binDir, "zed")]) {
661 yield* fs.writeFileString(command, "#!/bin/sh\n");
662 yield* fs.chmod(command, 0o755);
663 }
664​
665 let spawned: ChildProcess.StandardCommand | undefined;
666 yield* Effect.gen(function* () {
667 const launcher = yield* ExternalLauncher.ExternalLauncher;
668 assert.include(yield* launcher.resolveAvailableEditors(), "zed");
669 yield* launcher.launchEditor({ editor: "zed", cwd });
670 }).pipe(
671 Effect.provide(
672 layerTest({
673 platform: "darwin",
674 env: { HOME: home, PATH: binDir },
675 onSpawn: (command) => {
676 spawned = command;
677 },
678 }),
679 ),
680 );
681 assert.ok(spawned);
682 assert.equal(spawned.command, executable);
683 assert.deepEqual(spawned.args, [cwd]);
684 assert.equal(spawned.options.shell, false);
685 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
686 );
688​
689for (const { layout, pathNames, fallbackNames, expected } of [
690 { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" },
691 {
692 layout: "mixed locations",
693 pathNames: ["zed"],
694 fallbackNames: ["zeditor"],
695 expected: "fallback",
696 },
697 {
698 layout: "fallback directory",
699 pathNames: [],
700 fallbackNames: ["zed", "zeditor"],
701 expected: "fallback",
702 },
703]) {
704 it.effect.skipIf(windowsHost)(`prefers the Zed editor on Linux with ${layout}`, () =>
705 Effect.gen(function* () {
706 const fs = yield* FileSystem.FileSystem;
707 const path = yield* Path.Path;
708 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-linux-" });
709 const binDir = path.join(home, "bin");
710 const fallbackDir = path.join(home, ".local/bin");
711 for (const [dir, names] of [
712 [binDir, pathNames],
713 [fallbackDir, fallbackNames],
714 ] as const) {
715 yield* fs.makeDirectory(dir, { recursive: true });
716 for (const name of names) {
717 yield* fs.writeFileString(path.join(dir, name), "#!/bin/sh\n");
718 yield* fs.chmod(path.join(dir, name), 0o755);
719 }
720 }
721​
722 let spawned: ChildProcess.StandardCommand | undefined;
723 yield* Effect.gen(function* () {
724 const launcher = yield* ExternalLauncher.ExternalLauncher;
725 assert.include(yield* launcher.resolveAvailableEditors(), "zed");
726 yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" });
727 }).pipe(
728 Effect.provide(
729 layerTest({
730 platform: "linux",
731 env: { HOME: home, PATH: binDir },
732 onSpawn: (command) => {
733 spawned = command;
734 },
735 }),
736 ),
737 );
738 assert.ok(spawned);
739 assert.equal(
740 spawned.command,
741 expected === "fallback" ? path.join(fallbackDir, "zeditor") : expected,
742 );
743 assert.deepEqual(spawned.args, ["/workspace"]);
744 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
745 );
747​
748// Linux editor discovery also probes fixed system directories; tests point them at a temp
749// directory so an editor installed on the host cannot satisfy the lookup.
750const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({
751 ...path,
752 join: (...parts) =>
753 path.join(
754 ...parts.map((part) =>
755 ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part,
756 ),
757 ),
758});
759​
760it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directory", () =>
761 Effect.gen(function* () {
762 const fs = yield* FileSystem.FileSystem;
763 const path = yield* Path.Path;
764 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-fallback-" });
765 const localBin = path.join(home, ".local/bin");
766 const systemBin = path.join(home, "system-bin");
767 for (const [dir, name] of [
768 [localBin, "zed"],
769 [systemBin, "zeditor"],
770 ] as const) {
771 yield* fs.makeDirectory(dir, { recursive: true });
772 const executable = path.join(dir, name);
773 yield* fs.writeFileString(executable, "#!/bin/sh\necho 'Zed 0.200.0'\n");
774 yield* fs.chmod(executable, 0o755);
775 }
776 const editor = EDITORS.find((editor) => editor.id === "zed")!;
777 const resolve = resolveEditorCommand(editor, { HOME: home, PATH: "" }).pipe(
778 Effect.provideService(HostProcess.Platform, "linux"),
779 Effect.provideService(Path.Path, withSystemBin(path, systemBin)),
780 );
781 assert.deepEqual(
782 yield* resolve,
783 Option.some({ command: path.join(systemBin, "zeditor"), baseArgs: [] }),
784 );
785 yield* fs.remove(path.join(systemBin, "zeditor"));
786 assert.deepEqual(
787 yield* resolve,
788 Option.some({ command: path.join(localBin, "zed"), baseArgs: [] }),
789 );
790 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
791);
792​
793it.effect.skipIf(windowsHost)("does not offer the OpenZFS zed daemon as Zed on Linux", () =>
794 Effect.gen(function* () {
795 const fs = yield* FileSystem.FileSystem;
796 const path = yield* Path.Path;
797 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-" });
798 const binDir = path.join(home, "bin");
799 const systemBin = path.join(home, "system-bin");
800 yield* fs.makeDirectory(binDir, { recursive: true });
801 yield* fs.makeDirectory(systemBin, { recursive: true });
802 const zfsZed = path.join(binDir, "zed");
803 // OpenZFS zed only takes short options: `--version` is rejected with usage on stderr.
804 yield* fs.writeFileString(
805 zfsZed,
806 "#!/bin/sh\necho \"Invalid option '--'\" >&2\necho 'Usage: zed [OPTION]...' >&2\nexit 1\n",
807 );
808 yield* fs.chmod(zfsZed, 0o755);
809 const editor = EDITORS.find((editor) => editor.id === "zed")!;
810 const laterBin = path.join(home, "later-bin");
811 const resolveOn = (platform: NodeJS.Platform) =>
812 resolveEditorCommand(editor, { HOME: home, PATH: `${binDir}:${laterBin}` }).pipe(
813 Effect.provideService(HostProcess.Platform, platform),
814 Effect.provideService(Path.Path, withSystemBin(path, systemBin)),
815 );
816 assert.deepEqual(yield* resolveOn("linux"), Option.none());
817 assert.deepEqual(yield* resolveOn("darwin"), Option.none());
818​
819 const zedEditor = path.join(home, ".local/bin/zed");
820 yield* fs.makeDirectory(path.dirname(zedEditor), { recursive: true });
821 yield* fs.writeFileString(zedEditor, "#!/bin/sh\necho 'Zed 0.200.0'\n");
822 yield* fs.chmod(zedEditor, 0o755);
823 assert.deepEqual(yield* resolveOn("linux"), Option.some({ command: zedEditor, baseArgs: [] }));
824​
825 yield* fs.remove(zedEditor);
826 const laterZed = path.join(laterBin, "zed");
827 yield* fs.makeDirectory(laterBin, { recursive: true });
828 yield* fs.writeFileString(laterZed, "#!/bin/sh\necho 'Zed 0.200.0'\n");
829 yield* fs.chmod(laterZed, 0o755);
830 for (const platform of ["linux", "darwin"] as const) {
831 assert.deepEqual(
832 yield* resolveOn(platform),
833 Option.some({ command: laterZed, baseArgs: [] }),
834 );
835 }
836 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
837);
838​
839it.effect.skipIf(windowsHost)("does not open Zed with the OpenZFS zed daemon on Linux", () =>
840 Effect.gen(function* () {
841 const fs = yield* FileSystem.FileSystem;
842 const path = yield* Path.Path;
843 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-launch-" });
844 const binDir = path.join(home, "bin");
845 const systemBin = path.join(home, "system-bin");
846 yield* fs.makeDirectory(binDir, { recursive: true });
847 yield* fs.writeFileString(path.join(binDir, "zed"), "#!/bin/sh\nexit 1\n");
848 yield* fs.chmod(path.join(binDir, "zed"), 0o755);
849​
850 const spawned: ChildProcess.StandardCommand[] = [];
851 const exit = yield* Effect.gen(function* () {
852 const launcher = yield* ExternalLauncher.ExternalLauncher;
853 return yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" }).pipe(Effect.exit);
854 }).pipe(
855 Effect.provide(
856 layerTest({
857 platform: "linux",
858 env: { HOME: home, PATH: binDir },
859 path: withSystemBin(path, systemBin),
860 onSpawn: (command) => spawned.push(command),
861 spawnResult: (command) => (command.args[0] === "--version" ? { exitCode: 1 } : undefined),
862 }),
863 ),
864 );
865 assert.isTrue(Exit.isFailure(exit));
866 if (Exit.isFailure(exit)) {
867 assert.instanceOf(
868 Cause.squash(exit.cause),
869 ExternalLauncher.ExternalLauncherCommandNotFoundError,
870 );
871 }
872 assert.deepEqual(
873 spawned.map((command) => command.args),
874 [["--version"]],
875 );
876 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
877);
878​
879it.effect.each([
880 { editor: "webstorm", installPath: "Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm" },
881 { editor: "idea", installPath: "Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea" },
882] as const)(
883 "discovers and launches $editor from a versioned macOS bundle",
884 ({ editor, installPath }) =>
885 Effect.gen(function* () {
886 const fs = yield* FileSystem.FileSystem;
887 const path = yield* Path.Path;
888 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-versioned-" });
889 const executable = path.join(home, installPath);
890 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
891 yield* fs.writeFileString(executable, "#!/bin/sh\n");
892 yield* fs.chmod(executable, 0o755);
893​
894 let spawned: ChildProcess.StandardCommand | undefined;
895 yield* Effect.gen(function* () {
896 const launcher = yield* ExternalLauncher.ExternalLauncher;
897 assert.include(yield* launcher.resolveAvailableEditors(), editor);
898 yield* launcher.launchEditor({
899 editor,
900 cwd: "/workspace with spaces/file.ts:12:4",
901 projectRoot: "/workspace with spaces",
902 });
903 }).pipe(
904 Effect.provide(
905 layerTest({
906 platform: "darwin",
907 env: { HOME: home, PATH: path.join(home, "empty") },
908 onSpawn: (command) => {
909 spawned = command;
910 },
911 }),
912 ),
913 );
914​
915 assert.ok(spawned);
916 assert.equal(spawned.command, executable);
917 assert.deepEqual(spawned.args, [
918 "/workspace with spaces",
919 "--line",
920 "12",
921 "--column",
922 "3",
923 "/workspace with spaces/file.ts",
924 ]);
925 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
926);
927​
928it.effect("matches macOS bundles on the name boundary only", () =>
929 Effect.gen(function* () {
930 const fs = yield* FileSystem.FileSystem;
931 const path = yield* Path.Path;
932 const unrelatedHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-unrelated-" });
933 const unrelated = path.join(
934 unrelatedHome,
935 "Applications/WebStormHelper.app/Contents/MacOS/webstorm",
936 );
937 yield* fs.makeDirectory(path.dirname(unrelated), { recursive: true });
938 yield* fs.writeFileString(unrelated, "#!/bin/sh\n");
939 yield* fs.chmod(unrelated, 0o755);
940​
941 const editorsFor = (home: string) =>
942 Effect.gen(function* () {
943 const launcher = yield* ExternalLauncher.ExternalLauncher;
944 return yield* launcher.resolveAvailableEditors();
945 }).pipe(
946 Effect.provide(
947 layerTest({ platform: "darwin", env: { HOME: home, PATH: path.join(home, "bin") } }),
948 ),
949 );
950​
951 assert.notInclude(yield* editorsFor(unrelatedHome), "webstorm");
952​
953 const exactHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-exact-" });
954 const exact = path.join(exactHome, "Applications/WebStorm.app/Contents/MacOS/webstorm");
955 yield* fs.makeDirectory(path.dirname(exact), { recursive: true });
956 yield* fs.writeFileString(exact, "#!/bin/sh\n");
957 yield* fs.chmod(exact, 0o755);
958​
959 assert.include(yield* editorsFor(exactHome), "webstorm");
960 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
961);
962​
963it.effect("keeps the macOS VS Code Insiders bundle out of stable VS Code", () =>
964 Effect.gen(function* () {
965 const fs = yield* FileSystem.FileSystem;
966 const path = yield* Path.Path;
967 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-insiders-" });
968 // The real Insiders bundle ships both `code-insiders` and `code`.
969 const bin = path.join(
970 home,
971 "Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin",
972 );
973 yield* fs.makeDirectory(bin, { recursive: true });
974 for (const name of ["code", "code-insiders"]) {
975 yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
976 yield* fs.chmod(path.join(bin, name), 0o755);
977 }
978​
979 let spawned: ChildProcess.StandardCommand | undefined;
980 const editors = yield* Effect.gen(function* () {
981 const launcher = yield* ExternalLauncher.ExternalLauncher;
982 const available = yield* launcher.resolveAvailableEditors();
983 yield* launcher.launchEditor({ editor: "vscode-insiders", cwd: "/workspace/file.ts" });
984 return available;
985 }).pipe(
986 Effect.provide(
987 layerTest({
988 platform: "darwin",
989 env: { HOME: home, PATH: path.join(home, "empty") },
990 onSpawn: (command) => {
991 spawned = command;
992 },
993 }),
994 ),
995 );
996​
997 assert.notInclude(editors, "vscode");
998 assert.include(editors, "vscode-insiders");
999 assert.equal(spawned?.command, path.join(bin, "code-insiders"));
1000 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1002​
1003it.effect.each([
1005 platform: "darwin",
1006 scripts: "Library/Application Support/JetBrains/Toolbox/scripts",
1007 suffix: "",
1008 },
1009 { platform: "linux", scripts: ".local/share/JetBrains/Toolbox/scripts", suffix: "" },
1010 { platform: "win32", scripts: "JetBrains/Toolbox/scripts", suffix: ".cmd" },
1012 platform: "win32",
1013 scripts: "JetBrains/Toolbox/scripts",
1014 suffix: ".cmd",
1015 install: "Programs/IntelliJ IDEA/bin/idea64.exe",
1016 },
1017] as const)(
1018 "discovers a numbered JetBrains Toolbox script on $platform",
1019 ({ platform, scripts, suffix, ...row }) =>
1020 Effect.gen(function* () {
1021 const fs = yield* FileSystem.FileSystem;
1022 const path = yield* Path.Path;
1023 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-toolbox-numbered-" });
1024 const dir = path.join(home, scripts);
1025 yield* fs.makeDirectory(dir, { recursive: true });
1026 for (const name of ["idea10", "idea2"]) {
1027 yield* fs.writeFileString(path.join(dir, `${name}${suffix}`), "#!/bin/sh\n");
1028 yield* fs.chmod(path.join(dir, `${name}${suffix}`), 0o755);
1030 const install = "install" in row ? path.join(home, row.install) : undefined;
1031 if (install) {
1032 yield* fs.makeDirectory(path.dirname(install), { recursive: true });
1033 yield* fs.writeFileString(install, "");
1035​
1036 const editor = EDITORS.find((editor) => editor.id === "idea")!;
1037 const resolved = yield* resolveEditorCommand(editor, {
1038 HOME: home,
1039 LOCALAPPDATA: home,
1040 PATH: path.join(home, "empty"),
1041 PATHEXT: ".COM;.EXE;.BAT;.CMD",
1042 }).pipe(
1043 Effect.provideService(HostProcess.Platform, platform),
1044 // Keep IDEs installed on the host out of system locations such as /Applications.
1045 Effect.provideService(FileSystem.FileSystem, {
1046 ...fs,
1047 stat: (file) =>
1048 fs.stat(file.startsWith(`${home}${path.sep}`) ? file : path.join(home, "missing")),
1049 }),
1050 );
1051​
1052 assert.deepEqual(
1053 resolved,
1054 Option.some({ command: install ?? path.join(dir, `idea2${suffix}`), baseArgs: [] }),
1055 );
1056 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1058​
1059for (const { platform, installPath, onPath } of [
1060 { platform: "darwin", installPath: ".local/bin/agy", onPath: true },
1061 { platform: "linux", installPath: ".local/bin/agy", onPath: false },
1062 { platform: "win32", installPath: "agy/bin/agy.cmd", onPath: true },
1063] as const) {
1064 it.effect.skipIf(windowsHost && platform !== "win32")(
1065 `does not report the agy CLI as the Antigravity IDE on ${platform}`,
1066 () =>
1067 Effect.gen(function* () {
1068 const fs = yield* FileSystem.FileSystem;
1069 const path = yield* Path.Path;
1070 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cli-" });
1071 const executable = path.join(home, installPath);
1072 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
1073 yield* fs.writeFileString(executable, "#!/bin/sh\n");
1074 yield* fs.chmod(executable, 0o755);
1075 const editors = yield* Effect.gen(function* () {
1076 const launcher = yield* ExternalLauncher.ExternalLauncher;
1077 return yield* launcher.resolveAvailableEditors();
1078 }).pipe(
1079 Effect.provide(
1080 layerTest({
1081 platform,
1082 env: {
1083 HOME: home,
1084 LOCALAPPDATA: home,
1085 PATH: onPath ? path.dirname(executable) : path.join(home, "empty"),
1086 PATHEXT: ".COM;.EXE;.BAT;.CMD",
1087 },
1088 }),
1089 ),
1090 );
1091 assert.notInclude(editors, "antigravity");
1092 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1093 );
1095​
1096it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launchers first", () =>
1097 Effect.gen(function* () {
1098 const fs = yield* FileSystem.FileSystem;
1099 const path = yield* Path.Path;
1100 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-priority-" });
1101 const executable = path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/code");
1102 const env = { HOME: home, PATH: path.join(home, "bin") };
1103 const discover = Effect.gen(function* () {
1104 const launcher = yield* ExternalLauncher.ExternalLauncher;
1105 return yield* launcher.resolveAvailableEditors();
1106 });
1107 const before = yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env })));
1108 yield* fs.makeDirectory(executable, { recursive: true });
1109 assert.deepEqual(
1110 yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
1111 before,
1112 );
1113 yield* fs.remove(executable, { recursive: true });
1114 yield* fs.writeFileString(executable, "#!/bin/sh\n");
1115 yield* fs.chmod(executable, 0o644);
1116 assert.deepEqual(
1117 yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
1118 before,
1119 );
1120 yield* fs.chmod(executable, 0o755);
1121 yield* fs.makeDirectory(env.PATH);
1122 yield* fs.writeFileString(path.join(env.PATH, "cursor"), "#!/bin/sh\n");
1123 yield* fs.chmod(path.join(env.PATH, "cursor"), 0o755);
1124 let spawned: ChildProcess.StandardCommand | undefined;
1125 yield* Effect.gen(function* () {
1126 const launcher = yield* ExternalLauncher.ExternalLauncher;
1127 yield* launcher.launchEditor({ editor: "cursor", cwd: "/workspace" });
1128 }).pipe(
1129 Effect.provide(
1130 layerTest({
1131 platform: "darwin",
1132 env: { ...env, PATH: `${env.PATH}:/usr/bin` },
1133 onSpawn: (command) => {
1134 spawned = command;
1135 },
1136 }),
1137 ),
1138 );
1139 assert.equal(spawned?.command, "cursor");
1140 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1142​
1143it.effect(
1144 "memoizes editor discovery and refreshes in the background after the cache window",
1145 () => {
1146 let statCalls = 0;
1147 const rescanned = Deferred.makeUnsafe<void>();
1148 let initialScanDone = false;
1149 const fileInfo = { type: "File" } as FileSystem.File.Info;
1150 const layerLauncher = ExternalLauncher.layer.pipe(
1151 Layer.provide(
1152 Layer.mergeAll(
1153 FileSystem.layerNoop({
1154 stat: () =>
1155 Effect.sync(() => {
1156 statCalls += 1;
1157 return fileInfo;
1158 }).pipe(
1159 Effect.tap(() =>
1160 initialScanDone ? Deferred.succeed(rescanned, undefined) : Effect.void,
1161 ),
1162 ),
1163 }),
1164 Path.layer,
1165 Layer.succeed(
1166 ChildProcessSpawner.ChildProcessSpawner,
1167 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
1168 ),
1169 ),
1170 ),
1171 );
1172​
1173 return Effect.gen(function* () {
1174 const launcher = yield* ExternalLauncher.ExternalLauncher;
1175​
1176 const first = yield* launcher.resolveAvailableEditors();
1177 assert.equal(first.includes("vscode"), true);
1178 const statCallsAfterFirstScan = statCalls;
1179 initialScanDone = true;
1180 assert.isAbove(statCallsAfterFirstScan, 0);
1181​
1182 // Past the shared command-resolution cache TTL (30s) but within the
1183 // discovery cache window: the memoized set is reused without any scan.
1184 yield* TestClock.adjust("31 seconds");
1185 const second = yield* launcher.resolveAvailableEditors();
1186 assert.deepEqual([...second], [...first]);
1187 assert.equal(statCalls, statCallsAfterFirstScan);
1188​
1189 // Past the discovery cache window the next call still answers from the
1190 // memoized set and rescans in the background.
1191 yield* TestClock.adjust("30 seconds");
1192 const third = yield* launcher.resolveAvailableEditors();
1193 assert.deepEqual([...third], [...first]);
1194 yield* Deferred.await(rescanned);
1195 assert.isAbove(statCalls, statCallsAfterFirstScan);
1196 }).pipe(
1197 Effect.provide(
1198 Layer.mergeAll(
1199 layerLauncher,
1200 Layer.succeed(HostProcess.Platform, "win32"),
1201 ConfigProvider.layer(
1202 ConfigProvider.fromEnv({
1203 env: {
1204 PATH: "C:\\t3-editor-discovery-cache-test",
1205 PATHEXT: ".COM;.EXE;.BAT;.CMD",
1206 },
1207 }),
1208 ),
1209 TestClock.layer(),
1210 ),
1211 ),
1212 );
1213 },
1215​
1216it.effect.each(["Zed Nightly", "Zed Preview"])(
1217 "launches stable Zed on Windows when %s comes first on PATH",
1218 (channel) =>
1219 Effect.gen(function* () {
1220 const fs = yield* FileSystem.FileSystem;
1221 const path = yield* Path.Path;
1222 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-channels-" });
1223 // A user folder naming Zed and a channel does not mark either install.
1224 const programs = path.join(root, "Users", "zedpreview", "Programs");
1225 const prereleaseBin = path.join(programs, channel, "bin");
1226 const stableBin = path.join(programs, "Zed", "bin");
1227 for (const dir of [prereleaseBin, stableBin]) {
1228 yield* fs.makeDirectory(dir, { recursive: true });
1229 yield* fs.writeFileString(path.join(dir, "zed.EXE"), "");
1231 const env = { PATH: `${prereleaseBin};${stableBin}`, PATHEXT: ".COM;.EXE;.BAT;.CMD" };
1232​
1233 const launchZed = Effect.gen(function* () {
1234 let spawned: ChildProcess.StandardCommand | undefined;
1235 yield* Effect.gen(function* () {
1236 const launcher = yield* ExternalLauncher.ExternalLauncher;
1237 yield* launcher.launchEditor({ editor: "zed", cwd: "C:\\workspace" });
1238 }).pipe(
1239 Effect.provide(
1240 layerTest({
1241 platform: "win32",
1242 env,
1243 onSpawn: (command) => {
1244 spawned = command;
1245 },
1246 }),
1247 ),
1248 );
1249 assert.ok(spawned);
1250 return spawned;
1251 });
1252​
1253 const stable = yield* launchZed;
1254 assert.equal(stable.command, path.join(stableBin, "zed.EXE"));
1255 assert.deepEqual(stable.args, ["C:\\workspace"]);
1256​
1257 env.PATH = `${stableBin};${prereleaseBin}`;
1258 assert.equal((yield* launchZed).command, "zed");
1259​
1260 env.PATH = `${prereleaseBin};${stableBin}`;
1261 // With only the prerelease install left, it still opens by name.
1262 yield* fs.remove(path.join(stableBin, "zed.EXE"));
1263 assert.equal((yield* launchZed).command, "zed");
1264 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1266​
1267const launchWindowsShimEditor = (cwd: string) =>
1268 Effect.gen(function* () {
1269 const fileSystem = yield* FileSystem.FileSystem;
1270 const path = yield* Path.Path;
1271 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
1272 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
1273 let spawned: ChildProcess.StandardCommand | undefined;
1274 const exit = yield* Effect.gen(function* () {
1275 const launcher = yield* ExternalLauncher.ExternalLauncher;
1276 return yield* launcher.launchEditor({ editor: "vscode", cwd }).pipe(Effect.exit);
1277 }).pipe(
1278 Effect.provide(
1279 layerTest({
1280 platform: "win32",
1281 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
1282 resolveExecutable: (command) =>
1283 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
1284 onSpawn: (command) => {
1285 spawned = command;
1286 },
1287 }),
1288 ),
1289 );
1290 return { exit, spawned };
1291 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
1292​
1293it.effect.each([
1294 ["CRLF", "C:\\workspace\\file.ts\r\ncalc.exe"],
1295 ["LF", "C:\\workspace\\file.ts\ncalc.exe"],
1296 ["double quote", 'C:\\workspace\\file.ts" & calc.exe & "'],
1297] as const)("does not start a Windows command shim for a path with a $0", ([, cwd]) =>
1298 Effect.gen(function* () {
1299 const { exit, spawned } = yield* launchWindowsShimEditor(cwd);
1300 assert.equal(spawned, undefined);
1301 assert.isTrue(Exit.isFailure(exit));
1302 if (Exit.isFailure(exit)) {
1303 assert.instanceOf(
1304 Cause.squash(exit.cause),
1305 ExternalLauncher.ExternalLauncherUnsupportedTargetError,
1306 );
1308 }),
1310​
1311it.effect("starts a Windows command shim for unicode paths with cmd metacharacters", () =>
1312 Effect.gen(function* () {
1313 const { exit, spawned } = yield* launchWindowsShimEditor(
1314 "C:\\Users\\jö\\R&D (100%)\\naïve ^file!.ts:3:7",
1315 );
1316 assert.isTrue(Exit.isSuccess(exit));
1317 assert.ok(spawned);
1318 assert.equal(spawned.options.shell, true);
1319 assert.deepEqual(spawned.args, []);
1320 assert.isTrue(
1321 spawned.command.endsWith(
1322 ' ^"--goto^" ^"C:\\Users\\jö\\R^&D^ ^(100^%^)\\naïve^ ^^file^!.ts:3:7^"',
1323 ),
1324 );
1325 }),