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 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
528 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
529 }
530>()("t3/process/externalLauncher") {}
531
532const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
533 input: LaunchEditorInput,
534): Effect.fn.Return<
535 EditorLaunch,
536 ExternalLauncherError,
537 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
538> {
539 const platform = yield* HostProcess.Platform;
540 const env = yield* readEditorEnv();
541 yield* Effect.annotateCurrentSpan({
542 "externalLauncher.editor": input.editor,
543 "externalLauncher.cwd": input.cwd,
544 "externalLauncher.platform": platform,
545 });
546 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
547 if (!editorDef) {
548 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
549 }
550
551 const target = input.cwd;
552 let position = input.position;
553 if (editorDef.id === "zed" && position?.line !== undefined) {
554 // Zed resolves existing paths before positions, so ambiguous spellings must stay literal.
555 const collision =
556 /:\d+(?=:|$)/.test(target) ||
557 (yield* (yield* FileSystem.FileSystem)
558 .exists(`${target}:${position.line}${position.column ? `:${position.column}` : ""}`)
559 .pipe(Effect.orElseSucceed(() => true)));
560 if (collision) position = {};
561 }
562
563 if (editorDef.commands) {
564 const resolved = yield* resolveEditorCommand(editorDef, env);
565 if (Option.isNone(resolved)) {
566 return yield* new ExternalLauncherCommandNotFoundError({
567 editor: editorDef.id,
568 command: editorDef.commands[0],
569 });
570 }
571 const { command, baseArgs } = resolved.value;
572 const isDirectory =
573 editorDef.launchStyle === "goto" &&
574 (yield* (yield* FileSystem.FileSystem).stat(target).pipe(
575 Effect.map((info) => info.type === "Directory"),
576 Effect.orElseSucceed(() => false),
577 ));
578 return {
579 editor: editorDef.id,
580 target: input.cwd,
581 command,
582 args: [
583 ...baseArgs,
584 ...resolveCommandEditorArgs(editorDef, target, isDirectory, input.projectRoot, position),
585 ],
586 };
587 }
588
589 if (editorDef.id !== "file-manager") {
590 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
591 }
592
593 const command = yield* resolveUsableFileManagerCommand(platform, env);
594 if (command === undefined) {
595 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
596 }
597
598 if (input.reveal === true) {
599 // Explorer answers /select of a missing path by opening its default folder, not the parent.
600 const exists = yield* (yield* FileSystem.FileSystem)
601 .exists(target)
602 .pipe(Effect.orElseSucceed(() => true));
603 if (!exists) {
604 return yield* new ExternalLauncherRevealTargetMissingError({ editor: editorDef.id, target });
605 }
606 return yield* resolveFileManagerRevealLaunch(target, platform, env, command);
607 }
608
609 if (platform === "win32") {
610 // ShellExecute honours replacement folder handlers that explorer.exe bypasses.
611 return {
612 ...powerShellFileManagerLaunch(
613 target,
614 `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(normalizeWindowsFileManagerPath(target))}`,
615 resolvePowerShellPath(env),
616 ),
617 detached: WINDOWS_POWERSHELL_DETACHED,
618 };
619 }
620
621 return {
622 editor: editorDef.id,
623 target,
624 command,
625 args:
626 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
627 ? [yield* resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)]
628 : [target],
629 };
630});
631
632// Replacement managers can register under Directory, Drive, or Folder. Explorer
633// needs its /select argument passed verbatim through PowerShell because Node's
634// argument quoting changes how Explorer parses it.
635function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
636 const literal = escapePowerShellStringLiteral(target);
637 const folderClass = /^[a-z]:\\$/i.test(parent) ? "Drive" : "Directory";
638 // Explorer's ordinary open/explore handlers may also be explicit defaults.
639 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} + '"') }`;
640}
641
642function powerShellFileManagerLaunch(
643 target: string,
644 source: string,
645 powershellCommand: string,
646): EditorLaunch {
647 return {
648 editor: "file-manager",
649 target,
650 command: powershellCommand,
651 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
652 };
653}
654
655function normalizeWindowsFileManagerPath(target: string): string {
656 return target.replaceAll("/", "\\");
657}
658
659const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
660 target: string,
661 platform: NodeJS.Platform,
662 env: NodeJS.ProcessEnv,
663 command: string,
664): Effect.fn.Return<
665 EditorLaunch,
666 never,
667 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
668> {
669 if (platform === "darwin") {
670 // `open -R` reports targets Finder cannot reveal only through its exit status.
671 return {
672 editor: "file-manager",
673 target,
674 command: "open",
675 args: ["-R", target],
676 waitForExit: true,
677 };
678 }
679
680 if (platform === "win32") {
681 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
682 const windowsTarget = normalizeWindowsFileManagerPath(target);
683 return {
684 ...powerShellFileManagerLaunch(
685 target,
686 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
687 resolvePowerShellPath(env),
688 ),
689 detached: WINDOWS_POWERSHELL_DETACHED,
690 };
691 }
692
693 if (
694 command === "explorer.exe" &&
695 shouldUseWindowsHostFromWsl(platform, env) &&
696 env.WSL_DISTRO_NAME !== undefined
697 ) {
698 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
699 // WSL names may contain quotes that Explorer's /select cannot encode.
700 // Open the parent through the shell so replacement managers still apply.
701 const path = yield* Path.Path;
702 // .NET path parsing rejects characters that are legal in WSL filenames.
703 const [explorerTarget, parent] = yield* Effect.all(
704 [
705 resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME),
706 resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME),
707 ],
708 { concurrency: "unbounded" },
709 );
710 const source = explorerTarget.includes('"')
711 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
712 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
713 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
714 }
715 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
716 const path = yield* Path.Path;
717 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
718 }
719 const path = yield* Path.Path;
720 return {
721 editor: "file-manager",
722 target,
723 command: "explorer.exe",
724 args: [yield* resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
725 };
726 }
727
728 const path = yield* Path.Path;
729 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
730});
731
732const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
733 function* (target: string) {
734 const env = yield* readCommandLookupEnv;
735 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
736
737 const path = yield* Path.Path;
738 const uri = yield* path.toFileUrl(target);
739 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
740 const exitCode = yield* spawner.exitCode(
741 ChildProcess.make(
742 "gdbus",
743 [
744 "call",
745 "--session",
746 "--dest",
747 "org.freedesktop.FileManager1",
748 "--object-path",
749 "/org/freedesktop/FileManager1",
750 "--method",
751 "org.freedesktop.FileManager1.ShowItems",
752 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
753 `["${uri.href}"]`,
754 "",
755 ],
756 {
757 stdin: "ignore",
758 stdout: "ignore",
759 stderr: "ignore",
760 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
761 forceKillAfter: "1 second",
762 },
763 ),
764 );
765 return exitCode === 0;
766 },
767 Effect.timeout("2 seconds"),
768 Effect.catchTags({
769 BadArgument: () => Effect.succeed(false),
770 PlatformError: () => Effect.succeed(false),
771 TimeoutError: () => Effect.succeed(false),
772 }),
773);
774
775// Stock Windows answers "none"; any other verb may be a replacement file manager, which only
776// the PowerShell reveal honors. Reading stdout is about 600 ms faster than spawner.string here.
777const hasStockWindowsFolderVerb = Effect.fn("externalLauncher.hasStockWindowsFolderVerb")(
778 function* () {
779 const env = yield* readBrowserLaunchEnv;
780 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
781 const handle = yield* spawner.spawn(
782 ChildProcess.make(
783 `${resolveWindowsRoot(env)}\\System32\\reg.exe`,
784 ["query", "HKCR\\Directory\\shell", "/ve"],
785 { stdin: "ignore", stderr: "ignore" },
786 ),
787 );
788 const [stdout, exitCode] = yield* Effect.all(
789 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
790 { concurrency: "unbounded" },
791 );
792 return exitCode === 0 && /REG_SZ\s+none\s*$/im.test(stdout);
793 },
794 Effect.scoped,
795 Effect.timeout("2 seconds"),
796 Effect.orElseSucceed(() => false),
797);
798
799// Explorer parses /select itself, so it needs the argument verbatim rather than Node's quoting.
800const revealWindowsItem = Effect.fn("externalLauncher.revealWindowsItem")(function* (
801 target: string,
802) {
803 const command = `${resolveWindowsRoot(yield* readBrowserLaunchEnv)}\\explorer.exe`;
804 const args = [`/select,"${normalizeWindowsFileManagerPath(target)}"`];
805 yield* (yield* WindowsVerbatimSpawn)(command, args).pipe(
806 Effect.mapError(
807 (cause) =>
808 new ExternalLauncherEditorSpawnError({
809 editor: "file-manager",
810 target,
811 command,
812 args,
813 cause,
814 }),
815 ),
816 );
817});
818
819const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
820 input: LaunchEditorInput,
821 hasStockFolderVerb: Effect.Effect<boolean>,
822) {
823 // Clients send `~/` host paths as written, and launches run without a shell to expand them.
824 const home = yield* HostProcess.HomeDirectory;
825 const cwd = expandHomePath(input.cwd, home);
826 const projectRoot =
827 input.projectRoot === undefined ? undefined : expandHomePath(input.projectRoot, home);
828 const launch = yield* resolveEditorLaunch({ ...input, cwd, projectRoot });
829 if (input.editor === "file-manager" && input.reveal === true) {
830 const platform = yield* HostProcess.Platform;
831 if (
832 platform === "linux" &&
833 launch.command === "xdg-open" &&
834 (yield* tryRevealLinuxItem(launch.target))
835 ) {
836 return;
837 }
838 if (platform === "win32" && (yield* hasStockFolderVerb)) {
839 return yield* revealWindowsItem(launch.target);
840 }
841 }
842 yield* launchEditorProcess(launch);
843});
844
845const GRAPHICAL_SESSION_ENV_KEYS: ReadonlySet<string> = new Set([
846 "DISPLAY",
847 "WAYLAND_DISPLAY",
848 "XAUTHORITY",
849]);
850
851// The user manager's environment over D-Bus. `systemctl show-environment` would
852// shell-quote values with spaces as $'...', while this JSON carries them raw.
853const decodeManagerEnvironment = Schema.decodeUnknownEffect(
854 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
855);
856
857// Boot services miss the desktop environment imported later into the systemd user manager.
858const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSessionEnv")(
859 function* () {
860 const hostEnv = yield* HostProcess.Environment;
861 if ((yield* HostProcess.Platform) !== "linux" || hasGraphicalLinuxSession(hostEnv)) {
862 return {};
863 }
864 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
865 const output = yield* spawner.string(
866 ChildProcess.make(
867 "busctl",
868 [
869 "--user",
870 "--json=short",
871 "get-property",
872 "org.freedesktop.systemd1",
873 "/org/freedesktop/systemd1",
874 "org.freedesktop.systemd1.Manager",
875 "Environment",
876 ],
877 { stdin: "ignore", stderr: "ignore" },
878 ),
879 );
880 const { data } = yield* decodeManagerEnvironment(output);
881 return Object.fromEntries(
882 data.flatMap((line) => {
883 const separator = line.indexOf("=");
884 const key = line.slice(0, separator);
885 return separator > 0 && GRAPHICAL_SESSION_ENV_KEYS.has(key)
886 ? [[key, line.slice(separator + 1)]]
887 : [];
888 }),
889 );
890 },
891 Effect.timeout("2 seconds"),
892 Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})),
893);
894
895const launchProcess = Effect.fn("externalLauncher.launchProcess")(function* (
896 launch: ProcessLaunch,
897 onError: (cause: unknown) => ExternalLauncherError,
898): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
899 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
900 // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit.
901 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
902 const command = ChildProcess.make(launch.command, launch.args, {
903 ...launch.options,
904 env: { ...env, ...launch.options.env },
905 extendEnv: false,
906 });
907
908 if (launch.waitForExit) {
909 const exitCode = yield* spawner.exitCode(command).pipe(
910 Effect.mapError(onError),
911 Effect.catchDefect((cause) => Effect.fail(onError(cause))),
912 );
913 if (exitCode !== 0) {
914 return yield* onError(new Error(`${launch.command} exited with status ${exitCode}`));
915 }
916 return;
917 }
918
919 yield* spawner.spawn(command).pipe(
920 Effect.flatMap((handle) => handle.unref),
921 Effect.asVoid,
922 Effect.scoped,
923 Effect.mapError(onError),
924 // Node throws a missing command's ENOTDIR (PATH ending in a file) synchronously, as a defect.
925 Effect.catchDefect((cause) => Effect.fail(onError(cause))),
926 );
927});
928
929const isSpawnNotFound = (error: ExternalLauncherError) =>
930 error._tag === "ExternalLauncherBrowserSpawnError" &&
931 PlatformError.isPlatformError(error.cause) &&
932 error.cause.reason._tag === "NotFound" &&
933 error.cause.reason.method === "spawn";
934
935const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
936 target: string,
937): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
938 const { launch, env } = yield* resolveBrowserLaunch(target);
939 const spawnBrowser = (command: string) =>
940 launchProcess(
941 { ...launch, command },
942 (cause) =>
943 new ExternalLauncherBrowserSpawnError({ target, command, args: launch.args, cause }),
944 );
945 const wslDefault = launch.command === resolveWslPowerShellPath();
946 const firstAttempt = yield* spawnBrowser(launch.command).pipe(Effect.result);
947 if (firstAttempt._tag === "Success") return;
948 if (!wslDefault || !isSpawnNotFound(firstAttempt.failure)) {
949 return yield* firstAttempt.failure;
950 }
951 // Custom automount roots: only wslpath knows where the Windows root is; PATH interop is last.
952 const mounted = yield* toHostDrivePath(resolvePowerShellPath(env));
953 if (mounted.startsWith("/") && mounted !== launch.command) {
954 const mountedAttempt = yield* spawnBrowser(mounted).pipe(Effect.result);
955 if (mountedAttempt._tag === "Success") return;
956 if (!isSpawnNotFound(mountedAttempt.failure)) return yield* mountedAttempt.failure;
957 }
958 return yield* spawnBrowser(WSL_POWERSHELL_COMMAND);
959});
960
961const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
962 launch: EditorLaunch,
963): Effect.fn.Return<
964 void,
965 ExternalLauncherError,
966 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
967> {
968 const env = yield* readCommandLookupEnv;
969 if (!(yield* isCommandAvailable(launch.command, { env }))) {
970 return yield* new ExternalLauncherCommandNotFoundError({
971 editor: launch.editor,
972 command: launch.command,
973 });
974 }
975
976 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
977 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
978 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
979 }
980 yield* launchProcess(
981 {
982 command: spawnCommand.command,
983 args: spawnCommand.args,
984 waitForExit: launch.waitForExit ?? false,
985 options: {
986 detached: launch.detached ?? true,
987 shell: spawnCommand.shell,
988 env: yield* readGraphicalSessionEnv(),
989 stdin: "ignore",
990 stdout: "ignore",
991 stderr: "ignore",
992 },
993 },
994 (cause) =>
995 new ExternalLauncherEditorSpawnError({
996 editor: launch.editor,
997 target: launch.target,
998 command: spawnCommand.command,
999 args: spawnCommand.args,
1000 cause,
1001 }),
1002 );
1003});
1004
1005/** @public */
1006export const make = Effect.gen(function* () {
1007 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1008 const fileSystem = yield* FileSystem.FileSystem;
1009 const path = yield* Path.Path;
1010
1011 const provideCommandResolutionServices = <A, E, R>(
1012 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
1013 ) =>
1014 effect.pipe(
1015 Effect.provideService(FileSystem.FileSystem, fileSystem),
1016 Effect.provideService(Path.Path, path),
1017 );
1018
1019 const cachedAvailableEditors = yield* makeStaleWhileRevalidate(
1020 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
1021 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1022 ),
1023 EDITOR_DISCOVERY_CACHE_TTL,
1024 );
1025 const cachedFileManagerRevealKind = yield* makeStaleWhileRevalidate(
1026 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
1027 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1028 ),
1029 EDITOR_DISCOVERY_CACHE_TTL,
1030 );
1031 const cachedStockWindowsFolderVerb = yield* makeStaleWhileRevalidate(
1032 hasStockWindowsFolderVerb().pipe(
1033 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1034 ),
1035 EDITOR_DISCOVERY_CACHE_TTL,
1036 );
1037
1038 // Forwarders retain the underlying launcher and discovery spans.
1039 return ExternalLauncher.of({
1040 resolveAvailableEditors: Effect.fnUntraced(function* () {
1041 return yield* cachedAvailableEditors;
1042 }),
1043 resolveFileManagerRevealKind: Effect.fnUntraced(function* () {
1044 return yield* cachedFileManagerRevealKind;
1045 }),
1046 launchBrowser: Effect.fnUntraced(
1047 function* (target) {
1048 return yield* launchBrowser(target);
1049 },
1050 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1051 ),
1052 launchEditor: Effect.fnUntraced(
1053 function* (input) {
1054 return yield* provideCommandResolutionServices(
1055 launchEditor(input, cachedStockWindowsFolderVerb),
1056 );
1057 },
1058 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1059 ),
1060 });
1061});
1062
1063export const layer = Layer.effect(ExternalLauncher, make);