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

externalLauncher.ts

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