Open History to see the last commit
1import * as NodePath from "@effect/platform-node/NodePath";
2import {
3 EDITORS,
4 ExternalLauncherError,
5 ExternalLauncherBrowserSpawnError,
6 ExternalLauncherCommandNotFoundError,
7 ExternalLauncherEditorSpawnError,
8 ExternalLauncherUnknownEditorError,
9 ExternalLauncherUnsupportedEditorError,
10 ExternalLauncherUnsupportedTargetError,
11 type EditorId,
12 type FileManagerRevealKind,
13 type LaunchEditorInput,
14} from "@t3tools/contracts";
15import { resolveEditorCommand } from "@t3tools/shared/editor";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import {
18 isCommandAvailable,
19 resolveSpawnCommand,
20 withPathDirectoryListings,
21} from "@t3tools/shared/shell";
22import * as Clock from "effect/Clock";
23import * as Config from "effect/Config";
24import * as Context from "effect/Context";
25import * as Deferred from "effect/Deferred";
26import * as Effect from "effect/Effect";
27import * as Base64 from "effect/encoding/Base64";
28import * as Exit from "effect/Exit";
29import * as FileSystem from "effect/FileSystem";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as Ref from "effect/Ref";
34import * as Scope from "effect/Scope";
35import * as Stream from "effect/Stream";
36import * as ChildProcess from "effect/process/ChildProcess";
37import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
38
39export {
40 ExternalLauncherError,
41 ExternalLauncherBrowserSpawnError,
42 ExternalLauncherCommandNotFoundError,
43 ExternalLauncherEditorSpawnError,
44 ExternalLauncherUnknownEditorError,
45 ExternalLauncherUnsupportedEditorError,
46 ExternalLauncherUnsupportedTargetError,
47} from "@t3tools/contracts";
48export type { LaunchEditorInput };
49interface EditorLaunch {
50 readonly editor: EditorId;
51 readonly target: string;
52 readonly command: string;
53 readonly args: ReadonlyArray<string>;
54 readonly detached?: boolean;
55}
56
57interface ProcessLaunch {
58 readonly command: string;
59 readonly args: ReadonlyArray<string>;
60 readonly options: ChildProcess.CommandOptions;
61}
62
63interface TargetPathAndPosition {
64 readonly path: string;
65 readonly line: string;
66 readonly column: Option.Option<string>;
67}
68
69// cmd shims reparse %* after escaping is gone; newlines and quotes can expose shell operators.
70// oxlint-disable-next-line no-control-regex
71const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
72const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
73const POWERSHELL_ARGUMENTS_PREFIX = [
74 "-NoProfile",
75 "-NonInteractive",
76 "-ExecutionPolicy",
77 "Bypass",
78 "-EncodedCommand",
79] as const;
80
81// Detached Windows PowerShell exits 0 without executing; only WSL interop keeps detached launches.
82const WINDOWS_POWERSHELL_DETACHED = false;
83
84const DETACHED_IGNORE_STDIO_OPTIONS = {
85 detached: true,
86 stdin: "ignore",
87 stdout: "ignore",
88 stderr: "ignore",
89} as const satisfies ChildProcess.CommandOptions;
90
91const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
92 Object.fromEntries(
93 Object.entries(input).flatMap(([key, value]) =>
94 Option.match(value, {
95 onNone: () => [],
96 onSome: (resolved) => [[key, resolved]],
97 }),
98 ),
99 );
100
101const BrowserLaunchEnvConfig = Config.all({
102 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
103 windir: Config.String("windir").pipe(Config.option),
104 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
105 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
106 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
107 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
108 container: Config.String("container").pipe(Config.option),
109 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
110 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
111}).pipe(Config.map(compactEnv));
112
113const CommandLookupEnvConfig = Config.all({
114 PATH: Config.String("PATH").pipe(Config.option),
115 Path: Config.String("Path").pipe(Config.option),
116 path: Config.String("path").pipe(Config.option),
117 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
118 HOME: Config.String("HOME").pipe(Config.option),
119 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
120 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
121 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
122 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
123 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
124}).pipe(Config.map(compactEnv));
125
126const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
127const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
128
129function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
130 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
131 if (!match?.[1] || !match[2]) {
132 return Option.none();
133 }
134
135 return Option.some({
136 path: match[1],
137 line: match[2],
138 column: Option.fromUndefinedOr(match[3]),
139 });
140}
141
142function resolveCommandEditorArgs(
143 editor: (typeof EDITORS)[number],
144 target: string,
145): ReadonlyArray<string> {
146 const parsedTarget = parseTargetPathAndPosition(target);
147
148 switch (editor.launchStyle) {
149 case "direct-path":
150 return [target];
151 case "goto":
152 return Option.isSome(parsedTarget) ? ["--goto", 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
450// Shared scans must survive caller timeouts/disconnects; monotonic expiry prevents clock rollback extending stale entries.
451const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
452
453interface EditorDiscoveryCacheEntry {
454 readonly scan: Deferred.Deferred<ReadonlyArray<EditorId>>;
455 readonly expiresAtNanos: bigint | undefined;
456}
457
458export class ExternalLauncher extends Context.Service<
459 ExternalLauncher,
460 {
461 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
462 /** Requires file-manager in resolveAvailableEditors; Linux relies on its directory-handler probe. */
463 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
464 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
465 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
466 }
467>()("t3/process/externalLauncher") {}
468
469const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
470 input: LaunchEditorInput,
471): Effect.fn.Return<
472 EditorLaunch,
473 ExternalLauncherError,
474 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
475> {
476 const platform = yield* HostProcess.Platform;
477 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
478 yield* Effect.annotateCurrentSpan({
479 "externalLauncher.editor": input.editor,
480 "externalLauncher.cwd": input.cwd,
481 "externalLauncher.platform": platform,
482 });
483 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
484 if (!editorDef) {
485 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
486 }
487
488 if (editorDef.commands) {
489 const { command, baseArgs } = Option.getOrElse(
490 yield* resolveEditorCommand(editorDef, env),
491 () => ({
492 command: editorDef.commands[0],
493 baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [],
494 }),
495 );
496 return {
497 editor: editorDef.id,
498 target: input.cwd,
499 command,
500 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)],
501 };
502 }
503
504 if (editorDef.id !== "file-manager") {
505 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
506 }
507
508 const command = yield* resolveUsableFileManagerCommand(platform, env);
509 if (command === undefined) {
510 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
511 }
512
513 if (input.reveal === true) {
514 return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
515 }
516
517 return {
518 editor: editorDef.id,
519 target: input.cwd,
520 command,
521 args:
522 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
523 ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
524 : platform === "win32"
525 ? // Explorer interprets / as a switch and silently opens a fallback folder.
526 [normalizeWindowsFileManagerPath(input.cwd)]
527 : [input.cwd],
528 };
529});
530
531// A replacement manager registers a default Directory shell verb; stock Windows
532// uses "none". Explorer needs its /select argument passed verbatim through
533// PowerShell because Node's argument quoting changes how Explorer parses it.
534function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
535 const literal = escapePowerShellStringLiteral(target);
536 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} + '"') }`;
537}
538
539function powerShellFileManagerLaunch(
540 target: string,
541 source: string,
542 powershellCommand: string,
543): EditorLaunch {
544 return {
545 editor: "file-manager",
546 target,
547 command: powershellCommand,
548 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
549 };
550}
551
552function normalizeWindowsFileManagerPath(target: string): string {
553 return target.replaceAll("/", "\\");
554}
555
556const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
557 target: string,
558 platform: NodeJS.Platform,
559 env: NodeJS.ProcessEnv,
560 command: string,
561): Effect.fn.Return<
562 EditorLaunch,
563 never,
564 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
565> {
566 if (platform === "darwin") {
567 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
568 }
569
570 if (platform === "win32") {
571 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
572 const windowsTarget = normalizeWindowsFileManagerPath(target);
573 return {
574 ...powerShellFileManagerLaunch(
575 target,
576 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
577 resolvePowerShellPath(env),
578 ),
579 detached: WINDOWS_POWERSHELL_DETACHED,
580 };
581 }
582
583 if (
584 command === "explorer.exe" &&
585 shouldUseWindowsHostFromWsl(platform, env) &&
586 env.WSL_DISTRO_NAME !== undefined
587 ) {
588 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
589 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
590 // WSL names may contain quotes that Explorer's /select cannot encode.
591 // Open the parent through the shell so replacement managers still apply.
592 const path = yield* Path.Path;
593 // .NET path parsing rejects characters that are legal in WSL filenames.
594 const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME);
595 const source = explorerTarget.includes('"')
596 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
597 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
598 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
599 }
600 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
601 const path = yield* Path.Path;
602 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
603 }
604 const path = yield* Path.Path;
605 return {
606 editor: "file-manager",
607 target,
608 command: "explorer.exe",
609 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
610 };
611 }
612
613 const path = yield* Path.Path;
614 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
615});
616
617const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
618 function* (target: string) {
619 const env = yield* readCommandLookupEnv;
620 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
621
622 const path = yield* Path.Path;
623 const uri = yield* path.toFileUrl(target);
624 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
625 const exitCode = yield* spawner.exitCode(
626 ChildProcess.make(
627 "gdbus",
628 [
629 "call",
630 "--session",
631 "--dest",
632 "org.freedesktop.FileManager1",
633 "--object-path",
634 "/org/freedesktop/FileManager1",
635 "--method",
636 "org.freedesktop.FileManager1.ShowItems",
637 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
638 `["${uri.href}"]`,
639 "",
640 ],
641 {
642 stdin: "ignore",
643 stdout: "ignore",
644 stderr: "ignore",
645 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
646 forceKillAfter: "1 second",
647 },
648 ),
649 );
650 return exitCode === 0;
651 },
652 Effect.timeout("2 seconds"),
653 Effect.catchTags({
654 BadArgument: () => Effect.succeed(false),
655 PlatformError: () => Effect.succeed(false),
656 TimeoutError: () => Effect.succeed(false),
657 }),
658);
659
660const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
661 input: LaunchEditorInput,
662) {
663 const launch = yield* resolveEditorLaunch(input);
664 if (
665 input.editor === "file-manager" &&
666 input.reveal === true &&
667 launch.command === "xdg-open" &&
668 (yield* HostProcess.Platform) === "linux" &&
669 (yield* tryRevealLinuxItem(launch.target))
670 ) {
671 return;
672 }
673 yield* launchEditorProcess(launch);
674});
675
676const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
677 launch: ProcessLaunch,
678 onError: (cause: unknown) => ExternalLauncherError,
679): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
680 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
681 // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit.
682 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
683 const command = ChildProcess.make(launch.command, launch.args, {
684 ...launch.options,
685 env,
686 extendEnv: false,
687 });
688
689 yield* spawner.spawn(command).pipe(
690 Effect.flatMap((handle) => handle.unref),
691 Effect.asVoid,
692 Effect.scoped,
693 Effect.mapError(onError),
694 );
695});
696
697const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
698 target: string,
699): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
700 const launch = yield* resolveBrowserLaunch(target);
701 return yield* launchAndUnref(
702 launch,
703 (cause) =>
704 new ExternalLauncherBrowserSpawnError({
705 target,
706 command: launch.command,
707 args: launch.args,
708 cause,
709 }),
710 );
711});
712
713const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
714 launch: EditorLaunch,
715): Effect.fn.Return<
716 void,
717 ExternalLauncherError,
718 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
719> {
720 const env = yield* readCommandLookupEnv;
721 if (!(yield* isCommandAvailable(launch.command, { env }))) {
722 return yield* new ExternalLauncherCommandNotFoundError({
723 editor: launch.editor,
724 command: launch.command,
725 });
726 }
727
728 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
729 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
730 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
731 }
732 yield* launchAndUnref(
733 {
734 command: spawnCommand.command,
735 args: spawnCommand.args,
736 options: {
737 detached: launch.detached ?? true,
738 shell: spawnCommand.shell,
739 stdin: "ignore",
740 stdout: "ignore",
741 stderr: "ignore",
742 },
743 },
744 (cause) =>
745 new ExternalLauncherEditorSpawnError({
746 editor: launch.editor,
747 target: launch.target,
748 command: spawnCommand.command,
749 args: spawnCommand.args,
750 cause,
751 }),
752 );
753});
754
755/** @public */
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 scope = yield* Scope.Scope;
770 const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
771 Option.none(),
772 );
773 const runEditorDiscovery = (scan: Deferred.Deferred<ReadonlyArray<EditorId>>) =>
774 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
775 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
776 Effect.onExit((exit) =>
777 Effect.gen(function* () {
778 const expiresAtNanos =
779 (yield* Clock.monotonicTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS;
780 yield* Ref.update(editorDiscoveryCache, (current) =>
781 Option.isNone(current) || current.value.scan !== scan
782 ? current
783 : Exit.isSuccess(exit)
784 ? Option.some({ scan, expiresAtNanos })
785 : Option.none(),
786 );
787 yield* Deferred.done(scan, exit);
788 }),
789 ),
790 Effect.interruptible,
791 Effect.forkIn(scope),
792 );
793 // Claim and start atomically; interruption between them would leave an entry waiting on no scan.
794 const acquireEditorDiscovery = Effect.gen(function* () {
795 const nowNanos = yield* Clock.monotonicTimeNanos;
796 const [scan, isNewScan] = yield* Ref.modify(
797 editorDiscoveryCache,
798 (
799 current,
800 ): [
801 [EditorDiscoveryCacheEntry["scan"], boolean],
802 Option.Option<EditorDiscoveryCacheEntry>,
803 ] => {
804 if (
805 Option.isSome(current) &&
806 (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos)
807 ) {
808 return [[current.value.scan, false], current];
809 }
810 const scan = Deferred.makeUnsafe<ReadonlyArray<EditorId>>();
811 return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })];
812 },
813 );
814 if (isNewScan) {
815 yield* runEditorDiscovery(scan);
816 }
817 return scan;
818 }).pipe(Effect.uninterruptible);
819 const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);
820
821 return ExternalLauncher.of({
822 resolveAvailableEditors: () => cachedAvailableEditors,
823 resolveFileManagerRevealKind: () =>
824 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
825 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
826 ),
827 launchBrowser: (target) =>
828 launchBrowser(target).pipe(
829 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
830 ),
831 launchEditor: (input) =>
832 provideCommandResolutionServices(launchEditor(input)).pipe(
833 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
834 ),
835 });
836});
837
838export const layer = Layer.effect(ExternalLauncher, make);