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