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): stream source apply download progress and stop it only when idle
shoudi zhenga0953570cb56
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex 95bc683a..be3c1fde 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -299,8 +299,17 @@ through `onRuntimeDescriptors` so callers avoid a second status probe. Withindependency and voice tool preparations stay sequential on the sharednative-tools lock; collaboration services start concurrently when `node-services`is not pre-stopped for a TeamHub config restart. `runLocalmodels`-forwards `harness apply` `download:retrying` and `total: null` byte progress-(without a total), and `prepareByokRuntime` logs elapsed time every 10 s while mounting+reads the kit's JSON event lines from stdout and stderr alike and forwards+byte progress (`total: null` without a total) and the download+`connecting`, `switching` and `retrying` stages of every command, labeled per+command; a host is shown only when it is a plain hostname, and unknown states+are ignored. `harness apply` also forwards its extract, verify and install+stages. Setup's `source apply` (`prepareByokRuntime`, `applyNativeSource`) may+download Bifrost first, so it forwards these events and has no wall-clock+limit: `idleTimeoutMs` (240 s, above the kit's longest silent span, the BYOK+endpoint probe of up to about 35 s followed by Bifrost's health wait of up to+180 s) stops it only after that long with no output. The resume mount+keeps its 90 s wall clock. `prepareByokRuntime` logs elapsed time every 10 s while mountingthe BYOK gateway (a log line, since the job appends and persists every stageevent).diff --git a/packages/local-installation/src/byok-source.test.ts b/packages/local-installation/src/byok-source.test.tsindex e1ab2198..df47bc98 100644--- a/packages/local-installation/src/byok-source.test.ts+++ b/packages/local-installation/src/byok-source.test.ts@@ -146,7 +146,7 @@ describe("BYOK localmodels integration", () => {home,"subscription","codex",- new AbortController().signal,+ { signal: new AbortController().signal },{localmodels: async (_home, args) => {calls.push(args);@@ -173,7 +173,7 @@ describe("BYOK localmodels integration", () => {await makeHome(),"local","pi",- new AbortController().signal,+ { signal: new AbortController().signal },{localmodels: async () => ({code: 2,@@ -587,3 +587,83 @@ describe("restoreByokSource", () => {).rejects.toThrow();});});++describe("source apply timeouts and progress", () => {+ const onEvent = () => {};++ it("bounds a BYOK apply by silence, not wall clock, and forwards events", async () => {+ const localmodels = vi.fn(async () => ({+ code: 0,+ stdout: "{}",+ stderr: "",+ }));+ await prepareByokRuntime(+ {+ baseUrl: "https://api.example.com/v1",+ apiKey: "sk-test",+ modelId: "m",+ runtime: "claude",+ },+ { home: await makeHome(), signal: new AbortController().signal, onEvent },+ {+ prepareNative: async () => ({ code: 0, state: "ready", message: "" }),+ localmodels,+ },+ );+ const options = (localmodels.mock.calls[0] as unknown[])[2] as Record<+ string,+ unknown+ >;+ expect(options).toMatchObject({ idleTimeoutMs: 240_000, onEvent });+ expect(options).not.toHaveProperty("timeoutMs");+ });++ it("bounds a native source apply by silence and still reads its failure", async () => {+ const localmodels = vi.fn(async () => ({+ code: 2,+ stdout: JSON.stringify({+ code: "GATEWAY_FAILED",+ message: "No gateway.",+ }),+ stderr:+ '{"kind":"stage","stage":"download","state":"connecting","host":"registry.npmmirror.com"}\n',+ }));+ const outcome = await applyNativeSource(+ await makeHome(),+ "local",+ "pi",+ { signal: new AbortController().signal, onEvent },+ { localmodels },+ );+ expect(outcome).toMatchObject({+ message: "No gateway.",+ details: { code: "GATEWAY_FAILED" },+ });+ const options = (localmodels.mock.calls[0] as unknown[])[2] as Record<+ string,+ unknown+ >;+ expect(options).toMatchObject({ idleTimeoutMs: 240_000, onEvent });+ expect(options).not.toHaveProperty("timeoutMs");+ });++ it("keeps the resume mount's wall clock and forwards its events", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource(null));+ const localmodels = vi.fn(async () => ({+ code: 0,+ stdout: "{}",+ stderr: "",+ }));+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent },+ { localmodels },+ );+ const apply = localmodels.mock.calls.find((call) =>+ (call as unknown[])[1]?.toString().startsWith("source,apply"),+ ) as unknown[] | undefined;+ expect(apply?.[2]).toMatchObject({ timeoutMs: 90_000, onEvent });+ expect(apply?.[2]).not.toHaveProperty("idleTimeoutMs");+ });+});diff --git a/packages/local-installation/src/byok-source.ts b/packages/local-installation/src/byok-source.tsindex 69e0f418..dbfc03db 100644--- a/packages/local-installation/src/byok-source.ts+++ b/packages/local-installation/src/byok-source.ts@@ -213,13 +213,26 @@ export async function checkByokEndpoint(};}+// The kit's longest silent span is a BYOK apply with Bifrost already+// installed: the endpoint probe (up to about 35 s) and then Bifrost's health+// wait (up to 180 s), with no output between them. A download may run longer+// than any wall clock, so a source apply that still reports progress is never+// cut off.+const SOURCE_APPLY_IDLE_TIMEOUT_MS = 240_000;+// The installer switches the source through localmodels, as the Computer// does from Settings, so model-source.json has one writer.function applySource(home: string,mode: "local" | "subscription" | "byok",runtime: NativeRuntime,- options: { signal: AbortSignal; timeoutMs: number; input?: string },+ options: {+ signal: AbortSignal;+ timeoutMs?: number;+ idleTimeoutMs?: number;+ input?: string;+ onEvent?: (event: InstallerEvent) => void;+ },localmodels: typeof runLocalmodels,) {return localmodels(@@ -242,7 +255,13 @@ function applySource(],{signal: options.signal,- timeoutMs: options.timeoutMs,+ ...(options.timeoutMs === undefined+ ? {}+ : { timeoutMs: options.timeoutMs }),+ ...(options.idleTimeoutMs === undefined+ ? {}+ : { idleTimeoutMs: options.idleTimeoutMs }),+ ...(options.onEvent ? { onEvent: options.onEvent } : {}),...(options.input === undefined ? {} : { input: options.input }),},);@@ -357,8 +376,9 @@ export async function prepareByokRuntime(runtime,{signal: options.signal,- timeoutMs: 180_000,+ idleTimeoutMs: SOURCE_APPLY_IDLE_TIMEOUT_MS,input: byokStdin(validated),+ onEvent: options.onEvent,},dependencies.localmodels ?? runLocalmodels,);@@ -393,14 +413,18 @@ export async function applyNativeSource(home: string,mode: "local" | "subscription",runtime: NativeRuntime,- signal: AbortSignal,+ options: { signal: AbortSignal; onEvent?: (event: InstallerEvent) => void },dependencies: { localmodels?: typeof runLocalmodels } = {},): Promise<InstallOutcome | undefined> {const result = await applySource(home,mode,runtime,- { signal, timeoutMs: 180_000 },+ {+ signal: options.signal,+ idleTimeoutMs: SOURCE_APPLY_IDLE_TIMEOUT_MS,+ ...(options.onEvent ? { onEvent: options.onEvent } : {}),+ },dependencies.localmodels ?? runLocalmodels,);return result.code === 0@@ -547,7 +571,7 @@ export async function mountSavedByokSource(home,"byok",source.runtime,- { signal: options.signal, timeoutMs: 90_000 },+ { signal: options.signal, timeoutMs: 90_000, onEvent: options.onEvent },dependencies.localmodels ?? runLocalmodels,);if (result.code !== 0)diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.tsindex 316adda2..35818b2b 100644--- a/packages/local-installation/src/local-models.ts+++ b/packages/local-installation/src/local-models.ts@@ -664,6 +664,12 @@ export async function restoreLocalModels(// prepareLocalModels takes the lock itself, and the lock is not reentrant.return ((await prepareLocalModels(instance, options, dependencies)) ??- (await applyNativeSource(home, "local", "pi", options.signal, dependencies))+ (await applyNativeSource(+ home,+ "local",+ "pi",+ { signal: options.signal, onEvent: options.onEvent },+ dependencies,+ )));}diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.tsindex ed2c4001..4f40fbde 100644--- a/packages/local-installation/src/localmodels-tool.test.ts+++ b/packages/local-installation/src/localmodels-tool.test.ts@@ -839,3 +839,148 @@ test("uses a configured development localmodels checkout without downloading a k}),);});++test("maps source apply download stages to model gateway messages", async () => {+ const f = await fixture();+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));+ const onEvent = vi.fn();+ const lines = [+ {+ kind: "stage",+ stage: "download",+ state: "connecting",+ host: "registry.npmmirror.com",+ attempt: 1,+ attempts: 3,+ },+ {+ kind: "stage",+ stage: "download",+ state: "connecting",+ host: "evil.example/path?x=<b>",+ },+ {+ kind: "stage",+ stage: "download",+ state: "switching",+ from: "registry.npmmirror.com",+ to: "registry.npmjs.org",+ reason: "slow",+ completed: 10,+ },+ { kind: "stage", stage: "download", state: "switching", to: 42 },+ {+ kind: "stage",+ stage: "download",+ state: "retrying",+ attempt: 2,+ attempts: 3,+ reason: "private-secret-reason",+ completed: 5,+ waitSeconds: 2,+ },+ { kind: "stage", stage: "download", state: "teleporting" },+ {+ kind: "stage",+ stage: "download",+ state: "connecting",+ host: "a".repeat(254),+ },+ {+ kind: "progress",+ stage: "download",+ completed: 4,+ total: 10,+ unit: "bytes",+ },+ ];+ const run = vi.fn<typeof import("./process.js").runProcess>(+ async (_file, _args, options) => {+ options?.onOutput?.(+ lines.map((line) => JSON.stringify(line)).join("\n") ++ '\nnot json\n{"kind":"stage","stage":null}\n',+ );+ return { code: 0, stdout: "{}", stderr: "" };+ },+ );+ await runLocalmodels(+ f.home,+ ["source", "apply", "--mode", "byok", "--json"],+ { onEvent },+ { run },+ );+ const messages = onEvent.mock.calls+ .map(([event]) => event as { kind: string; message: string })+ .filter((event) => event.kind === "stage")+ .map((event) => event.message);+ expect(messages).toEqual([+ "Downloading the model gateway: connecting to registry.npmmirror.com…",+ "Downloading the model gateway: connecting…",+ "Downloading the model gateway: switching to registry.npmjs.org…",+ "Downloading the model gateway: switching…",+ "Downloading the model gateway: retrying…",+ "Downloading the model gateway: connecting…",+ "Downloading the model gateway…",+ ]);+ expect(onEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ progress: { completed: 4, total: 10, unit: "bytes" },+ }),+ );+ expect(JSON.stringify(onEvent.mock.calls)).not.toContain("private-secret");+});++test("labels gateway download stages as the application model gateway", async () => {+ const f = await fixture();+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));+ const onEvent = vi.fn();+ const run = vi.fn<typeof import("./process.js").runProcess>(+ async (_file, _args, options) => {+ options?.onOutput?.(+ '{"kind":"stage","stage":"download","state":"connecting","host":"github.com"}\n',+ );+ return { code: 0, stdout: "{}", stderr: "" };+ },+ );+ await runLocalmodels(f.home, ["gateway", "install"], { onEvent }, { run });+ expect(onEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ message:+ "Downloading the application model gateway: connecting to github.com…",+ }),+ );+});++test("reads source apply events from stderr while stdout stays the final document", async () => {+ const f = await fixture();+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));+ const onEvent = vi.fn();+ const { runProcess } = await import("./process.js");+ const run = vi.fn<typeof runProcess>((_file, _args, options) =>+ runProcess(+ process.execPath,+ [+ "-e",+ `process.stderr.write(JSON.stringify({kind:"stage",stage:"download",state:"connecting",host:"registry.npmmirror.com"})+"\\n");+process.stdout.write(JSON.stringify({code:"BYOK_PROBE_FAILED",message:"Endpoint refused."}));`,+ ],+ { ...options, cwd: undefined, env: process.env },+ ),+ );+ const result = await runLocalmodels(+ f.home,+ ["source", "apply", "--json"],+ { onEvent },+ { run },+ );+ expect(JSON.parse(result.stdout)).toEqual({+ code: "BYOK_PROBE_FAILED",+ message: "Endpoint refused.",+ });+ expect(onEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ message:+ "Downloading the model gateway: connecting to registry.npmmirror.com…",+ }),+ );+});diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.tsindex a8fe4deb..44578174 100644--- a/packages/local-installation/src/localmodels-tool.ts+++ b/packages/local-installation/src/localmodels-tool.ts@@ -464,6 +464,33 @@ export async function runLocalmodels(dependencies.run,);}+// Hosts come from the kit's mirror list; anything else is not shown.+function displayHost(value: unknown): string | undefined {+ return typeof value === "string" &&+ value.length <= 253 &&+ /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/.test(value)+ ? value+ : undefined;+}+function downloadStageMessage(+ value: Record<string, unknown>,+ label: string,+ harnessApply: boolean,+): string | undefined {+ if (value.state === "connecting") {+ const host = displayHost(value.host);+ return host ? `${label}: connecting to ${host}…` : `${label}: connecting…`;+ }+ if (value.state === "switching") {+ const host = displayHost(value.to);+ return host ? `${label}: switching to ${host}…` : `${label}: switching…`;+ }+ if (value.state === "retrying")+ return harnessApply+ ? "Retrying the Harness download…"+ : `${label}: retrying…`;+ return undefined;+}async function runLocalmodelsCommand(home: string,args: string[],@@ -490,6 +517,13 @@ async function runLocalmodelsCommand(delete env.PYTHONHOME;delete env.PYTHONSTARTUP;delete env.PYTHONINSPECT;+ const harnessApply = args[0] === "harness" && args[1] === "apply";+ const label =+ args[0] === "gateway"+ ? "Downloading the application model gateway"+ : args[0] === "source" && args[1] === "apply"+ ? "Downloading the model gateway"+ : "Downloading the selected Harness";let pending = "";const onOutput = (chunk: string) => {options.onOutput?.(chunk);@@ -504,13 +538,19 @@ async function runLocalmodelsCommand(} catch {continue;}- if (- args[0] === "harness" &&- args[1] === "apply" &&- value?.kind === "stage"- ) {+ if (value?.kind === "stage" && value.stage === "download") {+ const message = downloadStageMessage(value, label, harnessApply);+ if (message)+ options.onEvent?.({+ kind: "stage",+ stage: "runtime",+ state: "running",+ message,+ });+ continue;+ }+ if (harnessApply && value?.kind === "stage") {const messages: Record<string, string> = {- "download:retrying": "Retrying the Harness download…","extract:running":"Extracting Harness files and applying private permissions…","verify:running": "Verifying the installed Harness executable…",@@ -549,10 +589,6 @@ async function runLocalmodelsCommand(value.completed > value.total))continue;- const label =- args[0] === "gateway"- ? "Downloading the application model gateway"- : "Downloading the selected Harness";options.onEvent?.({kind: "stage",stage: "runtime",diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.tsindex 1e99000a..59d7e9a9 100644--- a/packages/local-installation/src/native-source-flow.test.ts+++ b/packages/local-installation/src/native-source-flow.test.ts@@ -297,7 +297,7 @@ test("choosing local models makes them the model source", async () => {path.resolve(f.home),"local","pi",- expect.any(AbortSignal),+ { signal: expect.any(AbortSignal), onEvent: expect.any(Function) },);});@@ -493,7 +493,7 @@ test("choosing a subscription again replaces a saved BYOK source", async () => {path.resolve(f.home),"subscription","codex",- expect.any(AbortSignal),+ { signal: expect.any(AbortSignal), onEvent: expect.any(Function) },);expect(restoreByokSource).not.toHaveBeenCalled();});@@ -508,7 +508,7 @@ test("a restart keeps a saved subscription source as before", async () => {expect.any(String),"subscription","codex",- expect.any(AbortSignal),+ { signal: expect.any(AbortSignal), onEvent: expect.any(Function) },);expect(restoreByokSource).not.toHaveBeenCalled();expect(prepareModelGateway).toHaveBeenCalledWith(diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex 4b9fc929..6830016f 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -556,12 +556,10 @@ async function runNativeSource((options.setupChoice === "local-models" ||options.localModelsApproval))- runtimeOutcome = await applyNativeSource(- home,- "local",- "pi",+ runtimeOutcome = await applyNativeSource(home, "local", "pi", {signal,- );+ onEvent: emit,+ });} else {runtimeOutcome = await prepareRuntime(choice, {home,@@ -580,12 +578,10 @@ async function runNativeSource(?.code === "RUNTIME_AUTH_REQUIRED"))runtimeOutcome =- (await applyNativeSource(- home,- "subscription",- choice,+ (await applyNativeSource(home, "subscription", choice, {signal,- )) ?? runtimeOutcome;+ onEvent: emit,+ })) ?? runtimeOutcome;}if (runtimeOutcome &&diff --git a/packages/local-installation/src/process.test.ts b/packages/local-installation/src/process.test.tsindex 3712c4d1..bed3322e 100644--- a/packages/local-installation/src/process.test.ts+++ b/packages/local-installation/src/process.test.ts@@ -1,4 +1,4 @@-import { expect, it } from "vitest";+import { expect, it, vi } from "vitest";import { PassThrough } from "node:stream";import { runProcess } from "./process.js";it("executes argument arrays literally and preserves JSON output", async () => {@@ -185,3 +185,67 @@ it("streams archive bytes into a native child without buffering them in argv", aexpect(result.code).toBe(0);expect(result.stdout.trim()).toBe("12345");});+it("stops a silent command after the idle timeout", async () => {+ const startedAt = Date.now();+ await expect(+ runProcess(process.execPath, ["-e", "setTimeout(() => {}, 10_000)"], {+ idleTimeoutMs: 300,+ }),+ ).rejects.toMatchObject({ code: "COMMAND_TIMEOUT" });+ expect(Date.now() - startedAt).toBeLessThan(5_000);+});+it("restarts the idle timeout on every output chunk", async () => {+ const chunks: string[] = [];+ const result = await runProcess(+ process.execPath,+ [+ "-e",+ `let n = 0;+const timer = setInterval(() => {+ (n % 2 ? process.stderr : process.stdout).write("tick\\n");+ if (++n === 8) { clearInterval(timer); }+}, 100);`,+ ],+ { idleTimeoutMs: 400, onOutput: (chunk) => chunks.push(chunk) },+ );+ // 800 ms of steady output outlives a 400 ms idle timeout.+ expect(result.code).toBe(0);+ expect(chunks.join("")).toBe("tick\n".repeat(8));+});+it("times out after output stops, and the wall-clock timeout still applies", async () => {+ await expect(+ runProcess(+ process.execPath,+ ["-e", "process.stdout.write('x'); setTimeout(() => {}, 10_000)"],+ { idleTimeoutMs: 300 },+ ),+ ).rejects.toMatchObject({ code: "COMMAND_TIMEOUT" });+ await expect(+ runProcess(+ process.execPath,+ ["-e", "setInterval(() => process.stdout.write('x'), 50)"],+ { idleTimeoutMs: 1_000, timeoutMs: 400 },+ ),+ ).rejects.toMatchObject({ code: "COMMAND_TIMEOUT" });+});+it("lets an abort win over the idle timeout and clears its timer", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const controller = new AbortController();+ const running = runProcess(+ process.execPath,+ ["-e", "setTimeout(() => {}, 10_000)"],+ { idleTimeoutMs: 60_000, signal: controller.signal },+ );+ // Observe the rejection before the timers run, so it is never unhandled.+ const rejected = expect(running).rejects.toMatchObject({+ name: "AbortError",+ });+ controller.abort();+ await vi.advanceTimersByTimeAsync(600);+ await rejected;+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+});diff --git a/packages/local-installation/src/process.ts b/packages/local-installation/src/process.tsindex 47b4e6f9..6324aa6e 100644--- a/packages/local-installation/src/process.ts+++ b/packages/local-installation/src/process.ts@@ -29,6 +29,8 @@ export interface ProcessOptions {env?: NodeJS.ProcessEnv;signal?: AbortSignal;timeoutMs?: number;+ /** Stops the command after this long without any stdout or stderr output. */+ idleTimeoutMs?: number;capture?: boolean;/** Private data sent directly to child stdin; never included in argv or env. */input?: string;@@ -119,8 +121,27 @@ export async function runProcess(options.timeoutMs,): undefined;+ let idleTimeout: ReturnType<typeof setTimeout> | undefined;+ const armIdleTimeout = () => {+ if (!options.idleTimeoutMs || failure) return;+ if (idleTimeout) clearTimeout(idleTimeout);+ idleTimeout = setTimeout(+ () =>+ stop(+ Object.assign(+ new Error(+ `Command produced no output for ${Math.round(options.idleTimeoutMs! / 1000)} s`,+ ),+ { code: "COMMAND_TIMEOUT" },+ ),+ ),+ options.idleTimeoutMs,+ );+ };+ armIdleTimeout();const output = (value: string, stream: "stdout" | "stderr") => {if (failure) return;+ armIdleTimeout();if (options.capture !== false &&stdout.length + stderr.length + value.length > 2_000_000@@ -161,6 +182,7 @@ export async function runProcess(child.once("close", (code) => {if (failure) kill("SIGKILL");if (timeout) clearTimeout(timeout);+ if (idleTimeout) clearTimeout(idleTimeout);if (killTimer) clearTimeout(killTimer);options.signal?.removeEventListener("abort", abort);if (failure) reject(failure);