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