Skip to content

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(desktop): keep following the install job through a dropped connection

shoudi zhengc3e31a9b829a
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index e8349d55..83584fff 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -29,6 +29,7 @@ import {
checkLocation,
followHttps,
hasNativePostgres,
+ InstallerApi,
installLocation,
legacyMigrationResult,
parseSetCookie,
@@ -3428,3 +3429,125 @@ describe("legacyMigrationResult", () => {
).toEqual({ skipped: [] });
});
});
+
+describe("InstallerApi polling", () => {
+ const reset = () =>
+ new TypeError("fetch failed", {
+ cause: Object.assign(new Error("socket hang up"), {
+ code: "ECONNRESET",
+ }),
+ });
+ const job = (fields: Record<string, unknown>) =>
+ Response.json({
+ id: "job",
+ instance: LOCAL_INSTANCE,
+ createdAt: "2026-11-03T00:00:00Z",
+ stage: "images",
+ stages: [{ id: "images", state: "running" }],
+ ...fields,
+ });
+ // An installer whose job polls answer from `polls`, in order; a function
+ // entry throws, and the last entry repeats.
+ const installer = (polls: (Record<string, unknown> | (() => never))[]) => {
+ const created: unknown[] = [];
+ const posts: string[] = [];
+ let reads = 0;
+ const fetcher = (async (input: URL, init: RequestInit = {}) => {
+ if (init.method === "POST") posts.push(input.pathname);
+ if (input.pathname === "/api/session")
+ return new Response("{}", {
+ headers: { "set-cookie": "linger_installer_session=s1; Path=/api" },
+ });
+ if (input.pathname === "/api/jobs" && init.method === "POST") {
+ created.push(JSON.parse(String(init.body)));
+ return job({ state: "queued" });
+ }
+ if (input.pathname === "/api/jobs") return Response.json({ items: [] });
+ if (input.pathname === "/api/jobs/job") {
+ const next = polls[Math.min(reads++, polls.length - 1)]!;
+ return typeof next === "function" ? next() : job(next);
+ }
+ return Response.json({}, { status: 404 });
+ }) as unknown as typeof fetch;
+ return { fetcher, created, posts, reads: () => reads };
+ };
+ const warnings: Record<string, unknown>[] = [];
+ const log = {
+ info: () => {},
+ warn: (_: string, fields?: Record<string, unknown>) =>
+ warnings.push(fields!),
+ error: () => {},
+ };
+ const open = (fetcher: typeof fetch, windowMs = 60_000) =>
+ InstallerApi.open("http://127.0.0.1:9/#token=abc", fetcher, 1, log, {
+ windowMs,
+ maxBackoffMs: 5,
+ });
+ const plan = { runtime: "codex" } as Parameters<InstallerApi["run"]>[0];
+
+ it("reconnects after a dropped connection and follows the same job", async () => {
+ warnings.length = 0;
+ const fake = installer([
+ () => {
+ throw reset();
+ },
+ { state: "succeeded", origin: "http://localhost:3000" },
+ ]);
+ const messages: string[] = [];
+ const result = await (
+ await open(fake.fetcher)
+ ).run(plan, new AbortController().signal, (_s, _p, message) =>
+ messages.push(message),
+ );
+ expect(result.origin).toBe("http://localhost:3000");
+ expect(fake.created).toHaveLength(1);
+ expect(fake.posts).toEqual(["/api/session", "/api/jobs"]);
+ expect(messages).toContain("Reconnecting to the installer…");
+ expect(warnings).toEqual([
+ { stage: "poll_job", job_id: "job", code: "ECONNRESET", attempt: 1 },
+ ]);
+ });
+
+ it("gives up once the installer stays unreachable", async () => {
+ const fake = installer([
+ () => {
+ throw reset();
+ },
+ ]);
+ await expect(
+ (await open(fake.fetcher, 30)).run(
+ plan,
+ new AbortController().signal,
+ () => {},
+ ),
+ ).rejects.toThrow(
+ "Couldn't read the installation progress. Try again to reconnect to the running installation.",
+ );
+ expect(fake.created).toHaveLength(1);
+ });
+
+ it("reports a failed job as before", async () => {
+ const fake = installer([{ state: "failed", message: "Images broke" }]);
+ await expect(
+ (await open(fake.fetcher)).run(
+ plan,
+ new AbortController().signal,
+ () => {},
+ ),
+ ).rejects.toThrow("Images broke");
+ });
+
+ it("stops reconnecting when the caller aborts", async () => {
+ const controller = new AbortController();
+ const fake = installer([
+ () => {
+ controller.abort();
+ throw reset();
+ },
+ ]);
+ await expect(
+ (await open(fake.fetcher)).run(plan, controller.signal, () => {}),
+ ).rejects.toThrow();
+ expect(fake.reads()).toBe(1);
+ });
+});
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index 23e07775..93ea3332 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -62,6 +62,7 @@ import {
NODE_RUNTIME_VERSION,
nodeRuntimeDownloadUrls,
} from "../../../../scripts/local-computer-node-distributions.mjs";
+import type { Logger } from "./log.js";
import type { Module, ModuleContext } from "./modules.js";
import { sameOrigin } from "./navigation.js";
import { humanTenant, type EnrollmentModule } from "./enrollment.js";
@@ -1954,6 +1955,7 @@ export class LocalServerModule implements Module {
target,
this.#options.fetch ?? fetch,
this.#options.pollMs ?? 1000,
+ this.#ctx?.log,
);
}
@@ -2484,18 +2486,59 @@ const LOCAL_MODEL_FAILURES = new Set([
"GPU_SHARING_REVOCATION_FAILED",
]);
+export interface Reconnect {
+ readonly windowMs: number;
+ readonly maxBackoffMs: number;
+}
+
+const RECONNECT: Reconnect = { windowMs: 60_000, maxBackoffMs: 5_000 };
+
+const TRANSIENT_CODES = new Set([
+ "ECONNRESET",
+ "ECONNREFUSED",
+ "EPIPE",
+ "ETIMEDOUT",
+ "UND_ERR_SOCKET",
+ "UND_ERR_CONNECT_TIMEOUT",
+ "UND_ERR_CLOSED",
+]);
+
+// The code of a transport failure worth retrying, found on the error or its
+// causes; undefined for anything else, HTTP and JSON errors included.
+const transientCode = (error: unknown): string | undefined => {
+ for (let at = error, depth = 0; at && depth < 5; depth++) {
+ if (!(at instanceof Error)) return undefined;
+ // The per-request timeout; the caller's own abort is ruled out before.
+ if (at.name === "TimeoutError" || at.name === "AbortError") return at.name;
+ const code = (at as { code?: unknown }).code;
+ if (typeof code === "string" && TRANSIENT_CODES.has(code)) return code;
+ at = at.cause;
+ }
+ return undefined;
+};
+
// The desktop is the installer's only client here: it starts the job and
// follows it, and nothing of the installer UI is shown.
export class InstallerApi {
readonly #origin: string;
readonly #fetch: typeof fetch;
readonly #pollMs: number;
+ readonly #log: Logger | undefined;
+ readonly #reconnect: Reconnect;
#cookie = "";
- private constructor(origin: string, fetcher: typeof fetch, pollMs: number) {
+ private constructor(
+ origin: string,
+ fetcher: typeof fetch,
+ pollMs: number,
+ log: Logger | undefined,
+ reconnect: Reconnect,
+ ) {
this.#origin = origin;
this.#fetch = fetcher;
this.#pollMs = pollMs;
+ this.#log = log;
+ this.#reconnect = reconnect;
}
// Exchanges the one-time token in the launcher URL for a session.
@@ -2503,11 +2546,19 @@ export class InstallerApi {
url: string,
fetcher: typeof fetch,
pollMs: number,
+ log?: Logger,
+ reconnect: Reconnect = RECONNECT,
): Promise<InstallerApi> {
const target = new URL(url);
const token = new URLSearchParams(target.hash.slice(1)).get("token");
if (!token) throw new Error("The installer did not provide a sign-in link");
- const api = new InstallerApi(target.origin, fetcher, pollMs);
+ const api = new InstallerApi(
+ target.origin,
+ fetcher,
+ pollMs,
+ log,
+ reconnect,
+ );
const response = await api.#call("/api/session", { token });
if (!response.ok)
throw new Error(`The installer refused the session (${response.status})`);
@@ -2583,6 +2634,8 @@ export class InstallerApi {
// first; that is asked for once too.
let approved: string | undefined;
let replanned = false;
+ // Where the bar last stood, kept while the installer cannot be reached.
+ let shown: [LocalServerStep, number] | undefined;
for (;;) {
const at = job.stage ? STAGES[job.stage] : undefined;
if (at) {
@@ -2606,9 +2659,10 @@ export class InstallerApi {
counter.total
? counter
: undefined;
+ shown = [at[0], at[1] + (at[2] - at[1]) * part];
onStep(
- at[0],
- at[1] + (at[2] - at[1]) * part,
+ shown[0],
+ shown[1],
job.message ?? "",
bytes && {
completed: bytes.completed,
@@ -2663,7 +2717,44 @@ export class InstallerApi {
: job.message || "The installation stopped",
);
await delay(this.#pollMs, undefined, { signal });
- job = await this.#json<Job>(`/api/jobs/${encodeURIComponent(job.id)}`);
+ job = await this.#poll(job.id, signal, () => {
+ if (shown) onStep(shown[0], shown[1], "Reconnecting to the installer…");
+ });
+ }
+ }
+
+ // Reads the job again. The read is idempotent, so a dropped connection is
+ // retried for a while: the job keeps running in the installer either way.
+ async #poll(
+ id: string,
+ signal: AbortSignal,
+ onReconnect: () => void,
+ ): Promise<Job> {
+ let since: number | undefined;
+ let wait = this.#pollMs;
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await this.#json<Job>(`/api/jobs/${encodeURIComponent(id)}`);
+ } catch (error) {
+ if (signal.aborted) throw error;
+ const code = transientCode(error);
+ if (!code) throw error;
+ this.#log?.warn("local_server.installer_unreachable", {
+ stage: "poll_job",
+ job_id: id,
+ code,
+ attempt,
+ });
+ since ??= Date.now();
+ if (Date.now() - since >= this.#reconnect.windowMs)
+ throw new Error(
+ "Couldn't read the installation progress. Try again to reconnect to the running installation.",
+ { cause: error },
+ );
+ onReconnect();
+ await delay(wait, undefined, { signal });
+ wait = Math.min(wait * 2, this.#reconnect.maxBackoffMs);
+ }
}
}