Files
paseo/packages/server/src/executable-resolution/executable-resolution.ts
T
paseo-bot[bot]andKiraPC 404d08d24b Report failed terminal launches and remove early exits (#6792)
* fix(server): report a terminal whose command cannot start instead of leaving a dead tab

Opening a terminal profile whose command is not installed left a tab that could
never be closed. Two problems sat on the same path.

A terminal that dies during creation was resurrected by its own create. The
worker sends terminalCreated, the createTerminal response and terminalExit in
the same tick, so the parent drains all three before the awaiting create
continuation resumes; that continuation called registerRecord a second time and
put back a terminal the exit had just removed. Removal is owned solely by the
terminalExit event and that event never comes twice, so the record outlived
every close attempt: getTerminals kept listing it, capture returned nothing,
kill was a silent no-op that still reported success, and only a daemon restart
cleared it.

The parent now tracks the ids with a create in flight and keeps the finished
record when an exit removes one of them, so the create continuation returns the
exited session instead of registering a live one. Removal still happens exactly
once, in the terminalExit path.

With the stuck tab gone, a missing command produced nothing at all: no tab and
no message. node-pty spawns directly through execve on POSIX, with no shell, so
a command that does not exist fails inside the spawn helper and surfaces as exit
code 1 with no output -- exactly what `false` produces, so the exit carries no
usable signal. createTerminal now resolves the command before spawning and fails
the create when it cannot be found, so the daemon answers create_terminal with a
null terminal and "<command>: command not found", which the app already renders.
A command that starts and then exits non-zero still opens its tab.

That resolution has to match what execve will do in the child, or a working
profile is refused: it uses the terminal's own environment, built first so the
check sees the per-cwd registered PATH and the entries buildTerminalEnvironment
prepends, and it resolves a command containing a separator against the
terminal's cwd rather than through PATH. Windows keeps resolving inside
resolveTerminalSpawnCommand, which has its own shim handling and fallback.

* fix(terminal): check exact executable names and verify launch output

---------

Co-authored-by: KiraPC <pasqualecarmine.carbone@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 23:02:39 +02:00

189 lines
5.5 KiB
TypeScript

import { createRequire } from "node:module";
import { existsSync } from "node:fs";
import { delimiter, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
import { windowsExecutableResolution } from "./windows.js";
type Which = (
command: string,
options: { all: true; path?: string; pathExt?: string },
) => Promise<string[]>;
const require = createRequire(import.meta.url);
const which = require("which") as Which;
const PROBE_TIMEOUT_MS = 2000;
function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise<string[]> {
if (process.platform !== "win32" && existsSync("/usr/bin/which")) {
return enumerateCandidatesViaSystemWhich(name, env);
}
return enumerateCandidatesViaLibrary(name, env);
}
async function enumerateCandidatesViaSystemWhich(
name: string,
env?: ProcessEnvRecord,
): Promise<string[]> {
try {
const { stdout } = await execCommand("/usr/bin/which", ["-a", name], {
baseEnv: env,
timeout: 3000,
killSignal: "SIGKILL",
});
return Array.from(new Set(stdout.trim().split("\n").filter(Boolean)));
} catch (error) {
// which exits 1 for a missing command. A failed lookup is not evidence of absence.
if (error instanceof Error && "code" in error && error.code === 1) return [];
throw error;
}
}
async function enumerateCandidatesViaLibrary(
name: string,
env?: ProcessEnvRecord,
): Promise<string[]> {
let candidates: string[];
try {
candidates = await which(name, { all: true, path: env?.PATH, pathExt: env?.PATHEXT });
} catch (error) {
// `which` throws ENOENT when the command is absent from PATH.
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return [];
}
throw error;
}
const seen = new Set<string>();
return candidates.filter((candidate) => {
if (seen.has(candidate)) {
return false;
}
seen.add(candidate);
return true;
});
}
export async function probeExecutable(
executablePath: string,
options: number | ExecutableResolutionOptions = PROBE_TIMEOUT_MS,
): Promise<boolean> {
const { probeTimeoutMs: timeoutMs = PROBE_TIMEOUT_MS, env } =
typeof options === "number" ? { probeTimeoutMs: options } : options;
try {
await execCommand(executablePath, ["--version"], {
baseEnv: env,
timeout: timeoutMs,
killSignal: "SIGKILL",
maxBuffer: 64 * 1024,
});
return true;
} catch (error) {
return classifyProbeError(error);
}
}
function classifyProbeError(error: unknown): boolean {
const err = error as NodeJS.ErrnoException & {
killed?: boolean;
};
if (err.killed) {
return true;
}
if (typeof err.code === "number") {
return true;
}
if (
err.code === "ENOENT" ||
err.code === "EACCES" ||
err.code === "ENOEXEC" ||
err.code === "UNKNOWN"
) {
return false;
}
return false;
}
/**
* Check a literal executable path. PATH search is handled by findExecutable().
*/
export function executableExists(
executablePath: string,
exists: typeof existsSync = existsSync,
): string | null {
if (process.platform === "win32") {
return windowsExecutableResolution.exists(executablePath, { exists });
}
return exists(executablePath) ? executablePath : null;
}
// PATH lookup that never runs the candidate, unlike findExecutable which probes
// each one with `--version`. A terminal spawn path cannot afford that probe: it
// would execute the profile command once before the terminal even opens.
// `path` overrides the PATH to search, so a caller can resolve against the
// environment its child process will actually get rather than the daemon's own.
export async function findExecutableWithoutProbing(
name: string,
options: { path?: string; cwd: string },
): Promise<string | null> {
if (!name) {
return null;
}
const path =
options.path === undefined
? undefined
: options.path
.split(delimiter)
.map((entry) => resolve(options.cwd, entry))
.join(delimiter);
const candidates = await enumerateCandidatesViaLibrary(name, { PATH: path });
return candidates[0] ?? null;
}
export interface ExecutableResolutionOptions {
probeTimeoutMs?: number;
env?: ProcessEnvRecord;
}
export async function findExecutable(
name: string,
options: number | ExecutableResolutionOptions = PROBE_TIMEOUT_MS,
): Promise<string | null> {
const { probeTimeoutMs = PROBE_TIMEOUT_MS, env } =
typeof options === "number" ? { probeTimeoutMs: options } : options;
const trimmed = name.trim();
if (!trimmed) {
return null;
}
if (process.platform === "win32") {
return windowsExecutableResolution.find(trimmed, {
enumeratePathCandidates: (command) => enumerateCandidates(command, env),
probeExecutable: (command, timeout) =>
probeExecutable(command, { probeTimeoutMs: timeout, env }),
exists: existsSync,
probeTimeoutMs,
});
}
if (hasPathSeparator(trimmed)) {
return (await probeExecutable(trimmed, { probeTimeoutMs, env })) ? trimmed : null;
}
const candidates = await enumerateCandidates(trimmed, env);
for (const candidate of candidates) {
if (await probeExecutable(candidate, { probeTimeoutMs, env })) {
return candidate;
}
}
return null;
}
export async function isCommandAvailable(command: string): Promise<boolean> {
return (await findExecutable(command)) !== null;
}