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