@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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