Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

externalLauncher.ts

507 lines15.7 KB

1/**
2 * ExternalLauncher - external application launch service interface.
3 *
4 * Owns process launch helpers for browser URLs and workspace paths
5 * in configured editor integrations.
6 *
7 * @module ExternalLauncher
8 */
9import {
10 EDITORS,
11 ExternalLauncherError,
12 ExternalLauncherBrowserSpawnError,
13 ExternalLauncherCommandNotFoundError,
14 ExternalLauncherEditorSpawnError,
15 ExternalLauncherUnknownEditorError,
16 ExternalLauncherUnsupportedEditorError,
17 type EditorId,
18 type LaunchEditorInput,
19} from "@t3tools/contracts";
20import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
21import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
22import * as Clock from "effect/Clock";
23import * as Config from "effect/Config";
24import * as Context from "effect/Context";
25import * as Effect from "effect/Effect";
26import * as Encoding from "effect/Encoding";
27import * as FileSystem from "effect/FileSystem";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Path from "effect/Path";
31import * as Ref from "effect/Ref";
32import * as ChildProcess from "effect/unstable/process/ChildProcess";
33import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
34​
35// ==============================
36// Definitions
37// ==============================
38​
39export {
40 ExternalLauncherError,
41 ExternalLauncherBrowserSpawnError,
42 ExternalLauncherCommandNotFoundError,
43 ExternalLauncherEditorSpawnError,
44 ExternalLauncherUnknownEditorError,
45 ExternalLauncherUnsupportedEditorError,
46 isExternalLauncherError,
47} from "@t3tools/contracts";
48export type { LaunchEditorInput };
49interface EditorLaunch {
50 readonly editor: EditorId;
51 readonly target: string;
52 readonly command: string;
53 readonly args: ReadonlyArray<string>;
55​
56interface ProcessLaunch {
57 readonly command: string;
58 readonly args: ReadonlyArray<string>;
59 readonly options: ChildProcess.CommandOptions;
61​
62interface TargetPathAndPosition {
63 readonly path: string;
64 readonly line: string;
65 readonly column: Option.Option<string>;
67​
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​
77const DETACHED_IGNORE_STDIO_OPTIONS = {
78 detached: true,
79 stdin: "ignore",
80 stdout: "ignore",
81 stderr: "ignore",
82} as const satisfies ChildProcess.CommandOptions;
83​
84const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
85 Object.fromEntries(
86 Object.entries(input).flatMap(([key, value]) =>
87 Option.match(value, {
88 onNone: () => [],
89 onSome: (resolved) => [[key, resolved]],
90 }),
91 ),
92 );
93​
94const BrowserLaunchEnvConfig = Config.all({
95 SYSTEMROOT: Config.string("SYSTEMROOT").pipe(Config.option),
96 windir: Config.string("windir").pipe(Config.option),
97 WSL_DISTRO_NAME: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
98 WSL_INTEROP: Config.string("WSL_INTEROP").pipe(Config.option),
99 SSH_CONNECTION: Config.string("SSH_CONNECTION").pipe(Config.option),
100 SSH_TTY: Config.string("SSH_TTY").pipe(Config.option),
101 container: Config.string("container").pipe(Config.option),
102}).pipe(Config.map(compactEnv));
103​
104const CommandLookupEnvConfig = Config.all({
105 PATH: Config.string("PATH").pipe(Config.option),
106 Path: Config.string("Path").pipe(Config.option),
107 path: Config.string("path").pipe(Config.option),
108 PATHEXT: Config.string("PATHEXT").pipe(Config.option),
109}).pipe(Config.map(compactEnv));
110​
111const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
112const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
113​
114function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
115 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
116 if (!match?.[1] || !match[2]) {
117 return Option.none();
118 }
119​
120 return Option.some({
121 path: match[1],
122 line: match[2],
123 column: Option.fromUndefinedOr(match[3]),
124 });
126​
127function resolveCommandEditorArgs(
128 editor: (typeof EDITORS)[number],
129 target: string,
130): ReadonlyArray<string> {
131 const parsedTarget = parseTargetPathAndPosition(target);
132​
133 switch (editor.launchStyle) {
134 case "direct-path":
135 return [target];
136 case "goto":
137 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
138 case "line-column":
139 return Option.match(parsedTarget, {
140 onNone: () => [target],
141 onSome: ({ path, line, column }) => [
142 "--line",
143 line,
144 ...Option.match(column, {
145 onNone: () => [],
146 onSome: (value) => ["--column", value],
147 }),
148 path,
149 ],
150 });
151 }
153​
154function resolveEditorArgs(
155 editor: (typeof EDITORS)[number],
156 target: string,
157): ReadonlyArray<string> {
158 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
159 return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
161​
162const resolveAvailableCommand = Effect.fn("externalLauncher.resolveAvailableCommand")(function* (
163 commands: ReadonlyArray<string>,
164 env: NodeJS.ProcessEnv,
165): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {
166 for (const command of commands) {
167 if (yield* isCommandAvailable(command, { env })) {
168 return Option.some(command);
169 }
170 }
171 return Option.none();
172});
173​
174function encodeUtf16LeBase64(input: string): string {
175 const bytes = new Uint8Array(input.length * 2);
176 for (let index = 0; index < input.length; index += 1) {
177 const code = input.charCodeAt(index);
178 bytes[index * 2] = code & 0xff;
179 bytes[index * 2 + 1] = code >>> 8;
180 }
181 return Encoding.encodeBase64(bytes);
183​
184function escapePowerShellStringLiteral(input: string): string {
185 return `'${input.replaceAll("'", "''")}'`;
187​
188function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
189 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
191​
192function resolveWslPowerShellPath(): string {
193 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
195​
196function shouldUseWindowsBrowserFromWsl(
197 platform: NodeJS.Platform,
198 env: NodeJS.ProcessEnv = {},
199): boolean {
200 return (
201 platform === "linux" &&
202 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
203 env.SSH_CONNECTION === undefined &&
204 env.SSH_TTY === undefined &&
205 env.container === undefined
206 );
208​
209function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {
210 const encodedCommand = encodeUtf16LeBase64(
211 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
212 );
213 return {
214 command,
215 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
216 options: {
217 detached: true,
218 shell: false,
219 stdin: "ignore",
220 stdout: "ignore",
221 stderr: "ignore",
222 },
223 };
225​
226function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
227 switch (platform) {
228 case "darwin":
229 return "open";
230 case "win32":
231 return "explorer";
232 default:
233 return "xdg-open";
234 }
236​
237function buildBrowserLaunch(
238 target: string,
239 platform: NodeJS.Platform,
240 env: NodeJS.ProcessEnv = {},
241): ProcessLaunch {
242 if (platform === "darwin") {
243 return {
244 command: "open",
245 args: [target],
246 options: DETACHED_IGNORE_STDIO_OPTIONS,
247 };
248 }
249​
250 if (platform === "win32") {
251 return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));
252 }
253​
254 if (shouldUseWindowsBrowserFromWsl(platform, env)) {
255 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());
256 }
257​
258 return {
259 command: "xdg-open",
260 args: [target],
261 options: DETACHED_IGNORE_STDIO_OPTIONS,
262 };
264​
265const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
266 platform: NodeJS.Platform,
267 env: NodeJS.ProcessEnv,
268): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {
269 const available: EditorId[] = [];
270​
271 for (const editor of EDITORS) {
272 if (editor.commands === null) {
273 const command = fileManagerCommandForPlatform(platform);
274 if (yield* isCommandAvailable(command, { env })) {
275 available.push(editor.id);
276 }
277 continue;
278 }
279​
280 const command = yield* resolveAvailableCommand(editor.commands, env);
281 if (Option.isSome(command)) {
282 available.push(editor.id);
283 }
284 }
285​
286 return available;
287});
288​
289const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
290 target: string,
291) {
292 const platform = yield* HostProcessPlatform;
293 const env = yield* readBrowserLaunchEnv;
294 return buildBrowserLaunch(target, platform, env);
295});
296​
297const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
298 const platform = yield* HostProcessPlatform;
299 const env = yield* readCommandLookupEnv;
300 return yield* buildAvailableEditors(platform, env);
301});
302​
303// Editor discovery walks PATH for every known editor and runs for every
304// client connect (the server config embeds the available editors). Memoize
305// the discovered set for a bounded window so repeat connects skip even the
306// per-command cache lookups in @t3tools/shared/shell.
307//
308// This deliberately does not use `Effect.cachedWithTTL`: that memoizes the
309// first caller's Exit whatever it is, including an interrupt. Callers run this
310// on the connection fiber under a timeout (`resolveAvailableEditorsForConfig`),
311// so one client disconnecting mid-scan would cache the interrupt and replay it
312// to every later connect for the whole TTL, breaking `server.getConfig`
313// permanently. Storing only on success means an interrupted scan leaves the
314// cache untouched and the next connect simply rescans.
315// Expiry uses the monotonic clock (Clock.currentTimeNanos), matching the
316// command-resolution cache in @t3tools/shared/shell, so a backward wall-clock
317// adjustment cannot keep an expired entry alive.
318const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
319​
320interface EditorDiscoveryCacheEntry {
321 readonly editors: ReadonlyArray<EditorId>;
322 readonly expiresAtNanos: bigint;
324​
325/**
326 * ExternalLauncher - Service tag for browser/editor launch operations.
327 */
328export class ExternalLauncher extends Context.Service<
329 ExternalLauncher,
330 {
331 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
332 /** Launch a URL target in the default browser. */
333 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
334 /**
335 * Launch a workspace path in a selected editor integration.
336 *
337 * Launches the editor as a detached process so server startup is not blocked.
338 */
339 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
340 }
341>()("t3/process/externalLauncher") {}
342​
343// ==============================
344// Implementations
345// ==============================
346​
347const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
348 input: LaunchEditorInput,
349): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {
350 const platform = yield* HostProcessPlatform;
351 const env = yield* readCommandLookupEnv;
352 yield* Effect.annotateCurrentSpan({
353 "externalLauncher.editor": input.editor,
354 "externalLauncher.cwd": input.cwd,
355 "externalLauncher.platform": platform,
356 });
357 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
358 if (!editorDef) {
359 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
360 }
361​
362 if (editorDef.commands) {
363 const command = Option.getOrElse(
364 yield* resolveAvailableCommand(editorDef.commands, env),
365 () => editorDef.commands[0],
366 );
367 return {
368 editor: editorDef.id,
369 target: input.cwd,
370 command,
371 args: resolveEditorArgs(editorDef, input.cwd),
372 };
373 }
374​
375 if (editorDef.id !== "file-manager") {
376 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
377 }
378​
379 return {
380 editor: editorDef.id,
381 target: input.cwd,
382 command: fileManagerCommandForPlatform(platform),
383 args: [input.cwd],
384 };
385});
386​
387const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
388 launch: ProcessLaunch,
389 onError: (cause: unknown) => ExternalLauncherError,
390): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
391 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
392 const command = ChildProcess.make(launch.command, launch.args, launch.options);
393​
394 yield* spawner.spawn(command).pipe(
395 Effect.flatMap((handle) => handle.unref),
396 Effect.asVoid,
397 Effect.scoped,
398 Effect.mapError(onError),
399 );
400});
401​
402const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
403 target: string,
404): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
405 const launch = yield* resolveBrowserLaunch(target);
406 return yield* launchAndUnref(
407 launch,
408 (cause) =>
409 new ExternalLauncherBrowserSpawnError({
410 target,
411 command: launch.command,
412 args: launch.args,
413 cause,
414 }),
415 );
416});
417​
418const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
419 launch: EditorLaunch,
420): Effect.fn.Return<
421 void,
422 ExternalLauncherError,
423 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
424> {
425 const env = yield* readCommandLookupEnv;
426 if (!(yield* isCommandAvailable(launch.command, { env }))) {
427 return yield* new ExternalLauncherCommandNotFoundError({
428 editor: launch.editor,
429 command: launch.command,
430 });
431 }
432​
433 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
434 yield* launchAndUnref(
435 {
436 command: spawnCommand.command,
437 args: spawnCommand.args,
438 options: {
439 detached: true,
440 shell: spawnCommand.shell,
441 stdin: "ignore",
442 stdout: "ignore",
443 stderr: "ignore",
444 },
445 },
446 (cause) =>
447 new ExternalLauncherEditorSpawnError({
448 editor: launch.editor,
449 target: launch.target,
450 command: spawnCommand.command,
451 args: spawnCommand.args,
452 cause,
453 }),
454 );
455});
456​
457export const make = Effect.gen(function* () {
458 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
459 const fileSystem = yield* FileSystem.FileSystem;
460 const path = yield* Path.Path;
461​
462 const provideCommandResolutionServices = <A, E, R>(
463 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
464 ) =>
465 effect.pipe(
466 Effect.provideService(FileSystem.FileSystem, fileSystem),
467 Effect.provideService(Path.Path, path),
468 );
469​
470 const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
471 Option.none(),
472 );
473 const cachedAvailableEditors = Effect.gen(function* () {
474 const nowNanos = yield* Clock.currentTimeNanos;
475 const entry = yield* Ref.get(editorDiscoveryCache);
476 if (Option.isSome(entry) && entry.value.expiresAtNanos > nowNanos) {
477 return entry.value.editors;
478 }
479 const editors = yield* provideCommandResolutionServices(resolveAvailableEditors());
480 yield* Ref.set(
481 editorDiscoveryCache,
482 Option.some({
483 editors,
484 expiresAtNanos: nowNanos + EDITOR_DISCOVERY_CACHE_TTL_NANOS,
485 }),
486 );
487 return editors;
488 });
489​
490 return ExternalLauncher.of({
491 resolveAvailableEditors: () => cachedAvailableEditors,
492 launchBrowser: (target) =>
493 launchBrowser(target).pipe(
494 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
495 ),
496 launchEditor: (input) =>
497 provideCommandResolutionServices(
498 Effect.flatMap(resolveEditorLaunch(input), (launch) =>
499 launchEditorProcess(launch).pipe(
500 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
501 ),
502 ),
503 ),
504 });
505});
506​
507export const layer = Layer.effect(ExternalLauncher, make);