Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions apps/desktop/src/main/brain/login-shell-path.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
169 changes: 123 additions & 46 deletions apps/desktop/src/main/brain/login-shell-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<NodeJS.ProcessEnv>,
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<boolean>;
},
): Promise<string[] | undefined> {
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<NodeJS.ProcessEnv>,
): Promise<string[] | undefined> {
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);
}