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