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

externalLauncher.ts

846 lines28.2 KB

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