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