Open History to see the last commit
1import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2import * as NodePath from "@effect/platform-node/NodePath";
3import {
4 EDITORS,
5 ExternalLauncherError,
6 ExternalLauncherBrowserSpawnError,
7 ExternalLauncherCommandNotFoundError,
8 ExternalLauncherEditorSpawnError,
9 ExternalLauncherRevealTargetMissingError,
10 ExternalLauncherUnknownEditorError,
11 ExternalLauncherUnsupportedEditorError,
12 ExternalLauncherUnsupportedTargetError,
13 type EditorId,
14 type FileManagerRevealKind,
15 type LaunchEditorInput,
16} from "@t3tools/contracts";
17import { resolveEditorCommand } from "@t3tools/shared/editor";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
20import * as Config from "effect/Config";
21import * as Context from "effect/Context";
22import * as Effect from "effect/Effect";
23import * as Base64 from "effect/encoding/Base64";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as Schema from "effect/Schema";
29import * as Stream from "effect/Stream";
30import * as ChildProcess from "effect/process/ChildProcess";
31import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
32
33import { makeStaleWhileRevalidate } from "../environment/staleWhileRevalidate.ts";
34import { WindowsVerbatimSpawn } from "./windowsVerbatimSpawn.ts";
35export {
36 ExternalLauncherError,
37 ExternalLauncherBrowserSpawnError,
38 ExternalLauncherCommandNotFoundError,
39 ExternalLauncherEditorSpawnError,
40 ExternalLauncherRevealTargetMissingError,
41 ExternalLauncherUnknownEditorError,
42 ExternalLauncherUnsupportedEditorError,
43 ExternalLauncherUnsupportedTargetError,
44} from "@t3tools/contracts";
45export type { LaunchEditorInput };
46interface EditorLaunch {
47 readonly editor: EditorId;
48 readonly target: string;
49 readonly command: string;
50 readonly args: ReadonlyArray<string>;
51 readonly detached?: boolean;
52 readonly waitForExit?: boolean;
53}
54
55interface ProcessLaunch {
56 readonly command: string;
57 readonly args: ReadonlyArray<string>;
58 readonly options: ChildProcess.CommandOptions;
59 readonly waitForExit?: boolean;
60}
61
62interface TargetPathAndPosition {
63 readonly path: string;
64 readonly line: string;
65 readonly column: Option.Option<string>;
66}
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 });
138}
139
140function resolveCommandEditorArgs(
141 editor: (typeof EDITORS)[number],
142 target: string,
143 isDirectory: boolean,
144 projectRoot: string | undefined,
145 position: LaunchEditorInput["position"],
146): ReadonlyArray<string> {
147 const parsedTarget =
148 position === undefined
149 ? parseTargetPathAndPosition(target)
150 : Option.fromUndefinedOr(position.line).pipe(
151 Option.map((line) => ({
152 path: target,
153 line: String(line),
154 column: Option.fromUndefinedOr(position.column).pipe(Option.map(String)),
155 })),
156 );
157 const positionedTarget = Option.match(parsedTarget, {
158 onNone: () => target,
159 onSome: ({ path, line, column }) => [path, line, ...Option.toArray(column)].join(":"),
160 });
161
162 switch (editor.launchStyle) {
163 case "direct-path":
164 return [positionedTarget];
165 case "goto":
166 // An existing folder wins over a position: `build:2026` is a legal folder name.
167 // Without a window flag, VS Code's window settings may replace the user's last active window.
168 if (isDirectory) return ["--new-window", target];
169 // VS Code splits every numeric colon segment, including ones inside the filename.
170 if (
171 position !== undefined &&
172 target.split(":").some((segment) => !Number.isNaN(Number(segment)))
173 )
174 return [target];
175 return Option.isSome(parsedTarget) ? ["--goto", positionedTarget] : [target];
176 case "line-column":
177 return Option.match(parsedTarget, {
178 onNone: () => [target],
179 onSome: ({ path, line, column }) => [
180 // Only positioned targets get the root: a folder target would open as a second project.
181 ...(projectRoot === undefined ? [] : [projectRoot]),
182 "--line",
183 line,
184 // JetBrains IDEs count `--column` from 0; targets count columns from 1.
185 ...Option.match(column, {
186 onNone: () => [],
187 onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))],
188 }),
189 path,
190 ],
191 });
192 }
193}
194
195function encodeUtf16LeBase64(input: string): string {
196 const bytes = new Uint8Array(input.length * 2);
197 for (let index = 0; index < input.length; index += 1) {
198 const code = input.charCodeAt(index);
199 bytes[index * 2] = code & 0xff;
200 bytes[index * 2 + 1] = code >>> 8;
201 }
202 return Base64.encode(bytes);
203}
204
205function escapePowerShellStringLiteral(input: string): string {
206 // PowerShell also recognises typographic apostrophes as single-quote delimiters.
207 return `'${input.replace(/['\u2018-\u201b]/g, "$&$&")}'`;
208}
209
210function resolveWindowsRoot(env: NodeJS.ProcessEnv): string {
211 return env.SYSTEMROOT || env.windir || String.raw`C:\Windows`;
212}
213
214function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
215 return `${resolveWindowsRoot(env)}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
216}
217
218function resolveWslPowerShellPath(): string {
219 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
220}
221
222// WSL automount roots vary; resolve PowerShell via PATH to match launchEditor's availability check.
223const WSL_POWERSHELL_COMMAND = "powershell.exe";
224
225function shouldUseWindowsHostFromWsl(
226 platform: NodeJS.Platform,
227 env: NodeJS.ProcessEnv = {},
228): boolean {
229 return (
230 platform === "linux" &&
231 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
232 env.SSH_CONNECTION === undefined &&
233 env.SSH_TTY === undefined &&
234 env.container === undefined
235 );
236}
237
238function resolveWindowsBrowserLaunch(
239 target: string,
240 command: string,
241 detached: boolean,
242): ProcessLaunch {
243 const encodedCommand = encodeUtf16LeBase64(
244 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
245 );
246 return {
247 command,
248 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
249 options: {
250 detached,
251 shell: false,
252 stdin: "ignore",
253 stdout: "ignore",
254 stderr: "ignore",
255 },
256 };
257}
258
259function hasGraphicalLinuxSession(env: NodeJS.ProcessEnv): boolean {
260 return [env.DISPLAY, env.WAYLAND_DISPLAY].some(
261 (value) => value !== undefined && value.trim().length > 0,
262 );
263}
264
265function fileManagerCommandForPlatform(
266 platform: NodeJS.Platform,
267 env: NodeJS.ProcessEnv,
268): string | undefined {
269 switch (platform) {
270 case "darwin":
271 return "open";
272 case "win32":
273 return "explorer";
274 default:
275 if (shouldUseWindowsHostFromWsl(platform, env)) {
276 return env.WSL_DISTRO_NAME?.trim() ? "explorer.exe" : undefined;
277 }
278 return hasGraphicalLinuxSession(env) ? "xdg-open" : undefined;
279 }
280}
281
282// xdg-open needs an inode/directory handler or detached launches silently fail.
283// Bound xdg-mime below discovery's timeout so a hung probe drops only the file manager.
284const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
285
286const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
287 function* (
288 env: NodeJS.ProcessEnv,
289 ): Effect.fn.Return<
290 boolean,
291 never,
292 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
293 > {
294 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
295 return false;
296 }
297
298 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
299 return yield* spawner
300 .spawn(
301 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
302 stdin: "ignore",
303 stderr: "ignore",
304 }),
305 )
306 .pipe(
307 Effect.flatMap((handle) =>
308 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
309 concurrency: "unbounded",
310 }),
311 ),
312 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
313 Effect.scoped,
314 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
315 Effect.orElseSucceed(() => false),
316 );
317 },
318);
319
320const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
321 function* (
322 command: string,
323 env: NodeJS.ProcessEnv,
324 ): Effect.fn.Return<
325 boolean,
326 never,
327 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
328 > {
329 if (!(yield* isCommandAvailable(command, { env }))) {
330 return false;
331 }
332 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
333 },
334);
335
336// WSL may lack Explorer on PATH or a distro name while WSLg still offers a Linux file manager.
337const resolveUsableFileManagerCommand = Effect.fn(
338 "externalLauncher.resolveUsableFileManagerCommand",
339)(function* (
340 platform: NodeJS.Platform,
341 env: NodeJS.ProcessEnv,
342): Effect.fn.Return<
343 string | undefined,
344 never,
345 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
346> {
347 const command = fileManagerCommandForPlatform(platform, env);
348 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
349 return command;
350 }
351 if (
352 shouldUseWindowsHostFromWsl(platform, env) &&
353 hasGraphicalLinuxSession(env) &&
354 (yield* isUsableFileManagerCommand("xdg-open", env))
355 ) {
356 return "xdg-open";
357 }
358 return undefined;
359});
360
361// Reveal uses PowerShell on Windows/WSL, so probe it separately from Explorer availability.
362// Linux relies on the file-manager gate's handler probe; WSL re-probes because the gate may use Explorer.
363const fileManagerRevealKindForPlatform = Effect.fn(
364 "externalLauncher.fileManagerRevealKindForPlatform",
365)(function* (
366 platform: NodeJS.Platform,
367 env: NodeJS.ProcessEnv,
368): Effect.fn.Return<
369 FileManagerRevealKind | undefined,
370 never,
371 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
372> {
373 if (platform === "darwin") return "finder";
374 if (platform === "win32") {
375 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
376 ? "file-explorer"
377 : undefined;
378 }
379 if (shouldUseWindowsHostFromWsl(platform, env)) {
380 if (
381 env.WSL_DISTRO_NAME?.trim() &&
382 (yield* isCommandAvailable("explorer.exe", { env })) &&
383 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
384 ) {
385 return "file-explorer";
386 }
387 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
388 ? "files"
389 : undefined;
390 }
391 return hasGraphicalLinuxSession(env) ? "files" : undefined;
392});
393
394function wslUncFallbackPath(target: string, distroName: string): string {
395 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
396 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
397}
398
399// wslpath -w is mount-aware, so a drive remapped in /etc/wsl.conf resolves to the
400// real letter and a Linux path resolves to the \\wsl.localhost UNC path. Fall back
401// to the UNC form by hand when wslpath is missing or fails.
402export const resolveWslFileManagerPath = Effect.fn("externalLauncher.resolveWslFileManagerPath")(
403 function* (
404 target: string,
405 distroName: string,
406 ): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
407 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
408 return yield* spawner
409 .spawn(ChildProcess.make("wslpath", ["-w", target], { stdin: "ignore", stderr: "ignore" }))
410 .pipe(
411 Effect.flatMap((handle) =>
412 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
413 concurrency: "unbounded",
414 }),
415 ),
416 Effect.map(([stdout, exitCode]) => {
417 const translated = stdout.trim();
418 return exitCode === 0 && translated.length > 0
419 ? translated
420 : wslUncFallbackPath(target, distroName);
421 }),
422 Effect.scoped,
423 Effect.timeout("2 seconds"),
424 Effect.orElseSucceed(() => wslUncFallbackPath(target, distroName)),
425 );
426 },
427);
428
429function buildBrowserLaunch(
430 target: string,
431 platform: NodeJS.Platform,
432 env: NodeJS.ProcessEnv = {},
433): ProcessLaunch {
434 if (platform === "darwin") {
435 return {
436 command: "open",
437 args: [target],
438 options: DETACHED_IGNORE_STDIO_OPTIONS,
439 };
440 }
441
442 if (platform === "win32") {
443 return resolveWindowsBrowserLaunch(
444 target,
445 resolvePowerShellPath(env),
446 WINDOWS_POWERSHELL_DETACHED,
447 );
448 }
449
450 if (shouldUseWindowsHostFromWsl(platform, env)) {
451 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
452 }
453
454 return {
455 command: "xdg-open",
456 args: [target],
457 options: DETACHED_IGNORE_STDIO_OPTIONS,
458 };
459}
460
461const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
462 platform: NodeJS.Platform,
463 env: NodeJS.ProcessEnv,
464): Effect.fn.Return<
465 ReadonlyArray<EditorId>,
466 never,
467 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
468> {
469 const available: EditorId[] = [];
470
471 for (const editor of EDITORS) {
472 if (editor.commands === null) {
473 if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
474 available.push(editor.id);
475 }
476 continue;
477 }
478
479 const command = yield* resolveEditorCommand(editor, env);
480 if (Option.isSome(command)) {
481 available.push(editor.id);
482 }
483 }
484
485 return available;
486});
487
488const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
489 target: string,
490) {
491 const platform = yield* HostProcess.Platform;
492 const env = yield* readBrowserLaunchEnv;
493 return buildBrowserLaunch(target, platform, env);
494});
495
496// Editors and the file manager open on the desktop session, so a boot-started
497// server discovers and launches them with that session's display.
498const readEditorEnv = Effect.fn("externalLauncher.readEditorEnv")(function* () {
499 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
500 return hasGraphicalLinuxSession(env) ? env : { ...env, ...(yield* readGraphicalSessionEnv()) };
501});
502
503const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
504 const platform = yield* HostProcess.Platform;
505 const env = yield* readEditorEnv();
506 return yield* buildAvailableEditors(platform, env);
507});
508
509const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
510 function* () {
511 const platform = yield* HostProcess.Platform;
512 const env = yield* readEditorEnv();
513 return yield* fileManagerRevealKindForPlatform(platform, env);
514 },
515);
516
517const EDITOR_DISCOVERY_CACHE_TTL = "60 seconds";
518
519export class ExternalLauncher extends Context.Service<
520 ExternalLauncher,
521 {
522 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
523 /** Requires file-manager in resolveAvailableEditors; Linux relies on its directory-handler probe. */
524 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
525 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
526 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
527 }
528>()("t3/process/externalLauncher") {}
529
530const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
531 input: LaunchEditorInput,
532): Effect.fn.Return<
533 EditorLaunch,
534 ExternalLauncherError,
535 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
536> {
537 const platform = yield* HostProcess.Platform;
538 const env = yield* readEditorEnv();
539 yield* Effect.annotateCurrentSpan({
540 "externalLauncher.editor": input.editor,
541 "externalLauncher.cwd": input.cwd,
542 "externalLauncher.platform": platform,
543 });
544 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
545 if (!editorDef) {
546 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
547 }
548
549 const target = input.cwd;
550 let position = input.position;
551 if (editorDef.id === "zed" && position?.line !== undefined) {
552 // Zed resolves existing paths before positions, so ambiguous spellings must stay literal.
553 const collision =
554 /:\d+(?=:|$)/.test(target) ||
555 (yield* (yield* FileSystem.FileSystem)
556 .exists(`${target}:${position.line}${position.column ? `:${position.column}` : ""}`)
557 .pipe(Effect.orElseSucceed(() => true)));
558 if (collision) position = {};
559 }
560
561 if (editorDef.commands) {
562 const resolved = yield* resolveEditorCommand(editorDef, env);
563 if (Option.isNone(resolved)) {
564 return yield* new ExternalLauncherCommandNotFoundError({
565 editor: editorDef.id,
566 command: editorDef.commands[0],
567 });
568 }
569 const { command, baseArgs } = resolved.value;
570 const isDirectory =
571 editorDef.launchStyle === "goto" &&
572 (yield* (yield* FileSystem.FileSystem).stat(target).pipe(
573 Effect.map((info) => info.type === "Directory"),
574 Effect.orElseSucceed(() => false),
575 ));
576 return {
577 editor: editorDef.id,
578 target: input.cwd,
579 command,
580 args: [
581 ...baseArgs,
582 ...resolveCommandEditorArgs(editorDef, target, isDirectory, input.projectRoot, position),
583 ],
584 };
585 }
586
587 if (editorDef.id !== "file-manager") {
588 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
589 }
590
591 const command = yield* resolveUsableFileManagerCommand(platform, env);
592 if (command === undefined) {
593 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
594 }
595
596 if (input.reveal === true) {
597 // Explorer answers /select of a missing path by opening its default folder, not the parent.
598 const exists = yield* (yield* FileSystem.FileSystem)
599 .exists(target)
600 .pipe(Effect.orElseSucceed(() => true));
601 if (!exists) {
602 return yield* new ExternalLauncherRevealTargetMissingError({ editor: editorDef.id, target });
603 }
604 return yield* resolveFileManagerRevealLaunch(target, platform, env, command);
605 }
606
607 if (platform === "win32") {
608 // ShellExecute honours replacement folder handlers that explorer.exe bypasses.
609 return {
610 ...powerShellFileManagerLaunch(
611 target,
612 `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(normalizeWindowsFileManagerPath(target))}`,
613 resolvePowerShellPath(env),
614 ),
615 detached: WINDOWS_POWERSHELL_DETACHED,
616 };
617 }
618
619 return {
620 editor: editorDef.id,
621 target,
622 command,
623 args:
624 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
625 ? [yield* resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)]
626 : [target],
627 };
628});
629
630// Replacement managers can register under Directory, Drive, or Folder. Explorer
631// needs its /select argument passed verbatim through PowerShell because Node's
632// argument quoting changes how Explorer parses it.
633function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
634 const literal = escapePowerShellStringLiteral(target);
635 const folderClass = /^[a-z]:\\$/i.test(parent) ? "Drive" : "Directory";
636 // Explorer's ordinary open/explore handlers may also be explicit defaults.
637 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} + '"') }`;
638}
639
640function powerShellFileManagerLaunch(
641 target: string,
642 source: string,
643 powershellCommand: string,
644): EditorLaunch {
645 return {
646 editor: "file-manager",
647 target,
648 command: powershellCommand,
649 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
650 };
651}
652
653function normalizeWindowsFileManagerPath(target: string): string {
654 return target.replaceAll("/", "\\");
655}
656
657const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
658 target: string,
659 platform: NodeJS.Platform,
660 env: NodeJS.ProcessEnv,
661 command: string,
662): Effect.fn.Return<
663 EditorLaunch,
664 never,
665 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
666> {
667 if (platform === "darwin") {
668 // `open -R` reports targets Finder cannot reveal only through its exit status.
669 return {
670 editor: "file-manager",
671 target,
672 command: "open",
673 args: ["-R", target],
674 waitForExit: true,
675 };
676 }
677
678 if (platform === "win32") {
679 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
680 const windowsTarget = normalizeWindowsFileManagerPath(target);
681 return {
682 ...powerShellFileManagerLaunch(
683 target,
684 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
685 resolvePowerShellPath(env),
686 ),
687 detached: WINDOWS_POWERSHELL_DETACHED,
688 };
689 }
690
691 if (
692 command === "explorer.exe" &&
693 shouldUseWindowsHostFromWsl(platform, env) &&
694 env.WSL_DISTRO_NAME !== undefined
695 ) {
696 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
697 // WSL names may contain quotes that Explorer's /select cannot encode.
698 // Open the parent through the shell so replacement managers still apply.
699 const path = yield* Path.Path;
700 // .NET path parsing rejects characters that are legal in WSL filenames.
701 const [explorerTarget, parent] = yield* Effect.all(
702 [
703 resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME),
704 resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME),
705 ],
706 { concurrency: "unbounded" },
707 );
708 const source = explorerTarget.includes('"')
709 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
710 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
711 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
712 }
713 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
714 const path = yield* Path.Path;
715 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
716 }
717 const path = yield* Path.Path;
718 return {
719 editor: "file-manager",
720 target,
721 command: "explorer.exe",
722 args: [yield* resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
723 };
724 }
725
726 const path = yield* Path.Path;
727 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
728});
729
730const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
731 function* (target: string) {
732 const env = yield* readCommandLookupEnv;
733 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
734
735 const path = yield* Path.Path;
736 const uri = yield* path.toFileUrl(target);
737 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
738 const exitCode = yield* spawner.exitCode(
739 ChildProcess.make(
740 "gdbus",
741 [
742 "call",
743 "--session",
744 "--dest",
745 "org.freedesktop.FileManager1",
746 "--object-path",
747 "/org/freedesktop/FileManager1",
748 "--method",
749 "org.freedesktop.FileManager1.ShowItems",
750 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
751 `["${uri.href}"]`,
752 "",
753 ],
754 {
755 stdin: "ignore",
756 stdout: "ignore",
757 stderr: "ignore",
758 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
759 forceKillAfter: "1 second",
760 },
761 ),
762 );
763 return exitCode === 0;
764 },
765 Effect.timeout("2 seconds"),
766 Effect.catchTags({
767 BadArgument: () => Effect.succeed(false),
768 PlatformError: () => Effect.succeed(false),
769 TimeoutError: () => Effect.succeed(false),
770 }),
771);
772
773// Stock Windows answers "none"; any other verb may be a replacement file manager, which only
774// the PowerShell reveal honors. Reading stdout is about 600 ms faster than spawner.string here.
775const hasStockWindowsFolderVerb = Effect.fn("externalLauncher.hasStockWindowsFolderVerb")(
776 function* () {
777 const env = yield* readBrowserLaunchEnv;
778 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
779 const handle = yield* spawner.spawn(
780 ChildProcess.make(
781 `${resolveWindowsRoot(env)}\\System32\\reg.exe`,
782 ["query", "HKCR\\Directory\\shell", "/ve"],
783 { stdin: "ignore", stderr: "ignore" },
784 ),
785 );
786 const [stdout, exitCode] = yield* Effect.all(
787 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
788 { concurrency: "unbounded" },
789 );
790 return exitCode === 0 && /REG_SZ\s+none\s*$/im.test(stdout);
791 },
792 Effect.scoped,
793 Effect.timeout("2 seconds"),
794 Effect.orElseSucceed(() => false),
795);
796
797// Explorer parses /select itself, so it needs the argument verbatim rather than Node's quoting.
798const revealWindowsItem = Effect.fn("externalLauncher.revealWindowsItem")(function* (
799 target: string,
800) {
801 const command = `${resolveWindowsRoot(yield* readBrowserLaunchEnv)}\\explorer.exe`;
802 const args = [`/select,"${normalizeWindowsFileManagerPath(target)}"`];
803 yield* (yield* WindowsVerbatimSpawn)(command, args).pipe(
804 Effect.mapError(
805 (cause) =>
806 new ExternalLauncherEditorSpawnError({
807 editor: "file-manager",
808 target,
809 command,
810 args,
811 cause,
812 }),
813 ),
814 );
815});
816
817const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
818 input: LaunchEditorInput,
819 hasStockFolderVerb: Effect.Effect<boolean>,
820) {
821 // Clients send `~/` host paths as written, and launches run without a shell to expand them.
822 const home = yield* HostProcess.HomeDirectory;
823 const cwd = expandHomePath(input.cwd, home);
824 const projectRoot =
825 input.projectRoot === undefined ? undefined : expandHomePath(input.projectRoot, home);
826 const launch = yield* resolveEditorLaunch({ ...input, cwd, projectRoot });
827 if (input.editor === "file-manager" && input.reveal === true) {
828 const platform = yield* HostProcess.Platform;
829 if (
830 platform === "linux" &&
831 launch.command === "xdg-open" &&
832 (yield* tryRevealLinuxItem(launch.target))
833 ) {
834 return;
835 }
836 if (platform === "win32" && (yield* hasStockFolderVerb)) {
837 return yield* revealWindowsItem(launch.target);
838 }
839 }
840 yield* launchEditorProcess(launch);
841});
842
843const GRAPHICAL_SESSION_ENV_KEYS: ReadonlySet<string> = new Set([
844 "DISPLAY",
845 "WAYLAND_DISPLAY",
846 "XAUTHORITY",
847]);
848
849// The user manager's environment over D-Bus. `systemctl show-environment` would
850// shell-quote values with spaces as $'...', while this JSON carries them raw.
851const decodeManagerEnvironment = Schema.decodeUnknownEffect(
852 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
853);
854
855// Boot services miss the desktop environment imported later into the systemd user manager.
856const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSessionEnv")(
857 function* () {
858 const hostEnv = yield* HostProcess.Environment;
859 if ((yield* HostProcess.Platform) !== "linux" || hasGraphicalLinuxSession(hostEnv)) {
860 return {};
861 }
862 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
863 const output = yield* spawner.string(
864 ChildProcess.make(
865 "busctl",
866 [
867 "--user",
868 "--json=short",
869 "get-property",
870 "org.freedesktop.systemd1",
871 "/org/freedesktop/systemd1",
872 "org.freedesktop.systemd1.Manager",
873 "Environment",
874 ],
875 { stdin: "ignore", stderr: "ignore" },
876 ),
877 );
878 const { data } = yield* decodeManagerEnvironment(output);
879 return Object.fromEntries(
880 data.flatMap((line) => {
881 const separator = line.indexOf("=");
882 const key = line.slice(0, separator);
883 return separator > 0 && GRAPHICAL_SESSION_ENV_KEYS.has(key)
884 ? [[key, line.slice(separator + 1)]]
885 : [];
886 }),
887 );
888 },
889 Effect.timeout("2 seconds"),
890 Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})),
891);
892
893const launchProcess = Effect.fn("externalLauncher.launchProcess")(function* (
894 launch: ProcessLaunch,
895 onError: (cause: unknown) => ExternalLauncherError,
896): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
897 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
898 // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit.
899 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
900 const command = ChildProcess.make(launch.command, launch.args, {
901 ...launch.options,
902 env: { ...env, ...launch.options.env },
903 extendEnv: false,
904 });
905
906 if (launch.waitForExit) {
907 const exitCode = yield* spawner.exitCode(command).pipe(Effect.mapError(onError));
908 if (exitCode !== 0) {
909 return yield* onError(new Error(`${launch.command} exited with status ${exitCode}`));
910 }
911 return;
912 }
913
914 yield* spawner.spawn(command).pipe(
915 Effect.flatMap((handle) => handle.unref),
916 Effect.asVoid,
917 Effect.scoped,
918 Effect.mapError(onError),
919 );
920});
921
922const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
923 target: string,
924): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
925 const launch = yield* resolveBrowserLaunch(target);
926 return yield* launchProcess(
927 launch,
928 (cause) =>
929 new ExternalLauncherBrowserSpawnError({
930 target,
931 command: launch.command,
932 args: launch.args,
933 cause,
934 }),
935 );
936});
937
938const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
939 launch: EditorLaunch,
940): Effect.fn.Return<
941 void,
942 ExternalLauncherError,
943 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
944> {
945 const env = yield* readCommandLookupEnv;
946 if (!(yield* isCommandAvailable(launch.command, { env }))) {
947 return yield* new ExternalLauncherCommandNotFoundError({
948 editor: launch.editor,
949 command: launch.command,
950 });
951 }
952
953 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
954 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
955 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
956 }
957 yield* launchProcess(
958 {
959 command: spawnCommand.command,
960 args: spawnCommand.args,
961 waitForExit: launch.waitForExit ?? false,
962 options: {
963 detached: launch.detached ?? true,
964 shell: spawnCommand.shell,
965 env: yield* readGraphicalSessionEnv(),
966 stdin: "ignore",
967 stdout: "ignore",
968 stderr: "ignore",
969 },
970 },
971 (cause) =>
972 new ExternalLauncherEditorSpawnError({
973 editor: launch.editor,
974 target: launch.target,
975 command: spawnCommand.command,
976 args: spawnCommand.args,
977 cause,
978 }),
979 );
980});
981
982/** @public */
983export const make = Effect.gen(function* () {
984 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
985 const fileSystem = yield* FileSystem.FileSystem;
986 const path = yield* Path.Path;
987
988 const provideCommandResolutionServices = <A, E, R>(
989 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
990 ) =>
991 effect.pipe(
992 Effect.provideService(FileSystem.FileSystem, fileSystem),
993 Effect.provideService(Path.Path, path),
994 );
995
996 const cachedAvailableEditors = yield* makeStaleWhileRevalidate(
997 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
998 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
999 ),
1000 EDITOR_DISCOVERY_CACHE_TTL,
1001 );
1002 const cachedFileManagerRevealKind = yield* makeStaleWhileRevalidate(
1003 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
1004 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1005 ),
1006 EDITOR_DISCOVERY_CACHE_TTL,
1007 );
1008 const cachedStockWindowsFolderVerb = yield* makeStaleWhileRevalidate(
1009 hasStockWindowsFolderVerb().pipe(
1010 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1011 ),
1012 EDITOR_DISCOVERY_CACHE_TTL,
1013 );
1014
1015 // Forwarders retain the underlying launcher and discovery spans.
1016 return ExternalLauncher.of({
1017 resolveAvailableEditors: Effect.fnUntraced(function* () {
1018 return yield* cachedAvailableEditors;
1019 }),
1020 resolveFileManagerRevealKind: Effect.fnUntraced(function* () {
1021 return yield* cachedFileManagerRevealKind;
1022 }),
1023 launchBrowser: Effect.fnUntraced(
1024 function* (target) {
1025 return yield* launchBrowser(target);
1026 },
1027 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1028 ),
1029 launchEditor: Effect.fnUntraced(
1030 function* (input) {
1031 return yield* provideCommandResolutionServices(
1032 launchEditor(input, cachedStockWindowsFolderVerb),
1033 );
1034 },
1035 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1036 ),
1037 });
1038});
1039
1040export const layer = Layer.effect(ExternalLauncher, make);