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(local-installation): serialize the quit-time model stop with the restore, and record the local source on setup
Dongdong Chenb51c017240a8
diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex e10077cb..2e27eda3 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -65,7 +65,9 @@ gateway (`stopLocalmodels`).location `desktop/local-server.json` names, it unloads the model library'sloaded models and stops the stack with the gateway the localmodels toolstarted, and keeps the services and the model controller running. It-prints one JSON line with what failed.+holds each home's local model lock (`withLocalModelsLock`) while it stops,+so the next launch's restore waits for it; a home whose lock a deployment+holds is skipped with a log line. It prints one JSON line with what failed.Every other mode first converts an install from before the rename to Linger(`migrateLegacyInstallation`); `--migrate` does only that and exits, for thediff --git a/apps/linger-installer/src/server/stop.test.ts b/apps/linger-installer/src/server/stop.test.tsindex 49c274d2..5c7c73f0 100644--- a/apps/linger-installer/src/server/stop.test.ts+++ b/apps/linger-installer/src/server/stop.test.ts@@ -3,6 +3,9 @@ import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import path from "node:path";import { tmpdir } from "node:os";+import { INSTANCE_BUSY } from "@linger/local-installation/instance";+import { withLocalModelsLock } from "@linger/local-installation/local-models";+import { parseInstallerArguments } from "../main.js";import { launchInstaller } from "./launch.js";import { privateDirectory, privateWrite } from "./storage.js";@@ -268,3 +271,35 @@ test("a quit stops only the local models, in every home, and keeps their control},]);});++test("a quit holds each home's local model lock while it stops the models", async () => {+ const value = await home();+ await mkdir(path.join(value, "runtime/localmodels"), { recursive: true });+ let held: unknown;+ const outcome = await stopDesktopLocalModels(options(value), {+ stopModels: async (at) => {+ // A restore checking the stack now finds the lock taken.+ held = await withLocalModelsLock(at, async () => "free").catch(+ (error: { code?: unknown }) => error.code,+ );+ },+ });+ expect(held).toBe(INSTANCE_BUSY);+ expect(outcome.failed).toEqual([]);+});++test("a quit while a deployment holds the lock leaves that home's models running", async () => {+ const value = await home();+ await mkdir(path.join(value, "runtime/localmodels"), { recursive: true });+ const stopModels = vi.fn(async () => {});+ const log: string[] = [];+ const outcome = await withLocalModelsLock(value, () =>+ stopDesktopLocalModels(+ { ...options(value), log: (message) => log.push(message) },+ { stopModels },+ ),+ );+ expect(stopModels).not.toHaveBeenCalled();+ expect(outcome.failed).toEqual([]);+ expect(log.join("\n")).toContain("another local model operation holds them");+});diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.tsindex 63b35790..6347d799 100644--- a/apps/linger-installer/src/server/stop.ts+++ b/apps/linger-installer/src/server/stop.ts@@ -1,7 +1,11 @@import { access, readFile } from "node:fs/promises";import path from "node:path";-import { loadInstance } from "@linger/local-installation/instance";+import {+ INSTANCE_BUSY,+ loadInstance,+} from "@linger/local-installation/instance";+import { withLocalModelsLock } from "@linger/local-installation/local-models";import { stopLocalmodels } from "@linger/local-installation/localmodels-tool";import { stopNativeSource } from "@linger/local-installation/native-source";@@ -74,7 +78,8 @@ export async function stopDesktopInstallation(* loaded models and the stack with the gateway the localmodels tool started,* in every home the desktop installed to. The services and the model* controller keep running, as the services do after a quit; the next launch- * brings the approved stack up again.+ * brings the approved stack up again. Each home's stop holds that home's+ * local model lock; a home whose lock another operation holds is skipped.*/export async function stopDesktopLocalModels(options: Pick<StopOptions, "home" | "signal" | "log">,@@ -82,13 +87,30 @@ export async function stopDesktopLocalModels(): Promise<StopOutcome> {const { failed, attempt } = attempts(options.log);for (const home of await installationHomes(options.home))- await attempt(home, () =>- stopModels(home, {- signal: options.signal,- log: options.log,- keepController: true,- }),- );+ await attempt(home, async () => {+ const stop = () =>+ stopModels(home, {+ signal: options.signal,+ log: options.log,+ keepController: true,+ });+ // Nothing ran localmodels in a home without its folder, and the lock+ // would create one there.+ if (!(await exists(path.join(home, "runtime", "localmodels"))))+ return stop();+ // The next launch's restore waits on this lock, so it never checks a+ // stack this stop is about to take down.+ try {+ await withLocalModelsLock(home, stop);+ } catch (error) {+ if ((error as { code?: unknown }).code !== INSTANCE_BUSY) throw error;+ // A deployment holds the stack; stopping it now would break that+ // apply, and the next launch restores the stack's approved state.+ options.log(+ `Left the local models in ${home} running: another local model operation holds them.`,+ );+ }+ });return { failed };}diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex 2dc24966..b0a59539 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -115,12 +115,18 @@ the `LINGER_LOCALMODELS_*` keys of the installer's instance runtime.Setup sets the Computer's model source through `localmodels source apply`(`byok-source.ts`): BYOK after the Runtime is ready, a local model after thestack is, and a subscription after its Runtime installs, signed in or not.+The local source is set only by a start whose request chose local models+(`setupChoice` or a plan approval); a restart from the saved choice keeps a+source the person switched to on the Models page.The installer reads `model-source.json` (`readByokEnvironment`) but neverwrites it. `restoreLocalModels` (`local-models.ts`) brings back alocal-models setup's stack while its services keep running, such as afterthe desktop's quit stopped it, but only while that source is `local` or notsaved yet: a ready stack costs one `setup binding` check, a stopped one gets-its approved plan applied again and the local source set again.+its approved plan applied again and the local source set again. Deployments,+that check and the quit-time stop share one lock per home+(`withLocalModelsLock`); the check waits up to 180 s for it, past the stop's+150 s hard exit, then asks to try again.Each native service runs under a detached supervisor(`native-process-worker.mjs`) whose record holds its PID, birth and andiff --git a/packages/local-installation/src/local-models.test.ts b/packages/local-installation/src/local-models.test.tsindex ed288c78..2990e050 100644--- a/packages/local-installation/src/local-models.test.ts+++ b/packages/local-installation/src/local-models.test.ts@@ -14,6 +14,7 @@ import {localModelsEnvironment,restoreLocalModels,stackProgress,+ withLocalModelsLock,} from "./local-models.js";import { writeSetupChoice } from "./setup-selection.js";import { runProcess } from "./process.js";@@ -536,6 +537,72 @@ test("a restore whose plan fails to apply reports why", async () => {});expect(commands(f)).not.toContain("source apply");});+test("a restore waits for a quit-time stop and checks the stack it left", async () => {+ const f = await stoppedLocalSetup("local");+ Object.assign(f.binding, f.ready);+ let release!: () => void;+ let acquired!: () => void;+ const locked = new Promise<void>((resolve) => (acquired = resolve));+ const stopping = withLocalModelsLock(+ f.home,+ () =>+ new Promise<void>((resolve) => {+ acquired();+ release = () => {+ // The stop takes the stack down before it lets go.+ Object.assign(f.binding, {+ ready: false,+ pi: null,+ reasons: [{ code: "gateway-unavailable" }],+ });+ resolve();+ };+ }),+ );+ await locked;+ const restoring = restoreLocalModels(f.instance, f.options, {+ localmodels: f.call,+ lockRetryMs: 5,+ });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(f.call).not.toHaveBeenCalled();+ release();+ await stopping;+ expect(await restoring).toBeUndefined();+ expect(commands(f)).toContain("stack apply");+ expect(commands(f).at(-1)).toBe("source apply");+});+test("a restore gives up when the stack stays locked", async () => {+ const f = await stoppedLocalSetup("local");+ let release!: () => void;+ let acquired!: () => void;+ const locked = new Promise<void>((resolve) => (acquired = resolve));+ const held = withLocalModelsLock(+ f.home,+ () =>+ new Promise<void>((resolve) => {+ release = resolve;+ acquired();+ }),+ );+ await locked;+ try {+ expect(+ await restoreLocalModels(f.instance, f.options, {+ localmodels: f.call,+ lockWaitMs: 30,+ lockRetryMs: 5,+ }),+ ).toMatchObject({+ state: "action_required",+ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },+ });+ expect(f.call).not.toHaveBeenCalled();+ } finally {+ release();+ await held;+ }+});test("a restored stack the model source refuses reports why", async () => {const f = await stoppedLocalSetup();const original = f.call.getMockImplementation()!;diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.tsindex 81fbc0d0..a284f2f1 100644--- a/packages/local-installation/src/local-models.ts+++ b/packages/local-installation/src/local-models.ts@@ -2,8 +2,10 @@ import { revokeFoundationGpuSharing } from "./foundation-services.js";import { randomUUID } from "node:crypto";import { rm } from "node:fs/promises";import path from "node:path";+import { sleep } from "@linger/service-kit";import {atomicPrivate,+ INSTANCE_BUSY,privateDirectory,readPrivate,withInstanceLock,@@ -53,6 +55,30 @@ interface Options {interface Dependencies {localmodels?: typeof runLocalmodels;}+interface RestoreDependencies extends Dependencies {+ // How long a restore waits for another holder of the stack's lock, and+ // how often it tries again.+ lockWaitMs?: number;+ lockRetryMs?: number;+}+// A little above the quit-time stop's 150 s hard exit, so a reopen during+// that stop sees where it left the stack.+const LOCK_WAIT_MS = 180_000;+/**+ * Runs `callback` holding the lock every deployment, restore check and+ * quit-time stop of a home's local model stack takes, so none of them sees+ * the stack half changed. Throws `INSTANCE_BUSY` at once when another holds+ * it; the caller creates `<home>/runtime/localmodels` first.+ */+export function withLocalModelsLock<T>(+ home: string,+ callback: () => Promise<T>,+): Promise<T> {+ return withInstanceLock(+ { root: path.join(path.resolve(home), "runtime/localmodels") } as Instance,+ callback,+ );+}// What each stack component downloads, as the setup page names it.const DOWNLOADS: Record<string, string> = {llm: "the local model",@@ -306,7 +332,7 @@ export async function prepareLocalModels(inputsFile = path.join(root, "plan-inputs.json");await privateDirectory(root);await privateDirectory(path.join(root, "models"));- return withInstanceLock({ root } as Instance, async () => {+ return withLocalModelsLock(home, async () => {let saved = await readPrivate(planFile);if (options.shareGpu === false) {try {@@ -538,7 +564,7 @@ export async function prepareLocalModels(export async function restoreLocalModels(instance: Instance,options: { signal: AbortSignal; onEvent: (e: InstallerEvent) => void },- dependencies: Dependencies = {},+ dependencies: RestoreDependencies = {},): Promise<InstallOutcome | undefined> {if ((await readSetupChoice(instance)) !== "local-models") return;const home = path.resolve(instance.root, "../..");@@ -549,12 +575,36 @@ export async function restoreLocalModels(const planID = await savedPlanID(home);if (!planID) return;const invoke = dependencies.localmodels ?? runLocalmodels;- const observed = await observeBinding(- path.join(home, "runtime/localmodels/plan.json"),- planID,- (args) => invoke(home, args, { signal: options.signal, timeoutMs: 120000 }),- );+ const observe = () =>+ observeBinding(+ path.join(home, "runtime/localmodels/plan.json"),+ planID,+ (args) =>+ invoke(home, args, { signal: options.signal, timeoutMs: 120000 }),+ );+ // A quit-time stop may still hold the lock; checking before it ends would+ // see a stack it is about to take down.+ const deadline = Date.now() + (dependencies.lockWaitMs ?? LOCK_WAIT_MS);+ let observed: Binding | null;+ for (;;) {+ try {+ observed = await withLocalModelsLock(home, observe);+ break;+ } catch (error) {+ if ((error as { code?: unknown }).code !== INSTANCE_BUSY) throw error;+ if (Date.now() >= deadline)+ return {+ code: 4,+ state: "action_required",+ message:+ "Another local model operation is still running. Try again once it ends.",+ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },+ };+ await sleep(dependencies.lockRetryMs ?? 1000, options.signal);+ }+ }if (observed?.ready) return;+ // 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))diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.tsindex fc866d42..7c867c6c 100644--- a/packages/local-installation/src/native-source-flow.test.ts+++ b/packages/local-installation/src/native-source-flow.test.ts@@ -51,6 +51,8 @@ import {TEAMHUB_COMMANDS,} from "./teamhub-binaries.js";import { prepareRuntime } from "./managed-runtimes.js";+import { applyNativeSource } from "./byok-source.js";+import { prepareLocalModels } from "./local-models.js";import {inspectNativeListeners,inspectNativeProcess,@@ -82,6 +84,11 @@ vi.mock("./byok-source.js", async (original) => ({...(await original<typeof import("./byok-source.js")>()),applyNativeSource: vi.fn(async () => undefined),}));+// Deploying local models runs the localmodels tool too.+vi.mock("./local-models.js", async (original) => ({+ ...(await original<typeof import("./local-models.js")>()),+ prepareLocalModels: vi.fn(async () => undefined),+}));vi.mock("./managed-runtimes.js", () => ({runtimeVersionFailure: vi.fn(() => undefined),prepareRuntime: vi.fn(),@@ -270,6 +277,50 @@ test("native services and owner creation continue while selected Runtime authentexpect(JSON.stringify(owner?.[1])).not.toContain(owner?.[2]?.input?.trim());expect(events.join("\n")).not.toContain(owner?.[2]?.input?.trim());});+test("choosing local models makes them the model source", async () => {+ const f = await fixture();+ const result = await installNativeSource({+ home: f.home,+ repo: f.repo,+ name: "native-flow",+ setupChoice: "local-models",+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ expect(result.code).toBe(0);+ expect(prepareLocalModels).toHaveBeenCalled();+ expect(applyNativeSource).toHaveBeenCalledWith(+ path.resolve(f.home),+ "local",+ "pi",+ expect.any(AbortSignal),+ );+});++test("a restart of local models keeps the model source the person switched to", async () => {+ const f = await fixture();+ await installNativeSource({+ home: f.home,+ repo: f.repo,+ name: "native-flow",+ setupChoice: "local-models",+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ vi.mocked(applyNativeSource).mockClear();+ // A resume after a reboot or an update reads the saved choice.+ const result = await installNativeSource({+ home: f.home,+ repo: f.repo,+ name: "native-flow",+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ expect(result.code).toBe(0);+ expect(vi.mocked(prepareLocalModels).mock.calls).toHaveLength(2);+ expect(applyNativeSource).not.toHaveBeenCalled();+});+test("only TeamHub's process gets the server identity key", async () => {const f = await fixture();vi.mocked(prepareRuntime).mockResolvedValue({diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex 39100c63..6f7b16c5 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -503,10 +503,21 @@ async function runNativeSource(localModelsApproval: options.localModelsApproval,localModelsReplan: options.localModelsReplan,});- if (runtimeOutcome?.code === 0)- runtimeOutcome =- (await applyNativeSource(home, "local", "pi", signal)) ??- runtimeOutcome;+ // A person who chose local models just now makes them the+ // source, replacing one an earlier setup left. A restart reads+ // the choice from setup-choice.json and passes no approval, so a+ // source the person switched since on the Models page stays.+ if (+ !runtimeOutcome &&+ (options.setupChoice === "local-models" ||+ options.localModelsApproval)+ )+ runtimeOutcome = await applyNativeSource(+ home,+ "local",+ "pi",+ signal,+ );} else {runtimeOutcome = await prepareRuntime(choice, {home,