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(local-installation): restore the local models when Linger opens again after a quit

Dongdong Chen012c2890cc74
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 9284ac1f..54435338 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -374,7 +374,9 @@ home> --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, with
its output in `<home>/installer/local-models-stop.log`, and does not wait
for it. It runs only when `desktop/local-server.json` names an
installation. The Computer exits with the app, so nothing uses the models
- until the next launch, whose resume applies the approved plan again. A
+ until the next launch, whose resume applies the approved plan again even
+ though the services still run, unless the person switched the Computer's
+ model source to a subscription or BYOK. A
quit for an update or a relaunch, and the `--quit` of setup or the
uninstaller (which stop the models themselves right after), leave them.
- `src/main/legacy-migration.ts`: on start, stops a bridge an older version
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index 6c60b940..ee63e2a8 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -524,7 +524,8 @@ export class LocalServerModule implements Module {
// stops the stack with the gateway the localmodels tool started, which
// would otherwise keep their memory and ports until the next reboot. The
// services and the model controller keep running, as after every quit;
- // the next launch brings the approved stack up again. The stop runs on
+ // the next launch's resume brings the approved stack up again while the
+ // model source is still local. The stop runs on
// after the app is gone, its output in the installer's folder. An update
// or an uninstall stops the models with the services instead.
async #stopLocalModels(): Promise<void> {
diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md
index 881cd306..e10077cb 100644
--- a/apps/linger-installer/AGENTS.md
+++ b/apps/linger-installer/AGENTS.md
@@ -37,7 +37,13 @@ installed without extension support included) gets its approved plan applied
again when the saved plan inputs still match the current choices; only a
plan the person approved is ever applied, and a stack still not ready ends
`LOCAL_MODELS_RECOVERY_REQUIRED` with the binding's reason codes in
-`details.reasons`. A failed job's `errorCode` is the runtime's cause when it
+`details.reasons`. When the services already run, a local-models setup
+whose Computer still uses the local model source (`model-source.json` says
+`local` or does not exist yet) has its stack checked once
+(`restoreLocalModels`), since a quit stops the models but not the services: a
+stack that is not ready gets the same restore, then becomes the model source
+again. A source switched to a subscription or BYOK leaves the stack stopped.
+A failed job's `errorCode` is the runtime's cause when it
has one (`RUNTIME_PLAN_REFUSED`, a harness plan refused before anything
changed, such as an unusable `SIMPLEX_PI_PATH` or a Windows runtime root too
long for Pi without long paths; `RUNTIME_ACTION_FAILED`;
diff --git a/apps/linger-installer/src/server/resume.test.ts b/apps/linger-installer/src/server/resume.test.ts
index f4c201f6..866b9161 100644
--- a/apps/linger-installer/src/server/resume.test.ts
+++ b/apps/linger-installer/src/server/resume.test.ts
@@ -54,11 +54,64 @@ test("leaves running services alone", async () => {
load: async () => instance,
engines: native(run, true),
pending: async () => false,
+ restore: async () => undefined,
}),
).toMatchObject({ code: 0, details: { origin: instance.origin } });
expect(run).not.toHaveBeenCalled();
});
+test("brings the local models back while the services keep running", async () => {
+ const run = vi.fn();
+ const restore = vi.fn(async () => undefined);
+ expect(
+ await resumeSourceInstance(options, {
+ load: async () => instance,
+ engines: native(run, true),
+ pending: async () => false,
+ restore,
+ }),
+ ).toMatchObject({ code: 0, state: "ready" });
+ expect(restore).toHaveBeenCalledWith(
+ instance,
+ expect.objectContaining({ signal: options.signal }),
+ );
+ expect(run).not.toHaveBeenCalled();
+});
+
+test("reports a local model restore that failed", async () => {
+ const failed = {
+ code: 4,
+ state: "action_required" as const,
+ message: "The local model stack is not ready.",
+ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },
+ };
+ expect(
+ await resumeSourceInstance(options, {
+ load: async () => instance,
+ engines: native(vi.fn(), true),
+ pending: async () => false,
+ restore: async () => failed,
+ }),
+ ).toEqual(failed);
+});
+
+test("leaves the local models to a full start", async () => {
+ const restore = vi.fn(async () => undefined);
+ await resumeSourceInstance(options, {
+ load: async () => instance,
+ engines: native(
+ vi.fn<ResumeEngine["run"]>(async () => ({
+ code: 0,
+ state: "ready",
+ message: "ok",
+ })),
+ false,
+ ),
+ restore,
+ });
+ expect(restore).not.toHaveBeenCalled();
+});
+
test("restarts running services for a changed user.env", async () => {
const run = vi.fn<ResumeEngine["run"]>(async () => ({
code: 0,
@@ -97,6 +150,7 @@ test("reports the source the services serve from", async () => {
load: async () => instance,
engines: native(vi.fn(), true),
pending: async () => false,
+ restore: async () => undefined,
}),
).toMatchObject({ code: 0, details: { source: "/source" } });
// The instance names a new checkout only once its services became ready
diff --git a/apps/linger-installer/src/server/resume.ts b/apps/linger-installer/src/server/resume.ts
index e3edfae1..781c82b3 100644
--- a/apps/linger-installer/src/server/resume.ts
+++ b/apps/linger-installer/src/server/resume.ts
@@ -2,6 +2,7 @@ import { realpath } from "node:fs/promises";
import path from "node:path";
import { loadInstance } from "@linger/local-installation/instance";
+import { restoreLocalModels } from "@linger/local-installation/local-models";
import { userEnvironmentPending } from "@linger/local-installation/user-environment";
import type { InstallOutcome } from "@linger/local-installation/events";
import {
@@ -49,6 +50,7 @@ export async function resumeSourceInstance(
load = loadInstance,
engines = ENGINES,
pending = userEnvironmentPending,
+ restore = restoreLocalModels,
} = {},
): Promise<InstallOutcome> {
const instance = await load({
@@ -75,13 +77,23 @@ export async function resumeSourceInstance(
(check) => check.ready,
) &&
!(await pending(instance))
- )
+ ) {
+ // A quit stops the local models but leaves the services running, so
+ // they come back here rather than with the services.
+ const restored = await restore(instance, {
+ signal: options.signal,
+ onEvent: (event) => {
+ if (event.message) options.log(event.message);
+ },
+ });
+ if (restored) return restored;
return {
code: 0,
state: "ready",
message: "Services are already running.",
details: { origin: instance.origin, source: instance.source.repo },
};
+ }
const outcome = await engine.run({
name: instance.name,
home: options.home,
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 5ed08ffa..2dc24966 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -116,7 +116,11 @@ Setup sets the Computer's model source through `localmodels source apply`
(`byok-source.ts`): BYOK after the Runtime is ready, a local model after the
stack is, and a subscription after its Runtime installs, signed in or not.
The installer reads `model-source.json` (`readByokEnvironment`) but never
-writes it.
+writes it. `restoreLocalModels` (`local-models.ts`) brings back a
+local-models setup's stack while its services keep running, such as after
+the desktop's quit stopped it, but only while that source is `local` or not
+saved yet: a ready stack costs one `setup binding` check, a stopped one gets
+its approved plan applied again and the local source set again.
Each native service runs under a detached supervisor
(`native-process-worker.mjs`) whose record holds its PID, birth and an
diff --git a/packages/local-installation/src/local-models.test.ts b/packages/local-installation/src/local-models.test.ts
index 8a23f16b..ed288c78 100644
--- a/packages/local-installation/src/local-models.test.ts
+++ b/packages/local-installation/src/local-models.test.ts
@@ -12,8 +12,10 @@ import { afterEach, expect, test, vi } from "vitest";
import {
prepareLocalModels,
localModelsEnvironment,
+ restoreLocalModels,
stackProgress,
} from "./local-models.js";
+import { writeSetupChoice } from "./setup-selection.js";
import { runProcess } from "./process.js";
import { runLocalmodels } from "./localmodels-tool.js";
import type { Instance } from "./instance.js";
@@ -430,6 +432,126 @@ test("Computer environment consumes the authoritative binding without parsing Pi
LINGER_LOCAL_MODELS_REVISION: "b".repeat(64),
});
});
+// A deployed local-models setup that a quit stopped, with the model source
+// saved as `mode`, or none saved.
+async function stoppedLocalSetup(mode?: string) {
+ const f = await deployedThenNotReady("gateway-unavailable");
+ await writeSetupChoice(f.instance, "local-models");
+ if (mode) {
+ const state = path.join(f.home, "runtime/localmodels/state");
+ await mkdir(state, { recursive: true });
+ await writeFile(
+ path.join(state, "model-source.json"),
+ JSON.stringify({
+ schema: "localmodels.model-source/v1",
+ mode,
+ runtime: mode === "local" ? "pi" : "claude",
+ runtime_model: "",
+ model_label: null,
+ gateway_url: null,
+ environment: {},
+ }),
+ { mode: 0o600 },
+ );
+ }
+ const original = f.call.getMockImplementation()!;
+ f.call.mockImplementation(async (...a) => {
+ // stack apply brings the stack and its Pi back.
+ if (a[1][0] === "stack" && a[1][1] === "apply")
+ Object.assign(f.binding, f.ready);
+ return original(...a);
+ });
+ return f;
+}
+function commands(f: {
+ call: { mock: { calls: Parameters<typeof runLocalmodels>[] } };
+}) {
+ return f.call.mock.calls.map(([, args]) => `${args[0]} ${args[1]}`);
+}
+test.each([undefined, "local"])(
+ "a stopped local stack is restored while the model source is %s",
+ async (mode) => {
+ const f = await stoppedLocalSetup(mode);
+ expect(
+ await restoreLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toBeUndefined();
+ expect(commands(f)).toEqual([
+ "setup binding",
+ "setup review",
+ "setup binding",
+ "stack apply",
+ "setup binding",
+ "source apply",
+ ]);
+ expect(f.call.mock.calls.at(-1)![1].slice(0, 6)).toEqual([
+ "source",
+ "apply",
+ "--mode",
+ "local",
+ "--runtime",
+ "pi",
+ ]);
+ },
+);
+test("a ready local stack costs one binding check", async () => {
+ const f = await stoppedLocalSetup("local");
+ Object.assign(f.binding, f.ready);
+ expect(
+ await restoreLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toBeUndefined();
+ expect(commands(f)).toEqual(["setup binding"]);
+});
+test.each(["subscription", "byok"])(
+ "a model source switched to %s keeps the local stack stopped",
+ async (mode) => {
+ const f = await stoppedLocalSetup(mode);
+ expect(
+ await restoreLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toBeUndefined();
+ expect(f.call).not.toHaveBeenCalled();
+ },
+);
+test("another setup choice never restores local models", async () => {
+ const f = await stoppedLocalSetup();
+ await writeSetupChoice(f.instance, "claude");
+ expect(
+ await restoreLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toBeUndefined();
+ expect(f.call).not.toHaveBeenCalled();
+});
+test("a restore whose plan fails to apply reports why", async () => {
+ const f = await stoppedLocalSetup();
+ const original = f.call.getMockImplementation()!;
+ f.call.mockImplementation(async (...a) =>
+ a[1][0] === "stack" ? { code: 1, stdout: "", stderr: "" } : original(...a),
+ );
+ expect(
+ await restoreLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toMatchObject({
+ state: "action_required",
+ details: {
+ code: "LOCAL_MODELS_RECOVERY_REQUIRED",
+ reasons: ["gateway-unavailable"],
+ },
+ });
+ expect(commands(f)).not.toContain("source apply");
+});
+test("a restored stack the model source refuses reports why", async () => {
+ const f = await stoppedLocalSetup();
+ const original = f.call.getMockImplementation()!;
+ f.call.mockImplementation(async (...a) =>
+ a[1][0] === "source"
+ ? {
+ code: 1,
+ stdout: JSON.stringify({ code: "GATEWAY_DOWN", message: "Down." }),
+ stderr: "",
+ }
+ : original(...a),
+ );
+ expect(
+ await restoreLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toMatchObject({ state: "failed", details: { code: "GATEWAY_DOWN" } });
+});
test("streams more than the process capture limit during an approved stack apply", async () => {
const f = await fixture();
diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.ts
index c1fac212..81fbc0d0 100644
--- a/packages/local-installation/src/local-models.ts
+++ b/packages/local-installation/src/local-models.ts
@@ -10,6 +10,7 @@ import {
type Instance,
} from "./instance.js";
import type { InstallOutcome, InstallerEvent } from "./events.js";
+import { applyNativeSource, readByokEnvironment } from "./byok-source.js";
import { localmodelsFailure } from "./localmodels-failure.js";
import { runLocalmodels } from "./localmodels-tool.js";
import {
@@ -219,18 +220,43 @@ export async function localModelsEnvironment(
LINGER_LOCAL_MODELS_REVISION: b.pi.configFingerprint,
};
}
-export async function hasSavedLocalModelsPlan(home: string): Promise<boolean> {
+// The saved plan's ID, or undefined when no plan was saved.
+async function savedPlanID(home: string): Promise<string | undefined> {
const raw = await readPrivate(
path.join(home, "runtime/localmodels/plan.json"),
);
- if (!raw) return false;
+ if (!raw) return undefined;
const saved = JSON.parse(raw) as { schema?: string; plan_id?: string };
if (
saved.schema !== "localmodels.stack-plan/v1" ||
!/^[a-f0-9]{64}$/.test(saved.plan_id ?? "")
)
throw new Error("Invalid saved upstream plan.");
- return true;
+ return saved.plan_id;
+}
+export async function hasSavedLocalModelsPlan(home: string): Promise<boolean> {
+ return (await savedPlanID(home)) !== undefined;
+}
+// What localmodels reports about the plan's deployed stack and its Pi, or
+// null when it could not tell.
+async function observeBinding(
+ planFile: string,
+ planID: string,
+ command: (
+ args: string[],
+ ) => Promise<{ code: number; stdout: string; stderr: string }>,
+): Promise<Binding | null> {
+ const result = await command([
+ "setup",
+ "binding",
+ "--plan",
+ planFile,
+ "--lang",
+ "en",
+ "--json",
+ ]);
+ if (result.code !== 0) return null;
+ return binding(JSON.parse(result.stdout), planID);
}
export async function reviewSavedModelPlan(
home: string,
@@ -413,18 +439,8 @@ export async function prepareLocalModels(
const bindFile = path.join(root, "binding.json");
const previous = await readPrivate(bindFile);
const observe = async () => {
- const result = await command([
- "setup",
- "binding",
- "--plan",
- planFile,
- "--lang",
- "en",
- "--json",
- ]);
- if (result.code !== 0) return null;
- const observed = binding(JSON.parse(result.stdout), summary.planId);
- reasons = observed.ready ? [] : reasonCodes(observed);
+ const observed = await observeBinding(planFile, summary.planId, command);
+ if (observed) reasons = observed.ready ? [] : reasonCodes(observed);
return observed;
};
let inputs:
@@ -511,3 +527,36 @@ export async function prepareLocalModels(
});
});
}
+/**
+ * Brings back the local model stack of a local-models setup whose services
+ * still run, such as when Linger opens again after a quit stopped the
+ * models. Only while the Computer's model source is local: a person who
+ * switched to a subscription or BYOK keeps that choice. A ready stack costs
+ * one binding check; otherwise this applies the approved plan again and makes
+ * the stack the model source. Returns the outcome when the restore fails.
+ */
+export async function restoreLocalModels(
+ instance: Instance,
+ options: { signal: AbortSignal; onEvent: (e: InstallerEvent) => void },
+ dependencies: Dependencies = {},
+): Promise<InstallOutcome | undefined> {
+ if ((await readSetupChoice(instance)) !== "local-models") return;
+ const home = path.resolve(instance.root, "../..");
+ // Installs from earlier releases may have no model source saved yet; their
+ // source is the local stack they set up.
+ const source = await readByokEnvironment(home);
+ if (source && source.mode !== "local") return;
+ 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 }),
+ );
+ if (observed?.ready) return;
+ return (
+ (await prepareLocalModels(instance, options, dependencies)) ??
+ (await applyNativeSource(home, "local", "pi", options.signal, dependencies))
+ );
+}