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