diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 363a07ee38..542d750c77 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -4,7 +4,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { CliConfig, t3Cli } from "./main"; -import { OpenLive } from "./open"; +import * as DesktopLauncher from "./process/Layers/DesktopLauncher"; import { Command } from "effect/unstable/cli"; import { version } from "../package.json" with { type: "json" }; import { ServerLive } from "./wsServer"; @@ -14,7 +14,7 @@ import { FetchHttpClient } from "effect/unstable/http"; const RuntimeLayer = Layer.empty.pipe( Layer.provideMerge(CliConfig.layer), Layer.provideMerge(ServerLive), - Layer.provideMerge(OpenLive), + Layer.provideMerge(DesktopLauncher.layer), Layer.provideMerge(NetService.layer), Layer.provideMerge(NodeServices.layer), Layer.provideMerge(FetchHttpClient.layer), diff --git a/apps/server/src/main.test.ts b/apps/server/src/main.test.ts index 1fa0a3752d..8fa75b4ac5 100644 --- a/apps/server/src/main.test.ts +++ b/apps/server/src/main.test.ts @@ -13,7 +13,7 @@ import { NetService } from "@t3tools/shared/Net"; import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main"; import { ServerConfig, type ServerConfigShape } from "./config"; -import { Open, type OpenShape } from "./open"; +import { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; import { Server, type ServerShape } from "./wsServer"; @@ -50,12 +50,12 @@ const testLayer = Layer.mergeAll( start: serverStart, stopSignal: Effect.void, } satisfies ServerShape), - Layer.succeed(Open, { + Layer.succeed(DesktopLauncher, { getAvailableEditors: Effect.succeed([]), openExternal: () => Effect.void, openBrowser: (_target: string) => Effect.void, openInEditor: () => Effect.void, - } satisfies OpenShape), + } satisfies DesktopLauncherShape), ServerSettingsService.layerTest(), AnalyticsService.layerTest, FetchHttpClient.layer, diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 019783c253..8e7b4c8cb7 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -18,7 +18,7 @@ import { type ServerConfigShape, } from "./config"; import { fixPath, resolveBaseDir } from "./os-jank"; -import { Open } from "./open"; +import { DesktopLauncher } from "./process/Services/DesktopLauncher"; import * as SqlitePersistence from "./persistence/Layers/Sqlite"; import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; @@ -336,7 +336,7 @@ export const recordStartupHeartbeat = Effect.gen(function* () { const makeServerRuntimeProgram = (input: CliInput) => Effect.gen(function* () { const { start, stopSignal } = yield* Server; - const openDeps = yield* Open; + const desktopLauncher = yield* DesktopLauncher; const config = yield* ServerConfig; @@ -366,7 +366,7 @@ const makeServerRuntimeProgram = (input: CliInput) => if (!config.noBrowser) { const target = config.devUrl?.toString() ?? bindUrl; - yield* openDeps.openBrowser(target).pipe( + yield* desktopLauncher.openBrowser(target).pipe( Effect.catch(() => Effect.logInfo("browser auto-open unavailable", { hint: `Open ${target} in your browser.`, diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts deleted file mode 100644 index 97d45b86bf..0000000000 --- a/apps/server/src/open.ts +++ /dev/null @@ -1,687 +0,0 @@ -/** - * Open - Browser/editor launch service interface. - * - * Owns process launch helpers for opening URLs in a browser, workspace paths in - * a configured editor, and generic external targets through the platform's - * default opener. - * - * @module Open - */ -import os from "node:os"; - -import { EDITORS, type EditorId } from "@t3tools/contracts"; -import { Effect, Exit, FileSystem, Layer, Option, Path, Schema, Scope, ServiceMap } from "effect"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; - -export class OpenError extends Schema.TaggedErrorClass()("OpenError", { - message: Schema.String, - cause: Schema.optional(Schema.Defect), -}) {} - -export interface OpenInEditorInput { - readonly cwd: string; - readonly editor: EditorId; -} - -export interface OpenApplicationInput { - readonly name: string | ReadonlyArray; - readonly arguments?: ReadonlyArray; -} - -export interface OpenExternalInput { - readonly target: string; - readonly wait?: boolean; - readonly background?: boolean; - readonly newInstance?: boolean; - readonly allowNonzeroExitCode?: boolean; - readonly app?: OpenApplicationInput | ReadonlyArray; -} - -export interface OpenRuntimeOptions { - readonly platform?: NodeJS.Platform; - readonly env?: NodeJS.ProcessEnv; - readonly isWsl?: boolean; - readonly isInsideContainer?: boolean; - readonly powerShellCommand?: string; -} - -interface OpenRuntime { - readonly platform: NodeJS.Platform; - readonly env: NodeJS.ProcessEnv; - readonly isWsl: boolean; - readonly isInsideContainer: boolean; - readonly powerShellCandidates: ReadonlyArray; - readonly windowsPathExtensions: ReadonlyArray; -} - -interface LaunchPlan { - readonly command: string; - readonly args: ReadonlyArray; - readonly wait: boolean; - readonly allowNonzeroExitCode: boolean; - readonly detached?: boolean; - readonly shell?: boolean; - readonly stdio?: "ignore"; -} - -interface ResolvedCommand { - readonly path: string; - readonly usesCmdWrapper: boolean; -} - -const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/; -const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const; -const WSL_POWERSHELL_CANDIDATES = [ - "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", - "/mnt/c/Program Files/PowerShell/7/pwsh.exe", - "powershell.exe", - "pwsh.exe", -] as const; -const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const; - -function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean { - return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target); -} - -function stripWrappingQuotes(value: string): string { - return value.replace(/^"+|"+$/g, ""); -} - -function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string { - return env.PATH ?? env.Path ?? env.path ?? ""; -} - -function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray { - const rawValue = env.PATHEXT; - const fallback = [".COM", ".EXE", ".BAT", ".CMD"]; - if (!rawValue) return fallback; - - const parsed = rawValue - .split(";") - .map((entry) => entry.trim()) - .filter((entry) => entry.length > 0) - .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`)); - - return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback; -} - -function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string { - return env.ComSpec ?? env.COMSPEC ?? "cmd.exe"; -} - -function resolveCommandCandidates( - command: string, - runtime: OpenRuntime, - pathService: Path.Path, -): ReadonlyArray { - if (runtime.platform !== "win32") return [command]; - const extension = pathService.extname(command); - const normalizedExtension = extension.toUpperCase(); - - if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) { - const commandWithoutExtension = command.slice(0, -extension.length); - return Array.from( - new Set([ - command, - `${commandWithoutExtension}${normalizedExtension}`, - `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`, - ]), - ); - } - - const candidates: string[] = []; - for (const extensionName of runtime.windowsPathExtensions) { - candidates.push(`${command}${extensionName}`); - candidates.push(`${command}${extensionName.toLowerCase()}`); - } - return Array.from(new Set(candidates)); -} - -function resolvePathDelimiter(platform: NodeJS.Platform): string { - return platform === "win32" ? ";" : ":"; -} - -function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean { - if (platform !== "linux") return false; - if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") { - return true; - } - return os.release().toLowerCase().includes("microsoft"); -} - -function quotePowerShellValue(value: string): string { - return `'${value.replaceAll("'", "''")}'`; -} - -function encodePowerShellCommand(command: string): string { - return Buffer.from(command, "utf16le").toString("base64"); -} - -function normalizeAppCandidates( - app: OpenExternalInput["app"], -): ReadonlyArray<{ readonly name: string; readonly arguments: ReadonlyArray } | undefined> { - if (!app) return [undefined]; - - const apps = Array.isArray(app) ? app : [app]; - const candidates: Array<{ readonly name: string; readonly arguments: ReadonlyArray }> = - []; - - for (const appDef of apps) { - const names = Array.isArray(appDef.name) ? appDef.name : [appDef.name]; - for (const name of names) { - candidates.push({ name, arguments: appDef.arguments ?? [] }); - } - } - - return candidates; -} - -function isUriLikeTarget(target: string): boolean { - return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target); -} - -function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: OpenRuntime): boolean { - return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target); -} - -function makeLaunchPlan( - runtime: OpenRuntime, - command: string, - args: ReadonlyArray, - options: { - readonly wait: boolean; - readonly allowNonzeroExitCode: boolean; - readonly detached?: boolean; - readonly shell?: boolean; - readonly stdio?: "ignore"; - }, -): LaunchPlan { - return { - command, - args, - wait: options.wait, - allowNonzeroExitCode: options.allowNonzeroExitCode, - shell: options.shell ?? false, - ...(options.detached !== undefined ? { detached: options.detached } : {}), - ...(options.stdio !== undefined ? { stdio: options.stdio } : {}), - }; -} - -function makeDarwinDefaultPlan(input: OpenExternalInput, runtime: OpenRuntime): LaunchPlan { - const args: string[] = []; - const wait = input.wait ?? false; - - if (wait) args.push("--wait-apps"); - if (input.background) args.push("--background"); - if (input.newInstance) args.push("--new"); - args.push(input.target); - - return makeLaunchPlan(runtime, "open", args, { - wait, - allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, - shell: false, - }); -} - -function makeDarwinApplicationPlan( - input: OpenExternalInput, - app: { readonly name: string; readonly arguments: ReadonlyArray }, - runtime: OpenRuntime, -): LaunchPlan { - const args: string[] = []; - const wait = input.wait ?? false; - - if (wait) args.push("--wait-apps"); - if (input.background) args.push("--background"); - if (input.newInstance) args.push("--new"); - args.push("-a", app.name); - args.push(input.target); - if (app.arguments.length > 0) { - args.push("--args", ...app.arguments); - } - - return makeLaunchPlan(runtime, "open", args, { - wait, - allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, - shell: false, - }); -} - -function makePowerShellPlan( - input: OpenExternalInput, - runtime: OpenRuntime, - powerShellCommand: string, -): LaunchPlan { - const encodedParts = ["Start"]; - const wait = input.wait ?? false; - - if (wait) encodedParts.push("-Wait"); - encodedParts.push(quotePowerShellValue(input.target)); - - return makeLaunchPlan( - runtime, - powerShellCommand, - [ - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-EncodedCommand", - encodePowerShellCommand(encodedParts.join(" ")), - ], - { - wait, - allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, - shell: false, - }, - ); -} - -function makeLinuxDefaultPlan(input: OpenExternalInput, runtime: OpenRuntime): LaunchPlan { - const wait = input.wait ?? false; - return makeLaunchPlan(runtime, "xdg-open", [input.target], { - wait, - allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, - detached: !wait, - ...(wait ? {} : { stdio: "ignore" as const }), - shell: false, - }); -} - -function makeWindowsExplorerPlan(input: OpenExternalInput, runtime: OpenRuntime): LaunchPlan { - return makeLaunchPlan(runtime, "explorer", [input.target], { - wait: false, - allowNonzeroExitCode: false, - shell: false, - }); -} - -function makeDirectApplicationPlan( - input: OpenExternalInput, - app: { readonly name: string; readonly arguments: ReadonlyArray }, - runtime: OpenRuntime, -): LaunchPlan { - return makeLaunchPlan(runtime, app.name, [...app.arguments, input.target], { - wait: input.wait ?? false, - allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, - shell: false, - }); -} - -function resolveExternalPlans( - input: OpenExternalInput, - runtime: OpenRuntime, -): ReadonlyArray { - const appCandidates = normalizeAppCandidates(input.app); - const plans: LaunchPlan[] = []; - const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime); - - for (const app of appCandidates) { - if (app) { - if (runtime.platform === "darwin") { - plans.push(makeDarwinApplicationPlan(input, app, runtime)); - } else { - plans.push(makeDirectApplicationPlan(input, app, runtime)); - } - continue; - } - - if (runtime.platform === "darwin") { - plans.push(makeDarwinDefaultPlan(input, runtime)); - continue; - } - - if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) { - for (const powerShellCommand of runtime.powerShellCandidates) { - plans.push(makePowerShellPlan(input, runtime, powerShellCommand)); - } - } - - if (runtime.platform === "win32") { - if (!(input.wait ?? false)) { - plans.push(makeWindowsExplorerPlan(input, runtime)); - } - continue; - } - - plans.push(makeLinuxDefaultPlan(input, runtime)); - } - - return plans; -} - -function toOpenError(message: string, cause: unknown): OpenError { - return new OpenError({ message, cause }); -} - -function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean { - return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never); -} - -function quoteForWindowsCmd(value: string): string { - return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`; -} - -function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray): string { - return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`; -} - -export interface OpenShape { - readonly getAvailableEditors: Effect.Effect, OpenError>; - readonly openExternal: (input: OpenExternalInput) => Effect.Effect; - readonly openBrowser: ( - target: string, - options?: Omit, - ) => Effect.Effect; - readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect; -} - -export class Open extends ServiceMap.Service()("t3/open") {} - -const makeOpen = (options: OpenRuntimeOptions = {}) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const pathService = yield* Path.Path; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - - const isInsideContainer = - options.isInsideContainer ?? - (typeof options.env?.CONTAINER === "string" || - typeof options.env?.container === "string" || - typeof options.env?.KUBERNETES_SERVICE_HOST === "string" - ? true - : yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false)))); - - const runtime: OpenRuntime = { - platform: options.platform ?? process.platform, - env: options.env ?? process.env, - isWsl: - options.isWsl ?? - detectWsl(options.platform ?? process.platform, options.env ?? process.env), - isInsideContainer, - powerShellCandidates: - options.powerShellCommand !== undefined - ? [options.powerShellCommand] - : (options.isWsl ?? - detectWsl(options.platform ?? process.platform, options.env ?? process.env)) - ? WSL_POWERSHELL_CANDIDATES - : WINDOWS_POWERSHELL_CANDIDATES, - windowsPathExtensions: resolveWindowsPathExtensions(options.env ?? process.env), - }; - - const resolveCommand = Effect.fn(function* ( - command: string, - ): Effect.fn.Return, never> { - const candidates = resolveCommandCandidates(command, runtime, pathService); - - const resolveExecutableFile = Effect.fn(function* ( - filePath: string, - ): Effect.fn.Return, never> { - const info = yield* fileSystem.stat(filePath).pipe(Effect.option); - if (Option.isNone(info) || info.value.type !== "File") return Option.none(); - - if (runtime.platform === "win32") { - const extension = pathService.extname(filePath); - if ( - extension.length === 0 || - !runtime.windowsPathExtensions.includes(extension.toUpperCase()) - ) { - return Option.none(); - } - - return Option.some({ - path: filePath, - usesCmdWrapper: isWindowsBatchShim(pathService, filePath), - } satisfies ResolvedCommand); - } - - return (info.value.mode & 0o111) !== 0 - ? Option.some({ - path: filePath, - usesCmdWrapper: false, - } satisfies ResolvedCommand) - : Option.none(); - }); - - if (command.includes("/") || command.includes("\\")) { - for (const candidate of candidates) { - const resolved = yield* resolveExecutableFile(candidate); - if (Option.isSome(resolved)) return resolved; - } - return Option.none(); - } - - const pathValue = resolvePathEnvironmentVariable(runtime.env); - if (pathValue.length === 0) return Option.none(); - - const pathEntries = pathValue - .split(resolvePathDelimiter(runtime.platform)) - .map((entry) => stripWrappingQuotes(entry.trim())) - .filter((entry) => entry.length > 0); - - for (const pathEntry of pathEntries) { - for (const candidate of candidates) { - const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate)); - if (Option.isSome(resolved)) { - return resolved; - } - } - } - - return Option.none(); - }); - - const commandAvailable = (command: string) => - resolveCommand(command).pipe(Effect.map(Option.isSome)); - - const fileManagerAvailable = Effect.gen(function* () { - const candidates = - runtime.platform === "darwin" - ? ["open"] - : runtime.platform === "win32" - ? [...runtime.powerShellCandidates, "explorer"] - : ["xdg-open"]; - - for (const candidate of candidates) { - if (yield* commandAvailable(candidate)) { - return true; - } - } - - return false; - }); - - const getAvailableEditors = Effect.gen(function* () { - const available: EditorId[] = []; - - for (const editor of EDITORS) { - if (editor.id === "file-manager") { - if (yield* fileManagerAvailable) { - available.push(editor.id); - } - continue; - } - - if (editor.command && (yield* commandAvailable(editor.command))) { - available.push(editor.id); - } - } - - return available as ReadonlyArray; - }).pipe(Effect.mapError((cause) => toOpenError("Failed to resolve available editors", cause))); - - const spawnPlan = ( - plan: LaunchPlan, - resolvedCommand: ResolvedCommand, - failureMessage: string, - ) => - spawner - .spawn( - ChildProcess.make( - resolvedCommand.usesCmdWrapper - ? resolveWindowsCommandShell(runtime.env) - : resolvedCommand.path, - resolvedCommand.usesCmdWrapper - ? [ - "/d", - "/v:off", - "/s", - "/c", - makeWindowsCmdCommandLine(resolvedCommand.path, plan.args), - ] - : [...plan.args], - { - detached: plan.detached, - shell: plan.shell, - ...(plan.stdio === "ignore" - ? { - stdin: "ignore", - stdout: "ignore", - stderr: "ignore", - } - : {}), - }, - ), - ) - .pipe(Effect.mapError((cause) => toOpenError(failureMessage, cause))); - - const waitForExit = ( - plan: LaunchPlan, - failureMessage: string, - handle: ChildProcessSpawner.ChildProcessHandle, - ) => - handle.exitCode.pipe( - Effect.flatMap((exitCode) => - !plan.allowNonzeroExitCode && (exitCode as number) !== 0 - ? Effect.fail( - new OpenError({ - message: `${failureMessage} (code=${exitCode as number})`, - }), - ) - : Effect.void, - ), - Effect.mapError((cause) => toOpenError(failureMessage, cause)), - ); - - const runWaitedPlan = ( - plan: LaunchPlan, - resolvedCommand: ResolvedCommand, - failureMessage: string, - ) => - Effect.acquireUseRelease( - Scope.make("sequential"), - (scope) => - Effect.gen(function* () { - const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe( - Scope.provide(scope), - ); - yield* waitForExit(plan, failureMessage, handle); - }), - (scope) => Scope.close(scope, Exit.void), - ); - - const runDetachedPlan = ( - plan: LaunchPlan, - resolvedCommand: ResolvedCommand, - failureMessage: string, - ) => - Effect.gen(function* () { - const childScope = yield* Scope.make("sequential"); - const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe( - Scope.provide(childScope), - Effect.catch((error) => - Scope.close(childScope, Exit.void).pipe(Effect.andThen(Effect.fail(error))), - ), - ); - - const releaseOnExit: Effect.Effect = handle.exitCode.pipe( - Effect.ignoreCause, - Effect.ensuring(Scope.close(childScope, Exit.void)), - ); - - yield* Effect.forkDetach(releaseOnExit); - }); - - const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, failureMessage: string) => - plan.wait - ? runWaitedPlan(plan, resolvedCommand, failureMessage) - : runDetachedPlan(plan, resolvedCommand, failureMessage); - - const runFirstAvailablePlan = ( - plans: ReadonlyArray, - failureMessage: string, - ): Effect.Effect => { - const [first, ...rest] = plans; - if (!first) { - return Effect.fail(new OpenError({ message: failureMessage })); - } - - return resolveCommand(first.command).pipe( - Effect.flatMap((resolvedCommand) => { - if (Option.isNone(resolvedCommand)) { - return rest.length === 0 - ? Effect.fail(new OpenError({ message: `Command not found: ${first.command}` })) - : runFirstAvailablePlan(rest, failureMessage); - } - - return runPlan(first, resolvedCommand.value, failureMessage).pipe( - Effect.catch((error) => - rest.length === 0 ? Effect.fail(error) : runFirstAvailablePlan(rest, failureMessage), - ), - ); - }), - ); - }; - - const openExternal = (input: OpenExternalInput) => { - if (input.target.trim().length === 0) { - return Effect.fail(new OpenError({ message: "Open target must not be empty" })); - } - - return runFirstAvailablePlan( - resolveExternalPlans(input, runtime), - `Failed to open ${input.target}`, - ); - }; - - const openInEditor = (input: OpenInEditorInput) => { - const editor = EDITORS.find((candidate) => candidate.id === input.editor); - if (!editor) { - return Effect.fail(new OpenError({ message: `Unknown editor: ${input.editor}` })); - } - - if (editor.command) { - return runFirstAvailablePlan( - [ - makeLaunchPlan( - runtime, - editor.command, - shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd], - { - wait: false, - allowNonzeroExitCode: false, - detached: true, - stdio: "ignore", - shell: false, - }, - ), - ], - `Failed to open ${input.cwd} in ${input.editor}`, - ); - } - - return openExternal({ target: input.cwd }); - }; - - return { - getAvailableEditors, - openExternal, - openBrowser: (target, openOptions = {}) => openExternal({ ...openOptions, target }), - openInEditor, - } satisfies OpenShape; - }); - -export const makeOpenLayer = (options: OpenRuntimeOptions = {}) => - Layer.effect(Open, makeOpen(options)); - -export const OpenLive = makeOpenLayer(); diff --git a/apps/server/src/open.test.ts b/apps/server/src/process/Layers/DesktopLauncher.test.ts similarity index 73% rename from apps/server/src/open.test.ts rename to apps/server/src/process/Layers/DesktopLauncher.test.ts index 41ed33eeb4..e869b1fbea 100644 --- a/apps/server/src/open.test.ts +++ b/apps/server/src/process/Layers/DesktopLauncher.test.ts @@ -14,7 +14,12 @@ import { } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; -import { makeOpenLayer, Open } from "./open"; +import { + make as makeDesktopLauncher, + type DetachedSpawnInput, + type LaunchRuntimeOptions, +} from "./DesktopLauncher"; +import { DesktopLauncher, DesktopLauncherSpawnError } from "../Services/DesktopLauncher"; const encoder = new TextEncoder(); @@ -121,21 +126,90 @@ function spawnerLayer( ); } +function spawnHarness( + calls: Array, + handler: (call: SpawnCall) => { + readonly code?: number; + readonly fail?: string; + readonly awaitExit?: Deferred.Deferred; + readonly onKill?: () => void; + } = () => ({ + code: 0, + }), +) { + return { + layer: spawnerLayer(calls, handler), + spawnDetached: ( + input: DetachedSpawnInput, + context: { + readonly operation: string; + readonly target?: string; + readonly editor?: string; + }, + ) => { + const call: SpawnCall = { + command: input.command, + args: [...input.args], + detached: input.detached, + shell: input.shell, + stdin: input.stdin, + stdout: input.stdout, + stderr: input.stderr, + }; + calls.push(call); + + const result = handler(call); + return result.fail + ? Effect.fail( + new DesktopLauncherSpawnError({ + operation: context.operation, + command: input.command, + args: [...input.args], + ...(context.target !== undefined ? { target: context.target } : {}), + ...(context.editor !== undefined ? { editor: context.editor } : {}), + }), + ) + : Effect.void; + }, + } as const; +} + const provideOpen = ( - options: Parameters[0], - spawnLayer: Layer.Layer, + options: LaunchRuntimeOptions, + harness: { + readonly layer: Layer.Layer; + readonly spawnDetached: ( + input: DetachedSpawnInput, + context: { + readonly operation: string; + readonly target?: string; + readonly editor?: string; + }, + ) => Effect.Effect; + }, ) => - makeOpenLayer(options).pipe( - Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, spawnLayer)), - ); + Layer.effect( + DesktopLauncher, + makeDesktopLauncher({ ...options, spawnDetached: harness.spawnDetached }), + ).pipe(Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, harness.layer))); const runOpen = ( - options: Parameters[0], - spawnLayer: Layer.Layer, - effect: Effect.Effect, -) => effect.pipe(Effect.provide(provideOpen(options, spawnLayer))); + options: LaunchRuntimeOptions, + harness: { + readonly layer: Layer.Layer; + readonly spawnDetached: ( + input: DetachedSpawnInput, + context: { + readonly operation: string; + readonly target?: string; + readonly editor?: string; + }, + ) => Effect.Effect; + }, + effect: Effect.Effect, +) => effect.pipe(Effect.provide(provideOpen(options, harness))); -const readOpen = Effect.service(Open); +const readOpen = Effect.service(DesktopLauncher); const writeExecutable = (filePath: string) => Effect.gen(function* () { @@ -161,7 +235,7 @@ it.effect("getAvailableEditors detects installed editors through the service", ( PATHEXT: ".COM;.EXE;.BAT;.CMD", }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -192,7 +266,7 @@ it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShe isInsideContainer: false, powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -214,7 +288,7 @@ it.effect("openInEditor uses --goto for editors that support it", () => platform: "darwin", env: { PATH: dir }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -252,7 +326,7 @@ it.effect("openInEditor launches Windows batch shims through cmd.exe without she PATHEXT: ".COM;.EXE;.BAT;.CMD", }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -275,15 +349,14 @@ it.effect("openInEditor launches Windows batch shims through cmd.exe without she }).pipe(Effect.provide(NodeFileSystem.layer)), ); -it.effect("openInEditor detached launches survive service scope shutdown", () => +it.effect("openInEditor detached launches bypass the scoped child-process spawner", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" }); yield* writeExecutable(`${dir}/zed`); const calls: Array = []; - const exitDeferred = yield* Deferred.make(); - let killCount = 0; + const harness = spawnHarness(calls); yield* Effect.acquireUseRelease( Scope.make("sequential"), @@ -295,12 +368,7 @@ it.effect("openInEditor detached launches survive service scope shutdown", () => platform: "darwin", env: { PATH: dir }, }, - spawnerLayer(calls, () => ({ - awaitExit: exitDeferred, - onKill: () => { - killCount += 1; - }, - })), + harness, ), ).pipe(Scope.provide(scope)); @@ -313,7 +381,6 @@ it.effect("openInEditor detached launches survive service scope shutdown", () => (scope) => Scope.close(scope, Exit.void), ); - assert.equal(killCount, 0); assert.deepEqual(calls, [ { command: `${dir}/zed`, @@ -325,10 +392,6 @@ it.effect("openInEditor detached launches survive service scope shutdown", () => stderr: "ignore", }, ]); - - yield* Deferred.succeed(exitDeferred, void 0); - yield* Effect.yieldNow; - assert.equal(killCount, 0); }).pipe(Effect.provide(NodeFileSystem.layer)), ); @@ -344,7 +407,7 @@ it.effect("openInEditor uses the default opener for file-manager on macOS", () = platform: "darwin", env: { PATH: dir }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -379,7 +442,7 @@ it.effect("openBrowser uses macOS open flags and app arguments", () => platform: "darwin", env: { PATH: dir }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -431,7 +494,7 @@ it.effect("openBrowser uses PowerShell on win32", () => PATHEXT: ".COM;.EXE;.BAT;.CMD", }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -469,7 +532,7 @@ it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () => isInsideContainer: false, powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`, }, - spawnerLayer(calls, (call) => + spawnHarness(calls, (call) => call.command.includes("powershell") ? { fail: "powershell unavailable" } : { @@ -509,7 +572,7 @@ it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () => isInsideContainer: false, powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -540,7 +603,7 @@ it.effect("openInEditor fails when the editor command is unavailable", () => platform: "darwin", env: { PATH: "" }, }, - spawnerLayer(calls), + spawnHarness(calls), readOpen, ); @@ -551,8 +614,80 @@ it.effect("openInEditor fails when the editor command is unavailable", () => }) .pipe(Effect.flip); - assert.equal(error._tag, "OpenError"); - assert.equal(error.message, "Command not found: cursor"); + assert.equal(error._tag, "DesktopLauncherCommandNotFoundError"); + assert.equal( + error.message, + "Desktop launcher command not found in openInEditor: cursor for editor cursor", + ); assert.deepEqual(calls, []); }), ); + +it.effect("openBrowser rejects an empty target with a validation error", () => + Effect.gen(function* () { + const calls: Array = []; + const open = yield* runOpen( + { + platform: "darwin", + env: { PATH: "" }, + }, + spawnHarness(calls), + readOpen, + ); + + const error = yield* open.openBrowser(" ").pipe(Effect.flip); + + assert.equal(error._tag, "DesktopLauncherValidationError"); + assert.equal( + error.message, + "Desktop launcher validation failed in openBrowser: target must not be empty", + ); + assert.deepEqual(calls, []); + }), +); + +it.effect("openBrowser reports exhausted fallback attempts when multiple launchers fail", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-fallback-errors-" }); + yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, { + recursive: true, + }); + yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`); + yield* writeExecutable(`${dir}/xdg-open`); + + const calls: Array = []; + const open = yield* runOpen( + { + platform: "linux", + env: { + PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, + WSL_DISTRO_NAME: "Ubuntu", + }, + isWsl: true, + isInsideContainer: false, + powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`, + }, + spawnHarness(calls, () => ({ fail: "launcher unavailable" })), + readOpen, + ); + + const error = yield* open.openBrowser("https://example.com").pipe(Effect.flip); + assert.equal(error._tag, "DesktopLauncherLaunchAttemptsExhaustedError"); + if (error._tag !== "DesktopLauncherLaunchAttemptsExhaustedError") { + throw new Error(`Unexpected error tag: ${error._tag}`); + } + assert.deepEqual( + error.attempts.map((attempt) => attempt.reason), + ["spawnFailed", "spawnFailed"], + ); + assert.deepEqual( + error.attempts.map((attempt) => attempt.command.includes("powershell")), + [true, false], + ); + assert.deepEqual( + calls.map((call) => call.command.includes("powershell")), + [true, false], + ); + }).pipe(Effect.provide(NodeFileSystem.layer)), +); diff --git a/apps/server/src/process/Layers/DesktopLauncher.ts b/apps/server/src/process/Layers/DesktopLauncher.ts new file mode 100644 index 0000000000..c8e19b2bdc --- /dev/null +++ b/apps/server/src/process/Layers/DesktopLauncher.ts @@ -0,0 +1,857 @@ +/** + * Open - Browser/editor launch service interface. + * + * Owns process launch helpers for opening URLs in a browser, workspace paths in + * a configured editor, and generic external targets through the platform's + * default opener. + * + * @module Open + */ +import OS from "node:os"; +import { spawn as spawnNodeChildProcess } from "node:child_process"; + +import { EDITORS, type EditorId } from "@t3tools/contracts"; +import { Array, Effect, FileSystem, Layer, Option, Path, Scope } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import { + DesktopLauncherCommandNotFoundError, + DesktopLauncherDiscoveryError, + DesktopLauncherLaunchAttemptsExhaustedError, + DesktopLauncherNonZeroExitError, + DesktopLauncherSpawnError, + DesktopLauncherUnknownEditorError, + DesktopLauncherValidationError, + DesktopLauncher, + type DesktopLauncherShape, + type OpenApplicationInput, + type OpenExternalInput, +} from "../Services/DesktopLauncher"; + +export interface DetachedSpawnInput { + readonly command: string; + readonly args: ReadonlyArray; + readonly detached?: boolean; + readonly shell?: boolean; + readonly stdin?: "ignore"; + readonly stdout?: "ignore"; + readonly stderr?: "ignore"; +} + +type DesktopLauncherOperation = + | "getAvailableEditors" + | "openBrowser" + | "openExternal" + | "openInEditor"; + +interface LaunchContext { + readonly operation: DesktopLauncherOperation; + readonly target?: string; + readonly editor?: EditorId; +} + +export interface LaunchRuntimeOptions { + readonly platform?: NodeJS.Platform; + readonly env?: NodeJS.ProcessEnv; + readonly isWsl?: boolean; + readonly isInsideContainer?: boolean; + readonly powerShellCommand?: string; + readonly spawnDetached?: ( + input: DetachedSpawnInput, + context: LaunchContext, + ) => Effect.Effect; +} + +interface LaunchRuntime { + readonly platform: NodeJS.Platform; + readonly env: NodeJS.ProcessEnv; + readonly isWsl: boolean; + readonly isInsideContainer: boolean; + readonly powerShellCandidates: ReadonlyArray; + readonly windowsPathExtensions: ReadonlyArray; +} + +interface LaunchPlan { + readonly command: string; + readonly args: ReadonlyArray; + readonly wait: boolean; + readonly allowNonzeroExitCode: boolean; + readonly detached?: boolean; + readonly shell?: boolean; + readonly stdio?: "ignore"; +} + +interface ResolvedCommand { + readonly path: string; + readonly usesCmdWrapper: boolean; +} + +interface OpenApplicationCandidate { + readonly name: string; + readonly arguments: ReadonlyArray; +} + +interface LaunchAttemptFailure { + readonly command: string; + readonly args: ReadonlyArray; + readonly reason: "commandNotFound" | "spawnFailed" | "nonZeroExit"; + readonly detail: string; + readonly exitCode?: number; +} + +type LaunchAttemptError = + | DesktopLauncherCommandNotFoundError + | DesktopLauncherNonZeroExitError + | DesktopLauncherSpawnError; + +type LaunchPlanError = LaunchAttemptError | DesktopLauncherLaunchAttemptsExhaustedError; + +const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/; +const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const; +const WSL_POWERSHELL_CANDIDATES = [ + "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", + "/mnt/c/Program Files/PowerShell/7/pwsh.exe", + "powershell.exe", + "pwsh.exe", +] as const; +const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const; + +function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean { + return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target); +} + +function stripWrappingQuotes(value: string): string { + return value.replace(/^"+|"+$/g, ""); +} + +function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string { + return env.PATH ?? env.Path ?? env.path ?? ""; +} + +function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray { + const rawValue = env.PATHEXT; + const fallback = [".COM", ".EXE", ".BAT", ".CMD"]; + if (!rawValue) return fallback; + + const parsed = rawValue + .split(";") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`)); + + return parsed.length > 0 ? Array.dedupe(parsed) : fallback; +} + +function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string { + return env.ComSpec ?? env.COMSPEC ?? "cmd.exe"; +} + +function resolveCommandCandidates( + command: string, + runtime: LaunchRuntime, + pathService: Path.Path, +): ReadonlyArray { + if (runtime.platform !== "win32") return [command]; + const extension = pathService.extname(command); + const normalizedExtension = extension.toUpperCase(); + + if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) { + const commandWithoutExtension = command.slice(0, -extension.length); + return Array.dedupe([ + command, + `${commandWithoutExtension}${normalizedExtension}`, + `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`, + ]); + } + + const candidates: string[] = []; + for (const extensionName of runtime.windowsPathExtensions) { + candidates.push(`${command}${extensionName}`); + candidates.push(`${command}${extensionName.toLowerCase()}`); + } + return Array.dedupe(candidates); +} + +function resolvePathDelimiter(platform: NodeJS.Platform): string { + return platform === "win32" ? ";" : ":"; +} + +function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean { + if (platform !== "linux") return false; + if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") { + return true; + } + return OS.release().toLowerCase().includes("microsoft"); +} + +function quotePowerShellValue(value: string): string { + return `'${value.replaceAll("'", "''")}'`; +} + +function encodePowerShellCommand(command: string): string { + return Buffer.from(command, "utf16le").toString("base64"); +} + +function normalizeAppCandidates( + app: OpenApplicationInput | ReadonlyArray | undefined, +): ReadonlyArray { + if (!app) return [undefined]; + + const apps = Array.ensure(app); + const candidates: Array = []; + + for (const appDef of apps) { + const names = Array.ensure(appDef.name); + for (const name of names) { + candidates.push({ name, arguments: appDef.arguments ?? [] }); + } + } + + return candidates; +} + +function isUriLikeTarget(target: string): boolean { + return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target); +} + +function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: LaunchRuntime): boolean { + return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target); +} + +function makeLaunchPlan( + command: string, + args: ReadonlyArray, + options: { + readonly wait: boolean; + readonly allowNonzeroExitCode: boolean; + readonly detached?: boolean; + readonly shell?: boolean; + readonly stdio?: "ignore"; + }, +): LaunchPlan { + return { + command, + args, + wait: options.wait, + allowNonzeroExitCode: options.allowNonzeroExitCode, + shell: options.shell ?? false, + ...(options.detached !== undefined ? { detached: options.detached } : {}), + ...(options.stdio !== undefined ? { stdio: options.stdio } : {}), + }; +} + +function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan { + const args: string[] = []; + const wait = input.wait ?? false; + + if (wait) args.push("--wait-apps"); + if (input.background) args.push("--background"); + if (input.newInstance) args.push("--new"); + args.push(input.target); + + return makeLaunchPlan("open", args, { + wait, + allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, + shell: false, + }); +} + +function makeDarwinApplicationPlan( + input: OpenExternalInput, + app: OpenApplicationCandidate, +): LaunchPlan { + const args: string[] = []; + const wait = input.wait ?? false; + + if (wait) args.push("--wait-apps"); + if (input.background) args.push("--background"); + if (input.newInstance) args.push("--new"); + args.push("-a", app.name); + args.push(input.target); + if (app.arguments.length > 0) { + args.push("--args", ...app.arguments); + } + + return makeLaunchPlan("open", args, { + wait, + allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, + shell: false, + }); +} + +function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan { + const encodedParts = ["Start"]; + const wait = input.wait ?? false; + + if (wait) encodedParts.push("-Wait"); + encodedParts.push(quotePowerShellValue(input.target)); + + return makeLaunchPlan( + powerShellCommand, + [ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-EncodedCommand", + encodePowerShellCommand(encodedParts.join(" ")), + ], + { + wait, + allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, + shell: false, + }, + ); +} + +function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan { + const wait = input.wait ?? false; + return makeLaunchPlan("xdg-open", [input.target], { + wait, + allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, + detached: !wait, + ...(wait ? {} : { stdio: "ignore" as const }), + shell: false, + }); +} + +function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan { + return makeLaunchPlan("explorer", [input.target], { + wait: false, + allowNonzeroExitCode: false, + shell: false, + }); +} + +function makeDirectApplicationPlan( + input: OpenExternalInput, + app: OpenApplicationCandidate, +): LaunchPlan { + return makeLaunchPlan(app.name, [...app.arguments, input.target], { + wait: input.wait ?? false, + allowNonzeroExitCode: input.allowNonzeroExitCode ?? false, + shell: false, + }); +} + +function resolveExternalPlans( + input: OpenExternalInput, + runtime: LaunchRuntime, +): ReadonlyArray { + const appCandidates = normalizeAppCandidates(input.app); + const plans: LaunchPlan[] = []; + const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime); + + for (const app of appCandidates) { + if (app) { + if (runtime.platform === "darwin") { + plans.push(makeDarwinApplicationPlan(input, app)); + } else { + plans.push(makeDirectApplicationPlan(input, app)); + } + continue; + } + + if (runtime.platform === "darwin") { + plans.push(makeDarwinDefaultPlan(input)); + continue; + } + + if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) { + for (const powerShellCommand of runtime.powerShellCandidates) { + plans.push(makePowerShellPlan(input, powerShellCommand)); + } + } + + if (runtime.platform === "win32") { + if (!(input.wait ?? false)) { + plans.push(makeWindowsExplorerPlan(input)); + } + continue; + } + + plans.push(makeLinuxDefaultPlan(input)); + } + + return plans; +} + +function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean { + return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never); +} + +function quoteForWindowsCmd(value: string): string { + return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`; +} + +function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray): string { + return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`; +} + +function resolveSpawnInput( + runtime: LaunchRuntime, + plan: LaunchPlan, + resolvedCommand: ResolvedCommand, +): DetachedSpawnInput { + return { + command: resolvedCommand.usesCmdWrapper + ? resolveWindowsCommandShell(runtime.env) + : resolvedCommand.path, + args: resolvedCommand.usesCmdWrapper + ? ["/d", "/v:off", "/s", "/c", makeWindowsCmdCommandLine(resolvedCommand.path, plan.args)] + : [...plan.args], + ...(plan.detached !== undefined ? { detached: plan.detached } : {}), + ...(plan.shell !== undefined ? { shell: plan.shell } : {}), + ...(plan.stdio === "ignore" + ? { + stdin: "ignore" as const, + stdout: "ignore" as const, + stderr: "ignore" as const, + } + : {}), + }; +} + +function makeCommandNotFoundError( + context: LaunchContext, + command: string, +): DesktopLauncherCommandNotFoundError { + return new DesktopLauncherCommandNotFoundError({ + operation: context.operation, + command, + ...(context.target !== undefined ? { target: context.target } : {}), + ...(context.editor !== undefined ? { editor: context.editor } : {}), + }); +} + +function makeSpawnError( + context: LaunchContext, + command: string, + args: ReadonlyArray, + cause?: unknown, +): DesktopLauncherSpawnError { + return new DesktopLauncherSpawnError({ + operation: context.operation, + command, + args: [...args], + ...(context.target !== undefined ? { target: context.target } : {}), + ...(context.editor !== undefined ? { editor: context.editor } : {}), + ...(cause !== undefined ? { cause } : {}), + }); +} + +function makeNonZeroExitError( + context: LaunchContext, + command: string, + args: ReadonlyArray, + exitCode: number, +): DesktopLauncherNonZeroExitError { + return new DesktopLauncherNonZeroExitError({ + operation: context.operation, + command, + args: [...args], + exitCode, + ...(context.target !== undefined ? { target: context.target } : {}), + ...(context.editor !== undefined ? { editor: context.editor } : {}), + }); +} + +function toLaunchAttemptFailure(error: LaunchAttemptError): LaunchAttemptFailure { + switch (error._tag) { + case "DesktopLauncherCommandNotFoundError": + return { + command: error.command, + args: [], + reason: "commandNotFound", + detail: error.message, + }; + case "DesktopLauncherSpawnError": + return { + command: error.command, + args: error.args, + reason: "spawnFailed", + detail: error.message, + }; + case "DesktopLauncherNonZeroExitError": + return { + command: error.command, + args: error.args, + reason: "nonZeroExit", + detail: error.message, + exitCode: error.exitCode, + }; + } +} + +/** + * Detached GUI launches must call `unref()` after spawn. The Effect + * `ChildProcessSpawner` owns spawned handles through scope finalizers and does + * not expose `unref()`, which means it cannot provide true fire-and-forget + * behavior for editor / file-manager launches. + */ +function defaultSpawnDetached( + input: DetachedSpawnInput, + context: LaunchContext, +): Effect.Effect { + return Effect.try({ + try: () => + spawnNodeChildProcess(input.command, [...input.args], { + ...(input.detached !== undefined ? { detached: input.detached } : {}), + ...(input.shell !== undefined ? { shell: input.shell } : {}), + ...(input.stdin === "ignore" && input.stdout === "ignore" && input.stderr === "ignore" + ? { stdio: "ignore" as const } + : {}), + }), + catch: (cause) => makeSpawnError(context, input.command, input.args, cause), + }).pipe( + Effect.flatMap((childProcess) => + Effect.callback((resume) => { + const onError = (error: Error) => { + childProcess.off("spawn", onSpawn); + resume(Effect.fail(makeSpawnError(context, input.command, input.args, error))); + }; + const onSpawn = () => { + childProcess.off("error", onError); + childProcess.unref(); + resume(Effect.void); + }; + + childProcess.once("error", onError); + childProcess.once("spawn", onSpawn); + + return Effect.sync(() => { + childProcess.off("error", onError); + childProcess.off("spawn", onSpawn); + }); + }), + ), + ); +} + +export const make = Effect.fn("makeDesktopLauncher")(function* ( + options: LaunchRuntimeOptions = {}, +) { + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + + const isInsideContainer = + options.isInsideContainer ?? + (typeof options.env?.CONTAINER === "string" || + typeof options.env?.container === "string" || + typeof options.env?.KUBERNETES_SERVICE_HOST === "string" + ? true + : yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false)))); + + const runtime: LaunchRuntime = { + platform: options.platform ?? process.platform, + env: options.env ?? process.env, + isWsl: + options.isWsl ?? detectWsl(options.platform ?? process.platform, options.env ?? process.env), + isInsideContainer, + powerShellCandidates: + options.powerShellCommand !== undefined + ? [options.powerShellCommand] + : (options.isWsl ?? + detectWsl(options.platform ?? process.platform, options.env ?? process.env)) + ? WSL_POWERSHELL_CANDIDATES + : WINDOWS_POWERSHELL_CANDIDATES, + windowsPathExtensions: resolveWindowsPathExtensions(options.env ?? process.env), + }; + + const resolveCommand = Effect.fn("resolveCommand")(function* ( + command: string, + ): Effect.fn.Return> { + const candidates = resolveCommandCandidates(command, runtime, pathService); + + const resolveExecutableFile = Effect.fn("resolveExecutableFile")(function* ( + filePath: string, + ): Effect.fn.Return> { + const info = yield* fileSystem.stat(filePath).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File") return Option.none(); + + if (runtime.platform === "win32") { + const extension = pathService.extname(filePath); + if ( + extension.length === 0 || + !runtime.windowsPathExtensions.includes(extension.toUpperCase()) + ) { + return Option.none(); + } + + return Option.some({ + path: filePath, + usesCmdWrapper: isWindowsBatchShim(pathService, filePath), + } satisfies ResolvedCommand); + } + + return (info.value.mode & 0o111) !== 0 + ? Option.some({ + path: filePath, + usesCmdWrapper: false, + } satisfies ResolvedCommand) + : Option.none(); + }); + + if (command.includes("/") || command.includes("\\")) { + for (const candidate of candidates) { + const resolved = yield* resolveExecutableFile(candidate); + if (Option.isSome(resolved)) return resolved; + } + return Option.none(); + } + + const pathValue = resolvePathEnvironmentVariable(runtime.env); + if (pathValue.length === 0) return Option.none(); + + const pathEntries = pathValue + .split(resolvePathDelimiter(runtime.platform)) + .map((entry) => stripWrappingQuotes(entry.trim())) + .filter((entry) => entry.length > 0); + + for (const pathEntry of pathEntries) { + for (const candidate of candidates) { + const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate)); + if (Option.isSome(resolved)) { + return resolved; + } + } + } + + return Option.none(); + }); + + const commandAvailable = (command: string) => + resolveCommand(command).pipe(Effect.map(Option.isSome)); + + const fileManagerAvailable = Effect.gen(function* () { + const candidates = + runtime.platform === "darwin" + ? ["open"] + : runtime.platform === "win32" + ? [...runtime.powerShellCandidates, "explorer"] + : ["xdg-open"]; + + for (const candidate of candidates) { + if (yield* commandAvailable(candidate)) { + return true; + } + } + + return false; + }); + + const getAvailableEditors: DesktopLauncherShape["getAvailableEditors"] = Effect.gen(function* () { + const available: EditorId[] = []; + + for (const editor of EDITORS) { + if (editor.id === "file-manager") { + if (yield* fileManagerAvailable) { + available.push(editor.id); + } + continue; + } + + if (editor.command && (yield* commandAvailable(editor.command))) { + available.push(editor.id); + } + } + + return available; + }).pipe( + Effect.mapError( + (cause) => + new DesktopLauncherDiscoveryError({ + operation: "getAvailableEditors", + detail: "failed to resolve available editors", + cause, + }), + ), + ); + + const spawnPlan = ( + plan: LaunchPlan, + resolvedCommand: ResolvedCommand, + context: LaunchContext, + ) => { + const input = resolveSpawnInput(runtime, plan, resolvedCommand); + return spawner + .spawn( + ChildProcess.make(input.command, [...input.args], { + detached: plan.detached, + shell: plan.shell, + ...(plan.stdio === "ignore" + ? { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + } + : {}), + }), + ) + .pipe(Effect.mapError((cause) => makeSpawnError(context, input.command, input.args, cause))); + }; + + const spawnDetached = options.spawnDetached ?? defaultSpawnDetached; + + const waitForExit = ( + plan: LaunchPlan, + context: LaunchContext, + spawnInput: DetachedSpawnInput, + handle: ChildProcessSpawner.ChildProcessHandle, + ) => + handle.exitCode.pipe( + Effect.flatMap((exitCode) => + !plan.allowNonzeroExitCode && exitCode !== 0 + ? Effect.fail( + makeNonZeroExitError(context, spawnInput.command, spawnInput.args, exitCode), + ) + : Effect.void, + ), + Effect.mapError((cause) => + makeSpawnError(context, spawnInput.command, spawnInput.args, cause), + ), + ); + + const runWaitedPlan = ( + plan: LaunchPlan, + resolvedCommand: ResolvedCommand, + context: LaunchContext, + ) => + Effect.acquireUseRelease( + Scope.make("sequential"), + (scope) => + Effect.gen(function* () { + const spawnInput = resolveSpawnInput(runtime, plan, resolvedCommand); + const handle = yield* spawnPlan(plan, resolvedCommand, context).pipe( + Scope.provide(scope), + ); + yield* waitForExit(plan, context, spawnInput, handle); + }), + (scope, exit) => Scope.close(scope, exit), + ); + + const runDetachedPlan = ( + plan: LaunchPlan, + resolvedCommand: ResolvedCommand, + context: LaunchContext, + ) => spawnDetached(resolveSpawnInput(runtime, plan, resolvedCommand), context); + + const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, context: LaunchContext) => + plan.wait + ? runWaitedPlan(plan, resolvedCommand, context) + : runDetachedPlan(plan, resolvedCommand, context); + + const runFirstAvailablePlan = Effect.fn("runFirstAvailablePlan")(function* ( + plans: ReadonlyArray, + context: LaunchContext, + ): Effect.fn.Return { + const failures: LaunchAttemptError[] = []; + + for (const plan of plans) { + const resolvedCommand = yield* resolveCommand(plan.command); + if (Option.isNone(resolvedCommand)) { + failures.push(makeCommandNotFoundError(context, plan.command)); + continue; + } + + const attempt = yield* Effect.result(runPlan(plan, resolvedCommand.value, context)); + if (attempt._tag === "Success") { + return; + } + + failures.push(attempt.failure); + } + + const [firstFailure] = failures; + if (failures.length === 1 && firstFailure) { + return yield* firstFailure; + } + + return yield* new DesktopLauncherLaunchAttemptsExhaustedError({ + operation: context.operation, + ...(context.target !== undefined ? { target: context.target } : {}), + ...(context.editor !== undefined ? { editor: context.editor } : {}), + attempts: failures.map(toLaunchAttemptFailure), + }); + }); + + const openTarget = Effect.fn("openTarget")(function* ( + operation: Extract, + input: OpenExternalInput, + context: Omit = {}, + ) { + if (input.target.trim().length === 0) { + return yield* new DesktopLauncherValidationError({ + operation, + detail: "target must not be empty", + target: input.target, + }); + } + + return yield* runFirstAvailablePlan(resolveExternalPlans(input, runtime), { + operation, + target: input.target, + ...(context.editor !== undefined ? { editor: context.editor } : {}), + }); + }); + + const openExternal: DesktopLauncherShape["openExternal"] = Effect.fn("openExternal")( + function* (input) { + return yield* openTarget("openExternal", input); + }, + ); + + const openBrowser: DesktopLauncherShape["openBrowser"] = Effect.fn("openBrowser")(function* ( + target, + openOptions = {}, + ) { + return yield* openTarget("openBrowser", { ...openOptions, target }); + }); + + const openInEditor: DesktopLauncherShape["openInEditor"] = Effect.fn("openInEditor")( + function* (input) { + const editor = EDITORS.find((candidate) => candidate.id === input.editor); + if (!editor) { + return yield* new DesktopLauncherUnknownEditorError({ editor: input.editor }); + } + + if (editor.command) { + return yield* runFirstAvailablePlan( + [ + makeLaunchPlan( + editor.command, + shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd], + { + wait: false, + allowNonzeroExitCode: false, + detached: true, + stdio: "ignore", + shell: false, + }, + ), + ], + { + operation: "openInEditor", + target: input.cwd, + editor: input.editor, + }, + ); + } + + return yield* openTarget( + "openInEditor", + { target: input.cwd }, + { target: input.cwd, editor: input.editor }, + ); + }, + ); + + return { + getAvailableEditors, + openExternal, + openBrowser, + openInEditor, + } satisfies DesktopLauncherShape; +}); + +export const layer = Layer.effect(DesktopLauncher, make()); diff --git a/apps/server/src/process/Services/DesktopLauncher.ts b/apps/server/src/process/Services/DesktopLauncher.ts new file mode 100644 index 0000000000..5d29bfb0b7 --- /dev/null +++ b/apps/server/src/process/Services/DesktopLauncher.ts @@ -0,0 +1,200 @@ +/** + * Open - Browser/editor launch service interface. + * + * Owns process launch helpers for opening URLs in a browser, workspace paths in + * a configured editor, and generic external targets through the platform's + * default opener. + * + * @module Open + */ + +import { type EditorId } from "@t3tools/contracts"; +import { Effect, Schema, ServiceMap } from "effect"; + +const DesktopLauncherLaunchAttemptSchema = Schema.Struct({ + command: Schema.String, + args: Schema.Array(Schema.String), + reason: Schema.Literals(["commandNotFound", "spawnFailed", "nonZeroExit"]), + detail: Schema.String, + exitCode: Schema.optional(Schema.Number), +}); + +export class DesktopLauncherDiscoveryError extends Schema.TaggedErrorClass()( + "DesktopLauncherDiscoveryError", + { + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Desktop launcher discovery failed in ${this.operation}: ${this.detail}`; + } +} + +export class DesktopLauncherValidationError extends Schema.TaggedErrorClass()( + "DesktopLauncherValidationError", + { + operation: Schema.String, + detail: Schema.String, + target: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Desktop launcher validation failed in ${this.operation}: ${this.detail}`; + } +} + +export class DesktopLauncherUnknownEditorError extends Schema.TaggedErrorClass()( + "DesktopLauncherUnknownEditorError", + { + editor: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Unknown desktop editor: ${this.editor}`; + } +} + +export class DesktopLauncherCommandNotFoundError extends Schema.TaggedErrorClass()( + "DesktopLauncherCommandNotFoundError", + { + operation: Schema.String, + command: Schema.String, + target: Schema.optional(Schema.String), + editor: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + const target = this.editor + ? ` for editor ${this.editor}` + : this.target + ? ` for ${this.target}` + : ""; + return `Desktop launcher command not found in ${this.operation}: ${this.command}${target}`; + } +} + +export class DesktopLauncherSpawnError extends Schema.TaggedErrorClass()( + "DesktopLauncherSpawnError", + { + operation: Schema.String, + command: Schema.String, + args: Schema.Array(Schema.String), + target: Schema.optional(Schema.String), + editor: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Desktop launcher failed to spawn ${this.command} in ${this.operation}`; + } +} + +export class DesktopLauncherNonZeroExitError extends Schema.TaggedErrorClass()( + "DesktopLauncherNonZeroExitError", + { + operation: Schema.String, + command: Schema.String, + args: Schema.Array(Schema.String), + exitCode: Schema.Number, + target: Schema.optional(Schema.String), + editor: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return `Desktop launcher command exited non-zero in ${this.operation}: ${this.command} (code=${this.exitCode})`; + } +} + +export class DesktopLauncherLaunchAttemptsExhaustedError extends Schema.TaggedErrorClass()( + "DesktopLauncherLaunchAttemptsExhaustedError", + { + operation: Schema.String, + target: Schema.optional(Schema.String), + editor: Schema.optional(Schema.String), + attempts: Schema.Array(DesktopLauncherLaunchAttemptSchema), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + const subject = this.editor ? `editor ${this.editor}` : this.target ? this.target : "target"; + return `Desktop launcher exhausted all launch attempts in ${this.operation} for ${subject}`; + } +} + +export const DesktopLauncherError = Schema.Union([ + DesktopLauncherCommandNotFoundError, + DesktopLauncherDiscoveryError, + DesktopLauncherLaunchAttemptsExhaustedError, + DesktopLauncherNonZeroExitError, + DesktopLauncherSpawnError, + DesktopLauncherUnknownEditorError, + DesktopLauncherValidationError, +]); + +export interface OpenInEditorInput { + readonly cwd: string; + readonly editor: EditorId; +} + +export interface OpenApplicationInput { + readonly name: string | ReadonlyArray; + readonly arguments?: ReadonlyArray; +} + +export interface OpenExternalInput { + readonly target: string; + readonly wait?: boolean; + readonly background?: boolean; + readonly newInstance?: boolean; + readonly allowNonzeroExitCode?: boolean; + readonly app?: OpenApplicationInput | ReadonlyArray; +} + +export interface DesktopLauncherShape { + readonly getAvailableEditors: Effect.Effect< + ReadonlyArray, + DesktopLauncherDiscoveryError + >; + readonly openExternal: ( + input: OpenExternalInput, + ) => Effect.Effect< + void, + | DesktopLauncherCommandNotFoundError + | DesktopLauncherLaunchAttemptsExhaustedError + | DesktopLauncherNonZeroExitError + | DesktopLauncherSpawnError + | DesktopLauncherValidationError + >; + readonly openBrowser: ( + target: string, + options?: Omit, + ) => Effect.Effect< + void, + | DesktopLauncherCommandNotFoundError + | DesktopLauncherLaunchAttemptsExhaustedError + | DesktopLauncherNonZeroExitError + | DesktopLauncherSpawnError + | DesktopLauncherValidationError + >; + readonly openInEditor: ( + input: OpenInEditorInput, + ) => Effect.Effect< + void, + | DesktopLauncherCommandNotFoundError + | DesktopLauncherLaunchAttemptsExhaustedError + | DesktopLauncherNonZeroExitError + | DesktopLauncherSpawnError + | DesktopLauncherUnknownEditorError + | DesktopLauncherValidationError + >; +} + +export class DesktopLauncher extends ServiceMap.Service()( + "t3/desktop-launcher", +) {} diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index ba5eddc030..90a76bbd9b 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -48,7 +48,7 @@ import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistenc import { SqlClient, SqlError } from "effect/unstable/sql"; import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService"; import { ProviderRegistry, type ProviderRegistryShape } from "./provider/Services/ProviderRegistry"; -import { Open, type OpenShape } from "./open"; +import { DesktopLauncher, type DesktopLauncherShape } from "./process/Services/DesktopLauncher"; import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; import type { GitCoreShape } from "./git/Services/GitCore.ts"; import { GitCore } from "./git/Services/GitCore.ts"; @@ -62,10 +62,10 @@ const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeU const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); -const defaultOpenService: OpenShape = { +const defaultDesktopLauncherService: DesktopLauncherShape = { getAvailableEditors: Effect.succeed([]), openExternal: () => Effect.void, - openBrowser: () => Effect.void, + openBrowser: (_target) => Effect.void, openInEditor: () => Effect.void, }; @@ -501,7 +501,7 @@ describe("WebSocket Server", () => { staticDir?: string; providerLayer?: Layer.Layer; providerRegistry?: ProviderRegistryShape; - open?: OpenShape; + desktopLauncher?: DesktopLauncherShape; gitManager?: GitManagerShape; gitCore?: Pick; terminalManager?: TerminalManagerShape; @@ -522,7 +522,10 @@ describe("WebSocket Server", () => { ProviderRegistry, options.providerRegistry ?? defaultProviderRegistryService, ); - const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService); + const desktopLauncherLayer = Layer.succeed( + DesktopLauncher, + options.desktopLauncher ?? defaultDesktopLauncherService, + ); const serverConfigLayer = Layer.succeed(ServerConfig, { mode: "web", port: 0, @@ -558,7 +561,7 @@ describe("WebSocket Server", () => { const dependenciesLayer = Layer.empty.pipe( Layer.provideMerge(runtimeLayer), Layer.provideMerge(providerRegistryLayer), - Layer.provideMerge(openLayer), + Layer.provideMerge(desktopLauncherLayer), Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)), Layer.provideMerge(serverConfigLayer), Layer.provideMerge(AnalyticsService.layerTest), @@ -1031,7 +1034,7 @@ describe("WebSocket Server", () => { it("routes shell.openInEditor through the injected open service", async () => { const openCalls: Array<{ cwd: string; editor: string }> = []; - const openService: OpenShape = { + const desktopLauncherService: DesktopLauncherShape = { getAvailableEditors: Effect.succeed([]), openExternal: () => Effect.void, openBrowser: () => Effect.void, @@ -1041,7 +1044,10 @@ describe("WebSocket Server", () => { }, }; - server = await createTestServer({ cwd: "/my/workspace", open: openService }); + server = await createTestServer({ + cwd: "/my/workspace", + desktopLauncher: desktopLauncherService, + }); const addr = server.address(); const port = typeof addr === "object" && addr !== null ? addr.port : 0; @@ -1534,7 +1540,7 @@ describe("WebSocket Server", () => { }; process.on("unhandledRejection", onUnhandledRejection); - const brokenOpenService: OpenShape = { + const brokenDesktopLauncherService: DesktopLauncherShape = { getAvailableEditors: Effect.succeed([]), openExternal: () => Effect.void, openBrowser: () => Effect.void, @@ -1543,7 +1549,10 @@ describe("WebSocket Server", () => { }; try { - server = await createTestServer({ cwd: "/test", open: brokenOpenService }); + server = await createTestServer({ + cwd: "/test", + desktopLauncher: brokenDesktopLauncherService, + }); const addr = server.address(); const port = typeof addr === "object" && addr !== null ? addr.port : 0; diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index 9983e0209b..7a87add734 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -58,7 +58,7 @@ import { ProviderService } from "./provider/Services/ProviderService"; import { ProviderRegistry } from "./provider/Services/ProviderRegistry"; import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery"; import { clamp } from "effect/Number"; -import { Open } from "./open"; +import { DesktopLauncher } from "./process/Services/DesktopLauncher"; import { ServerConfig } from "./config"; import { GitCore } from "./git/Services/GitCore.ts"; import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute"; @@ -218,7 +218,7 @@ export type ServerRuntimeServices = | TerminalManager | Keybindings | ServerSettingsService - | Open + | DesktopLauncher | AnalyticsService; export class ServerLifecycleError extends Schema.TaggedErrorClass()( @@ -250,7 +250,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< logWebSocketEvents, autoBootstrapProjectFromCwd, } = serverConfig; - const open = yield* Open; + const open = yield* DesktopLauncher; const availableEditors = yield* open.getAvailableEditors.pipe( Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })), ); @@ -618,7 +618,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< const projectionReadModelQuery = yield* ProjectionSnapshotQuery; const checkpointDiffQuery = yield* CheckpointDiffQuery; const orchestrationReactor = yield* OrchestrationReactor; - const { openInEditor } = open; const subscriptionsScope = yield* Scope.make("sequential"); yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void)); @@ -810,7 +809,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< case WS_METHODS.shellOpenInEditor: { const body = stripRequestTag(request.body); - return yield* openInEditor(body); + return yield* open.openInEditor(body); } case WS_METHODS.gitStatus: {