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

externalLauncher.test.ts

970 lines36.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - the Windows reveal smoke test drives a real PowerShell through Node process and filesystem APIs.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, it } from "@effect/vitest";
8import * as ConfigProvider from "effect/ConfigProvider";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
18​
19import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
20import { SpawnExecutableResolution } from "@t3tools/shared/shell";
21import * as ExternalLauncher from "./externalLauncher.ts";
22​
23// Tests below write `#!/bin/sh` stubs into a real temp dir and hand that
24// directory to a posix-mocked resolver as PATH. On a Windows host the temp
25// path carries a drive letter, so the posix `:` split shatters it; there is
26// no posix executable to find there anyway.
27const windowsHost = HostProcessPlatform.defaultValue() === "win32";
28​
29interface MockSpawnResult {
30 readonly exitCode?: number;
31 readonly stdout?: string;
32 /** Never deliver an exit code, like a child wedged on a broken desktop session. */
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 testLayer = (input: {
61 readonly platform: NodeJS.Platform;
62 readonly env?: Record<string, string>;
63 readonly resolveExecutable?: (command: string) => string | undefined;
64 readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
65 readonly onUnref?: () => void;
66 readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined;
67}) => {
68 const spawnerLayer = Layer.succeed(
69 ChildProcessSpawner.ChildProcessSpawner,
70 ChildProcessSpawner.make((command) =>
71 Effect.sync(() => {
72 assert.equal(ChildProcess.isStandardCommand(command), true);
73 if (!ChildProcess.isStandardCommand(command)) {
74 throw new Error("Expected a standard command");
75 }
76 input.onSpawn?.(command);
77 return makeMockDetachedHandle({
78 ...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }),
79 ...input.spawnResult?.(command),
80 });
81 }),
82 ),
83 );
84​
85 return Layer.mergeAll(
86 ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, spawnerLayer))),
87 Layer.succeed(HostProcessPlatform, input.platform),
88 Layer.succeed(
89 SpawnExecutableResolution,
90 (command) => input.resolveExecutable?.(command) ?? command,
91 ),
92 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
93 );
94};
95​
96it.effect("launches the default browser through the platform command", () => {
97 let spawned: ChildProcess.StandardCommand | undefined;
98 let didUnref = false;
99 return Effect.gen(function* () {
100 const launcher = yield* ExternalLauncher.ExternalLauncher;
101​
102 yield* launcher.launchBrowser("https://example.com/some path");
103​
104 assert.ok(spawned);
105 assert.equal(spawned.command, "xdg-open");
106 assert.deepEqual(spawned.args, ["https://example.com/some path"]);
107 assert.equal(spawned.options.detached, true);
108 assert.equal(didUnref, true);
109 }).pipe(
110 Effect.provide(
111 testLayer({
112 platform: "linux",
113 onSpawn: (command) => {
114 spawned = command;
115 },
116 onUnref: () => {
117 didUnref = true;
118 },
119 }),
120 ),
121 );
122});
123​
124it.effect("launches an installed editor with platform-safe arguments", () =>
125 Effect.gen(function* () {
126 const fileSystem = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
129 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
130​
131 let spawned: ChildProcess.StandardCommand | undefined;
132 yield* Effect.gen(function* () {
133 const launcher = yield* ExternalLauncher.ExternalLauncher;
134 yield* launcher.launchEditor({
135 editor: "vscode",
136 cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
137 });
138 }).pipe(
139 Effect.provide(
140 testLayer({
141 platform: "win32",
142 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
143 resolveExecutable: (command) =>
144 command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
145 onSpawn: (command) => {
146 spawned = command;
147 },
148 }),
149 ),
150 );
151​
152 assert.ok(spawned);
153 assert.equal(spawned.command, '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"');
154 assert.deepEqual(spawned.args, [
155 '^"--goto^"',
156 '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
157 ]);
158 assert.equal(spawned.options.shell, true);
159 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
160);
161​
162it.effect.skipIf(windowsHost)("reveals a file in Finder with open -R on macOS", () =>
163 Effect.gen(function* () {
164 const fileSystem = yield* FileSystem.FileSystem;
165 const path = yield* Path.Path;
166 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
167 const openPath = path.join(binDir, "open");
168 yield* fileSystem.writeFileString(openPath, "#!/bin/sh\n");
169 yield* fileSystem.chmod(openPath, 0o755);
170​
171 let spawned: ChildProcess.StandardCommand | undefined;
172 yield* Effect.gen(function* () {
173 const launcher = yield* ExternalLauncher.ExternalLauncher;
174 yield* launcher.launchEditor({
175 editor: "file-manager",
176 cwd: "/workspace/media/linux-mini-v2.mp4",
177 reveal: true,
178 });
179 }).pipe(
180 Effect.provide(
181 testLayer({
182 platform: "darwin",
183 env: { PATH: binDir },
184 onSpawn: (command) => {
185 spawned = command;
186 },
187 }),
188 ),
189 );
190​
191 assert.ok(spawned);
192 assert.equal(spawned.command, "open");
193 assert.deepEqual(spawned.args, ["-R", "/workspace/media/linux-mini-v2.mp4"]);
194 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
195);
196​
197it.effect("reveals a file in File Explorer through PowerShell on Windows", () =>
198 Effect.gen(function* () {
199 const fileSystem = yield* FileSystem.FileSystem;
200 const path = yield* Path.Path;
201 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
202 yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
203 // resolvePowerShellPath builds `${SYSTEMROOT}\System32\...` with Windows
204 // separators, which on the posix test filesystem is one file name.
205 const systemRoot = path.join(binDir, "system-root");
206 const powerShellPath = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
207 yield* fileSystem.makeDirectory(path.dirname(powerShellPath), { recursive: true });
208 yield* fileSystem.writeFileString(powerShellPath, "");
209​
210 let spawned: ChildProcess.StandardCommand | undefined;
211 const kind = yield* Effect.gen(function* () {
212 const launcher = yield* ExternalLauncher.ExternalLauncher;
213 yield* launcher.launchEditor({
214 editor: "file-manager",
215 // Web file links normalize separators even when the server runs on
216 // Windows. Explorer's `/select` switch requires Windows separators.
217 cwd: "C:/workspace with spaces/media/author's clip.mp4",
218 reveal: true,
219 });
220 return yield* launcher.resolveFileManagerRevealKind();
221 }).pipe(
222 Effect.provide(
223 testLayer({
224 platform: "win32",
225 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: systemRoot },
226 onSpawn: (command) => {
227 spawned = command;
228 },
229 }),
230 ),
231 );
232​
233 assert.equal(kind, "file-explorer");
234 assert.ok(spawned);
235 assert.equal(spawned.command, powerShellPath);
236 assert.deepEqual(spawned.args.slice(0, -1), [
237 "-NoProfile",
238 "-NonInteractive",
239 "-ExecutionPolicy",
240 "Bypass",
241 "-EncodedCommand",
242 ]);
243 const encodedCommand = spawned.args[spawned.args.length - 1] ?? "";
244 const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
245 // explorer.exe expects `/select,"<path>"` with only the path quoted;
246 // PowerShell 5.1's Start-Process passes the argument string verbatim.
247 assert.equal(
248 decodedCommand,
249 "$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + 'C:\\workspace with spaces\\media\\author''s clip.mp4' + '\"')",
250 );
251 assert.equal(spawned.options.shell, false);
252 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
253);
254​
255// Real-chain smoke check for the Explorer selection contract: runs the exact
256// PowerShell source the reveal launch encodes, against a stub that records
257// the raw argument tail it receives, and asserts a spaced path arrives as the
258// single `/select,"<path>"` switch. Mock argv assertions cannot prove this —
259// only Windows' own PowerShell -> CreateProcess quoting chain can, so the
260// test runs only where that chain exists.
261// oxlint-disable-next-line t3code/no-global-process-runtime -- the skip decision needs the real host platform, outside any Effect runtime.
262it.skipIf(process.platform !== "win32")(
263 "delivers the raw /select switch for spaced paths through real PowerShell",
264 { timeout: 60_000 },
265 async () => {
266 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-reveal-smoke-"));
267 try {
268 const recorderPath = NodePath.join(tempDir, "recorder.cmd");
269 const outputPath = NodePath.join(tempDir, "argv.txt");
270 NodeFS.writeFileSync(recorderPath, `@echo off\r\n>"${outputPath}" echo(%*\r\n`);
271​
272 const target = "C:/workspace with spaces/media/author's clip.mp4";
273 const explorerTarget = target.replaceAll("/", "\\");
274 const source = ExternalLauncher.buildFileExplorerRevealPowerShellSource(
275 recorderPath,
276 explorerTarget,
277 );
278 const powerShellPath = `${process.env.SYSTEMROOT ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
279 NodeChildProcess.execFileSync(
280 powerShellPath,
281 [
282 "-NoProfile",
283 "-NonInteractive",
284 "-ExecutionPolicy",
285 "Bypass",
286 "-EncodedCommand",
287 Buffer.from(source, "utf16le").toString("base64"),
288 ],
289 { timeout: 30_000 },
290 );
291​
292 // Start-Process returns before the recorder runs; wait for its output.
293 // The waits run outside the Effect runtime on purpose: the test
294 // exercises the real Windows process chain in real time.
295 // @effect-diagnostics-next-line globalTimers:off
296 const sleep = (millis: number) => new Promise((resolve) => setTimeout(resolve, millis));
297 // @effect-diagnostics-next-line globalDate:off
298 const deadline = Date.now() + 20_000;
299 // @effect-diagnostics-next-line globalDate:off
300 while (!NodeFS.existsSync(outputPath) && Date.now() < deadline) {
301 await sleep(100);
302 }
303 await sleep(200);
304 const recorded = NodeFS.readFileSync(outputPath, "utf8").trim();
305 assert.equal(recorded, `/select,"${explorerTarget}"`);
306 } finally {
307 NodeFS.rmSync(tempDir, { recursive: true, force: true });
308 }
309 },
310);
311​
312it.effect("does not advertise reveal on Windows when PowerShell is missing", () =>
313 Effect.gen(function* () {
314 const fileSystem = yield* FileSystem.FileSystem;
315 const path = yield* Path.Path;
316 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
317 yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
318​
319 const result = yield* Effect.gen(function* () {
320 const launcher = yield* ExternalLauncher.ExternalLauncher;
321 return {
322 kind: yield* launcher.resolveFileManagerRevealKind(),
323 editors: yield* launcher.resolveAvailableEditors(),
324 };
325 }).pipe(
326 Effect.provide(
327 testLayer({
328 platform: "win32",
329 env: {
330 PATH: binDir,
331 PATHEXT: ".COM;.EXE;.BAT;.CMD",
332 SYSTEMROOT: path.join(binDir, "missing-system-root"),
333 },
334 }),
335 ),
336 );
337​
338 // Plain "open in file manager" still works through explorer; only the
339 // reveal capability, which launches PowerShell, must stay hidden.
340 assert.equal(result.editors.includes("file-manager"), true);
341 assert.isUndefined(result.kind);
342 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
343);
344​
345it.effect.skipIf(windowsHost)(
346 "reveals a WSL file in Windows File Explorer through its UNC path",
347 () =>
348 Effect.gen(function* () {
349 const fileSystem = yield* FileSystem.FileSystem;
350 const path = yield* Path.Path;
351 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
352 for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) {
353 const filePath = path.join(binDir, name);
354 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
355 yield* fileSystem.chmod(filePath, 0o755);
356 }
357​
358 let spawned: ChildProcess.StandardCommand | undefined;
359 const result = yield* Effect.gen(function* () {
360 const launcher = yield* ExternalLauncher.ExternalLauncher;
361 const kind = yield* launcher.resolveFileManagerRevealKind();
362 const editors = yield* launcher.resolveAvailableEditors();
363 yield* launcher.launchEditor({
364 editor: "file-manager",
365 cwd: "/home/t3/workspace/media/clip.mp4",
366 reveal: true,
367 });
368 return { kind, editors };
369 }).pipe(
370 Effect.provide(
371 testLayer({
372 platform: "linux",
373 env: {
374 PATH: binDir,
375 WSL_DISTRO_NAME: "Ubuntu-24.04",
376 WSL_INTEROP: "/run/WSL/1_interop",
377 },
378 onSpawn: (command) => {
379 spawned = command;
380 },
381 }),
382 ),
383 );
384​
385 assert.equal(result.kind, "file-explorer");
386 assert.equal(result.editors.includes("file-manager"), true);
387 assert.ok(spawned);
388 // The reveal routes through interop PowerShell so Explorer receives its
389 // raw `/select,"<path>"` switch even for spaced paths.
390 assert.equal(spawned.command, "powershell.exe");
391 const encodedCommand = spawned.args[spawned.args.length - 1] ?? "";
392 const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
393 assert.equal(
394 decodedCommand,
395 "$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace\\media\\clip.mp4' + '\"')",
396 );
397 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
398);
399​
400it.effect.skipIf(windowsHost)(
401 "does not advertise reveal from WSL when interop PowerShell is missing",
402 () =>
403 Effect.gen(function* () {
404 const fileSystem = yield* FileSystem.FileSystem;
405 const path = yield* Path.Path;
406 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
407 const explorerPath = path.join(binDir, "explorer.exe");
408 yield* fileSystem.writeFileString(explorerPath, "");
409 yield* fileSystem.chmod(explorerPath, 0o755);
410​
411 const result = yield* Effect.gen(function* () {
412 const launcher = yield* ExternalLauncher.ExternalLauncher;
413 return {
414 kind: yield* launcher.resolveFileManagerRevealKind(),
415 editors: yield* launcher.resolveAvailableEditors(),
416 };
417 }).pipe(
418 Effect.provide(
419 testLayer({
420 platform: "linux",
421 env: {
422 PATH: binDir,
423 WSL_DISTRO_NAME: "Ubuntu-24.04",
424 WSL_INTEROP: "/run/WSL/1_interop",
425 },
426 }),
427 ),
428 );
429​
430 assert.equal(result.editors.includes("file-manager"), true);
431 assert.isUndefined(result.kind);
432 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
433);
434​
435// When interop PowerShell is missing the capability advertises the Linux
436// "files" kind (or nothing), so the reveal must open the Linux file manager
437// the label promised even though plain open still prefers File Explorer.
438it.effect.skipIf(windowsHost)(
439 "reveals through the Linux file manager when WSL lacks interop PowerShell",
440 () =>
441 Effect.gen(function* () {
442 const fileSystem = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
445 for (const name of ["explorer.exe", "xdg-open", "xdg-mime"]) {
446 const filePath = path.join(binDir, name);
447 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
448 yield* fileSystem.chmod(filePath, 0o755);
449 }
450​
451 const spawnedCommands: ChildProcess.StandardCommand[] = [];
452 const kind = yield* Effect.gen(function* () {
453 const launcher = yield* ExternalLauncher.ExternalLauncher;
454 const revealKind = yield* launcher.resolveFileManagerRevealKind();
455 yield* launcher.launchEditor({
456 editor: "file-manager",
457 cwd: "/home/t3/workspace/media/clip.mp4",
458 reveal: true,
459 });
460 return revealKind;
461 }).pipe(
462 Effect.provide(
463 testLayer({
464 platform: "linux",
465 env: {
466 PATH: binDir,
467 WSL_DISTRO_NAME: "Ubuntu-24.04",
468 WSL_INTEROP: "/run/WSL/1_interop",
469 DISPLAY: ":0",
470 },
471 onSpawn: (command) => {
472 spawnedCommands.push(command);
473 },
474 spawnResult: (command) =>
475 command.command === "xdg-mime"
476 ? { stdout: "org.gnome.Nautilus.desktop\n" }
477 : undefined,
478 }),
479 ),
480 );
481​
482 assert.equal(kind, "files");
483 const launch = spawnedCommands.find((command) => command.command === "xdg-open");
484 assert.ok(launch);
485 assert.deepEqual(launch.args, ["/home/t3/workspace/media"]);
486 assert.isUndefined(spawnedCommands.find((command) => command.command === "explorer.exe"));
487 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
488);
489​
490// Interop can exist without `explorer.exe` on PATH (appendWindowsPath=false)
491// while WSLg still provides a working Linux file manager; the host must keep
492// the Linux open/reveal path instead of losing the editor entirely.
493it.effect.skipIf(windowsHost)(
494 "falls back to the Linux file manager when WSL lacks the Explorer bridge",
495 () =>
496 Effect.gen(function* () {
497 const fileSystem = yield* FileSystem.FileSystem;
498 const path = yield* Path.Path;
499 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
500 for (const name of ["xdg-open", "xdg-mime"]) {
501 const filePath = path.join(binDir, name);
502 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
503 yield* fileSystem.chmod(filePath, 0o755);
504 }
505​
506 const spawnedCommands: ChildProcess.StandardCommand[] = [];
507 const result = yield* Effect.gen(function* () {
508 const launcher = yield* ExternalLauncher.ExternalLauncher;
509 const editors = yield* launcher.resolveAvailableEditors();
510 const kind = yield* launcher.resolveFileManagerRevealKind();
511 yield* launcher.launchEditor({
512 editor: "file-manager",
513 cwd: "/home/t3/workspace/media/clip.mp4",
514 reveal: true,
515 });
516 return { editors, kind };
517 }).pipe(
518 Effect.provide(
519 testLayer({
520 platform: "linux",
521 env: {
522 PATH: binDir,
523 WSL_DISTRO_NAME: "Ubuntu-24.04",
524 WSL_INTEROP: "/run/WSL/1_interop",
525 DISPLAY: ":0",
526 },
527 onSpawn: (command) => {
528 spawnedCommands.push(command);
529 },
530 spawnResult: (command) =>
531 command.command === "xdg-mime"
532 ? { stdout: "org.gnome.Nautilus.desktop\n" }
533 : undefined,
534 }),
535 ),
536 );
537​
538 assert.equal(result.editors.includes("file-manager"), true);
539 assert.equal(result.kind, "files");
540 const launch = spawnedCommands.find((command) => command.command === "xdg-open");
541 assert.ok(launch);
542 assert.deepEqual(launch.args, ["/home/t3/workspace/media"]);
543 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
544);
545​
546it.effect.skipIf(windowsHost)(
547 "falls back to opening the containing directory for WSL paths Explorer cannot select",
548 () =>
549 Effect.gen(function* () {
550 const fileSystem = yield* FileSystem.FileSystem;
551 const path = yield* Path.Path;
552 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
553 for (const name of ["explorer.exe", "powershell.exe"]) {
554 const filePath = path.join(binDir, name);
555 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
556 yield* fileSystem.chmod(filePath, 0o755);
557 }
558​
559 let spawned: ChildProcess.StandardCommand | undefined;
560 yield* Effect.gen(function* () {
561 const launcher = yield* ExternalLauncher.ExternalLauncher;
562 yield* launcher.launchEditor({
563 editor: "file-manager",
564 cwd: '/home/t3/work "quoted"/clip.mp4',
565 reveal: true,
566 });
567 }).pipe(
568 Effect.provide(
569 testLayer({
570 platform: "linux",
571 env: {
572 PATH: binDir,
573 WSL_DISTRO_NAME: "Ubuntu-24.04",
574 WSL_INTEROP: "/run/WSL/1_interop",
575 },
576 onSpawn: (command) => {
577 spawned = command;
578 },
579 }),
580 ),
581 );
582​
583 // Explorer's raw switch cannot express a double quote, so the launch
584 // opens the parent directory instead of misparsing a /select argument.
585 assert.ok(spawned);
586 assert.equal(spawned.command, "explorer.exe");
587 assert.deepEqual(spawned.args, ['\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\work "quoted"']);
588 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
589);
590​
591it.effect.skipIf(windowsHost)("reveals by opening the containing directory on Linux", () =>
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"]) {
597 const filePath = path.join(binDir, name);
598 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
599 yield* fileSystem.chmod(filePath, 0o755);
600 }
601​
602 const spawnedCommands: ChildProcess.StandardCommand[] = [];
603 yield* Effect.gen(function* () {
604 const launcher = yield* ExternalLauncher.ExternalLauncher;
605 yield* launcher.launchEditor({
606 editor: "file-manager",
607 cwd: "/workspace/media/linux-mini-v2.mp4",
608 reveal: true,
609 });
610 }).pipe(
611 Effect.provide(
612 testLayer({
613 platform: "linux",
614 env: { PATH: binDir, DISPLAY: ":0" },
615 onSpawn: (command) => {
616 spawnedCommands.push(command);
617 },
618 spawnResult: (command) =>
619 command.command === "xdg-mime" ? { stdout: "org.gnome.Nautilus.desktop\n" } : undefined,
620 }),
621 ),
622 );
623​
624 const spawned = spawnedCommands.find((command) => command.command === "xdg-open");
625 assert.ok(spawned);
626 assert.deepEqual(spawned.args, ["/workspace/media"]);
627 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
628);
629​
630it.effect.skipIf(windowsHost)(
631 "does not advertise a Linux file manager without a graphical session",
632 () =>
633 Effect.gen(function* () {
634 const fileSystem = yield* FileSystem.FileSystem;
635 const path = yield* Path.Path;
636 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
637 const xdgOpenPath = path.join(binDir, "xdg-open");
638 yield* fileSystem.writeFileString(xdgOpenPath, "#!/bin/sh\n");
639 yield* fileSystem.chmod(xdgOpenPath, 0o755);
640​
641 const editors = yield* Effect.gen(function* () {
642 const launcher = yield* ExternalLauncher.ExternalLauncher;
643 return yield* launcher.resolveAvailableEditors();
644 }).pipe(Effect.provide(testLayer({ platform: "linux", env: { PATH: binDir } })));
645​
646 assert.equal(editors.includes("file-manager"), false);
647 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
648);
649​
650it.effect.skipIf(windowsHost)(
651 "advertises a Linux file manager when a directory handler is installed",
652 () =>
653 Effect.gen(function* () {
654 const fileSystem = yield* FileSystem.FileSystem;
655 const path = yield* Path.Path;
656 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
657 for (const name of ["xdg-open", "xdg-mime"]) {
658 const filePath = path.join(binDir, name);
659 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
660 yield* fileSystem.chmod(filePath, 0o755);
661 }
662​
663 let probe: ChildProcess.StandardCommand | undefined;
664 const editors = yield* Effect.gen(function* () {
665 const launcher = yield* ExternalLauncher.ExternalLauncher;
666 return yield* launcher.resolveAvailableEditors();
667 }).pipe(
668 Effect.provide(
669 testLayer({
670 platform: "linux",
671 env: { PATH: binDir, DISPLAY: ":0" },
672 onSpawn: (command) => {
673 probe = command;
674 },
675 spawnResult: (command) =>
676 command.command === "xdg-mime"
677 ? { stdout: "org.gnome.Nautilus.desktop\n" }
678 : undefined,
679 }),
680 ),
681 );
682​
683 assert.equal(editors.includes("file-manager"), true);
684 assert.ok(probe);
685 assert.equal(probe.command, "xdg-mime");
686 assert.deepEqual(probe.args, ["query", "default", "inode/directory"]);
687 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
688);
689​
690// `xdg-open` with a display variable but no `inode/directory` handler exits
691// nonzero after the launch has already detached: without this gate the server
692// advertises a reveal that is a silent no-op.
693it.effect.skipIf(windowsHost)(
694 "does not advertise a Linux file manager without a directory handler",
695 () =>
696 Effect.gen(function* () {
697 const fileSystem = yield* FileSystem.FileSystem;
698 const path = yield* Path.Path;
699 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
700 for (const name of ["xdg-open", "xdg-mime"]) {
701 const filePath = path.join(binDir, name);
702 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
703 yield* fileSystem.chmod(filePath, 0o755);
704 }
705​
706 const editors = yield* Effect.gen(function* () {
707 const launcher = yield* ExternalLauncher.ExternalLauncher;
708 return yield* launcher.resolveAvailableEditors();
709 }).pipe(
710 Effect.provide(
711 testLayer({
712 platform: "linux",
713 env: { PATH: binDir, DISPLAY: ":0" },
714 spawnResult: (command) => (command.command === "xdg-mime" ? { stdout: "" } : undefined),
715 }),
716 ),
717 );
718​
719 assert.equal(editors.includes("file-manager"), false);
720 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
721);
722​
723it.effect.skipIf(windowsHost)(
724 "does not advertise a Linux file manager when the handler query fails",
725 () =>
726 Effect.gen(function* () {
727 const fileSystem = yield* FileSystem.FileSystem;
728 const path = yield* Path.Path;
729 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
730 for (const name of ["xdg-open", "xdg-mime"]) {
731 const filePath = path.join(binDir, name);
732 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
733 yield* fileSystem.chmod(filePath, 0o755);
734 }
735​
736 const editors = yield* Effect.gen(function* () {
737 const launcher = yield* ExternalLauncher.ExternalLauncher;
738 return yield* launcher.resolveAvailableEditors();
739 }).pipe(
740 Effect.provide(
741 testLayer({
742 platform: "linux",
743 env: { PATH: binDir, DISPLAY: ":0" },
744 spawnResult: (command) =>
745 command.command === "xdg-mime"
746 ? { exitCode: 47, stdout: "org.gnome.Nautilus.desktop\n" }
747 : undefined,
748 }),
749 ),
750 );
751​
752 assert.equal(editors.includes("file-manager"), false);
753 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
754);
755​
756// The handler probe carries its own timeout because the editor scan's outer
757// timeout in server.getConfig degrades to an EMPTY editor list: a wedged
758// xdg-mime must cost only the file manager, never the other editors. Runs on
759// the live clock so the probe's real timeout fires.
760it.live.skipIf(windowsHost)("a stalled handler probe drops only the file manager", () =>
761 Effect.gen(function* () {
762 const fileSystem = yield* FileSystem.FileSystem;
763 const path = yield* Path.Path;
764 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
765 for (const name of ["xdg-open", "xdg-mime", "code"]) {
766 const filePath = path.join(binDir, name);
767 yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
768 yield* fileSystem.chmod(filePath, 0o755);
769 }
770​
771 const editors = yield* Effect.gen(function* () {
772 const launcher = yield* ExternalLauncher.ExternalLauncher;
773 return yield* launcher.resolveAvailableEditors();
774 }).pipe(
775 Effect.provide(
776 testLayer({
777 platform: "linux",
778 env: { PATH: binDir, DISPLAY: ":0" },
779 spawnResult: (command) => (command.command === "xdg-mime" ? { stall: true } : undefined),
780 }),
781 ),
782 );
783​
784 assert.equal(editors.includes("vscode"), true);
785 assert.equal(editors.includes("file-manager"), false);
786 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
787);
788​
789it.effect.skipIf(windowsHost)(
790 "does not advertise a Linux file manager when xdg-mime is missing",
791 () =>
792 Effect.gen(function* () {
793 const fileSystem = yield* FileSystem.FileSystem;
794 const path = yield* Path.Path;
795 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
796 const xdgOpenPath = path.join(binDir, "xdg-open");
797 yield* fileSystem.writeFileString(xdgOpenPath, "#!/bin/sh\n");
798 yield* fileSystem.chmod(xdgOpenPath, 0o755);
799​
800 const editors = yield* Effect.gen(function* () {
801 const launcher = yield* ExternalLauncher.ExternalLauncher;
802 return yield* launcher.resolveAvailableEditors();
803 }).pipe(
804 Effect.provide(testLayer({ platform: "linux", env: { PATH: binDir, DISPLAY: ":0" } })),
805 );
806​
807 assert.equal(editors.includes("file-manager"), false);
808 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
809);
810​
811it.effect("discovers editors through the service API", () =>
812 Effect.gen(function* () {
813 const fileSystem = yield* FileSystem.FileSystem;
814 const path = yield* Path.Path;
815 const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
816 yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
817 yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
818​
819 const editors = yield* Effect.gen(function* () {
820 const launcher = yield* ExternalLauncher.ExternalLauncher;
821 return yield* launcher.resolveAvailableEditors();
822 }).pipe(
823 Effect.provide(
824 testLayer({
825 platform: "win32",
826 env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
827 }),
828 ),
829 );
830​
831 assert.equal(editors.includes("vscode"), true);
832 assert.equal(editors.includes("file-manager"), true);
833 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
834);
835​
836it.effect("memoizes editor discovery and refreshes after the cache window", () => {
837 let statCalls = 0;
838 const fileInfo = { type: "File" } as FileSystem.File.Info;
839 const launcherLayer = ExternalLauncher.layer.pipe(
840 Layer.provide(
841 Layer.mergeAll(
842 FileSystem.layerNoop({
843 stat: () =>
844 Effect.sync(() => {
845 statCalls += 1;
846 return fileInfo;
847 }),
848 }),
849 Path.layer,
850 Layer.succeed(
851 ChildProcessSpawner.ChildProcessSpawner,
852 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
853 ),
854 ),
855 ),
856 );
857​
858 return Effect.gen(function* () {
859 const launcher = yield* ExternalLauncher.ExternalLauncher;
860​
861 const first = yield* launcher.resolveAvailableEditors();
862 assert.equal(first.includes("vscode"), true);
863 const statCallsAfterFirstScan = statCalls;
864 assert.isAbove(statCallsAfterFirstScan, 0);
865​
866 // Past the shared command-resolution cache TTL (30s) but within the
867 // discovery cache window: the memoized set is reused without any scan.
868 yield* TestClock.adjust("31 seconds");
869 const second = yield* launcher.resolveAvailableEditors();
870 assert.deepEqual([...second], [...first]);
871 assert.equal(statCalls, statCallsAfterFirstScan);
872​
873 // Past the discovery cache window the next call rescans.
874 yield* TestClock.adjust("30 seconds");
875 yield* launcher.resolveAvailableEditors();
876 assert.isAbove(statCalls, statCallsAfterFirstScan);
877 }).pipe(
878 Effect.provide(
879 Layer.mergeAll(
880 launcherLayer,
881 Layer.succeed(HostProcessPlatform, "win32"),
882 ConfigProvider.layer(
883 ConfigProvider.fromEnv({
884 env: {
885 PATH: "C:\\t3-editor-discovery-cache-test",
886 PATHEXT: ".COM;.EXE;.BAT;.CMD",
887 },
888 }),
889 ),
890 TestClock.layer(),
891 ),
892 ),
893 );
894});
895​
896// A client that disconnects mid-scan interrupts the shared discovery effect on
897// the connection fiber. The cache must not retain that interrupt: doing so
898// replayed it to every later connect for the whole TTL, so `server.getConfig`
899// failed and no client could reconnect until the server restarted.
900it.effect("rescans after an interrupted discovery instead of caching the interrupt", () => {
901 const fileInfo = { type: "File" } as FileSystem.File.Info;
902 let blockFirstScan = true;
903 let scans = 0;
904 const launcherLayer = ExternalLauncher.layer.pipe(
905 Layer.provide(
906 Layer.mergeAll(
907 FileSystem.layerNoop({
908 // The first scan parks inside `stat` so the interrupt lands while
909 // discovery is in flight, which is what a client disconnecting
910 // mid-connect does to the shared effect.
911 stat: () =>
912 Effect.gen(function* () {
913 scans += 1;
914 if (blockFirstScan) {
915 return yield* Effect.never;
916 }
917 return fileInfo;
918 }),
919 }),
920 Path.layer,
921 Layer.succeed(
922 ChildProcessSpawner.ChildProcessSpawner,
923 ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
924 ),
925 ),
926 ),
927 );
928​
929 return Effect.gen(function* () {
930 const launcher = yield* ExternalLauncher.ExternalLauncher;
931​
932 const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors());
933 yield* Effect.yieldNow;
934 yield* Fiber.interrupt(fiber);
935​
936 // The next connect must still get a real answer well inside the TTL.
937 blockFirstScan = false;
938 scans = 0;
939 const editors = yield* launcher.resolveAvailableEditors();
940 assert.equal(editors.includes("vscode"), true);
941 assert.isAbove(scans, 0);
942 }).pipe(
943 Effect.provide(
944 Layer.mergeAll(
945 launcherLayer,
946 Layer.succeed(HostProcessPlatform, "win32"),
947 ConfigProvider.layer(
948 ConfigProvider.fromEnv({
949 env: {
950 PATH: "C:\\t3-editor-discovery-interrupt-test",
951 PATHEXT: ".COM;.EXE;.BAT;.CMD",
952 },
953 }),
954 ),
955 ),
956 ),
957 );
958});
959​
960it.effect("rejects unknown editors through the service API", () =>
961 Effect.gen(function* () {
962 const launcher = yield* ExternalLauncher.ExternalLauncher;
963 const error = yield* launcher
964 .launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
965 .pipe(Effect.flip);
966 assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError);
967 assert.equal(error.editor, "missing-editor");
968 assert.equal(error.message, "Unknown editor: missing-editor");
969 }).pipe(Effect.provide(testLayer({ platform: "linux", env: { PATH: "" } }))),
970);