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