Compare commits

...
Author SHA1 Message Date
d15190803a Show Pi model names with slashes and underscores in full (#9823)
* fix(pi): keep slashes and underscores in model display names

Pi model labels were built as `${provider}/${name}` and then cut at the
last `/`, so a free-text name such as "... ~60-70 tok/s, 52/56)" was shown
as "56)". Underscores were also rewritten to spaces ("IQ3_S" -> "IQ3 S").
The compact model trigger in the app repeated the last-`/` cut.

Build the Pi label from the model's own `name`/`id`: shorten only
path-like values with no whitespace (OpenRouter reports names like
"google/gemini-2.5-flash-lite"), and keep free-text names intact. The
compact trigger now strips only a leading provider namespace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(pi): cover model labels through the catalog and drop stale ACP copies

acp-agent.test.ts still imported transformPiModels, which the Pi label
fix removed, so its modelTransformer test and a stale copy of the old
Pi label tests failed. The modelTransformer test now supplies its own
transformer, and the Pi label cases run through fetchCatalog with the
reported model names instead of an exported helper.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(pi): keep colons inside free-text model names

The vendor-prefix strip cut a free-text Pi name at its first ": ", so
"Qwen3 IQ3_S (tail skip: on, 52/56)" showed as "on, 52/56)". Strip only
when the text before ": " has no parenthesis or comma, which keeps
OpenRouter's "Vendor: Model" names shortened.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 04:55:28 +00:00
Josh BendavidandClaude Opus 5.5 ade3817a45 fix(server): fall back to the next socket directory when the bind is refused (#9214)
A PASEO_HOME on AFS passes the socket directory checks, then refuses the
Unix socket bind with EPERM, and the terminal worker failed to start. The
worker now binds each eligible candidate in turn and moves on when the
filesystem refuses the socket (EPERM, EACCES, EOPNOTSUPP, ENOTSUP). Other
listen errors still fail the start.

Fixes #9213

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:56:04 +00:00
10 changed files with 304 additions and 154 deletions
+1
View File
@@ -29,6 +29,7 @@ The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its
- Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them.
- Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs.
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-<uid>/` or `/tmp/paseo-<uid>/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded.
- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it.
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
@@ -31,6 +31,7 @@ import {
toolbarSlot,
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
import { shortModelLabel } from "./utils";
const SNAP_POINTS = ["80%", "90%"];
const MODEL_LIST_TOP_INSET = 4;
@@ -66,11 +67,6 @@ interface CompactModelSheetProps {
children: ReactNode;
}
function shortModelLabel(label: string): string {
const separatorIndex = label.lastIndexOf("/");
return separatorIndex === -1 ? label : label.slice(separatorIndex + 1);
}
function resolveModelSheetProfileActions(
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
onEditProfile: ((profileId: string) => void) | undefined,
@@ -4,6 +4,7 @@ import {
getAgentControlHintKey,
normalizeModelId,
resolveAgentModelSelection,
shortModelLabel,
} from "./utils";
describe("getAgentControlHintKey", () => {
@@ -251,3 +252,19 @@ describe("resolveAgentModelSelection", () => {
expect(selection.displayThinking).toBe("Max");
});
});
describe("shortModelLabel", () => {
it("drops a provider namespace", () => {
expect(shortModelLabel("openrouter/gpt-5.5")).toBe("gpt-5.5");
expect(shortModelLabel("openrouter/google/gemini-2.5-flash")).toBe("gemini-2.5-flash");
});
it("keeps slashes inside a display name", () => {
expect(shortModelLabel("DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)")).toBe(
"DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)",
);
expect(shortModelLabel("llama-swap/DeepSeek V4.1 Flash (56/56)")).toBe(
"DeepSeek V4.1 Flash (56/56)",
);
});
});
@@ -35,6 +35,12 @@ export function normalizeModelId(modelId: string | null | undefined): string | n
return normalized;
}
// Drops a provider namespace ("openrouter/gpt-5.5" -> "gpt-5.5") for the compact trigger.
// A namespace segment has no spaces, so slashes inside a display name ("52/56") survive.
export function shortModelLabel(label: string): string {
return label.replace(/^(?:[^\s/]+\/)+(?=\S)/, "");
}
export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor {
switch (featureId) {
case FAST_MODE_FEATURE_ID:
@@ -51,7 +51,6 @@ import {
} from "./copilot-acp-agent.js";
import { GenericACPAgentClient } from "./generic-acp-agent.js";
import { parseKiroExtensionCommands } from "./kiro-acp-agent.js";
import { transformPiModels } from "./pi/agent.js";
import type { AgentStreamEvent } from "../agent-sdk-types.js";
import type {
AgentCapabilityFlags,
@@ -2260,7 +2259,12 @@ describe("ACPAgentClient modelTransformer", () => {
provider: "pi",
logger: createTestLogger(),
defaultCommand: ["test-acp"],
modelTransformer: transformPiModels,
modelTransformer: (models) =>
models.map((model) => ({
...model,
label: model.label.split("/").at(-1) ?? model.label,
description: model.id,
})),
});
await expect(
@@ -2914,60 +2918,6 @@ describe("ACP providers advertise session listing", () => {
});
});
describe("transformPiModels", () => {
test("keeps slash-free labels unchanged", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "gpt-4.1-mini",
label: "GPT 4.1 Mini",
description: "Fast",
},
]),
).toEqual([
{
provider: "pi",
id: "gpt-4.1-mini",
label: "GPT 4.1 Mini",
description: "Fast",
},
]);
});
test("uses the last path segment as label and preserves existing descriptions", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "openrouter/openai/gpt-4.1-mini",
label: "openrouter/openai/gpt-4.1-mini",
description: undefined,
},
{
provider: "pi",
id: "anthropic/claude-sonnet-4",
label: "anthropic/claude-sonnet-4",
description: "Balanced",
},
]),
).toEqual([
{
provider: "pi",
id: "openrouter/openai/gpt-4.1-mini",
label: "gpt-4.1-mini",
description: "openrouter/openai/gpt-4.1-mini",
},
{
provider: "pi",
id: "anthropic/claude-sonnet-4",
label: "claude-sonnet-4",
description: "Balanced",
},
]);
});
});
describe("ACPAgentSession slash commands", () => {
test("returns immediately for ACP sessions that do not wait for async command discovery", async () => {
const session = new ACPAgentSession(
@@ -19,12 +19,7 @@ import { pathToFileURL } from "node:url";
import { describe, expect, onTestFinished, test } from "vitest";
import type { AgentSession, AgentSessionConfig, AgentStreamEvent } from "../../agent-sdk-types.js";
import {
PiProviderOptionsSchema,
PiRpcAgentClient,
PiRpcAgentSession,
transformPiModels,
} from "./agent.js";
import { PiProviderOptionsSchema, PiRpcAgentClient, PiRpcAgentSession } from "./agent.js";
import { PiCliRuntime } from "./cli-runtime.js";
import { FakePi } from "./test-utils/fake-pi.js";
import { createPiExtensionHost } from "./extensions/index.js";
@@ -3970,35 +3965,73 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
});
});
describe("transformPiModels", () => {
test("normalizes labels that include the upstream provider prefix", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "openrouter/google/gemini-2.5-flash-lite",
label: "openrouter/google/gemini_2.5 flash lite",
},
{
provider: "pi",
id: "openrouter/openai/gpt-5.5",
label: "openrouter/OpenAI: GPT-5.5",
},
]),
).toEqual([
{
provider: "pi",
id: "openrouter/google/gemini-2.5-flash-lite",
label: "gemini 2.5 flash lite",
description: "openrouter/google/gemini_2.5 flash lite",
describe("Pi catalog model labels", () => {
test.each([
{
name: "keeps slashes and underscores inside a free-text model name",
model: {
provider: "llama-swap",
id: "s-q3fn(p-t)",
name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
},
{
provider: "pi",
id: "openrouter/openai/gpt-5.5",
label: "GPT-5.5",
description: "openrouter/OpenAI: GPT-5.5",
label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
},
{
name: "keeps a free-text name that ends in a slash-separated word",
model: {
provider: "llama-swap",
id: "ds-strata-6",
name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
},
]);
label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
},
{
name: "keeps a colon inside a free-text model name",
model: {
provider: "llama-swap",
id: "qwen3-tail",
name: "Qwen3 IQ3_S (tail skip: on, 52/56)",
},
label: "Qwen3 IQ3_S (tail skip: on, 52/56)",
},
{
name: "drops the vendor prefix from an upstream model name",
model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" },
label: "GPT-5.5",
},
{
name: "shortens a path-like name to its last segment",
model: {
provider: "openrouter",
id: "google/gemini-2.5-flash-lite",
name: "google/gemini-2.5-flash-lite",
},
label: "gemini-2.5-flash-lite",
},
{
name: "falls back to the last segment of a path-like id",
model: { provider: "openrouter", id: "google/gemini_2.5-flash-lite" },
label: "gemini 2.5-flash-lite",
},
{
name: "falls back to an id with spaces when the name is blank",
model: { provider: "local", id: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", name: " " },
label: "DeepSeek-V4.1-Flash 2.25bpw (Strata)",
},
])("$name", async ({ model, label }) => {
const pi = new FakePi();
pi.queueSessionSetup((session) => {
session.models = [model];
});
const catalog = await createClient(pi).fetchCatalog({
scope: "workspace",
cwd: "/workspace/project",
force: false,
});
expect(catalog.models.map((entry) => entry.label)).toEqual([label]);
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
});
});
@@ -313,34 +313,25 @@ interface PiSlashCommandInvocation {
type AutoCompactMode = boolean | "toggle" | "unknown";
function normalizePiModelLabel(label: string): string {
const normalizedLabel = label.trim().replace(/[_\s]+/g, " ");
const vendorSeparatorIndex = normalizedLabel.indexOf(": ");
if (vendorSeparatorIndex === -1) {
return normalizedLabel;
// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a
// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept.
function stripVendorPrefix(label: string): string {
const vendorSeparatorIndex = label.indexOf(": ");
if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) {
return label;
}
return normalizedLabel.slice(vendorSeparatorIndex + 2).trim();
return label.slice(vendorSeparatorIndex + 2).trim();
}
export function transformPiModels(models: AgentModelDefinition[]): AgentModelDefinition[] {
return models.map((model) => {
if (!model.label.includes("/")) {
return model;
}
const segments = model.label.split("/").filter((segment) => segment.length > 0);
const rawLabel = segments.at(-1);
if (!rawLabel) {
return model;
}
return {
...model,
label: normalizePiModelLabel(rawLabel),
description: model.description ?? model.label,
};
});
// A Pi model name is either a path ("google/gemini_2.5-flash", as OpenRouter reports it) or
// free text that can contain slashes and underscores ("IQ3_S ... 52/56"). Only shorten paths.
function piModelLabel(model: Pick<PiModel, "id" | "name">): string {
const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim();
if (/\s/.test(text)) {
return stripVendorPrefix(text);
}
const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text;
return stripVendorPrefix(lastSegment.replace(/_+/g, " "));
}
function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel {
@@ -1166,7 +1157,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti
return {
provider,
id: `${model.provider}/${model.id}`,
label: `${model.provider}/${model.name ?? model.id}`,
label: piModelLabel(model),
description: `${model.provider}/${model.id}`,
metadata: {
provider: model.provider,
@@ -2817,15 +2808,13 @@ export class PiRpcAgentClient implements AgentClient {
"get_state",
() => catalogSession.getState(),
);
const models = transformPiModels(
piModels.map((model) => {
const mapped = mapPiModel(model, PI_PROVIDER);
const isConfigured =
model.provider === configuredModel?.provider && model.id === configuredModel?.id;
if (isConfigured) mapped.isDefault = true;
return mapped;
}),
);
const models = piModels.map((model) => {
const mapped = mapPiModel(model, PI_PROVIDER);
const isConfigured =
model.provider === configuredModel?.provider && model.id === configuredModel?.id;
if (isConfigured) mapped.isDefault = true;
return mapped;
});
return { models, modes: [] };
} finally {
context?.signal.removeEventListener("abort", handleAbort);
@@ -19,7 +19,7 @@ import {
type TerminalWorkerRecord,
} from "./terminal-worker-record.js";
import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js";
import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
import {
TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV,
TERMINAL_WORKER_PROTOCOL_VERSION,
@@ -700,23 +700,25 @@ function runWorker(argv: string[]): void {
}
async function start(): Promise<void> {
const socketPath = resolveTerminalWorkerSocketPath({
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
paseoHome: args.paseoHome,
workerPid: process.pid,
recordId: args.recordId,
listen: (candidatePath) => {
if (process.platform !== "win32") {
rmSync(candidatePath, { force: true });
}
const listening = createServer(handleConnection);
return new Promise<Server>((resolve, reject) => {
listening.once("error", reject);
listening.listen(candidatePath, () => {
listening.off("error", reject);
resolve(listening);
});
});
},
});
if (process.platform !== "win32") {
rmSync(socketPath, { force: true });
}
const listening = createServer(handleConnection);
await new Promise<void>((resolve, reject) => {
listening.once("error", reject);
listening.listen(socketPath, () => {
listening.off("error", reject);
resolve();
});
});
server = listening;
server = listener;
if (process.platform !== "win32") {
chmodSync(socketPath, PRIVATE_FILE_MODE);
}
@@ -1,10 +1,11 @@
import { afterEach, describe, expect, it } from "vitest";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
import { createServer } from "node:net";
import { createServer, type Server } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { isPlatform } from "../test-utils/platform.js";
import {
listenOnTerminalWorkerSocket,
resolveTerminalWorkerSocketPath,
TerminalWorkerSocketPathError,
} from "./terminal-worker-socket-path.js";
@@ -25,7 +26,36 @@ function longHome(root: string): string {
return home;
}
afterEach(() => {
const openServers: Server[] = [];
function listenFor(socketPath: string): Promise<Server> {
const server = createServer();
return new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(socketPath, () => {
openServers.push(server);
resolve(server);
});
});
}
// Stands in for a filesystem that passes the directory checks but refuses AF_UNIX bind, as AFS
// does with EPERM.
function refuseBindUnder(directory: string, code: string) {
return (socketPath: string): Promise<Server> => {
if (socketPath.startsWith(directory + path.sep)) {
return Promise.reject(
Object.assign(new Error(`listen ${code}: ${socketPath}`), { code, syscall: "listen" }),
);
}
return listenFor(socketPath);
};
}
afterEach(async () => {
await Promise.all(
openServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))),
);
for (const dir of temporaryDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
@@ -142,6 +172,66 @@ describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => {
});
});
describe.skipIf(isPlatform("win32"))("terminal worker socket listen", () => {
it("falls back to the next directory when the home's filesystem refuses the bind", async () => {
const home = makeDir("tw-b-", "/tmp");
const tmpDir = makeDir("tw-t-", "/tmp");
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
paseoHome: home,
recordId: "test",
workerPid: 11,
tmpDir,
listen: refuseBindUnder(homeSocketDirectory, "EPERM"),
});
expect(path.dirname(socketPath)).toBe(path.join(tmpDir, `paseo-${process.getuid!()}`));
expect(listener.address()).toBe(socketPath);
});
it("throws a listen error that does not mean the filesystem refuses sockets", async () => {
const home = makeDir("tw-u-", "/tmp");
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
await expect(
listenOnTerminalWorkerSocket({
paseoHome: home,
recordId: "test",
workerPid: 12,
tmpDir: makeDir("tw-t-", "/tmp"),
listen: refuseBindUnder(homeSocketDirectory, "EADDRINUSE"),
}),
).rejects.toMatchObject({ code: "EADDRINUSE" });
});
it("names every candidate's bind error when no directory accepts a socket", async () => {
const home = makeDir("tw-n-", "/tmp");
const tmpDir = makeDir("tw-t-", "/tmp");
let caught: unknown;
try {
await listenOnTerminalWorkerSocket({
paseoHome: home,
recordId: "test",
workerPid: 13,
tmpDir,
listen: refuseBindUnder("", "EPERM"),
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError);
const rejected = (caught as TerminalWorkerSocketPathError).rejected;
expect(rejected.slice(0, 2)).toEqual([
expect.objectContaining({
path: expect.stringContaining(path.join(home, "terminal-worker", "sock")),
reason: "cannot bind a socket here (EPERM)",
}),
expect.objectContaining({
path: expect.stringContaining(path.join(tmpDir, `paseo-${process.getuid!()}`)),
reason: "cannot bind a socket here (EPERM)",
}),
]);
});
});
it("uses a separate socket for each record even when its pid is reused", () => {
const paseoHome = makeDir("tw-id-");
const first = resolveTerminalWorkerSocketPath({ paseoHome, workerPid: 42, recordId: "old" });
@@ -14,6 +14,9 @@ const SOCKET_PATH_BYTE_BUDGET: Partial<Record<NodeJS.Platform, number>> = {
};
const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
const OWNER_ONLY_MODE = 0o700;
// Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other
// network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM.
const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
export interface TerminalWorkerSocketPathInput {
paseoHome: string;
@@ -24,6 +27,16 @@ export interface TerminalWorkerSocketPathInput {
uid?: number;
}
export interface TerminalWorkerSocketListenInput<T> extends TerminalWorkerSocketPathInput {
/** Binds a fresh listener at the path, removing any stale socket there first. */
listen: (socketPath: string) => Promise<T>;
}
export interface TerminalWorkerSocketListener<T> {
socketPath: string;
listener: T;
}
export interface RejectedSocketCandidate {
path: string;
byteLength: number;
@@ -36,7 +49,7 @@ export class TerminalWorkerSocketPathError extends Error {
constructor(rejected: RejectedSocketCandidate[], budget: number) {
super(
[
`No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
`No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
...rejected.map(
(candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`,
),
@@ -57,18 +70,73 @@ export function terminalWorkerSocketId(paseoHome: string, workerPid: number): st
* Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
* tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
* A shared root is never chmodded: an existing directory there is used only when it is a real
* directory owned by this user with mode 0700.
* directory owned by this user with mode 0700. It does not bind; the worker listens through
* `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
*/
export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string {
const platform = input.platform ?? process.platform;
const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
if (platform === "win32") {
return `\\\\.\\pipe\\paseo-tw-${id}`;
return windowsPipePath(input);
}
const budget = socketPathByteBudget(platform);
const rejected: RejectedSocketCandidate[] = [];
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
return candidate.path;
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
/**
* Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
* moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
*/
export async function listenOnTerminalWorkerSocket<T>(
input: TerminalWorkerSocketListenInput<T>,
): Promise<TerminalWorkerSocketListener<T>> {
const { listen } = input;
const platform = input.platform ?? process.platform;
if (platform === "win32") {
const socketPath = windowsPipePath(input);
return { socketPath, listener: await listen(socketPath) };
}
const budget = socketPathByteBudget(platform);
const rejected: RejectedSocketCandidate[] = [];
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
try {
return { socketPath: candidate.path, listener: await listen(candidate.path) };
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error;
rejected.push({
path: candidate.path,
byteLength: candidate.byteLength,
reason: `cannot bind a socket here (${code})`,
});
}
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
function windowsPipePath(input: TerminalWorkerSocketPathInput): string {
return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
}
function socketFileId(input: TerminalWorkerSocketPathInput): string {
return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
}
function socketPathByteBudget(platform: NodeJS.Platform): number {
return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
}
/** Yields each candidate that fits the budget in an owner-only directory, in order. */
function* eligibleUnixSocketPaths(
input: TerminalWorkerSocketPathInput,
budget: number,
rejected: RejectedSocketCandidate[],
): Generator<{ path: string; byteLength: number }> {
const uid = input.uid ?? process.getuid?.() ?? 0;
const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
const fileName = `tw-${id}.sock`;
const fileName = `tw-${socketFileId(input)}.sock`;
const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
const candidates: Array<{ directory: string; prepare: () => string | null }> = [
{
@@ -87,7 +155,6 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI
}),
];
const rejected: RejectedSocketCandidate[] = [];
const seen = new Set<string>();
for (const candidate of candidates) {
const socketPath = path.join(candidate.directory, fileName);
@@ -108,9 +175,8 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI
rejected.push({ path: socketPath, byteLength, reason: problem });
continue;
}
return socketPath;
yield { path: socketPath, byteLength };
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
function prepareSharedRootDirectory(directory: string, uid: number): string | null {