Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

externalLauncher.ts

808 lines27.2 KB

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