Open History to see the last commit
1import {
2 EDITORS,
3 ExternalLauncherError,
4 ExternalLauncherBrowserSpawnError,
5 ExternalLauncherCommandNotFoundError,
6 ExternalLauncherEditorSpawnError,
7 ExternalLauncherUnknownEditorError,
8 ExternalLauncherUnsupportedEditorError,
9 ExternalLauncherUnsupportedTargetError,
10 type EditorId,
11 type FileManagerRevealKind,
12 type LaunchEditorInput,
13} from "@t3tools/contracts";
14import { resolveEditorCommand } from "@t3tools/shared/editor";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import {
17 isCommandAvailable,
18 resolveSpawnCommand,
19 withPathDirectoryListings,
20} from "@t3tools/shared/shell";
21import * as Clock from "effect/Clock";
22import * as Config from "effect/Config";
23import * as Context from "effect/Context";
24import * as Deferred from "effect/Deferred";
25import * as Effect from "effect/Effect";
26import * as Base64 from "effect/encoding/Base64";
27import * as Exit from "effect/Exit";
28import * as FileSystem from "effect/FileSystem";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Path from "effect/Path";
32import * as Ref from "effect/Ref";
33import * as Scope from "effect/Scope";
34import * as Stream from "effect/Stream";
35import * as ChildProcess from "effect/process/ChildProcess";
36import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
37
38export {
39 ExternalLauncherError,
40 ExternalLauncherBrowserSpawnError,
41 ExternalLauncherCommandNotFoundError,
42 ExternalLauncherEditorSpawnError,
43 ExternalLauncherUnknownEditorError,
44 ExternalLauncherUnsupportedEditorError,
45 ExternalLauncherUnsupportedTargetError,
46} from "@t3tools/contracts";
47export type { LaunchEditorInput };
48interface EditorLaunch {
49 readonly editor: EditorId;
50 readonly target: string;
51 readonly command: string;
52 readonly args: ReadonlyArray<string>;
53 readonly detached?: boolean;
54}
55
56interface ProcessLaunch {
57 readonly command: string;
58 readonly args: ReadonlyArray<string>;
59 readonly options: ChildProcess.CommandOptions;
60}
61
62interface TargetPathAndPosition {
63 readonly path: string;
64 readonly line: string;
65 readonly column: Option.Option<string>;
66}
67
68/**
69 * Windows command shims (`code.cmd`) forward arguments through `%*`, which
70 * cmd.exe parses a second time after the first escaping layer is gone: a
71 * line break ends the command there, and a double quote closes the quoting
72 * that keeps `&` or `|` literal. Neither can occur in a Windows path.
73 */
74// oxlint-disable-next-line no-control-regex
75const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
76const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
77const POWERSHELL_ARGUMENTS_PREFIX = [
78 "-NoProfile",
79 "-NonInteractive",
80 "-ExecutionPolicy",
81 "Bypass",
82 "-EncodedCommand",
83] as const;
84
85// Windows PowerShell started with DETACHED_PROCESS exits 0 without running its
86// command, so native Windows launches through it stay attached. WSL interop
87// PowerShell starts from a Linux process and keeps the detached launch.
88const WINDOWS_POWERSHELL_DETACHED = false;
89
90const DETACHED_IGNORE_STDIO_OPTIONS = {
91 detached: true,
92 stdin: "ignore",
93 stdout: "ignore",
94 stderr: "ignore",
95} as const satisfies ChildProcess.CommandOptions;
96
97const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
98 Object.fromEntries(
99 Object.entries(input).flatMap(([key, value]) =>
100 Option.match(value, {
101 onNone: () => [],
102 onSome: (resolved) => [[key, resolved]],
103 }),
104 ),
105 );
106
107const BrowserLaunchEnvConfig = Config.all({
108 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
109 windir: Config.String("windir").pipe(Config.option),
110 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
111 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
112 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
113 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
114 container: Config.String("container").pipe(Config.option),
115 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
116 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
117}).pipe(Config.map(compactEnv));
118
119const CommandLookupEnvConfig = Config.all({
120 PATH: Config.String("PATH").pipe(Config.option),
121 Path: Config.String("Path").pipe(Config.option),
122 path: Config.String("path").pipe(Config.option),
123 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
124 HOME: Config.String("HOME").pipe(Config.option),
125 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
126 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
127 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
128 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
129 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
130}).pipe(Config.map(compactEnv));
131
132const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
133const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
134
135function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
136 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
137 if (!match?.[1] || !match[2]) {
138 return Option.none();
139 }
140
141 return Option.some({
142 path: match[1],
143 line: match[2],
144 column: Option.fromUndefinedOr(match[3]),
145 });
146}
147
148function resolveCommandEditorArgs(
149 editor: (typeof EDITORS)[number],
150 target: string,
151): ReadonlyArray<string> {
152 const parsedTarget = parseTargetPathAndPosition(target);
153
154 switch (editor.launchStyle) {
155 case "direct-path":
156 return [target];
157 case "goto":
158 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
159 case "line-column":
160 return Option.match(parsedTarget, {
161 onNone: () => [target],
162 onSome: ({ path, line, column }) => [
163 "--line",
164 line,
165 ...Option.match(column, {
166 onNone: () => [],
167 onSome: (value) => ["--column", value],
168 }),
169 path,
170 ],
171 });
172 }
173}
174
175function encodeUtf16LeBase64(input: string): string {
176 const bytes = new Uint8Array(input.length * 2);
177 for (let index = 0; index < input.length; index += 1) {
178 const code = input.charCodeAt(index);
179 bytes[index * 2] = code & 0xff;
180 bytes[index * 2 + 1] = code >>> 8;
181 }
182 return Base64.encode(bytes);
183}
184
185function escapePowerShellStringLiteral(input: string): string {
186 return `'${input.replaceAll("'", "''")}'`;
187}
188
189function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
190 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
191}
192
193function resolveWslPowerShellPath(): string {
194 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
195}
196
197// File reveals from WSL resolve PowerShell through the interop PATH rather
198// than the fixed /mnt/c mount: the automount root is configurable, and a
199// PATH-resolved command keeps the advertised capability aligned with the
200// availability check `launchEditor` performs before spawning.
201const WSL_POWERSHELL_COMMAND = "powershell.exe";
202
203function shouldUseWindowsHostFromWsl(
204 platform: NodeJS.Platform,
205 env: NodeJS.ProcessEnv = {},
206): boolean {
207 return (
208 platform === "linux" &&
209 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
210 env.SSH_CONNECTION === undefined &&
211 env.SSH_TTY === undefined &&
212 env.container === undefined
213 );
214}
215
216function resolveWindowsBrowserLaunch(
217 target: string,
218 command: string,
219 detached: boolean,
220): ProcessLaunch {
221 const encodedCommand = encodeUtf16LeBase64(
222 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
223 );
224 return {
225 command,
226 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
227 options: {
228 detached,
229 shell: false,
230 stdin: "ignore",
231 stdout: "ignore",
232 stderr: "ignore",
233 },
234 };
235}
236
237function hasGraphicalLinuxSession(env: NodeJS.ProcessEnv): boolean {
238 return [env.DISPLAY, env.WAYLAND_DISPLAY].some(
239 (value) => value !== undefined && value.trim().length > 0,
240 );
241}
242
243function fileManagerCommandForPlatform(
244 platform: NodeJS.Platform,
245 env: NodeJS.ProcessEnv,
246): string | undefined {
247 switch (platform) {
248 case "darwin":
249 return "open";
250 case "win32":
251 return "explorer";
252 default:
253 if (shouldUseWindowsHostFromWsl(platform, env)) {
254 return env.WSL_DISTRO_NAME?.trim() ? "explorer.exe" : undefined;
255 }
256 return hasGraphicalLinuxSession(env) ? "xdg-open" : undefined;
257 }
258}
259
260// A graphical session variable plus an executable `xdg-open` does not prove
261// that opening a directory does anything: without an `inode/directory` MIME
262// handler, `xdg-open` exits nonzero after the launcher has already detached, so
263// the client would see a silent no-op. The probe carries its own timeout well
264// inside the scan timeout `server.getConfig` applies to editor discovery: that
265// outer timeout degrades to an empty editor list, so a hung `xdg-mime` (broken
266// D-Bus or desktop session) must cost only the file manager, not every
267// discovered editor.
268const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
269
270const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
271 function* (
272 env: NodeJS.ProcessEnv,
273 ): Effect.fn.Return<
274 boolean,
275 never,
276 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
277 > {
278 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
279 return false;
280 }
281
282 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
283 return yield* spawner
284 .spawn(
285 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
286 stdin: "ignore",
287 stderr: "ignore",
288 }),
289 )
290 .pipe(
291 Effect.flatMap((handle) =>
292 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
293 concurrency: "unbounded",
294 }),
295 ),
296 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
297 Effect.scoped,
298 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
299 Effect.orElseSucceed(() => false),
300 );
301 },
302);
303
304const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
305 function* (
306 command: string,
307 env: NodeJS.ProcessEnv,
308 ): Effect.fn.Return<
309 boolean,
310 never,
311 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
312 > {
313 if (!(yield* isCommandAvailable(command, { env }))) {
314 return false;
315 }
316 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
317 },
318);
319
320// WSL hosts prefer the Windows Explorer bridge, but interop can exist without
321// `explorer.exe` on PATH (appendWindowsPath=false) or without a distro name
322// while WSLg still provides a working Linux file manager, so they keep the
323// `xdg-open` fallback instead of losing the editor entirely.
324const resolveUsableFileManagerCommand = Effect.fn(
325 "externalLauncher.resolveUsableFileManagerCommand",
326)(function* (
327 platform: NodeJS.Platform,
328 env: NodeJS.ProcessEnv,
329): Effect.fn.Return<
330 string | undefined,
331 never,
332 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
333> {
334 const command = fileManagerCommandForPlatform(platform, env);
335 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
336 return command;
337 }
338 if (
339 shouldUseWindowsHostFromWsl(platform, env) &&
340 hasGraphicalLinuxSession(env) &&
341 (yield* isUsableFileManagerCommand("xdg-open", env))
342 ) {
343 return "xdg-open";
344 }
345 return undefined;
346});
347
348// Reveal on Windows and WSL runs through PowerShell (see
349// resolveFileManagerRevealLaunch), not the `explorer` command that gates the
350// file-manager editor itself, so the capability must probe the executables the
351// reveal actually spawns. Callers gate on file-manager availability first;
352// the Linux "files" kind relies on that gate for the directory-handler probe,
353// while the WSL fallback re-probes because its availability may have come
354// from the Explorer bridge instead.
355const fileManagerRevealKindForPlatform = Effect.fn(
356 "externalLauncher.fileManagerRevealKindForPlatform",
357)(function* (
358 platform: NodeJS.Platform,
359 env: NodeJS.ProcessEnv,
360): Effect.fn.Return<
361 FileManagerRevealKind | undefined,
362 never,
363 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
364> {
365 if (platform === "darwin") return "finder";
366 if (platform === "win32") {
367 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
368 ? "file-explorer"
369 : undefined;
370 }
371 if (shouldUseWindowsHostFromWsl(platform, env)) {
372 if (
373 env.WSL_DISTRO_NAME?.trim() &&
374 (yield* isCommandAvailable("explorer.exe", { env })) &&
375 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
376 ) {
377 return "file-explorer";
378 }
379 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
380 ? "files"
381 : undefined;
382 }
383 return hasGraphicalLinuxSession(env) ? "files" : undefined;
384});
385
386function resolveWslFileManagerPath(target: string, distroName: string): string {
387 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
388 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
389}
390
391function buildBrowserLaunch(
392 target: string,
393 platform: NodeJS.Platform,
394 env: NodeJS.ProcessEnv = {},
395): ProcessLaunch {
396 if (platform === "darwin") {
397 return {
398 command: "open",
399 args: [target],
400 options: DETACHED_IGNORE_STDIO_OPTIONS,
401 };
402 }
403
404 if (platform === "win32") {
405 return resolveWindowsBrowserLaunch(
406 target,
407 resolvePowerShellPath(env),
408 WINDOWS_POWERSHELL_DETACHED,
409 );
410 }
411
412 if (shouldUseWindowsHostFromWsl(platform, env)) {
413 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
414 }
415
416 return {
417 command: "xdg-open",
418 args: [target],
419 options: DETACHED_IGNORE_STDIO_OPTIONS,
420 };
421}
422
423const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
424 platform: NodeJS.Platform,
425 env: NodeJS.ProcessEnv,
426): Effect.fn.Return<
427 ReadonlyArray<EditorId>,
428 never,
429 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
430> {
431 // Independent probes share PATH listings and retain EDITORS order.
432 const found = yield* Effect.forEach(
433 EDITORS,
434 (editor) =>
435 editor.commands === null
436 ? resolveUsableFileManagerCommand(platform, env).pipe(
437 Effect.map((command) => command !== undefined),
438 )
439 : resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome)),
440 { concurrency: "unbounded" },
441 );
442 return EDITORS.flatMap((editor, index) => (found[index] ? [editor.id] : []));
443});
444
445const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
446 target: string,
447) {
448 const platform = yield* HostProcess.Platform;
449 const env = yield* readBrowserLaunchEnv;
450 return buildBrowserLaunch(target, platform, env);
451});
452
453const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
454 const platform = yield* HostProcess.Platform;
455 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
456 return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
457});
458
459const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
460 function* () {
461 const platform = yield* HostProcess.Platform;
462 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
463 return yield* fileManagerRevealKindForPlatform(platform, env);
464 },
465);
466
467// Callers apply a timeout (`resolveAvailableEditorsForConfig`) and disconnect
468// mid-connect; neither may cancel a scan other connects are waiting on, or
469// throw away work a slow host (a busy server at startup, a long PATH) needs
470// more than one connect to finish. Expiry uses the monotonic clock
471// (Clock.monotonicTimeNanos), matching the command-resolution cache in
472// @t3tools/shared/shell, so a backward wall-clock adjustment cannot keep an
473// expired entry alive.
474const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
475
476interface EditorDiscoveryCacheEntry {
477 readonly scan: Deferred.Deferred<ReadonlyArray<EditorId>>;
478 readonly expiresAtNanos: bigint | undefined;
479}
480
481export class ExternalLauncher extends Context.Service<
482 ExternalLauncher,
483 {
484 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
485 /**
486 * Only meaningful when `resolveAvailableEditors` includes "file-manager":
487 * on Linux that availability check also carries the directory-handler probe
488 * this capability relies on.
489 */
490 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
491 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
492 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
493 }
494>()("t3/process/externalLauncher") {}
495
496const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
497 input: LaunchEditorInput,
498): Effect.fn.Return<
499 EditorLaunch,
500 ExternalLauncherError,
501 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
502> {
503 const platform = yield* HostProcess.Platform;
504 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
505 yield* Effect.annotateCurrentSpan({
506 "externalLauncher.editor": input.editor,
507 "externalLauncher.cwd": input.cwd,
508 "externalLauncher.platform": platform,
509 });
510 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
511 if (!editorDef) {
512 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
513 }
514
515 if (editorDef.commands) {
516 const { command, baseArgs } = Option.getOrElse(
517 yield* resolveEditorCommand(editorDef, env),
518 () => ({
519 command: editorDef.commands[0],
520 baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [],
521 }),
522 );
523 return {
524 editor: editorDef.id,
525 target: input.cwd,
526 command,
527 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)],
528 };
529 }
530
531 if (editorDef.id !== "file-manager") {
532 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
533 }
534
535 const command = yield* resolveUsableFileManagerCommand(platform, env);
536 if (command === undefined) {
537 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
538 }
539
540 if (input.reveal === true) {
541 return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
542 }
543
544 return {
545 editor: editorDef.id,
546 target: input.cwd,
547 command,
548 args:
549 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
550 ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
551 : platform === "win32"
552 ? // Explorer reads `/` as a switch, so `C:/repo` silently opens
553 // a default folder instead of the target.
554 [normalizeWindowsFileManagerPath(input.cwd)]
555 : [input.cwd],
556 };
557});
558
559/**
560 * Explorer's contract is the single argument `/select,"<path>"` with only the
561 * path quoted; Node's default spawn quoting wraps the whole argument when the
562 * path has spaces and Explorer misparses it, silently opening a fallback
563 * folder. A single `-ArgumentList` string in Windows PowerShell 5.1 reaches the
564 * child's command line verbatim, preserving the raw switch.
565 */
566function buildFileExplorerRevealPowerShellSource(explorerCommand: string, target: string): string {
567 return `$ProgressPreference = 'SilentlyContinue'; Start-Process ${escapePowerShellStringLiteral(explorerCommand)} -ArgumentList ('/select,"' + ${escapePowerShellStringLiteral(target)} + '"')`;
568}
569
570function fileExplorerRevealLaunch(
571 target: string,
572 explorerTarget: string,
573 powershellCommand: string,
574): EditorLaunch {
575 return {
576 editor: "file-manager",
577 target,
578 command: powershellCommand,
579 args: [
580 ...POWERSHELL_ARGUMENTS_PREFIX,
581 encodeUtf16LeBase64(buildFileExplorerRevealPowerShellSource("explorer.exe", explorerTarget)),
582 ],
583 };
584}
585
586function normalizeWindowsFileManagerPath(target: string): string {
587 return target.replaceAll("/", "\\");
588}
589
590const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
591 target: string,
592 platform: NodeJS.Platform,
593 env: NodeJS.ProcessEnv,
594 command: string,
595): Effect.fn.Return<
596 EditorLaunch,
597 never,
598 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
599> {
600 if (platform === "darwin") {
601 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
602 }
603
604 if (platform === "win32") {
605 return {
606 ...fileExplorerRevealLaunch(
607 target,
608 normalizeWindowsFileManagerPath(target),
609 resolvePowerShellPath(env),
610 ),
611 detached: WINDOWS_POWERSHELL_DETACHED,
612 };
613 }
614
615 if (
616 command === "explorer.exe" &&
617 shouldUseWindowsHostFromWsl(platform, env) &&
618 env.WSL_DISTRO_NAME !== undefined
619 ) {
620 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
621 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
622 // Explorer's raw switch cannot express a double quote, and unlike
623 // Windows paths a WSL path may legally contain one: open the containing
624 // directory in File Explorer instead, matching the advertised
625 // "file-explorer" kind.
626 if (explorerTarget.includes('"')) {
627 const path = yield* Path.Path;
628 return {
629 editor: "file-manager",
630 target,
631 command: "explorer.exe",
632 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
633 };
634 }
635 return fileExplorerRevealLaunch(target, explorerTarget, WSL_POWERSHELL_COMMAND);
636 }
637 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
638 const path = yield* Path.Path;
639 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
640 }
641 const path = yield* Path.Path;
642 return {
643 editor: "file-manager",
644 target,
645 command: "explorer.exe",
646 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
647 };
648 }
649
650 // Linux file managers have no portable "select this file" flag, so open
651 // the containing directory instead.
652 const path = yield* Path.Path;
653 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
654});
655
656const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
657 launch: ProcessLaunch,
658 onError: (cause: unknown) => ExternalLauncherError,
659): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
660 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
661 // The desktop app runs this server with ELECTRON_RUN_AS_NODE. A launched file
662 // manager or browser passes its environment on to everything started from it,
663 // so any Electron app opened from there would start as plain Node and exit.
664 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
665 const command = ChildProcess.make(launch.command, launch.args, {
666 ...launch.options,
667 env,
668 extendEnv: false,
669 });
670
671 yield* spawner.spawn(command).pipe(
672 Effect.flatMap((handle) => handle.unref),
673 Effect.asVoid,
674 Effect.scoped,
675 Effect.mapError(onError),
676 );
677});
678
679const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
680 target: string,
681): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
682 const launch = yield* resolveBrowserLaunch(target);
683 return yield* launchAndUnref(
684 launch,
685 (cause) =>
686 new ExternalLauncherBrowserSpawnError({
687 target,
688 command: launch.command,
689 args: launch.args,
690 cause,
691 }),
692 );
693});
694
695const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
696 launch: EditorLaunch,
697): Effect.fn.Return<
698 void,
699 ExternalLauncherError,
700 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
701> {
702 const env = yield* readCommandLookupEnv;
703 if (!(yield* isCommandAvailable(launch.command, { env }))) {
704 return yield* new ExternalLauncherCommandNotFoundError({
705 editor: launch.editor,
706 command: launch.command,
707 });
708 }
709
710 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
711 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
712 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
713 }
714 yield* launchAndUnref(
715 {
716 command: spawnCommand.command,
717 args: spawnCommand.args,
718 options: {
719 detached: launch.detached ?? true,
720 shell: spawnCommand.shell,
721 stdin: "ignore",
722 stdout: "ignore",
723 stderr: "ignore",
724 },
725 },
726 (cause) =>
727 new ExternalLauncherEditorSpawnError({
728 editor: launch.editor,
729 target: launch.target,
730 command: spawnCommand.command,
731 args: spawnCommand.args,
732 cause,
733 }),
734 );
735});
736
737/** @public Service construction is part of the canonical Effect module API. */
738export const make = Effect.gen(function* () {
739 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
740 const fileSystem = yield* FileSystem.FileSystem;
741 const path = yield* Path.Path;
742
743 const provideCommandResolutionServices = <A, E, R>(
744 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
745 ) =>
746 effect.pipe(
747 Effect.provideService(FileSystem.FileSystem, fileSystem),
748 Effect.provideService(Path.Path, path),
749 );
750
751 const scope = yield* Scope.Scope;
752 const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
753 Option.none(),
754 );
755 const runEditorDiscovery = (scan: Deferred.Deferred<ReadonlyArray<EditorId>>) =>
756 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
757 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
758 Effect.onExit((exit) =>
759 Effect.gen(function* () {
760 const expiresAtNanos =
761 (yield* Clock.monotonicTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS;
762 yield* Ref.update(editorDiscoveryCache, (current) =>
763 Option.isNone(current) || current.value.scan !== scan
764 ? current
765 : Exit.isSuccess(exit)
766 ? Option.some({ scan, expiresAtNanos })
767 : Option.none(),
768 );
769 yield* Deferred.done(scan, exit);
770 }),
771 ),
772 Effect.interruptible,
773 Effect.forkIn(scope),
774 );
775 // Claiming the cache entry and starting its scan must not be split by an
776 // interrupt, or the entry would wait on a scan that never runs.
777 const acquireEditorDiscovery = Effect.gen(function* () {
778 const nowNanos = yield* Clock.monotonicTimeNanos;
779 const [scan, isNewScan] = yield* Ref.modify(
780 editorDiscoveryCache,
781 (
782 current,
783 ): [
784 [EditorDiscoveryCacheEntry["scan"], boolean],
785 Option.Option<EditorDiscoveryCacheEntry>,
786 ] => {
787 if (
788 Option.isSome(current) &&
789 (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos)
790 ) {
791 return [[current.value.scan, false], current];
792 }
793 const scan = Deferred.makeUnsafe<ReadonlyArray<EditorId>>();
794 return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })];
795 },
796 );
797 if (isNewScan) {
798 yield* runEditorDiscovery(scan);
799 }
800 return scan;
801 }).pipe(Effect.uninterruptible);
802 const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);
803
804 return ExternalLauncher.of({
805 resolveAvailableEditors: () => cachedAvailableEditors,
806 resolveFileManagerRevealKind: () =>
807 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
808 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
809 ),
810 launchBrowser: (target) =>
811 launchBrowser(target).pipe(
812 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
813 ),
814 launchEditor: (input) =>
815 provideCommandResolutionServices(
816 Effect.flatMap(resolveEditorLaunch(input), launchEditorProcess),
817 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
818 });
819});
820
821export const layer = Layer.effect(ExternalLauncher, make);