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