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 the old local services until a move restarts them

Dongdong Chen4e39dd613d9a
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index cbfa37b7..1fc58429 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -173,8 +173,11 @@ Gateway and runs Agents. The daemon exits with the app.
version that unpacked the source; when this app brings another source
package (it was installed over an older one), that launch unpacks it and
resumes on it, with the "Updating Linger" page instead of the older
- interface, then prunes the older folder. A failure shows the start failure
- page, whose Retry tries again. An app older than the recorded version
+ interface. Only when the installer reports the services serving from the
+ new folder (`details.source`) and the origin answers does it record that
+ folder and prune the older one; otherwise the older services keep running
+ from their folder, the record keeps naming it, and the start failure page's
+ Retry moves them again. An app older than the recorded version
(a downgrade) leaves the services on their newer source and logs
`local_server.source_newer_than_app`. A Quick Install that stopped
before the computer enrolled is not resumed: setup shows again and Install
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index 83584fff..e5f1ade4 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -126,7 +126,12 @@ if (args.includes("--resume")) {
const code = fs.existsSync(path.join(home, "resume-fails")) ? 1 : 0;
const runtimeFile = path.join(home, "resume-runtime.json");
const runtime = fs.existsSync(runtimeFile) ? JSON.parse(fs.readFileSync(runtimeFile, "utf8")) : undefined;
- process.stdout.write("noise\n" + JSON.stringify({ code, message: code ? "Native teamhub stopped" : "ok", ...(runtime ? { runtime } : {}) }) + "\n");
+ // The folder the services serve from: the one asked for, unless they
+ // were left running on another (resume-serving names it).
+ const repo = args[args.indexOf("--source-repo") + 1];
+ const servingFile = path.join(home, "resume-serving");
+ const source = fs.existsSync(servingFile) ? fs.readFileSync(servingFile, "utf8") : fs.existsSync(repo) ? fs.realpathSync(repo) : repo;
+ process.stdout.write("noise\n" + JSON.stringify({ code, message: code ? "Native teamhub stopped" : "ok", details: { source }, ...(runtime ? { runtime } : {}) }) + "\n");
process.exit(code);
}
const origin = "http://127.0.0.1:4321";
@@ -2394,6 +2399,47 @@ describe("LocalServerModule after a restart", () => {
await f.host.stop("quit");
});
+ it("keeps the older source until the services serve from the newer one", async () => {
+ const root = tempDirectory();
+ const archive = sourceArchive(root);
+ const f = installedBy(archive);
+ const sources = path.join(f.home, "desktop", "source");
+ const previous = path.join(sources, "previous");
+ const current = path.join(sources, archive.sha256.slice(0, 16));
+ // The move stopped before the restart (the local model was not ready).
+ writeFileSync(path.join(f.home, "resume-fails"), "");
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));
+ // Try Again: the installer answers but the services still run from the
+ // older folder.
+ rmSync(path.join(f.home, "resume-fails"));
+ writeFileSync(path.join(f.home, "resume-serving"), previous);
+ f.bus.emit("local-server.retry");
+ await vi.waitFor(() => expect(f.showStartFailed).toHaveBeenCalledTimes(2));
+ expect(f.module.status().phase).toBe("failed");
+ expect(f.setServer).not.toHaveBeenCalled();
+ expect(
+ JSON.parse(
+ readFileSync(path.join(f.home, "desktop", "local-server.json"), "utf8"),
+ ),
+ ).toMatchObject({ repo: previous });
+ expect(readdirSync(sources).sort()).toEqual(
+ [path.basename(current), "previous"].sort(),
+ );
+ // Once they restart on the newer folder, it is recorded and the older
+ // one goes.
+ rmSync(path.join(f.home, "resume-serving"));
+ f.bus.emit("local-server.retry");
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
+ expect(
+ JSON.parse(
+ readFileSync(path.join(f.home, "desktop", "local-server.json"), "utf8"),
+ ),
+ ).toMatchObject({ repo: current });
+ expect(readdirSync(sources)).toEqual([path.basename(current)]);
+ await f.host.stop("quit");
+ });
+
it("starts the services on their own source package when it is this app's", async () => {
const root = tempDirectory();
const archive = sourceArchive(root);
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index 93ea3332..2e737818 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -2073,8 +2073,20 @@ export class LocalServerModule implements Module {
)))
? await this.#ensureSource(record.home, signal)
: record.repo;
- await this.#runResume(record, repo, signal);
- if (repo !== record.repo) await this.#moved(record, repo);
+ const serving = await this.#runResume(record, repo, signal);
+ if (repo !== record.repo) {
+ // The record moves, and the older folder goes, only once the
+ // services run from the new one and answer; until then the older
+ // services keep running from their folder, and Retry moves them.
+ if (
+ serving !== (await realpath(repo).catch(() => repo)) ||
+ !(await this.#reachable(record.origin))
+ )
+ throw new Error(
+ "Linger could not restart on this version. The earlier version is still installed; try again.",
+ );
+ await this.#moved(record, repo);
+ }
if (update)
this.#ctx?.log.info("local_server.source_updated", {
source: path.basename(repo),
@@ -2151,16 +2163,19 @@ export class LocalServerModule implements Module {
await this.#pruneSources(record.home, [repo]);
}
+ // Resolves with the source folder the installer reports the services
+ // serving from.
async #runResume(
record: LocalRecord,
repo: string,
signal: AbortSignal,
- ): Promise<void> {
+ ): Promise<string | undefined> {
await this.#adoptSourceKeys(record.home);
const node = await this.#ensureNode(signal);
const outcome = await new Promise<{
code: number;
message: string;
+ details?: { source?: unknown };
runtime?: InstanceRuntime;
}>((resolve, reject) => {
const child = spawn(
@@ -2197,6 +2212,7 @@ export class LocalServerModule implements Module {
JSON.parse(last) as {
code: number;
message: string;
+ details?: { source?: unknown };
runtime?: InstanceRuntime;
},
);
@@ -2208,6 +2224,8 @@ export class LocalServerModule implements Module {
if (outcome.code !== 0)
throw new Error(outcome.message || "The installation stopped");
this.#adoptRuntime(outcome.runtime);
+ const source = outcome.details?.source;
+ return typeof source === "string" ? source : undefined;
}
// Every resume reports the runtime and localmodels tool paths, so an
diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md
index 5e3dbb05..21e94437 100644
--- a/apps/linger-installer/AGENTS.md
+++ b/apps/linger-installer/AGENTS.md
@@ -22,8 +22,14 @@ on stderr for the desktop to show.
stopped services headless, reusing its saved choices; the desktop client runs it
after a reboot and reads the outcome from the single JSON line on stdout. It
also restarts running services when the instance's `user.env` no longer
-matches the configuration they started with. With `--external-computer`, a
-successful outcome carries `runtime`, the same instance runtime as
+matches the configuration they started with, or when `--source-repo` names
+another checkout than the instance's. An instance follows a new checkout only
+once its services are ready on it: until then `instance.json` keeps naming the
+checkout they run from, the new checkout's migrations run only after the
+runtime (the local model, for one) is ready, and a run that stops earlier
+leaves the running services and their schema as they were. A successful
+outcome's `details.source` names the checkout the services serve from. With
+`--external-computer`, a successful outcome carries `runtime`, the same instance runtime as
`GET /api/instances/{name}/runtime` (runtime and localmodels tool paths), so
the desktop's Computer follows them.
diff --git a/apps/linger-installer/src/server/resume.test.ts b/apps/linger-installer/src/server/resume.test.ts
index 71fdea95..f79bec41 100644
--- a/apps/linger-installer/src/server/resume.test.ts
+++ b/apps/linger-installer/src/server/resume.test.ts
@@ -91,6 +91,30 @@ test("moves running services to a new source tree", async () => {
);
});
+test("reports the source the services serve from", async () => {
+ expect(
+ await resumeSourceInstance(options, {
+ load: async () => instance,
+ engines: native(vi.fn(), true),
+ pending: async () => false,
+ }),
+ ).toMatchObject({ code: 0, details: { source: "/source" } });
+ // The instance names a new checkout only once its services became ready
+ // on it, so a run that never restarted them reports the old one.
+ const run = vi.fn<ResumeEngine["run"]>(async () => ({
+ code: 0,
+ state: "ready",
+ message: "ok",
+ }));
+ const old = { ...instance, source: { repo: "/old-source" } } as Instance;
+ expect(
+ await resumeSourceInstance(options, {
+ load: async () => old,
+ engines: native(run, true),
+ }),
+ ).toMatchObject({ code: 0, details: { source: "/old-source" } });
+});
+
test("needs an installed source instance", async () => {
expect(
await resumeSourceInstance(options, {
diff --git a/apps/linger-installer/src/server/resume.ts b/apps/linger-installer/src/server/resume.ts
index 532d1075..b205bbc7 100644
--- a/apps/linger-installer/src/server/resume.ts
+++ b/apps/linger-installer/src/server/resume.ts
@@ -67,8 +67,10 @@ export async function resumeSourceInstance(
const repo = await realpath(options.sourceRepo).catch(() =>
path.resolve(options.sourceRepo),
);
+ // The instance names the checkout its services last became ready on, so
+ // services that still run from an earlier one never count as running.
if (
- (!instance.source || instance.source.repo === repo) &&
+ instance.source.repo === repo &&
(await engine.probe(instance, options.signal)).every(
(check) => check.ready,
) &&
@@ -78,7 +80,7 @@ export async function resumeSourceInstance(
code: 0,
state: "ready",
message: "Services are already running.",
- details: { origin: instance.origin },
+ details: { origin: instance.origin, source: instance.source.repo },
};
const outcome = await engine.run({
name: instance.name,
@@ -90,13 +92,18 @@ export async function resumeSourceInstance(
if (event.message) options.log(event.message);
},
});
- return outcome.code === 0
- ? {
- ...outcome,
- details: {
- ...(outcome.details as object | undefined),
- origin: instance.origin,
- },
- }
- : outcome;
+ if (outcome.code !== 0) return outcome;
+ // The instance names a checkout only once its services serve from it.
+ const serving = await load({
+ name: options.instanceName,
+ home: options.home,
+ });
+ return {
+ ...outcome,
+ details: {
+ ...(outcome.details as object | undefined),
+ origin: instance.origin,
+ source: serving?.source?.repo,
+ },
+ };
}
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index abd24dcf..1550aac1 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -9,7 +9,15 @@ vi.mock("./model-gateway.js", () => ({
}));
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ writeFile,
+} from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import { afterEach, expect, test, vi } from "vitest";
@@ -49,6 +57,7 @@ import {
import { prepareNativeDatabase } from "./native-database.js";
import { prepareSourceComputer } from "./source-computer.js";
import { connectComputer } from "./computer.js";
+import { loadInstance } from "./instance.js";
vi.mock("./process.js", () => ({ runProcess: vi.fn() }));
vi.mock("./apple-developer-tools.js", () => ({
needsAppleDeveloperTools: vi.fn(),
@@ -484,6 +493,64 @@ async function runFlow(f: Awaited<ReturnType<typeof fixture>>) {
});
}
+test("a move to a new checkout that fails before the restart leaves the services on the old one", async () => {
+ const f = await fixture();
+ const install = (repo: string) =>
+ installNativeSource({
+ home: f.home,
+ repo,
+ name: "desktop",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ expect((await install(f.repo)).code).toBe(0);
+ const old = await realpath(f.repo);
+ const next = path.join(f.home, "next");
+ await cp(f.repo, next, { recursive: true });
+ // The Runtime (the local model, for one) is not ready on the new checkout.
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 4,
+ state: "action_required",
+ message: "The upstream stack is not ready.",
+ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },
+ });
+ vi.mocked(runProcess).mockClear();
+ vi.mocked(startNativeProcess).mockClear();
+ expect(await install(next)).toMatchObject({ code: 4 });
+ const stored = await loadInstance({ home: f.home, name: "desktop" });
+ expect(stored?.source?.repo).toBe(old);
+ expect(startNativeProcess).not.toHaveBeenCalled();
+ expect(
+ vi
+ .mocked(runProcess)
+ .mock.calls.some(([, args]) => args.includes("migrate")),
+ ).toBe(false);
+ // Trying again once the Runtime is ready restarts them on the new one.
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ expect((await install(next)).code).toBe(0);
+ const moved = await realpath(next);
+ expect(
+ (await loadInstance({ home: f.home, name: "desktop" }))?.source?.repo,
+ ).toBe(moved);
+ expect(
+ vi
+ .mocked(startNativeProcess)
+ .mock.calls.filter(([options]) => options.name !== "livekit")
+ .map(([options]) => options.cwd),
+ ).toEqual([moved, moved, moved]);
+});
+
test("an unchanged TeamHub leaves a running node-services alone", async () => {
const f = await fixture();
for (const name of ["teamhub", "node-services", "web"]) f.running.add(name);
diff --git a/packages/local-installation/src/native-source.test.ts b/packages/local-installation/src/native-source.test.ts
index 0282c39b..2a6f1435 100644
--- a/packages/local-installation/src/native-source.test.ts
+++ b/packages/local-installation/src/native-source.test.ts
@@ -6,6 +6,7 @@ import { afterEach, expect, test } from "vitest";
import { loadInstance } from "./instance.js";
import { updateUserKeys } from "./user-environment.js";
import { readLiveKitSettings } from "./native-livekit.js";
+import { saveSourceBinding } from "./source-checkout.js";
import {
checkNativeSourceEnvironment,
nativeSourceInstanceName,
@@ -171,7 +172,12 @@ test("an owned native instance follows a new checkout and keeps its data", async
expect(await readFile(path.join(first.instance.root, "kept"), "utf8")).toBe(
"data",
);
+ // The services still run from the first checkout until they restart.
expect(
(await loadInstance({ home: f.home, name: "desktop" }))?.releaseDir,
- ).toBe(next);
+ ).toBe(f.repo);
+ await saveSourceBinding(moved.instance);
+ const saved = await loadInstance({ home: f.home, name: "desktop" });
+ expect(saved?.releaseDir).toBe(next);
+ expect(saved?.source).toEqual(moved.instance.source);
});
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index ecbf9a71..1acc5038 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -7,13 +7,12 @@ import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import {
prepareSourceConfiguration,
+ saveSourceBinding,
validateSourceRepository,
type EnvironmentReport,
type SourceInstallOptions,
} from "./source-checkout.js";
import {
- atomicPrivate,
- loadInstance,
privateDirectory,
readLocalIdentityKey,
withInstanceLock,
@@ -91,32 +90,6 @@ export async function prepareNativeConfiguration(
) {
const repo = await validateSourceRepository(repository);
const name = options.name ?? (await nativeSourceInstanceName(repo));
- const bound = (instance?: Instance) =>
- instance?.mode === "source-native" &&
- instance.source &&
- instance.releaseDir !== repo;
- const existing = options.rebindSource
- ? await loadInstance({ name, home: options.home })
- : undefined;
- if (existing && bound(existing))
- // Instance data lives under its root; services restart on the new
- // checkout because their recorded configuration no longer matches.
- await withInstanceLock(existing, async () => {
- const instance = await loadInstance({ name, home: options.home });
- if (!instance || !bound(instance)) return;
- const previous = instance.releaseDir;
- instance.releaseDir = repo;
- instance.source!.repo = repo;
- if (instance.computerExecutable.startsWith(previous + path.sep))
- instance.computerExecutable = path.join(
- repo,
- path.relative(previous, instance.computerExecutable),
- );
- await atomicPrivate(
- path.join(instance.root, "instance.json"),
- JSON.stringify(instance, null, 2) + "\n",
- );
- });
return prepareSourceConfiguration(repo, { ...options, name });
}
export async function checkNativeSourceEnvironment(options: {
@@ -812,9 +785,12 @@ async function runNativeSource(
stage,
message: `The data from the earlier Simplex app can't be upgraded to Linger, so Linger starts with a fresh workspace. The earlier data was moved, not deleted, to ${legacyBackup}.\n`,
});
- await command("migrate");
+ // The runtime is ready before the checkout's migrations run: when it is
+ // not, services still running from an earlier checkout keep the
+ // schema they know.
await runtime;
signal.throwIfAborted();
+ await command("migrate");
await prepareFoundationServices(current, choice, {
home,
signal,
@@ -883,6 +859,7 @@ async function runNativeSource(
await startNativeProcess(serviceOptions(name));
}
const checks = await waitHealthy(current, signal, emit, ends);
+ await saveSourceBinding(current);
emit({
kind: "stage",
stage: "services",
diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.ts
index 3e401932..612d72c1 100644
--- a/packages/local-installation/src/source-checkout.ts
+++ b/packages/local-installation/src/source-checkout.ts
@@ -90,6 +90,36 @@ async function allocatePort(reserved: Set<number>): Promise<number> {
}
}
}
+// Points an instance at another checkout of the same source; its data and
+// ports stay.
+function rebind(instance: Instance, repo: string): void {
+ const previous = instance.releaseDir;
+ instance.releaseDir = repo;
+ instance.source!.repo = repo;
+ if (instance.computerExecutable.startsWith(previous + path.sep))
+ instance.computerExecutable = path.join(
+ repo,
+ path.relative(previous, instance.computerExecutable),
+ );
+}
+/**
+ * Records that the instance's services run from the checkout it was
+ * prepared with. Call it under the instance lock. Until then instance.json
+ * keeps naming the checkout the running services came from, so a resume
+ * never takes services left on an older checkout for the new one.
+ */
+export async function saveSourceBinding(instance: Instance): Promise<void> {
+ const stored = await loadInstance({
+ name: instance.name,
+ home: path.resolve(instance.root, "../.."),
+ });
+ if (!stored?.source || stored.releaseDir === instance.releaseDir) return;
+ rebind(stored, instance.releaseDir);
+ await atomicPrivate(
+ path.join(stored.root, "instance.json"),
+ JSON.stringify(stored, null, 2) + "\n",
+ );
+}
export async function prepareSourceConfiguration(
repository: string,
options: {
@@ -98,6 +128,10 @@ export async function prepareSourceConfiguration(
port?: number;
computerName?: string;
externalComputer?: boolean;
+ // A source instance bound to another checkout follows this one, in
+ // memory only: the caller saves the binding (saveSourceBinding) once
+ // the services run from it.
+ rebindSource?: boolean;
},
): Promise<{
instance: Instance;
@@ -107,6 +141,13 @@ export async function prepareSourceConfiguration(
const repo = await validateSourceRepository(repository);
const instance = await initializeInstance({ ...options, releaseDir: repo });
return withInstanceLock(instance, async () => {
+ if (
+ options.rebindSource &&
+ instance.mode === "source-native" &&
+ instance.source &&
+ instance.releaseDir !== repo
+ )
+ rebind(instance, repo);
if (
instance.releaseDir !== repo ||
(!instance.source &&