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

externalLauncher.test.ts

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