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

externalLauncher.ts

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