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

externalLauncher.ts

939 lines32.0 KB

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