Improve WSL-hosted Windows interop for process spawning, editor/file-manager launch, and browser open #170
Closedjuliusmarmingewants to merge 10 commits into
main fromt3code/improve-windows-wsl-interopopened View on GitHub- apps/server/src/provider/Layers/ProviderHealth.ts line 220Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -180,14 +198,8 @@180198181- const child = yield* spawner.spawn(command);182-183- const [stdout, stderr, exitCode] = yield* Effect.all(184- [185- collectStreamAsString(child.stdout),186- collectStreamAsString(child.stderr),187- child.exitCode.pipe(Effect.map(Number)),188- ],189- { concurrency: "unbounded" },190- );191-192- return { stdout, stderr, code: exitCode } satisfies CommandResult;193- }).pipe(Effect.scoped);199+ return {200+ stdout: result.stdout,201+ stderr: result.stderr,202+ code: result.code ?? 0,203+ timedOut: result.timedOut,204+ } satisfies CommandResult;205+};@@ -26,0 +68,21 @@68+69+ return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";70+}71+72+function toSpawnOptions(options: ProcessSpawnOptions) {73+ return {74+ cwd: options.cwd,75+ env: options.env,76+ shell: shouldUseShell(options),77+ ...(options.stdio !== undefined ? { stdio: options.stdio } : {}),78+ ...(options.detached !== undefined ? { detached: options.detached } : {}),79+ };80+}81+82+export function spawnProcess(83+ command: string,84+ args: readonly string[],85+ options: ProcessSpawnOptions = {},86+): ChildProcessHandle {87+ return spawn(command, args, toSpawnOptions(options));88+}
- apps/server/src/git/Layers/GitService.ts lines 71 to 83OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -117,0 +63,21 @@63+ throw new GitCommandError({64+ operation: commandInput.operation,65+ command: quoteGitCommand(commandInput.args),66+ cwd: commandInput.cwd,67+ detail: `${quoteGitCommand(commandInput.args)} timed out.`,68+ });69+ }70+71+ const exitCode = result.code ?? 0;72+ if (!input.allowNonZeroExit && exitCode !== 0) {73+ const trimmedStderr = result.stderr.trim();74+ throw new GitCommandError({75+ operation: commandInput.operation,76+ command: quoteGitCommand(commandInput.args),77+ cwd: commandInput.cwd,78+ detail:79+ trimmedStderr.length > 080+ ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`81+ : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,82+ });83+ }
- apps/server/src/codexAppServerManager.ts lines 210 to 220Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -198,10 +194,11 @@198- const child = spawn(codexBinaryPath, ["app-server"], {199- cwd: resolvedCwd,200- env: {201- ...process.env,202- ...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),203- },204- stdio: ["pipe", "pipe", "pipe"],205- shell: process.platform === "win32",206- });207- const output = readline.createInterface({ input: child.stdout });194+ const managedProcess = await this.runPromise(195+ spawnManagedCommand(196+ makeRuntimeCommand(codexBinaryPath, ["app-server"], {197+ cwd: resolvedCwd,198+ env: {199+ ...process.env,200+ ...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),201+ },202+ extendEnv: false,203+ }),204+ ),apps/server/src/processRunner.ts lines 75 to 81OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -24,3 +66,16 @@2466 return [command, ...args].join(" ");2567 }266869+function resolveRuntimeEnvironment(70+ runtimeEnvironment: ServerRuntimeEnvironment | undefined,71+): ServerRuntimeEnvironment {72+ return runtimeEnvironment ?? detectServerRuntimeEnvironment();73+}74+75+function shouldUseShell(options: RuntimeShellOptions): boolean | string {76+ if (options.shell !== undefined) {77+ return options.shell;78+ }79+80+ return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";81+}
- apps/server/src/codexAppServerManager.ts line 577OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -573,4 +561,17 @@573- });574- this.emitLifecycleEvent(context, "session/exited", message);575- this.sessions.delete(context.session.sessionId);576- });561+ yield* Effect.forkScoped(562+ Effect.matchCauseEffect(context.child.exitCode, {563+ onFailure: (cause) =>564+ Effect.sync(() => {565+ if (context.stopping) {566+ return;567+ }568+569+ const message =570+ cause instanceof Error ? cause.message : "codex app-server process errored.";571+ this.updateSession(context, {572+ status: "error",573+ activeTurnId: undefined,574+ lastError: message,575+ });576+ this.emitErrorEvent(context, "process/error", message);577+ this.sessions.delete(context.session.sessionId);
- @@ -26,0 +80,21 @@80+ return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";81+}82+83+function toSpawnOptions(options: ProcessSpawnOptions) {84+ return {85+ cwd: options.cwd,86+ env: options.env,87+ shell: shouldUseShell(options),88+ ...(options.stdio !== undefined ? { stdio: options.stdio } : {}),89+ ...(options.detached !== undefined ? { detached: options.detached } : {}),90+ };91+}92+93+export function toRuntimeCommandOptions(94+ options: RuntimeCommandOptions = {},95+): ChildProcess.CommandOptions {96+ return {97+ ...options,98+ shell: options.shell ?? shouldUseShell(options),99+ };100+}@@ -26,0 +80,21 @@80+ return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";81+}82+83+function toSpawnOptions(options: ProcessSpawnOptions) {84+ return {85+ cwd: options.cwd,86+ env: options.env,87+ shell: shouldUseShell(options),88+ ...(options.stdio !== undefined ? { stdio: options.stdio } : {}),89+ ...(options.detached !== undefined ? { detached: options.detached } : {}),90+ };91+}92+93+export function toRuntimeCommandOptions(94+ options: RuntimeCommandOptions = {},95+): ChildProcess.CommandOptions {96+ return {97+ ...options,98+ shell: options.shell ?? shouldUseShell(options),99+ };100+}apps/server/src/provider/Layers/ProviderHealth.ts line 63Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -36,5 +59,4 @@3659 }37603861 function isCommandMissingCause(error: unknown): boolean {39- if (!(error instanceof Error)) return false;40- const lower = error.message.toLowerCase();62+ const lower = errorMessage(error).toLowerCase();
- apps/server/src/processRunner.ts line 111OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -26,0 +91,21 @@91+ runtimeEnvironment: ServerRuntimeEnvironment | undefined,92+): ServerRuntimeEnvironment {93+ return runtimeEnvironment ?? detectServerRuntimeEnvironment();94+}95+96+function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {97+ return env.PATH ?? env.Path ?? env.path ?? "";98+}99+100+function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {101+ const rawValue = env.PATHEXT;102+ const fallback = [".COM", ".EXE", ".BAT", ".CMD"];103+ if (!rawValue) return fallback;104+105+ const parsed = rawValue106+ .split(";")107+ .map((entry) => entry.trim())108+ .filter((entry) => entry.length > 0)109+ .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));110+ return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;111+}apps/server/src/codexAppServerManager.ts line 188Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -171,6 +161,21 @@171161 export interface CodexAppServerManagerEvents {172162 event: [event: ProviderEvent];173163 }174164175165 export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {176166 private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();167+ private readonly runPromise: <A, E>(168+ effect: Effect.Effect<A, E, NodeServices.NodeServices>,169+ options?: Effect.RunOptions | undefined,170+ ) => Promise<A>;171+172+ constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {173+ super();174+ this.runPromise = services175+ ? Effect.runPromiseWith(services)176+ : ((effect, options) =>177+ Effect.runPromise(178+ effect as unknown as Effect.Effect<unknown, never>,179+ options,180+ )) as typeof this.runPromise;181+ }
- apps/server/src/processRunner.ts line 115Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -26,0 +153,21 @@153+ return true;154+ }155+ return windowsPathExtensions.includes(extension.toUpperCase());156+ } catch {157+ return false;158+ }159+}160+161+function resolveEffectiveEnvironment(options: ProcessLaunchPlanOptions): NodeJS.ProcessEnv {162+ const env = (options.env ?? {}) as NodeJS.ProcessEnv;163+ if (options.inheritParentEnv === false) {164+ return { ...env };165+ }166+167+ return {168+ ...process.env,169+ ...env,170+ };171+}172+173+function resolveWindowsCommand(apps/server/src/processRunner.ts lines 214 to 231OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -26,0 +211,21 @@211+ return null;212+}213+214+function quoteWindowsBatchArgument(argument: string): string {215+ if (argument.length === 0) {216+ return '""';217+ }218+219+ const escaped = argument220+ .replaceAll("^", "^^")221+ .replaceAll("%", "%%")222+ .replaceAll("!", "^!")223+ .replaceAll("&", "^&")224+ .replaceAll("|", "^|")225+ .replaceAll("<", "^<")226+ .replaceAll(">", "^>")227+ .replaceAll("(", "^(")228+ .replaceAll(")", "^)")229+ .replaceAll('"', '""');230+ return `"${escaped}"`;231+}
- apps/server/src/codexAppServerManager.ts line 564Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -558,9 +547,13 @@558- lastError: message,559- });560- this.emitErrorEvent(context, "process/error", message);561- });547+ private async attachProcessListeners(context: CodexSessionContext): Promise<void> {548+ await this.runPromise(549+ Effect.gen(550+ function* (this: CodexAppServerManager) {551+ yield* Effect.forkScoped(552+ Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stdout)), (line) =>553+ Effect.sync(() => {554+ this.handleStdoutLine(context, line);555+ }),556+ ),557+ );562558563- context.child.on("exit", (code, signal) => {564- if (context.stopping) {565- return;566- }559+ yield* Effect.forkScoped(
- apps/server/src/processRunner.ts line 269Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -26,0 +268,21 @@268+ args: ReadonlyArray<string>,269+ options: RuntimeCommandOptions = {},270+): ChildProcess.StandardCommand {271+ const launchPlan = resolveProcessLaunchPlan(command, args, {272+ cwd: options.cwd,273+ env: options.env,274+ runtimeEnvironment: options.runtimeEnvironment,275+ shell: options.shell,276+ inheritParentEnv: options.extendEnv !== false,277+ });278+ return ChildProcess.make(launchPlan.command, launchPlan.args, {279+ ...toRuntimeCommandOptions(options, launchPlan.shell),280+ });281+}282+283+interface ManagedChildProcess {284+ readonly scope: Scope.Closeable;285+ readonly handle: ChildProcessSpawner.ChildProcessHandle;286+}287+288+export const spawnManagedCommand = (command: ChildProcess.Command) =>apps/server/src/processRunner.ts lines 223 to 234Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -26,0 +233,21 @@233+234+ return {235+ command: resolved.path,236+ args: [...args],237+ shell: false,238+ runtimeEnvironment,239+ };240+}241+242+function toSpawnOptions(243+ options: ProcessSpawnOptions,244+ launchPlan: ProcessLaunchPlan,245+) {246+ return {247+ cwd: options.cwd,248+ env: options.env,249+ shell: launchPlan.shell,250+ ...(options.stdio !== undefined ? { stdio: options.stdio } : {}),251+ ...(options.detached !== undefined ? { detached: options.detached } : {}),252+ };253+}
- apps/server/src/codexAppServerManager.ts line 836Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -786,14 +833,18 @@786833 });787- this.writeMessage(context, {834+ void this.writeMessage(context, {788835 method,789836 id,790837 params,838+ }).catch((error) => {839+ clearTimeout(timeout);840+ context.pending.delete(String(id));841+ reject(error instanceof Error ? error : new Error(String(error)));791842 });792843 });793844794845 return result as TResponse;795846 }796847797- private writeMessage(context: CodexSessionContext, message: unknown): void {848+ private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {798849 const encoded = JSON.stringify(message);799- if (!context.child.stdin.writable) {850+ if (context.stopping) {@@ -219,5 +338,20 @@219338 if (editorDef.id !== "file-manager") {220339 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });221340 }222341223- return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };342+ const candidateCommands = resolveOpenCommand(editorDef.id, {343+ platform,344+ env,345+ runtimeEnvironment,346+ });347+ const command =348+ candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??349+ candidateCommands[0];350+ if (!command) {351+ return yield* new OpenError({ message: "Editor command not found: file-manager" });352+ }353+354+ let target = stripLineColumnSuffix(input.cwd);355+ if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {356+ target = yield* Effect.try({357+ try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
- @@ -26,0 +355,21 @@355+ command: string,356+ args: readonly string[],357+ options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},358+): Promise<void> {359+ return new Promise<void>((resolve, reject) => {360+ const child = spawnProcess(command, args, {361+ ...options,362+ detached: true,363+ stdio: "ignore",364+ });365+366+ const handleSpawn = () => {367+ child.unref();368+ resolve();369+ };370+371+ child.once("spawn", handleSpawn);372+ child.once("error", (error) => {373+ reject(normalizeSpawnError(command, args, error));374+ });375+ });
- apps/server/src/codexAppServerManager.ts line 606OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -576,0 +586,21 @@586+ activeTurnId: undefined,587+ lastError: message,588+ });589+ this.emitErrorEvent(context, "process/error", message);590+ this.sessions.delete(context.session.sessionId);591+ }),592+ onSuccess: (code) =>593+ Effect.sync(() => {594+ if (context.stopping) {595+ return;596+ }597+598+ const message = `codex app-server exited (code=${code}).`;599+ this.updateSession(context, {600+ status: "closed",601+ activeTurnId: undefined,602+ lastError: code === 0 ? context.session.lastError : message,603+ });604+ this.emitLifecycleEvent(context, "session/exited", message);605+ this.sessions.delete(context.session.sessionId);606+ }),
- @@ -49,3 +49,4 @@4949 export const ServerProviderStatuses = Schema.Array(ServerProviderStatus);5050 export type ServerProviderStatuses = typeof ServerProviderStatuses.Type;515152+export const ServerRuntimePlatform = Schema.Literals(["windows", "linux", "macos"]);@@ -572,5 +577,16 @@572- lastError: code === 0 ? context.session.lastError : message,573- });574- this.emitLifecycleEvent(context, "session/exited", message);575- this.sessions.delete(context.session.sessionId);576- });577+ yield* Effect.forkScoped(578+ Effect.matchCauseEffect(context.child.exitCode, {579+ onFailure: (cause) =>580+ Effect.promise(() =>581+ this.handleUnexpectedProcessExit(context, {582+ kind: "failure",583+ message: messageFromCodexProcessCause(cause),584+ }),585+ ),586+ onSuccess: (code) =>587+ Effect.promise(() =>588+ this.handleUnexpectedProcessExit(context, {589+ kind: "exit",590+ code,591+ }),592+ ),
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
4d6e1834-665d-49be-a9be-407a60d295b2You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.