Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(installer): preserve setup and uninstall failure diagnostics
Codexd18a91d3c955
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 14702f9c..69c57218 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -366,6 +366,10 @@ Gateway and runs Agents. The daemon exits with the app.left alone and it gives up after about two minutes. When the stop fails,the uninstaller offers Retry; Cancel (the default when silent) ends it withexit code 1 before anything is removed, so the uninstall can be run again.+ The stop helper records its latest outcome in `<home>/installer/stop-latest.json`+ and retains the first failure in `stop-first-failure.json`. These bounded+ records contain only allowlisted failure stages, codes and service names,+ never error text or paths; a successful retry keeps the first failure.It keeps `%APPDATA%\Linger` and the Linger home with all their data; alater install starts the services again (resume, or setup's Install).Setup over an installed release stops it the same way before it replacesdiff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex 9bd1bfdb..f140a786 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -54,6 +54,9 @@ whose Computer still uses the local model source (`model-source.json` says(`restoreLocalModels`), since a quit stops the models but not the services: astack that is not ready gets the same restore, then becomes the model sourceagain. A source switched to a subscription or BYOK leaves the stack stopped.+A failed installation records the stage that caused it, even when native+checkout preparation and runtime setup ran in parallel. A BYOK mount failure+belongs to runtime and keeps the redacted provider error in the job.A failed job's `errorCode` is the runtime's cause when ithas one (`RUNTIME_PLAN_REFUSED`, a harness plan refused before anythingchanged, such as an unusable `SIMPLEX_PI_PATH` or a Windows runtime root toodiff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.tsindex cdf294a3..224a440d 100644--- a/apps/linger-installer/src/main.ts+++ b/apps/linger-installer/src/main.ts@@ -261,20 +261,42 @@ async function stopInstallation(options: ReturnType<typeof parseInstallerArguments>,) {const { stopDesktopInstallation } = await import("./server/stop.js");- setTimeout(() => process.exit(1), 150_000).unref();+ const { recordStopOutcome, stopFailure } =+ await import("./server/stop-diagnostics.js");+ const failures: ReturnType<typeof stopFailure>[] = [];+ const save = () =>+ Promise.race([+ recordStopOutcome(options.home, failures).catch(() => {+ process.stderr.write("Could not save stop diagnostics.\n");+ }),+ new Promise<void>((resolve) => setTimeout(resolve, 6_000)),+ ]);+ let expired = false;+ const watchdog = setTimeout(() => {+ expired = true;+ failures.push(stopFailure("helper", { name: "TimeoutError" }));+ void save().finally(() => process.exit(1));+ }, 150_000).unref();const outcome = await stopDesktopInstallation({home: options.home,instanceName: options.instanceName!,signal: AbortSignal.timeout(120_000),log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")),- }).catch((error: unknown) => ({- failed: [- {- home: options.home,- message: error instanceof Error ? error.message : String(error),- },- ],- }));+ onFailure: (stage, error) => failures.push(stopFailure(stage, error)),+ }).catch((error: unknown) => {+ failures.push(stopFailure("helper", error));+ return {+ failed: [+ {+ home: options.home,+ message: error instanceof Error ? error.message : String(error),+ },+ ],+ };+ });+ if (expired) return;+ clearTimeout(watchdog);+ await save();process.stdout.write(`${JSON.stringify(outcome)}\n`, () =>process.exit(outcome.failed.length ? 1 : 0),);diff --git a/apps/linger-installer/src/server/jobs.test.ts b/apps/linger-installer/src/server/jobs.test.tsindex 9f8eb26d..aa55165d 100644--- a/apps/linger-installer/src/server/jobs.test.ts+++ b/apps/linger-installer/src/server/jobs.test.ts@@ -281,6 +281,53 @@ test.each([},);+test("a runtime failure stays on the persisted job after checkout cleanup logs", async () => {+ const { jobs, dir } = await setup(async (_input, _signal, emit) => {+ emit({+ kind: "stage",+ stage: "runtime",+ state: "failed",+ message: "Could not mount the model endpoint.",+ });+ emit({+ kind: "log",+ stage: "services",+ message: "Stopping PostgreSQL after the installation failure.",+ });+ return {+ code: 1,+ state: "failed",+ message: "Could not mount the model endpoint.",+ details: { stage: "runtime" },+ };+ });+ const job = await jobs.start({ instance: "default" });+ await jobs.wait(job.id);+ const saved: unknown = JSON.parse(+ await readFile(path.join(dir, `${job.id}.json`), "utf8"),+ );+ expect(saved).toMatchObject({+ job: {+ state: "failed",+ stage: "runtime",+ stages: expect.arrayContaining([+ expect.objectContaining({+ id: "runtime",+ state: "failed",+ message: "Could not mount the model endpoint.",+ }),+ ]),+ },+ events: expect.arrayContaining([+ expect.objectContaining({+ kind: "stage",+ stage: "runtime",+ state: "failed",+ }),+ ]),+ });+});+const localPlan = {planId: "a".repeat(64),gpuIndex: 1,diff --git a/apps/linger-installer/src/server/jobs.ts b/apps/linger-installer/src/server/jobs.tsindex d11cf63e..33a2c516 100644--- a/apps/linger-installer/src/server/jobs.ts+++ b/apps/linger-installer/src/server/jobs.ts@@ -417,11 +417,20 @@ export class JobManager {computer?: Job["computer"];knowledge?: string;code?: unknown;+ stage?: unknown;localModelsPlan?: unknown;runtime?: unknown;loginCommand?: unknown;loginInstructions?: unknown;};+ if (record.job.state === "failed") {+ // The outcome names the cause when parallel work or cleanup+ // reported its own progress after the step that failed.+ const failedStage = record.job.stages.find(+ ({ id }) => id === details.stage,+ );+ if (failedStage) record.job.stage = failedStage.id;+ }if (["RUNTIME_AUTH_REQUIRED",diff --git a/apps/linger-installer/src/server/stop-diagnostics.test.ts b/apps/linger-installer/src/server/stop-diagnostics.test.tsnew file mode 100644index 00000000..9cfbead2--- /dev/null+++ b/apps/linger-installer/src/server/stop-diagnostics.test.ts@@ -0,0 +1,69 @@+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { homedir, tmpdir } from "node:os";+import path from "node:path";+import { expect, test } from "vitest";+import { recordStopOutcome, stopFailure } from "./stop-diagnostics.js";+import { LOCALMODELS_KIT_VERIFICATION_FAILED } from "@linger/local-installation/localmodels-tool";+import { NATIVE_PROCESS_IDENTITY_UNVERIFIED } from "@linger/local-installation/native-process";+import {+ NATIVE_SERVICE_STOP_FAILED,+ nativeServices,+} from "@linger/local-installation/native-source";+import { windowsPrivatePath } from "@linger/local-installation/windows-private";++test("keeps every structured stop code and native service", () => {+ for (const code of [+ LOCALMODELS_KIT_VERIFICATION_FAILED,+ NATIVE_PROCESS_IDENTITY_UNVERIFIED,+ NATIVE_SERVICE_STOP_FAILED,+ ])+ expect(stopFailure("services", { code }).code).toBe(code);+ for (const service of nativeServices)+ expect(stopFailure("services", { nativeService: service }).service).toBe(+ service,+ );+});++test("persists bounded redacted first failure and latest successful retry", async () => {+ const home = await mkdtemp(+ path.join(+ process.platform === "win32" ? homedir() : tmpdir(),+ "stop-diagnostics-",+ ),+ );+ try {+ if (process.platform === "win32")+ await windowsPrivatePath(home, "directory", true);+ const failure = stopFailure("services", {+ code: "NATIVE_PROCESS_IDENTITY_UNVERIFIED",+ nativeService: "postgres",+ message: "secret",+ });+ await recordStopOutcome(home, Array(100).fill(failure));+ const firstPath = path.join(home, "installer", "stop-first-failure.json");+ const first = await readFile(firstPath, "utf8");+ expect(first).not.toContain("secret");+ expect(JSON.parse(first)).toMatchObject({+ exitCode: 1,+ failures: Array(12).fill(failure),+ });+ await recordStopOutcome(home, []);+ expect(await readFile(firstPath, "utf8")).toBe(first);+ expect(+ JSON.parse(+ await readFile(+ path.join(home, "installer", "stop-latest.json"),+ "utf8",+ ),+ ),+ ).toMatchObject({ exitCode: 0, failures: [] });+ expect(+ stopFailure("localmodels", { code: "secret", nativeService: "secret" }),+ ).toEqual({ stage: "localmodels", code: "STOP_FAILED" });+ expect(stopFailure("manager", { name: "TimeoutError" }).code).toBe(+ "TIMEOUT",+ );+ } finally {+ await rm(home, { recursive: true, force: true });+ }+}, 60_000);diff --git a/apps/linger-installer/src/server/stop-diagnostics.ts b/apps/linger-installer/src/server/stop-diagnostics.tsnew file mode 100644index 00000000..b6df680c--- /dev/null+++ b/apps/linger-installer/src/server/stop-diagnostics.ts@@ -0,0 +1,68 @@+import { writeFile } from "node:fs/promises";+import path from "node:path";+import { LOCALMODELS_KIT_VERIFICATION_FAILED } from "@linger/local-installation/localmodels-tool";+import { NATIVE_PROCESS_IDENTITY_UNVERIFIED } from "@linger/local-installation/native-process";+import {+ NATIVE_SERVICE_STOP_FAILED,+ nativeServices,+} from "@linger/local-installation/native-source";+import { privateDirectory, privateWrite } from "./storage.js";++type Stage = "manager" | "services" | "localmodels" | "helper";+interface Failure {+ stage: Stage;+ code: string;+ service?: string;+}+const codes = new Set<string>([+ LOCALMODELS_KIT_VERIFICATION_FAILED,+ NATIVE_PROCESS_IDENTITY_UNVERIFIED,+ NATIVE_SERVICE_STOP_FAILED,+]);+const services = new Set<string>(nativeServices);++// Only structured allowlisted fields are persisted; errors can contain secrets.+export function stopFailure(stage: Stage, error: unknown): Failure {+ const value = error as {+ code?: unknown;+ nativeService?: unknown;+ name?: unknown;+ } | null;+ const code =+ typeof value?.code === "string" && codes.has(value.code)+ ? value.code+ : value?.name === "TimeoutError"+ ? "TIMEOUT"+ : "STOP_FAILED";+ const service =+ typeof value?.nativeService === "string" &&+ services.has(value.nativeService)+ ? value.nativeService+ : undefined;+ return { stage, code, ...(service ? { service } : {}) };+}++export async function recordStopOutcome(+ home: string,+ failures: Failure[],+): Promise<void> {+ const directory = path.join(home, "installer");+ const report = {+ time: new Date().toISOString(),+ exitCode: failures.length ? 1 : 0,+ failures: failures.slice(0, 12),+ };+ await privateDirectory(directory);+ if (failures.length) {+ try {+ await writeFile(+ path.join(directory, "stop-first-failure.json"),+ JSON.stringify(report),+ { flag: "wx", mode: 0o600 },+ );+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;+ }+ }+ await privateWrite(path.join(directory, "stop-latest.json"), report);+}diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.tsindex 9e22688e..cfd604b3 100644--- a/apps/linger-installer/src/server/stop.ts+++ b/apps/linger-installer/src/server/stop.ts@@ -19,6 +19,10 @@ export interface StopOptions {instanceName: string;signal: AbortSignal;log: (message: string) => void;+ onFailure?: (+ stage: "manager" | "services" | "localmodels",+ error: unknown,+ ) => void;}export interface StopOutcome {@@ -55,19 +59,29 @@ export async function stopDesktopInstallation(fetch: fetcher = fetch,}: StopDependencies = {},): Promise<StopOutcome> {- const { failed, attempt } = attempts(options.log);+ const { failed, attempt } = attempts(+ options.log,+ "the installation",+ options.onFailure,+ );for (const home of await installationHomes(options.home)) {// The services stop even when the manager could not: an earlier release's// manager has no /api/stop, and a stale session may name another server.- await attempt(home, () => stopManager(home, options, fetcher));- await attempt(home, async () => {- const instance = await load({ name: options.instanceName, home });- if (!instance) return;- options.log(`Stopping the services in ${instance.root}.`);- await stopInstance(instance, options.signal);- });- await attempt(home, () =>- stopModels(home, { signal: options.signal, log: options.log }),+ await attempt(home, () => stopManager(home, options, fetcher), "manager");+ await attempt(+ home,+ async () => {+ const instance = await load({ name: options.instanceName, home });+ if (!instance) return;+ options.log(`Stopping the services in ${instance.root}.`);+ await stopInstance(instance, options.signal);+ },+ "services",+ );+ await attempt(+ home,+ () => stopModels(home, { signal: options.signal, log: options.log }),+ "localmodels",);}return { failed };@@ -115,12 +129,21 @@ export async function stopDesktopLocalModels(}// Runs each step and records the ones that failed, so every home is tried.-function attempts(log: (message: string) => void, target = "the installation") {+function attempts(+ log: (message: string) => void,+ target = "the installation",+ onFailure?: StopOptions["onFailure"],+) {const failed: StopOutcome["failed"] = [];- const attempt = async (home: string, step: () => Promise<void>) => {+ const attempt = async (+ home: string,+ step: () => Promise<void>,+ stage: "manager" | "services" | "localmodels" = "localmodels",+ ) => {try {await step();} catch (error) {+ onFailure?.(stage, error);const message = error instanceof Error ? error.message : String(error);log(`Could not stop ${target} in ${home}: ${message}`);failed.push({ home, message });diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.tsindex 329a0421..2cafaa52 100644--- a/packages/local-installation/src/localmodels-tool.ts+++ b/packages/local-installation/src/localmodels-tool.ts@@ -118,6 +118,9 @@ async function writeStamps(JSON.stringify({ manifestSha256: source.manifestSha256, stamps }),).catch(() => undefined);}+/** Marks a stop that could not verify the pinned localmodels kit. */+export const LOCALMODELS_KIT_VERIFICATION_FAILED =+ "LOCALMODELS_KIT_VERIFICATION_FAILED";// Assets hashed at once.const CONCURRENCY = 16;async function verify(@@ -588,7 +591,20 @@ export async function stopLocalmodels(installed?: (home: string) => Promise<boolean>;} = {},): Promise<void> {- if (!(await (dependencies.installed ?? hasPinnedTool)(home))) return;+ let installed: boolean;+ try {+ installed = await (dependencies.installed ?? hasPinnedTool)(home);+ } catch (error) {+ throw Object.assign(+ new Error(error instanceof Error ? error.message : String(error), {+ cause: error,+ }),+ {+ code: LOCALMODELS_KIT_VERIFICATION_FAILED,+ },+ );+ }+ if (!installed) return;const run =dependencies.run ??((home, args, options = {}) =>diff --git a/packages/local-installation/src/native-process.test.ts b/packages/local-installation/src/native-process.test.tsindex c273ed91..be406aa7 100644--- a/packages/local-installation/src/native-process.test.ts+++ b/packages/local-installation/src/native-process.test.ts@@ -21,6 +21,8 @@ vi.mock("./instance.js", async (original) => {});import { test as base, vi, type TestContext } from "vitest";import {+ NATIVE_PROCESS_IDENTITY_UNVERIFIED,+ NATIVE_PROCESS_REPLACED,nativeConfigurationChanged,startNativeProcess,inspectNativeProcess,@@ -119,7 +121,12 @@ test("refuses to signal a PID whose recorded lease differs", async (context) =>altered.lease = "0".repeat(64);await writeFile(file, JSON.stringify(altered), { mode: 0o600 });expect((await inspectNativeProcess(root, "web")).running).toBe(false);- await expect(stopNativeProcess(root, "web")).rejects.toThrow(/identity/i);+ await expect(stopNativeProcess(root, "web")).rejects.toMatchObject({+ code:+ process.platform === "win32"+ ? NATIVE_PROCESS_IDENTITY_UNVERIFIED+ : NATIVE_PROCESS_REPLACED,+ });await expect(startNativeProcess(options)).rejects.toThrow(/identity/i);expect(() => process.kill(processState.pid!, 0)).not.toThrow();await writeFile(file, original, { mode: 0o600 });diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.tsindex 219158af..98511f93 100644--- a/packages/local-installation/src/native-process.ts+++ b/packages/local-installation/src/native-process.ts@@ -471,6 +471,8 @@ async function endUnreapedGroup(child: ChildProcess): Promise<void> {* program: none of the service's own processes are left.*/export const NATIVE_PROCESS_REPLACED = "NATIVE_PROCESS_REPLACED";+export const NATIVE_PROCESS_IDENTITY_UNVERIFIED =+ "NATIVE_PROCESS_IDENTITY_UNVERIFIED";export async function stopNativeProcess(root: string,name: NativeService,@@ -603,8 +605,11 @@ async function windowsStopSnapshot(// A fresh snapshot distinguishes that from a live, unverifiable process.if (current.unverified?.command === "") current = await read();if (current.unverified) {- throw new Error(- `Native ${name} process identity cannot be verified; identity record retained.`,+ throw Object.assign(+ new Error(+ `Native ${name} process identity cannot be verified; identity record retained.`,+ ),+ { code: NATIVE_PROCESS_IDENTITY_UNVERIFIED },);}return current;diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.tsindex b9cf7919..8d6dcd83 100644--- a/packages/local-installation/src/native-source-flow.test.ts+++ b/packages/local-installation/src/native-source-flow.test.ts@@ -51,7 +51,7 @@ import {TEAMHUB_COMMANDS,} from "./teamhub-binaries.js";import { prepareRuntime } from "./managed-runtimes.js";-import { applyNativeSource } from "./byok-source.js";+import { applyNativeSource, prepareByokRuntime } from "./byok-source.js";import { prepareLocalModels } from "./local-models.js";import {inspectNativeListeners,@@ -83,6 +83,7 @@ vi.mock("./native-livekit.js", async (original) => ({vi.mock("./byok-source.js", async (original) => ({...(await original<typeof import("./byok-source.js")>()),applyNativeSource: vi.fn(async () => undefined),+ prepareByokRuntime: vi.fn(),}));// Deploying local models runs the localmodels tool too.vi.mock("./local-models.js", async (original) => ({@@ -1096,6 +1097,82 @@ test("a failed Runtime reports its own outcome while the checkout preparation st});});+test.each(["returned", "thrown"])(+ "a %s BYOK failure after PostgreSQL startup fails the runtime stage",+ async (failure) => {+ const f = await fixture();+ let signalPostgresStarted!: () => void;+ const postgresStarted = new Promise<void>((resolve) => {+ signalPostgresStarted = resolve;+ });+ vi.mocked(prepareNativeDatabase).mockImplementation(async () => {+ f.running.add("postgres");+ signalPostgresStarted();+ return {};+ });+ const message = "Could not mount the model endpoint: ConnectionResetError.";+ vi.mocked(prepareByokRuntime).mockImplementation(async (_byok, options) => {+ await postgresStarted;+ options.onEvent({+ kind: "stage",+ stage: "runtime",+ state: "running",+ message: "Mounting BYOK endpoint on local Bifrost gateway…",+ });+ if (failure === "thrown") throw new Error(message);+ return { code: 1, state: "failed", message };+ });+ const events: InstallerEvent[] = [];+ const result = await installNativeSource({+ ...f,+ name: "native-flow",+ byok: {+ baseUrl: "https://example.test/v1",+ modelId: "test",+ apiKey: "test-key",+ runtime: "pi",+ },+ signal: new AbortController().signal,+ onEvent: (event) => events.push(event),+ });+ expect(result).toMatchObject({+ state: "failed",+ message: expect.stringContaining(message),+ details: { stage: "runtime" },+ });+ expect(events.filter((event) => event.state === "failed")).toEqual([+ { kind: "stage", stage: "runtime", state: "failed", message },+ ]);+ expect(f.running.size).toBe(0);+ },+);++test("an invalid checkout fails preflight before starting the runtime", async () => {+ const f = await fixture();+ const events: InstallerEvent[] = [];+ const result = await installNativeSource({+ ...f,+ name: "native-flow",+ repo: path.join(f.repo, "missing"),+ setupChoice: "pi",+ signal: new AbortController().signal,+ onEvent: (event) => events.push(event),+ });+ expect(result).toMatchObject({+ state: "failed",+ details: { stage: "preflight" },+ });+ expect(events.filter((event) => event.state === "failed")).toEqual([+ {+ kind: "stage",+ stage: "preflight",+ state: "failed",+ message: expect.any(String),+ },+ ]);+ expect(prepareRuntime).not.toHaveBeenCalled();+});+test("an installation stopped from outside stays cancelled", async () => {const f = await fixture();const controller = new AbortController();diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex 85c0562a..029e153a 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -71,6 +71,8 @@ export const nativeServices = ["livekit","postgres",] as const;+/** Marks a native service whose stop failed without a more specific code. */+export const NATIVE_SERVICE_STOP_FAILED = "NATIVE_SERVICE_STOP_FAILED";function requireNative(instance: Instance) {if (instance.mode !== "source-native" || !instance.source)throw new Error("This operation requires a native source instance.");@@ -382,9 +384,6 @@ export async function installNativeSource(const timings = timer.finish();options.onEvent({kind: "log",- stage:- (outcome.details as { stage?: InstallStage } | undefined)?.stage ??- "preflight",message: `Native install timings (s): ${Object.entries(timings).map(([stage, seconds]) => `${stage} ${seconds}`).join(", ")}\n`,@@ -1096,6 +1095,7 @@ async function runNativeSource(}options.signal.throwIfAborted();if (runtimeFailedFirst) {+ stage = "runtime";// eslint-disable-next-line @typescript-eslint/only-throw-error -- rethrows the first failure unchangedif (runtimeError) throw runtimeError;if (@@ -1103,8 +1103,24 @@ async function runNativeSource(runtimeOutcome.code !== 0 &&(runtimeOutcome.details as { code?: string } | undefined)?.code !=="RUNTIME_AUTH_REQUIRED"- )- return runtimeOutcome;+ ) {+ const message = safe(runtimeOutcome.message);+ if (+ runtimeOutcome.state === "failed" ||+ runtimeOutcome.state === "prerequisite_unavailable"+ )+ emit({ kind: "stage", stage, state: "failed", message });+ return {+ ...runtimeOutcome,+ message,+ details: {+ ...(typeof runtimeOutcome.details === "object"+ ? runtimeOutcome.details+ : {}),+ stage,+ },+ };+ }}throw error;} finally {@@ -1186,7 +1202,18 @@ export async function stopNativeSource(await stopComputer(instance, { signal });for (const name of nativeServices) {signal?.throwIfAborted();- await stopNativeProcess(instance.root, name);+ try {+ await stopNativeProcess(instance.root, name);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ throw Object.assign(+ new Error(+ error instanceof Error ? error.message : `Could not stop ${name}.`,+ { cause: error },+ ),+ { code: code ?? NATIVE_SERVICE_STOP_FAILED, nativeService: name },+ );+ }}await reclaimEarlierProcesses(instance,diff --git a/packages/local-installation/src/ports.test.ts b/packages/local-installation/src/ports.test.tsindex f0b34dea..6c702b43 100644--- a/packages/local-installation/src/ports.test.ts+++ b/packages/local-installation/src/ports.test.ts@@ -61,6 +61,15 @@ it("never returns a reserved port", async () => {);});+it("reports the loopback bind error if it cannot find an alternative", async () => {+ const taken = (await listen("127.0.0.1"))!;+ const reserved = new Set(Array.from({ length: 65536 }, (_, port) => port));+ reserved.delete(taken);+ await expect(freePort(reserved, { preferred: taken })).rejects.toThrow(+ "TCP: 127.0.0.1 bind: EADDRINUSE",+ );+});+it("checks UDP ports separately", async () => {const socket = createSocket("udp4");await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", resolve));diff --git a/packages/local-installation/src/ports.ts b/packages/local-installation/src/ports.tsindex 4b648fd2..9fe366df 100644--- a/packages/local-installation/src/ports.ts+++ b/packages/local-installation/src/ports.ts@@ -12,15 +12,19 @@ const NO_IPV6 = new Set(["EADDRNOTAVAIL", "EAFNOSUPPORT", "EINVAL"]);type Protocol = "tcp" | "udp";-function bindable(+function bindConflict(port: number,host: string,protocol: Protocol,-): Promise<boolean> {+): Promise<string | undefined> {const ipv6 = host.includes(":");return new Promise((resolve) => {const failed = (error: NodeJS.ErrnoException) =>- resolve(ipv6 && NO_IPV6.has(error.code ?? ""));+ resolve(+ ipv6 && NO_IPV6.has(error.code ?? "")+ ? undefined+ : `${host} bind: ${error.code ?? error.name}`,+ );if (protocol === "udp") {const socket = createSocket(ipv6 ? "udp6" : "udp4");socket.once("error", (error) => {@@ -31,13 +35,13 @@ function bindable(}failed(error);});- socket.bind(port, host, () => socket.close(() => resolve(true)));+ socket.bind(port, host, () => socket.close(() => resolve(undefined)));return;}const server = net.createServer();server.once("error", failed);server.listen({ port, host, exclusive: true }, () =>- server.close(() => resolve(true)),+ server.close(() => resolve(undefined)),);});}@@ -57,18 +61,28 @@ function answers(port: number, host: string): Promise<boolean> {});}+async function portConflict(+ port: number,+ protocol: Protocol,+): Promise<string | undefined> {+ for (const host of LOOPBACK) {+ const conflict = await bindConflict(port, host, protocol);+ if (conflict) return conflict;+ }+ if (protocol === "udp") return undefined;+ const answered = await Promise.all(+ LOOPBACK.map((host) => answers(port, host)),+ );+ const host = LOOPBACK[answered.indexOf(true)];+ return host ? `${host} already answers TCP connections` : undefined;+}+/** Whether no program uses `port` on IPv4 or IPv6 loopback. */export async function portFree(port: number,protocol: Protocol = "tcp",): Promise<boolean> {- for (const host of LOOPBACK)- if (!(await bindable(port, host, protocol))) return false;- if (protocol === "udp") return true;- const answered = await Promise.all(- LOOPBACK.map((host) => answers(port, host)),- );- return !answered.includes(true);+ return (await portConflict(port, protocol)) === undefined;}function ephemeral(protocol: Protocol): Promise<number> {@@ -101,17 +115,19 @@ export async function freePort(): Promise<number> {const protocol = options.protocol ?? "tcp";let port = options.preferred;+ let lastConflict: string | undefined;for (let attempt = 0; ; attempt++) {- if (- port !== undefined &&- !reserved.has(port) &&- (await portFree(port, protocol))- ) {- reserved.add(port);- return port;+ if (port !== undefined && !reserved.has(port)) {+ lastConflict = await portConflict(port, protocol);+ if (lastConflict === undefined) {+ reserved.add(port);+ return port;+ }}if (attempt >= 100)- throw new Error("No free local port is available on this computer.");+ throw new Error(+ `No free local port is available on this computer. ${protocol.toUpperCase()}: ${lastConflict ?? "all candidates were reserved"}.`,+ );port = await ephemeral(protocol);}}