Open History to see the last commit
1import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2import * as NodePath from "@effect/platform-node/NodePath";
3import {
4 EDITORS,
5 ExternalLauncherError,
6 ExternalLauncherBrowserSpawnError,
7 ExternalLauncherCommandNotFoundError,
8 ExternalLauncherEditorSpawnError,
9 ExternalLauncherUnknownEditorError,
10 ExternalLauncherUnsupportedEditorError,
11 ExternalLauncherUnsupportedTargetError,
12 type EditorId,
13 type FileManagerRevealKind,
14 type LaunchEditorInput,
15} from "@t3tools/contracts";
16import { resolveEditorCommand } from "@t3tools/shared/editor";
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import {
19 isCommandAvailable,
20 resolveSpawnCommand,
21 withPathDirectoryListings,
22} from "@t3tools/shared/shell";
23import * as Config from "effect/Config";
24import * as Context from "effect/Context";
25import * as Effect from "effect/Effect";
26import * as Base64 from "effect/encoding/Base64";
27import * as FileSystem from "effect/FileSystem";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Path from "effect/Path";
31import * as Schema from "effect/Schema";
32import * as Stream from "effect/Stream";
33import * as ChildProcess from "effect/process/ChildProcess";
34import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
35
36import { makeStaleWhileRevalidate } from "../environment/staleWhileRevalidate.ts";
37export {
38 ExternalLauncherError,
39 ExternalLauncherBrowserSpawnError,
40 ExternalLauncherCommandNotFoundError,
41 ExternalLauncherEditorSpawnError,
42 ExternalLauncherUnknownEditorError,
43 ExternalLauncherUnsupportedEditorError,
44 ExternalLauncherUnsupportedTargetError,
45} from "@t3tools/contracts";
46export type { LaunchEditorInput };
47interface EditorLaunch {
48 readonly editor: EditorId;
49 readonly target: string;
50 readonly command: string;
51 readonly args: ReadonlyArray<string>;
52 readonly detached?: boolean;
53}
54
55interface ProcessLaunch {
56 readonly command: string;
57 readonly args: ReadonlyArray<string>;
58 readonly options: ChildProcess.CommandOptions;
59}
60
61interface TargetPathAndPosition {
62 readonly path: string;
63 readonly line: string;
64 readonly column: Option.Option<string>;
65}
66
67// cmd shims reparse %* after escaping is gone; newlines and quotes can expose shell operators.
68const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
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
78// Detached Windows PowerShell exits 0 without executing; only WSL interop keeps detached launches.
79const WINDOWS_POWERSHELL_DETACHED = false;
80
81const DETACHED_IGNORE_STDIO_OPTIONS = {
82 detached: true,
83 stdin: "ignore",
84 stdout: "ignore",
85 stderr: "ignore",
86} as const satisfies ChildProcess.CommandOptions;
87
88const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
89 Object.fromEntries(
90 Object.entries(input).flatMap(([key, value]) =>
91 Option.match(value, {
92 onNone: () => [],
93 onSome: (resolved) => [[key, resolved]],
94 }),
95 ),
96 );
97
98const BrowserLaunchEnvConfig = Config.all({
99 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
100 windir: Config.String("windir").pipe(Config.option),
101 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
102 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
103 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
104 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
105 container: Config.String("container").pipe(Config.option),
106 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
107 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
108}).pipe(Config.map(compactEnv));
109
110const CommandLookupEnvConfig = Config.all({
111 PATH: Config.String("PATH").pipe(Config.option),
112 Path: Config.String("Path").pipe(Config.option),
113 path: Config.String("path").pipe(Config.option),
114 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
115 HOME: Config.String("HOME").pipe(Config.option),
116 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
117 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
118 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
119 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
120 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
121}).pipe(Config.map(compactEnv));
122
123const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
124const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
125
126function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
127 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
128 if (!match?.[1] || !match[2]) {
129 return Option.none();
130 }
131
132 return Option.some({
133 path: match[1],
134 line: match[2],
135 column: Option.fromUndefinedOr(match[3]),
136 });
137}
138
139function resolveCommandEditorArgs(
140 editor: (typeof EDITORS)[number],
141 target: string,
142 isDirectory: boolean,
143): ReadonlyArray<string> {
144 const parsedTarget = parseTargetPathAndPosition(target);
145
146 switch (editor.launchStyle) {
147 case "direct-path":
148 return [target];
149 case "goto":
150 if (Option.isSome(parsedTarget)) return ["--goto", target];
151 // Without a window flag, VS Code's window settings may replace the user's last active window.
152 return isDirectory ? ["--new-window", target] : [target];
153 case "line-column":
154 return Option.match(parsedTarget, {
155 onNone: () => [target],
156 onSome: ({ path, line, column }) => [
157 "--line",
158 line,
159 // JetBrains IDEs count `--column` from 0; targets count columns from 1.
160 ...Option.match(column, {
161 onNone: () => [],
162 onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))],
163 }),
164 path,
165 ],
166 });
167 }
168}
169
170function encodeUtf16LeBase64(input: string): string {
171 const bytes = new Uint8Array(input.length * 2);
172 for (let index = 0; index < input.length; index += 1) {
173 const code = input.charCodeAt(index);
174 bytes[index * 2] = code & 0xff;
175 bytes[index * 2 + 1] = code >>> 8;
176 }
177 return Base64.encode(bytes);
178}
179
180function escapePowerShellStringLiteral(input: string): string {
181 return `'${input.replaceAll("'", "''")}'`;
182}
183
184function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
185 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
186}
187
188function resolveWslPowerShellPath(): string {
189 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
190}
191
192// WSL automount roots vary; resolve PowerShell via PATH to match launchEditor's availability check.
193const WSL_POWERSHELL_COMMAND = "powershell.exe";
194
195function shouldUseWindowsHostFromWsl(
196 platform: NodeJS.Platform,
197 env: NodeJS.ProcessEnv = {},
198): boolean {
199 return (
200 platform === "linux" &&
201 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
202 env.SSH_CONNECTION === undefined &&
203 env.SSH_TTY === undefined &&
204 env.container === undefined
205 );
206}
207
208function resolveWindowsBrowserLaunch(
209 target: string,
210 command: string,
211 detached: boolean,
212): 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,
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// xdg-open needs an inode/directory handler or detached launches silently fail.
253// Bound xdg-mime below discovery's timeout so a hung probe drops only the file manager.
254const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
255
256const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
257 function* (
258 env: NodeJS.ProcessEnv,
259 ): Effect.fn.Return<
260 boolean,
261 never,
262 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
263 > {
264 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
265 return false;
266 }
267
268 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
269 return yield* spawner
270 .spawn(
271 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
272 stdin: "ignore",
273 stderr: "ignore",
274 }),
275 )
276 .pipe(
277 Effect.flatMap((handle) =>
278 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
279 concurrency: "unbounded",
280 }),
281 ),
282 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
283 Effect.scoped,
284 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
285 Effect.orElseSucceed(() => false),
286 );
287 },
288);
289
290const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
291 function* (
292 command: string,
293 env: NodeJS.ProcessEnv,
294 ): Effect.fn.Return<
295 boolean,
296 never,
297 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
298 > {
299 if (!(yield* isCommandAvailable(command, { env }))) {
300 return false;
301 }
302 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
303 },
304);
305
306// WSL may lack Explorer on PATH or a distro name while WSLg still offers a Linux file manager.
307const resolveUsableFileManagerCommand = Effect.fn(
308 "externalLauncher.resolveUsableFileManagerCommand",
309)(function* (
310 platform: NodeJS.Platform,
311 env: NodeJS.ProcessEnv,
312): Effect.fn.Return<
313 string | undefined,
314 never,
315 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
316> {
317 const command = fileManagerCommandForPlatform(platform, env);
318 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
319 return command;
320 }
321 if (
322 shouldUseWindowsHostFromWsl(platform, env) &&
323 hasGraphicalLinuxSession(env) &&
324 (yield* isUsableFileManagerCommand("xdg-open", env))
325 ) {
326 return "xdg-open";
327 }
328 return undefined;
329});
330
331// Reveal uses PowerShell on Windows/WSL, so probe it separately from Explorer availability.
332// Linux relies on the file-manager gate's handler probe; WSL re-probes because the gate may use Explorer.
333const fileManagerRevealKindForPlatform = Effect.fn(
334 "externalLauncher.fileManagerRevealKindForPlatform",
335)(function* (
336 platform: NodeJS.Platform,
337 env: NodeJS.ProcessEnv,
338): Effect.fn.Return<
339 FileManagerRevealKind | undefined,
340 never,
341 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
342> {
343 if (platform === "darwin") return "finder";
344 if (platform === "win32") {
345 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
346 ? "file-explorer"
347 : undefined;
348 }
349 if (shouldUseWindowsHostFromWsl(platform, env)) {
350 if (
351 env.WSL_DISTRO_NAME?.trim() &&
352 (yield* isCommandAvailable("explorer.exe", { env })) &&
353 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
354 ) {
355 return "file-explorer";
356 }
357 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
358 ? "files"
359 : undefined;
360 }
361 return hasGraphicalLinuxSession(env) ? "files" : undefined;
362});
363
364function resolveWslFileManagerPath(target: string, distroName: string): string {
365 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
366 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
367}
368
369function buildBrowserLaunch(
370 target: string,
371 platform: NodeJS.Platform,
372 env: NodeJS.ProcessEnv = {},
373): ProcessLaunch {
374 if (platform === "darwin") {
375 return {
376 command: "open",
377 args: [target],
378 options: DETACHED_IGNORE_STDIO_OPTIONS,
379 };
380 }
381
382 if (platform === "win32") {
383 return resolveWindowsBrowserLaunch(
384 target,
385 resolvePowerShellPath(env),
386 WINDOWS_POWERSHELL_DETACHED,
387 );
388 }
389
390 if (shouldUseWindowsHostFromWsl(platform, env)) {
391 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
392 }
393
394 return {
395 command: "xdg-open",
396 args: [target],
397 options: DETACHED_IGNORE_STDIO_OPTIONS,
398 };
399}
400
401const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
402 platform: NodeJS.Platform,
403 env: NodeJS.ProcessEnv,
404): Effect.fn.Return<
405 ReadonlyArray<EditorId>,
406 never,
407 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
408> {
409 const available: EditorId[] = [];
410
411 for (const editor of EDITORS) {
412 if (editor.commands === null) {
413 if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
414 available.push(editor.id);
415 }
416 continue;
417 }
418
419 const command = yield* resolveEditorCommand(editor, env);
420 if (Option.isSome(command)) {
421 available.push(editor.id);
422 }
423 }
424
425 return available;
426});
427
428const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
429 target: string,
430) {
431 const platform = yield* HostProcess.Platform;
432 const env = yield* readBrowserLaunchEnv;
433 return buildBrowserLaunch(target, platform, env);
434});
435
436const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
437 const platform = yield* HostProcess.Platform;
438 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
439 return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
440});
441
442const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
443 function* () {
444 const platform = yield* HostProcess.Platform;
445 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
446 return yield* fileManagerRevealKindForPlatform(platform, env);
447 },
448);
449
450const EDITOR_DISCOVERY_CACHE_TTL = "60 seconds";
451
452export class ExternalLauncher extends Context.Service<
453 ExternalLauncher,
454 {
455 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
456 /** Requires file-manager in resolveAvailableEditors; Linux relies on its directory-handler probe. */
457 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
458 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
459 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
460 }
461>()("t3/process/externalLauncher") {}
462
463const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
464 input: LaunchEditorInput,
465): Effect.fn.Return<
466 EditorLaunch,
467 ExternalLauncherError,
468 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
469> {
470 const platform = yield* HostProcess.Platform;
471 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
472 yield* Effect.annotateCurrentSpan({
473 "externalLauncher.editor": input.editor,
474 "externalLauncher.cwd": input.cwd,
475 "externalLauncher.platform": platform,
476 });
477 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
478 if (!editorDef) {
479 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
480 }
481
482 if (editorDef.commands) {
483 const resolved = yield* resolveEditorCommand(editorDef, env);
484 if (Option.isNone(resolved)) {
485 return yield* new ExternalLauncherCommandNotFoundError({
486 editor: editorDef.id,
487 command: editorDef.commands[0],
488 });
489 }
490 const { command, baseArgs } = resolved.value;
491 const isDirectory =
492 editorDef.launchStyle === "goto" &&
493 (yield* (yield* FileSystem.FileSystem).stat(input.cwd).pipe(
494 Effect.map((info) => info.type === "Directory"),
495 Effect.orElseSucceed(() => false),
496 ));
497 return {
498 editor: editorDef.id,
499 target: input.cwd,
500 command,
501 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd, isDirectory)],
502 };
503 }
504
505 if (editorDef.id !== "file-manager") {
506 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
507 }
508
509 const command = yield* resolveUsableFileManagerCommand(platform, env);
510 if (command === undefined) {
511 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
512 }
513
514 const target = expandHomePath(input.cwd, yield* HostProcess.HomeDirectory);
515 if (input.reveal === true) {
516 return yield* resolveFileManagerRevealLaunch(target, platform, env, command);
517 }
518
519 return {
520 editor: editorDef.id,
521 target,
522 command,
523 args:
524 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
525 ? [resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)]
526 : platform === "win32"
527 ? // Explorer interprets / as a switch and silently opens a fallback folder.
528 [normalizeWindowsFileManagerPath(target)]
529 : [target],
530 };
531});
532
533// A replacement manager registers a default Directory shell verb; stock Windows
534// uses "none". Explorer needs its /select argument passed verbatim through
535// PowerShell because Node's argument quoting changes how Explorer parses it.
536function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
537 const literal = escapePowerShellStringLiteral(target);
538 return `$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`;
539}
540
541function powerShellFileManagerLaunch(
542 target: string,
543 source: string,
544 powershellCommand: string,
545): EditorLaunch {
546 return {
547 editor: "file-manager",
548 target,
549 command: powershellCommand,
550 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
551 };
552}
553
554function normalizeWindowsFileManagerPath(target: string): string {
555 return target.replaceAll("/", "\\");
556}
557
558const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
559 target: string,
560 platform: NodeJS.Platform,
561 env: NodeJS.ProcessEnv,
562 command: string,
563): Effect.fn.Return<
564 EditorLaunch,
565 never,
566 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
567> {
568 if (platform === "darwin") {
569 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
570 }
571
572 if (platform === "win32") {
573 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
574 const windowsTarget = normalizeWindowsFileManagerPath(target);
575 return {
576 ...powerShellFileManagerLaunch(
577 target,
578 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
579 resolvePowerShellPath(env),
580 ),
581 detached: WINDOWS_POWERSHELL_DETACHED,
582 };
583 }
584
585 if (
586 command === "explorer.exe" &&
587 shouldUseWindowsHostFromWsl(platform, env) &&
588 env.WSL_DISTRO_NAME !== undefined
589 ) {
590 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
591 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
592 // WSL names may contain quotes that Explorer's /select cannot encode.
593 // Open the parent through the shell so replacement managers still apply.
594 const path = yield* Path.Path;
595 // .NET path parsing rejects characters that are legal in WSL filenames.
596 const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME);
597 const source = explorerTarget.includes('"')
598 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
599 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
600 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
601 }
602 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
603 const path = yield* Path.Path;
604 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
605 }
606 const path = yield* Path.Path;
607 return {
608 editor: "file-manager",
609 target,
610 command: "explorer.exe",
611 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
612 };
613 }
614
615 const path = yield* Path.Path;
616 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
617});
618
619const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
620 function* (target: string) {
621 const env = yield* readCommandLookupEnv;
622 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
623
624 const path = yield* Path.Path;
625 const uri = yield* path.toFileUrl(target);
626 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
627 const exitCode = yield* spawner.exitCode(
628 ChildProcess.make(
629 "gdbus",
630 [
631 "call",
632 "--session",
633 "--dest",
634 "org.freedesktop.FileManager1",
635 "--object-path",
636 "/org/freedesktop/FileManager1",
637 "--method",
638 "org.freedesktop.FileManager1.ShowItems",
639 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
640 `["${uri.href}"]`,
641 "",
642 ],
643 {
644 stdin: "ignore",
645 stdout: "ignore",
646 stderr: "ignore",
647 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
648 forceKillAfter: "1 second",
649 },
650 ),
651 );
652 return exitCode === 0;
653 },
654 Effect.timeout("2 seconds"),
655 Effect.catchTags({
656 BadArgument: () => Effect.succeed(false),
657 PlatformError: () => Effect.succeed(false),
658 TimeoutError: () => Effect.succeed(false),
659 }),
660);
661
662const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
663 input: LaunchEditorInput,
664) {
665 const launch = yield* resolveEditorLaunch(input);
666 if (
667 input.editor === "file-manager" &&
668 input.reveal === true &&
669 launch.command === "xdg-open" &&
670 (yield* HostProcess.Platform) === "linux" &&
671 (yield* tryRevealLinuxItem(launch.target))
672 ) {
673 return;
674 }
675 yield* launchEditorProcess(launch);
676});
677
678const GRAPHICAL_SESSION_ENV_KEYS: ReadonlySet<string> = new Set([
679 "DISPLAY",
680 "WAYLAND_DISPLAY",
681 "XAUTHORITY",
682]);
683
684// The user manager's environment over D-Bus. `systemctl show-environment` would
685// shell-quote values with spaces as $'...', while this JSON carries them raw.
686const decodeManagerEnvironment = Schema.decodeUnknownEffect(
687 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
688);
689
690// Boot services miss the desktop environment imported later into the systemd user manager.
691const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSessionEnv")(
692 function* () {
693 const hostEnv = yield* HostProcess.Environment;
694 if ((yield* HostProcess.Platform) !== "linux" || hasGraphicalLinuxSession(hostEnv)) {
695 return {};
696 }
697 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
698 const output = yield* spawner.string(
699 ChildProcess.make(
700 "busctl",
701 [
702 "--user",
703 "--json=short",
704 "get-property",
705 "org.freedesktop.systemd1",
706 "/org/freedesktop/systemd1",
707 "org.freedesktop.systemd1.Manager",
708 "Environment",
709 ],
710 { stdin: "ignore", stderr: "ignore" },
711 ),
712 );
713 const { data } = yield* decodeManagerEnvironment(output);
714 return Object.fromEntries(
715 data.flatMap((line) => {
716 const separator = line.indexOf("=");
717 const key = line.slice(0, separator);
718 return separator > 0 && GRAPHICAL_SESSION_ENV_KEYS.has(key)
719 ? [[key, line.slice(separator + 1)]]
720 : [];
721 }),
722 );
723 },
724 Effect.timeout("2 seconds"),
725 Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})),
726);
727
728const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
729 launch: ProcessLaunch,
730 onError: (cause: unknown) => ExternalLauncherError,
731): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
732 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
733 // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit.
734 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
735 const command = ChildProcess.make(launch.command, launch.args, {
736 ...launch.options,
737 env: { ...env, ...launch.options.env },
738 extendEnv: false,
739 });
740
741 yield* spawner.spawn(command).pipe(
742 Effect.flatMap((handle) => handle.unref),
743 Effect.asVoid,
744 Effect.scoped,
745 Effect.mapError(onError),
746 );
747});
748
749const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
750 target: string,
751): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
752 const launch = yield* resolveBrowserLaunch(target);
753 return yield* launchAndUnref(
754 launch,
755 (cause) =>
756 new ExternalLauncherBrowserSpawnError({
757 target,
758 command: launch.command,
759 args: launch.args,
760 cause,
761 }),
762 );
763});
764
765const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
766 launch: EditorLaunch,
767): Effect.fn.Return<
768 void,
769 ExternalLauncherError,
770 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
771> {
772 const env = yield* readCommandLookupEnv;
773 if (!(yield* isCommandAvailable(launch.command, { env }))) {
774 return yield* new ExternalLauncherCommandNotFoundError({
775 editor: launch.editor,
776 command: launch.command,
777 });
778 }
779
780 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
781 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
782 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
783 }
784 yield* launchAndUnref(
785 {
786 command: spawnCommand.command,
787 args: spawnCommand.args,
788 options: {
789 detached: launch.detached ?? true,
790 shell: spawnCommand.shell,
791 env: yield* readGraphicalSessionEnv(),
792 stdin: "ignore",
793 stdout: "ignore",
794 stderr: "ignore",
795 },
796 },
797 (cause) =>
798 new ExternalLauncherEditorSpawnError({
799 editor: launch.editor,
800 target: launch.target,
801 command: spawnCommand.command,
802 args: spawnCommand.args,
803 cause,
804 }),
805 );
806});
807
808/** @public */
809export const make = Effect.gen(function* () {
810 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
811 const fileSystem = yield* FileSystem.FileSystem;
812 const path = yield* Path.Path;
813
814 const provideCommandResolutionServices = <A, E, R>(
815 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
816 ) =>
817 effect.pipe(
818 Effect.provideService(FileSystem.FileSystem, fileSystem),
819 Effect.provideService(Path.Path, path),
820 );
821
822 const cachedAvailableEditors = yield* makeStaleWhileRevalidate(
823 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
824 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
825 ),
826 EDITOR_DISCOVERY_CACHE_TTL,
827 );
828 const cachedFileManagerRevealKind = yield* makeStaleWhileRevalidate(
829 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
830 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
831 ),
832 EDITOR_DISCOVERY_CACHE_TTL,
833 );
834
835 // Forwarders retain the underlying launcher and discovery spans.
836 return ExternalLauncher.of({
837 resolveAvailableEditors: Effect.fnUntraced(function* () {
838 return yield* cachedAvailableEditors;
839 }),
840 resolveFileManagerRevealKind: Effect.fnUntraced(function* () {
841 return yield* cachedFileManagerRevealKind;
842 }),
843 launchBrowser: Effect.fnUntraced(
844 function* (target) {
845 return yield* launchBrowser(target);
846 },
847 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
848 ),
849 launchEditor: Effect.fnUntraced(
850 function* (input) {
851 return yield* provideCommandResolutionServices(launchEditor(input));
852 },
853 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
854 ),
855 });
856});
857
858export const layer = Layer.effect(ExternalLauncher, make);