From 4bfdf8807e5061144e3c3b13559d12e42aa3447a Mon Sep 17 00:00:00 2001 From: Yue Arc <135290367+yuearc@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:56:22 +0800 Subject: [PATCH] fix(desktop): wait for buffered stdout when login shell exits early In readLoginShellPath(), parsing output inside child.once('exit') races with Node's stdout pipe flush: 'exit' can fire before the final stdout chunk carrying __PIBOT_PATH_END__ is delivered, silently returning undefined and dropping the user's login-shell PATH. Extract collectLoginShellPath() to wait for buffered stdout chunks/end/close after exit 0 when the closing marker has not yet arrived, while still resolving immediately once both exit 0 and the closing marker are observed so detached shell helpers (e.g. gitstatusd) holding stdout open do not stall until timeout. Also enforce idempotent settlement, release listeners and destroy stdout on early completion, and add offline Vitest coverage. Signed-off-by: Yue Arc <135290367+yuearc@users.noreply.github.com> --- .../src/main/brain/login-shell-path.test.ts | 87 +++++++++ .../src/main/brain/login-shell-path.ts | 169 +++++++++++++----- 2 files changed, 210 insertions(+), 46 deletions(-) create mode 100644 apps/desktop/src/main/brain/login-shell-path.test.ts diff --git a/apps/desktop/src/main/brain/login-shell-path.test.ts b/apps/desktop/src/main/brain/login-shell-path.test.ts new file mode 100644 index 00000000..c9c323bd --- /dev/null +++ b/apps/desktop/src/main/brain/login-shell-path.test.ts @@ -0,0 +1,87 @@ +import { EventEmitter } from "node:events"; +import { PassThrough } from "node:stream"; +import { describe, expect, it } from "vitest"; +import { + collectLoginShellPath, + type LoginShellChild, + readLoginShellPath, +} from "./login-shell-path.ts"; + +class FakeChild extends EventEmitter implements LoginShellChild { + readonly pid = 4242; + readonly stdout = new PassThrough(); +} + +describe("login-shell-path", () => { + it("waits for buffered stdout chunks that arrive after exit", async () => { + const child = new FakeChild(); + const pending = collectLoginShellPath(child, { + timeoutMs: 500, + checkDir: async (entry) => entry === "/opt/homebrew/bin" || entry === "/usr/local/bin", + }); + + // Simulate Node emitting "exit" before stdout finishes delivering the closing marker across chunks. + child.stdout.write("__PIBOT_PATH_START__/opt/homebrew/bin:"); + child.emit("exit", 0); + await new Promise((r) => setTimeout(r, 15)); + child.stdout.write("/usr/local/bin:/missing/dir__PIBOT_PATH_"); + child.stdout.end("END__"); + + expect(await pending).toEqual(["/opt/homebrew/bin", "/usr/local/bin"]); + }); + + it("resolves immediately on exit once markers arrive even if a helper keeps stdout open", async () => { + const child = new FakeChild(); + const started = performance.now(); + const pending = collectLoginShellPath(child, { + timeoutMs: 3_000, + checkDir: async () => true, + }); + + child.stdout.write("__PIBOT_PATH_START__/usr/bin:/usr/local/bin__PIBOT_PATH_END__"); + child.emit("exit", 0); + // Intentionally leave stdout open without emitting "close" (e.g. detached zsh helper). + + expect(await pending).toEqual(["/usr/bin", "/usr/local/bin"]); + expect(performance.now() - started).toBeLessThan(500); + expect(child.stdout.destroyed).toBe(true); + expect(child.listenerCount("close")).toBe(0); + }); + + it("returns undefined once stdout drains without markers after exit 0", async () => { + const child = new FakeChild(); + const pending = collectLoginShellPath(child, { + timeoutMs: 500, + checkDir: async () => true, + }); + + child.emit("exit", 0); + child.stdout.end("motd noise without markers"); + + expect(await pending).toBeUndefined(); + }); + + it("kills the process group and settles once when output exceeds maxOutput", async () => { + const child = new FakeChild(); + let kills = 0; + const pending = collectLoginShellPath(child, { + timeoutMs: 500, + maxOutput: 16, + killGroup: () => { + kills++; + }, + checkDir: async () => true, + }); + + child.stdout.write("x".repeat(32)); + child.stdout.write("y".repeat(32)); + child.emit("exit", 0); + + expect(await pending).toBeUndefined(); + expect(kills).toBe(1); + }); + + it("returns undefined on win32 without spawning a shell", async () => { + expect(await readLoginShellPath("win32", {})).toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/main/brain/login-shell-path.ts b/apps/desktop/src/main/brain/login-shell-path.ts index 235ecc55..d85bdc6d 100644 --- a/apps/desktop/src/main/brain/login-shell-path.ts +++ b/apps/desktop/src/main/brain/login-shell-path.ts @@ -2,6 +2,7 @@ import { spawn } from "node:child_process"; import { readFileSync, statSync } from "node:fs"; import { mkdir, rename, stat, writeFile } from "node:fs/promises"; import { isAbsolute, join } from "node:path"; +import type { Readable } from "node:stream"; const TIMEOUT_MS = 3_000; const MAX_OUTPUT = 64 * 1024; @@ -41,70 +42,146 @@ export async function writeCachedLoginShellPath(dataDir: string, path: readonly await rename(temp, file); } -/** Read only PATH from the user's login shell; failures deliberately return no override. */ -export async function readLoginShellPath( - platform: NodeJS.Platform, - env: Readonly, +const MARK_RE = new RegExp(`${MARK_START}(.*?)${MARK_END}`, "s"); + +export interface LoginShellChild { + readonly pid?: number | undefined; + readonly stdout: Readable | null; + once(event: "error", listener: () => void): this; + once(event: "exit" | "close", listener: (code: number | null) => void): this; + off(event: "error", listener: () => void): this; + off(event: "exit" | "close", listener: (code: number | null) => void): this; +} + +export async function collectLoginShellPath( + child: LoginShellChild, + options?: { + timeoutMs?: number; + maxOutput?: number; + killGroup?: () => void; + checkDir?: (entry: string) => Promise; + }, ): Promise { - if (platform === "win32") return undefined; - const shell = - env.SHELL === "/bin/zsh" || env.SHELL === "/bin/bash" - ? env.SHELL - : platform === "darwin" - ? "/bin/zsh" - : "/bin/bash"; - return new Promise((resolve) => { - const child = spawn(shell, ["-lic", `printf '${MARK_START}%s${MARK_END}' "$PATH"`], { - env: { ...env, PATH: env.PATH ?? "" }, - stdio: ["ignore", "pipe", "ignore"], - // An interactive zsh often starts helpers (gitstatusd, instant prompt): own process group, - // so a timeout ends all of them, not only the shell. - detached: true, - }); - const killGroup = () => { + const timeoutMs = options?.timeoutMs ?? TIMEOUT_MS; + const maxOutput = options?.maxOutput ?? MAX_OUTPUT; + const killGroup = + options?.killGroup ?? + (() => { try { if (child.pid) process.kill(-child.pid, "SIGKILL"); } catch { // Already gone: nothing left to stop. } - }; + }); + const checkDir = + options?.checkDir ?? + (async (entry: string) => { + try { + return (await stat(entry)).isDirectory(); + } catch { + return false; + } + }); + return new Promise((resolve) => { let output = ""; - const timer = setTimeout(() => { - killGroup(); - resolve(undefined); - }, TIMEOUT_MS); - const finish = (value: string[] | undefined) => { - clearTimeout(timer); - resolve(value); - }; + let settled = false; + let parsing = false; + let exitCode: number | null | undefined; + let stdoutEnded = false; const stdout = child.stdout; - if (!stdout) return finish(undefined); - stdout.setEncoding("utf8"); - stdout.on("data", (chunk: string) => { + if (!stdout) { + resolve(undefined); + return; + } + const onData = (chunk: string) => { + if (settled) return; output += chunk; - if (output.length > MAX_OUTPUT) { + if (output.length > maxOutput) { killGroup(); finish(undefined); + return; } - }); - child.once("error", () => finish(undefined)); - child.once("exit", (code) => { + if (exitCode === 0 && output.includes(MARK_END)) tryParse(); + }; + const onEnd = () => { + stdoutEnded = true; + tryParse(); + }; + const onError = () => finish(undefined); + const onClose = (code: number | null) => { + stdoutEnded = true; + if (exitCode === undefined) exitCode = code; + if (exitCode !== 0) return finish(undefined); + tryParse(); + }; + const onExit = (code: number | null) => { + exitCode = code; if (code !== 0) return finish(undefined); - const match = new RegExp(`${MARK_START}(.*?)${MARK_END}`, "s").exec(output); - if (!match) return finish(undefined); + tryParse(); + }; + const finish = (value: string[] | undefined) => { + if (settled) return; + settled = true; + clearTimeout(timer); + stdout.off("data", onData); + stdout.off("end", onEnd); + child.off("error", onError); + child.off("close", onClose); + child.off("exit", onExit); + if (!stdoutEnded) stdout.destroy(); + resolve(value); + }; + const timer = setTimeout(() => { + killGroup(); + finish(undefined); + }, timeoutMs); + const tryParse = () => { + if (settled || parsing || exitCode !== 0) return; + const match = MARK_RE.exec(output); + if (!match) { + if (stdoutEnded) finish(undefined); + return; + } + parsing = true; const candidates = (match[1] ?? "").split(":"); void Promise.all( candidates.map(async (entry) => { if (!isAbsolute(entry) || /[\0\r\n]/.test(entry)) return undefined; - try { - return (await stat(entry)).isDirectory() ? entry : undefined; - } catch { - return undefined; - } + return (await checkDir(entry)) ? entry : undefined; }), - ).then((entries) => - finish([...new Set(entries.filter((entry): entry is string => Boolean(entry)))]), + ).then( + (entries) => + finish([...new Set(entries.filter((entry): entry is string => Boolean(entry)))]), + () => finish(undefined), ); - }); + }; + stdout.setEncoding("utf8"); + stdout.on("data", onData); + stdout.once("end", onEnd); + child.once("error", onError); + child.once("close", onClose); + child.once("exit", onExit); + }); +} + +/** Read only PATH from the user's login shell; failures deliberately return no override. */ +export async function readLoginShellPath( + platform: NodeJS.Platform, + env: Readonly, +): Promise { + if (platform === "win32") return undefined; + const shell = + env.SHELL === "/bin/zsh" || env.SHELL === "/bin/bash" + ? env.SHELL + : platform === "darwin" + ? "/bin/zsh" + : "/bin/bash"; + const child = spawn(shell, ["-lic", `printf '${MARK_START}%s${MARK_END}' "$PATH"`], { + env: { ...env, PATH: env.PATH ?? "" }, + stdio: ["ignore", "pipe", "ignore"], + // An interactive zsh often starts helpers (gitstatusd, instant prompt): own process group, + // so a timeout ends all of them, not only the shell. + detached: true, }); + return collectLoginShellPath(child); }