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

externalLauncher.test.ts

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