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