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): set a pre-Linger Simplex database aside for a fresh one

claude-opus-5-5-medium16d3ccc3b184
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 66765272..f14e37a4 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -82,7 +82,13 @@ Gateway and runs Agents. The daemon exits with the app.
and clears it after 60 s if it still holds the password) and "Open account
file location" (`shell.showItemInFolder`); an unreadable file shows why
instead. Only the email and file are kept; Show and Copy read the file
- again, and closing the setup window hides the password. After a logout
+ again, and closing the setup window hides the password. When the
+ installer set a database from the earlier Simplex app aside
+ (`simplex-backup-*` in the instance, see the local-installation package),
+ the desktop logs `local_server.legacy_data_set_aside`, clears its
+ enrollment so it enrolls this computer again in the fresh database, keeps
+ that folder as `legacyBackup` in its config so this happens once, and the
+ ready screen says where the earlier data went. After a logout
the SPA's login page asks `window.lingerDesktop.localAccount.available()`
on load, every 15 s and when the window comes back into view; it is true
only while the window shows the origin in `local-server.json`, the
diff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.ts
index 3f09f97d..9950d192 100644
--- a/apps/desktop/src/main/config.ts
+++ b/apps/desktop/src/main/config.ts
@@ -34,6 +34,9 @@ const desktopConfig = z.object({
// The runtime the person chose in that installation; the daemon marks it
// so TeamHub places Another Me on it.
preferredRuntime: z.enum(["codex", "claude", "pi"]).optional(),
+ // The backup of the earlier Simplex app's data that the local server
+ // already told about and enrolled this computer again for.
+ legacyBackup: z.string().optional(),
window: z
.object({
x: z.number().int(),
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index f3fe6360..a51be164 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -1510,6 +1510,43 @@ describe("LocalServerModule", () => {
await f.host.stop("quit");
});
+ it("enrolls this computer again, once, after the installer set the earlier Simplex data aside", async () => {
+ const backup = (home: string) =>
+ path.join(
+ home,
+ "instances",
+ LOCAL_INSTANCE,
+ "simplex-backup-2026-11-17T03-04-05-678Z",
+ );
+ const prepare = (home: string) => {
+ checkout(home);
+ mkdirSync(backup(home), { recursive: true });
+ };
+ const f = fixture(withCheckout, {}, prepare);
+ await f.host.start();
+ await f.module.begin();
+ expect(f.unenroll).toHaveBeenCalledOnce();
+ expect(f.unenroll.mock.invocationCallOrder[0]).toBeLessThan(
+ f.enroll.mock.invocationCallOrder[0]!,
+ );
+ expect(f.config().legacyBackup).toBe(backup(f.home));
+ expect(f.module.status()).toMatchObject({
+ phase: "ready",
+ legacyBackup: backup(f.home),
+ });
+ await f.host.stop("quit");
+
+ // Told about already: the enrollment of the fresh database stays.
+ const again = fixture(withCheckout, {}, prepare);
+ again.host.ctx.config.update({ legacyBackup: backup(again.home) });
+ await again.host.start();
+ await again.module.begin();
+ expect(again.unenroll).not.toHaveBeenCalled();
+ expect(again.enroll).toHaveBeenCalled();
+ expect(again.module.status().legacyBackup).toBeUndefined();
+ await again.host.stop("quit");
+ });
+
it("shows no download step when nothing is downloaded", async () => {
const f = fixture(withCheckout, {}, checkout);
await f.host.start();
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index d1f1108a..b8809ab0 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -31,6 +31,7 @@ import {
readLocalLogin,
} from "@linger/local-installation/account";
import { downloadVerified } from "@linger/local-installation/download";
+import { latestLegacyBackup } from "@linger/local-installation/legacy-database";
import { legacyMigrationPending } from "@linger/local-installation/home";
import {
type SetupChoice,
@@ -263,6 +264,9 @@ export interface LocalServerStatus {
readonly origin?: string;
// While the "signin" step waits for the person.
readonly signIn?: RuntimeSignIn;
+ // Where this installation moved the data of the earlier Simplex app,
+ // which it could not upgrade.
+ readonly legacyBackup?: string;
}
export interface LocalServerOptions {
@@ -367,6 +371,7 @@ export class LocalServerModule implements Module {
#offDaemon: (() => void) | undefined;
#daemonFailure: string | undefined;
#signIn: RuntimeSignIn | undefined;
+ #legacyBackup: string | undefined;
// The installer that runs the sign-in, and what the person asked for
// while the step waits.
#signInInstaller: InstallerApi | undefined;
@@ -464,6 +469,7 @@ export class LocalServerModule implements Module {
},
...(this.#origin ? { origin: this.#origin } : {}),
...(this.#signIn ? { signIn: this.#signIn } : {}),
+ ...(this.#legacyBackup ? { legacyBackup: this.#legacyBackup } : {}),
};
}
@@ -774,6 +780,23 @@ export class LocalServerModule implements Module {
runtime: runtime.setupChoice,
keys: Object.keys(runtime.environment),
});
+ // The installer set a database from before Linger aside for a fresh
+ // one; this computer's enrollment belongs to the old one, so it
+ // enrolls again. Noted in the config so that happens once.
+ const legacyBackup = await latestLegacyBackup(
+ path.join(home, "instances", LOCAL_INSTANCE),
+ );
+ if (
+ legacyBackup &&
+ legacyBackup !== this.#ctx?.config.get().legacyBackup
+ ) {
+ this.#ctx?.log.warn("local_server.legacy_data_set_aside", {
+ backup: legacyBackup,
+ });
+ await this.#ctx?.get<EnrollmentModule>("Enrollment").unenroll();
+ this.#ctx?.config.update({ legacyBackup });
+ this.#legacyBackup = legacyBackup;
+ }
this.#advance("connect", 0, "Connecting this computer…");
const login = await installer.login();
await this.#signInAs(home, job.origin, login.email, login.password);
diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.ts
index b2770546..b5d25a38 100644
--- a/apps/desktop/src/main/setup-window.ts
+++ b/apps/desktop/src/main/setup-window.ts
@@ -422,8 +422,13 @@ const localServerState = (
location,
keys,
signIn,
+ legacyBackup,
} = local.status();
const home = os.homedir();
+ const shown = (folder: string) =>
+ folder === home || folder.startsWith(home + path.sep)
+ ? "~" + folder.slice(home.length)
+ : folder;
return {
available,
phase,
@@ -436,13 +441,11 @@ const localServerState = (
localModels,
location: {
...location,
- path:
- location.path === home || location.path.startsWith(home + path.sep)
- ? "~" + location.path.slice(home.length)
- : location.path,
+ path: shown(location.path),
},
keys,
...(signIn ? { signIn } : {}),
+ ...(legacyBackup ? { legacyBackup: shown(legacyBackup) } : {}),
...(account ? { account } : {}),
};
};
diff --git a/apps/desktop/src/shared/setup.ts b/apps/desktop/src/shared/setup.ts
index f00d8c3a..668d2e12 100644
--- a/apps/desktop/src/shared/setup.ts
+++ b/apps/desktop/src/shared/setup.ts
@@ -49,6 +49,9 @@ export interface SetupLocalServer {
// Once installed: the owner account, for signing in again after logging
// out.
readonly account?: SetupLocalAccount;
+ // Where the installation moved the earlier Simplex app's data it could
+ // not upgrade (~ for the home folder).
+ readonly legacyBackup?: string;
}
// The owner account in the installation's local-account.json. The password
diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.html
index 0321417a..571a3506 100644
--- a/apps/desktop/src/shell/setup.html
+++ b/apps/desktop/src/shell/setup.html
@@ -1317,6 +1317,16 @@
section.active .account {
animation: enter 420ms 160ms var(--ease) both;
}
+ /* The earlier Simplex app's data this install could not upgrade. */
+ .legacy-note {
+ width: 100%;
+ max-width: 420px;
+ margin: 12px auto 0;
+ color: var(--muted);
+ font-size: 12px;
+ text-align: left;
+ overflow-wrap: anywhere;
+ }
/* Confetti for a finished install, drawn over the whole window. */
#confetti {
position: fixed;
@@ -1621,6 +1631,7 @@
</p>
<p class="account-error" id="account-error" role="alert"></p>
</div>
+ <p class="legacy-note" id="legacy-note" hidden></p>
<div class="start">
<button class="primary large" id="open" type="button">
<span>Open Linger</span
@@ -2450,6 +2461,12 @@
}
$("ready-lead").textContent = "Running on this computer, just for you.";
renderAccount(local.account);
+ $("legacy-note").hidden = !local.legacyBackup;
+ $("legacy-note").textContent = local.legacyBackup
+ ? "Your data from the earlier Simplex app can't be upgraded to Linger, so this is a fresh workspace. The earlier data was moved, not deleted, to " +
+ local.legacyBackup +
+ "."
+ : "";
};
// The password stays masked until Show; the main process copies it.
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 869e3a4f..e5a4283b 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -49,6 +49,22 @@ never leaves a directory that later attempts treat as initialized. A `postgres-d
`PG_VERSION` but no `postmaster.opts` (which only a started server writes)
never served a connection, holds no data, and is initialized again.
+Every Linger release creates TeamHub's schema from the 852 baseline
+migration, which refuses a database that already holds one. A database from
+the desktop app before the rename has `public.accounts` but no applied 852
+row in `goose_db_version`, so it can never migrate (`legacy-database.ts`).
+Once the database is up, Native checks for that; for such a database it
+stops PostgreSQL, marks `local-account.json` as not provisioned (so the
+account step creates the owner again with the same email and password) and
+moves `data/agent`, `data/artifacts`, `computer-enrollment.token` and, last,
+`native/postgres-data` into `simplex-backup-<UTC time>` in the instance,
+deleting nothing. The database moves last so that a run stopped partway
+still finds it and finishes the move, into the same folder when nothing
+there would be overwritten. It then opens a
+fresh cluster and logs where the data went. The desktop finds the newest backup folder
+after the job, enrolls its Computer again once (the old Computer ID is
+unknown to the fresh database) and shows the folder on its ready screen.
+
Move a freshly downloaded or unpacked file or folder into place with
`renameRetrying` from `fs-retry.ts`: on Windows antivirus and indexing hold
new files for a moment, and a plain rename then fails with EPERM.
diff --git a/packages/local-installation/src/account.ts b/packages/local-installation/src/account.ts
index 09a51724..d81f901a 100644
--- a/packages/local-installation/src/account.ts
+++ b/packages/local-installation/src/account.ts
@@ -94,6 +94,28 @@ interface LocalAccount {
provisioned: boolean;
}
+// For a database made again from nothing: the next account step creates
+// the owner again with the saved email and password.
+export async function unprovisionLocalAccount(root: string): Promise<void> {
+ const file = path.join(root, "local-account.json");
+ const text = await readPrivate(file);
+ if (text === undefined) return;
+ let account: LocalAccount;
+ try {
+ account = JSON.parse(text) as LocalAccount;
+ } catch {
+ // Never expose parser errors containing the private password.
+ throw new Error(
+ "The local account file is invalid; existing credentials will not be overwritten.",
+ );
+ }
+ if (account.provisioned !== true) return;
+ await atomicPrivate(
+ file,
+ JSON.stringify({ ...account, provisioned: false }, null, 2) + "\n",
+ );
+}
+
// Called under the instance lock. TeamHub owns deployment-owner creation;
// its idempotent command never resets an existing account password.
export async function ensureLocalAccount(
diff --git a/packages/local-installation/src/legacy-database.test.ts b/packages/local-installation/src/legacy-database.test.ts
new file mode 100644
index 00000000..115768ca
--- /dev/null
+++ b/packages/local-installation/src/legacy-database.test.ts
@@ -0,0 +1,249 @@
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ latestLegacyBackup,
+ preLingerSchema,
+ setAsideLegacyData,
+ TEAMHUB_BASELINE_VERSION,
+} from "./legacy-database.js";
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+
+async function temporary(): Promise<string> {
+ const root = await mkdtemp(path.join(tmpdir(), "linger-legacy-db-"));
+ roots.push(root);
+ return root;
+}
+
+async function put(file: string, contents: string): Promise<void> {
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
+ await writeFile(file, contents, { mode: 0o600 });
+}
+
+// Answers the detection queries as psql would for a database whose tables
+// and applied goose versions are given.
+function database(tables: string[], versions: number[] = []) {
+ const asked: string[] = [];
+ const query = async (sql: string) => {
+ asked.push(sql);
+ if (sql.includes("to_regclass"))
+ return `${tables.includes("accounts") ? "t" : "f"}|${
+ tables.includes("goose_db_version") ? "t" : "f"
+ }\n`;
+ return versions.includes(TEAMHUB_BASELINE_VERSION) ? "t\n" : "f\n";
+ };
+ return { query, asked };
+}
+
+describe("preLingerSchema", () => {
+ it("leaves a new, empty database to the migrations", async () => {
+ const { query, asked } = database([]);
+ expect(await preLingerSchema(query)).toBe(false);
+ expect(asked).toHaveLength(1);
+ });
+
+ it("leaves a database that Linger migrated before", async () => {
+ const { query } = database(
+ ["accounts", "goose_db_version"],
+ [0, TEAMHUB_BASELINE_VERSION, 853],
+ );
+ expect(await preLingerSchema(query)).toBe(false);
+ });
+
+ // A migration killed inside the baseline rolls back with it, leaving
+ // only the version table; the next run applies the baseline again.
+ it("leaves a database whose baseline has not run yet", async () => {
+ const { query } = database(["goose_db_version"], [0]);
+ expect(await preLingerSchema(query)).toBe(false);
+ });
+
+ it("finds a TeamHub schema that the baseline did not make", async () => {
+ expect(
+ await preLingerSchema(
+ database(["accounts", "goose_db_version"], [0, 851]).query,
+ ),
+ ).toBe(true);
+ expect(await preLingerSchema(database(["accounts"]).query)).toBe(true);
+ });
+
+ it("names the version of the baseline migration that guards it", () => {
+ const baseline = fileURLToPath(
+ new URL(
+ `../../../apps/teamhub/migrations/00${TEAMHUB_BASELINE_VERSION}_baseline.sql`,
+ import.meta.url,
+ ),
+ );
+ expect(existsSync(baseline)).toBe(true);
+ });
+});
+
+describe("setAsideLegacyData", () => {
+ it("moves the database and its data into one backup and keeps the account", async () => {
+ const root = await temporary();
+ await put(path.join(root, "native/postgres-data/PG_VERSION"), "17\n");
+ await put(path.join(root, "native/postgres-password"), "secret\n");
+ await put(path.join(root, "data/agent/agent_1/state.json"), "{}");
+ await put(path.join(root, "computer-enrollment.token"), "token\n");
+ const account = {
+ email: "[email protected]",
+ password: "a-private-password",
+ provisioned: true,
+ };
+ await put(path.join(root, "local-account.json"), JSON.stringify(account));
+
+ const backup = await setAsideLegacyData(
+ root,
+ new AbortController().signal,
+ new Date("2026-11-17T03:04:05.678Z"),
+ );
+
+ expect(backup).toBe(
+ path.join(root, "simplex-backup-2026-11-17T03-04-05-678Z"),
+ );
+ expect(
+ await readFile(path.join(backup, "postgres-data/PG_VERSION"), "utf8"),
+ ).toBe("17\n");
+ expect(existsSync(path.join(backup, "agent/agent_1/state.json"))).toBe(
+ true,
+ );
+ expect(existsSync(path.join(backup, "computer-enrollment.token"))).toBe(
+ true,
+ );
+ // Absent before, so nothing to move.
+ expect(existsSync(path.join(backup, "artifacts"))).toBe(false);
+ expect(existsSync(path.join(root, "native/postgres-data"))).toBe(false);
+ expect(existsSync(path.join(root, "computer-enrollment.token"))).toBe(
+ false,
+ );
+ expect(existsSync(path.join(root, "native/postgres-password"))).toBe(true);
+ expect(existsSync(path.join(root, "data/agent/agent_1"))).toBe(false);
+ expect(existsSync(path.join(root, "data/artifacts"))).toBe(true);
+ // The fresh database gets the same owner again.
+ expect(
+ JSON.parse(await readFile(path.join(root, "local-account.json"), "utf8")),
+ ).toEqual({ ...account, provisioned: false });
+ expect(await latestLegacyBackup(root)).toBe(backup);
+ });
+
+ it("keeps the database in place until the end, so a rerun finishes a stopped move in the same folder", async () => {
+ const root = await temporary();
+ await put(path.join(root, "native/postgres-data/PG_VERSION"), "17\n");
+ await put(path.join(root, "data/agent/agent_1/state.json"), "{}");
+ await put(path.join(root, "data/artifacts/a.txt"), "a");
+ const account = {
+ email: "[email protected]",
+ password: "a-private-password",
+ provisioned: true,
+ };
+ await put(path.join(root, "local-account.json"), JSON.stringify(account));
+ const first = path.join(root, "simplex-backup-2026-11-17T03-04-05-678Z");
+ // A non-empty directory where the artifacts go makes their move fail,
+ // as a locked file or a cancelled install would.
+ await put(path.join(first, "artifacts/x"), "");
+
+ await expect(
+ setAsideLegacyData(
+ root,
+ new AbortController().signal,
+ new Date("2026-11-17T03:04:05.678Z"),
+ ),
+ ).rejects.toThrow();
+ expect(existsSync(path.join(root, "native/postgres-data/PG_VERSION"))).toBe(
+ true,
+ );
+ expect(existsSync(path.join(first, "agent/agent_1/state.json"))).toBe(true);
+ expect(
+ JSON.parse(await readFile(path.join(root, "local-account.json"), "utf8")),
+ ).toEqual({ ...account, provisioned: false });
+
+ // The lock is gone on the next run.
+ await rm(path.join(first, "artifacts"), { recursive: true });
+ const backup = await setAsideLegacyData(
+ root,
+ new AbortController().signal,
+ new Date("2026-11-17T03:05:00.000Z"),
+ );
+ expect(backup).toBe(first);
+ expect(existsSync(path.join(backup, "postgres-data/PG_VERSION"))).toBe(
+ true,
+ );
+ expect(existsSync(path.join(backup, "artifacts/a.txt"))).toBe(true);
+ expect(existsSync(path.join(root, "native/postgres-data"))).toBe(false);
+ expect(existsSync(path.join(root, "data/agent"))).toBe(true);
+ });
+
+ it("finishes in the same folder after only the database failed to move", async () => {
+ const root = await temporary();
+ const first = path.join(root, "simplex-backup-2026-11-17T03-04-05-678Z");
+ // The earlier run moved everything else and made empty places again.
+ await put(path.join(first, "agent/agent_1/state.json"), "{}");
+ await mkdir(path.join(root, "data/agent"), { recursive: true });
+ await put(path.join(root, "native/postgres-data/PG_VERSION"), "17\n");
+
+ expect(await setAsideLegacyData(root, new AbortController().signal)).toBe(
+ first,
+ );
+ expect(existsSync(path.join(first, "postgres-data/PG_VERSION"))).toBe(true);
+ expect(existsSync(path.join(first, "agent/agent_1/state.json"))).toBe(true);
+ expect(existsSync(path.join(root, "data/agent"))).toBe(true);
+ });
+
+ it("starts a new folder after a finished backup or when entries would meet", async () => {
+ const root = await temporary();
+ await mkdir(
+ path.join(root, "simplex-backup-2026-11-17T03-04-05-678Z/postgres-data"),
+ { recursive: true },
+ );
+ await put(path.join(root, "native/postgres-data/PG_VERSION"), "17\n");
+ const later = await setAsideLegacyData(
+ root,
+ new AbortController().signal,
+ new Date("2026-11-18T00:00:00.000Z"),
+ );
+ expect(later).toBe(
+ path.join(root, "simplex-backup-2026-11-18T00-00-00-000Z"),
+ );
+
+ await rm(path.join(later, "postgres-data"), { recursive: true });
+ await put(path.join(later, "agent/old.json"), "{}");
+ await put(path.join(root, "data/agent/new.json"), "{}");
+ await put(path.join(root, "native/postgres-data/PG_VERSION"), "17\n");
+ const newest = await setAsideLegacyData(
+ root,
+ new AbortController().signal,
+ new Date("2026-11-19T00:00:00.000Z"),
+ );
+ expect(newest).toBe(
+ path.join(root, "simplex-backup-2026-11-19T00-00-00-000Z"),
+ );
+ expect(existsSync(path.join(newest, "agent/new.json"))).toBe(true);
+ });
+});
+
+describe("latestLegacyBackup", () => {
+ it("names the newest backup, and none without one", async () => {
+ const root = await temporary();
+ expect(await latestLegacyBackup(root)).toBeUndefined();
+ expect(
+ await latestLegacyBackup(path.join(root, "missing")),
+ ).toBeUndefined();
+ for (const name of [
+ "simplex-backup-2026-11-17T03-04-05-678Z",
+ "simplex-backup-2026-12-01T00-00-00-000Z",
+ "native",
+ ])
+ await mkdir(path.join(root, name));
+ expect(await latestLegacyBackup(root)).toBe(
+ path.join(root, "simplex-backup-2026-12-01T00-00-00-000Z"),
+ );
+ });
+});
diff --git a/packages/local-installation/src/legacy-database.ts b/packages/local-installation/src/legacy-database.ts
new file mode 100644
index 00000000..bb0ed10d
--- /dev/null
+++ b/packages/local-installation/src/legacy-database.ts
@@ -0,0 +1,133 @@
+import { lstat, readdir } from "node:fs/promises";
+import path from "node:path";
+import { unprovisionLocalAccount } from "./account.js";
+import { renameRetrying } from "./fs-retry.js";
+import { privateDirectory } from "./private-files.js";
+
+// Every Linger release applies TeamHub's schema from this baseline
+// (apps/teamhub/migrations/00852_baseline.sql), which refuses a database
+// that already holds a TeamHub schema. Only the desktop app from before the
+// rename to Linger made such a database without the baseline.
+export const TEAMHUB_BASELINE_VERSION = 852;
+
+// Whether the database holds a TeamHub schema that the baseline never
+// created, so no migration can ever apply to it. `query` returns psql's
+// unaligned output for one statement.
+export async function preLingerSchema(
+ query: (sql: string) => Promise<string>,
+): Promise<boolean> {
+ const [accounts, versions] = (
+ await query(
+ "SELECT to_regclass('public.accounts') IS NOT NULL, to_regclass('public.goose_db_version') IS NOT NULL",
+ )
+ )
+ .trim()
+ .split("|");
+ if (accounts !== "t") return false;
+ if (versions !== "t") return true;
+ return (
+ (
+ await query(
+ `SELECT EXISTS (SELECT 1 FROM public.goose_db_version WHERE version_id = ${TEAMHUB_BASELINE_VERSION} AND is_applied)`,
+ )
+ ).trim() !== "t"
+ );
+}
+
+// The instance data that belongs to a database. A database from before
+// Linger moves into one timestamped folder with them, and nothing is deleted.
+const LEGACY_DATA = [
+ ["data/agent", "agent"],
+ ["data/artifacts", "artifacts"],
+ ["computer-enrollment.token", "computer-enrollment.token"],
+] as const;
+
+const BACKUP_PREFIX = "simplex-backup-";
+
+async function exists(file: string): Promise<boolean> {
+ return lstat(file).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ return false;
+ },
+ );
+}
+
+async function emptyDirectory(directory: string): Promise<boolean> {
+ return readdir(directory).then(
+ (names) => names.length === 0,
+ () => false,
+ );
+}
+
+// A run that stopped before the database moved left a folder without it;
+// the rest goes there too, so the person is shown one folder with all of
+// it. Only empty directories that run made again may meet a moved entry.
+async function unfinishedBackup(root: string): Promise<string | undefined> {
+ const latest = await latestLegacyBackup(root);
+ if (!latest || (await exists(path.join(latest, "postgres-data"))))
+ return undefined;
+ for (const [from, to] of LEGACY_DATA) {
+ const source = path.join(root, from);
+ if (
+ (await exists(source)) &&
+ (await exists(path.join(latest, to))) &&
+ !(await emptyDirectory(source))
+ )
+ return undefined;
+ }
+ return latest;
+}
+
+// Moves the database and its data into a folder in the instance and leaves
+// empty places for a fresh database; returns the folder.
+export async function setAsideLegacyData(
+ root: string,
+ signal: AbortSignal,
+ now = new Date(),
+): Promise<string> {
+ const backup =
+ (await unfinishedBackup(root)) ??
+ path.join(
+ root,
+ `${BACKUP_PREFIX}${now.toISOString().replace(/[:.]/g, "-")}`,
+ );
+ const move = async (from: string, to: string) => {
+ const source = path.join(root, from);
+ const target = path.join(backup, to);
+ if (!(await exists(source))) return;
+ // An empty place an earlier run made again stays for the fresh data.
+ if ((await exists(target)) && (await emptyDirectory(source))) return;
+ await renameRetrying(source, target, { signal });
+ };
+ // The fresh database has no owner; the saved credentials create it again.
+ await unprovisionLocalAccount(root);
+ await privateDirectory(backup);
+ for (const [from, to] of LEGACY_DATA) await move(from, to);
+ await Promise.all(
+ ["data/agent", "data/artifacts"].map((directory) =>
+ privateDirectory(path.join(root, directory)),
+ ),
+ );
+ // Last: while the database is in place, a run that stopped partway finds
+ // it again and finishes the move.
+ await move("native/postgres-data", "postgres-data");
+ return backup;
+}
+
+// The folder the latest database from before Linger went to, if any. The
+// desktop tells the person about it once and enrolls its Computer again.
+export async function latestLegacyBackup(
+ root: string,
+): Promise<string | undefined> {
+ const names = await readdir(root).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ return [];
+ });
+ const latest = names
+ .filter((name) => name.startsWith(BACKUP_PREFIX))
+ .sort()
+ .at(-1);
+ return latest && path.join(root, latest);
+}
diff --git a/packages/local-installation/src/native-database.test.ts b/packages/local-installation/src/native-database.test.ts
index 5d5f6eb2..4bcde1a1 100644
--- a/packages/local-installation/src/native-database.test.ts
+++ b/packages/local-installation/src/native-database.test.ts
@@ -1,9 +1,19 @@
import { runProcess } from "./process.js";
vi.mock("./process.js", () => ({ runProcess: vi.fn() }));
-import { inspectNativeProcess, startNativeProcess } from "./native-process.js";
+import {
+ inspectNativeProcess,
+ startNativeProcess,
+ stopNativeProcess,
+} from "./native-process.js";
vi.mock("./native-process.js", () => ({
inspectNativeProcess: vi.fn(async () => ({ running: true })),
startNativeProcess: vi.fn(async () => {}),
+ stopNativeProcess: vi.fn(async () => {}),
+}));
+import { setAsideLegacyData } from "./legacy-database.js";
+vi.mock("./legacy-database.js", async (original) => ({
+ ...(await original<typeof import("./legacy-database.js")>()),
+ setAsideLegacyData: vi.fn(),
}));
import { removeRetrying, renameRetrying } from "./fs-retry.js";
vi.mock("./fs-retry.js", () => ({
@@ -110,6 +120,7 @@ describe("prepareNativeDatabase on Windows", () => {
"pg_isready.exe",
"psql.exe",
"createdb.exe",
+ "psql.exe",
]);
expect(vi.mocked(startNativeProcess).mock.calls[0]![0]).toMatchObject({
executable: path.join(options.postgresBin, "postgres.exe"),
@@ -210,3 +221,53 @@ describe("prepareNativeDatabase initdb", () => {
});
});
});
+
+describe("prepareNativeDatabase with an existing TeamHub schema", () => {
+ const backup = path.join(instance.root, "simplex-backup-x");
+ const programs = () =>
+ run.mock.calls.map(([command]) => path.basename(command));
+ // psql answers the schema check from `schema` and the baseline check
+ // from `baseline`.
+ const answer = (schema: () => string, baseline: string) =>
+ run.mockImplementation(async (command, args) =>
+ path.basename(command) !== "psql" || !args.includes("simplexai")
+ ? ok()
+ : ok(
+ args.some((arg) => arg.includes("to_regclass"))
+ ? schema()
+ : args.some((arg) => arg.includes("goose_db_version"))
+ ? baseline
+ : "1",
+ ),
+ );
+
+ it("sets a database from before Linger aside and opens a fresh one", async () => {
+ let fresh = false;
+ answer(() => (fresh ? "f|f\n" : "t|t\n"), "f\n");
+ vi.mocked(setAsideLegacyData).mockImplementation(async () => {
+ fresh = true;
+ return backup;
+ });
+ expect(await prepareNativeDatabase(options)).toEqual({
+ legacyBackup: backup,
+ });
+ expect(stopNativeProcess).toHaveBeenCalledWith(instance.root, "postgres");
+ expect(setAsideLegacyData).toHaveBeenCalledWith(
+ instance.root,
+ options.signal,
+ );
+ expect(
+ vi.mocked(stopNativeProcess).mock.invocationCallOrder[0],
+ ).toBeLessThan(vi.mocked(setAsideLegacyData).mock.invocationCallOrder[0]!);
+ expect(programs().filter((name) => name === "initdb")).toHaveLength(2);
+ expect(startNativeProcess).toHaveBeenCalledTimes(2);
+ });
+
+ it("leaves a database that Linger migrated alone", async () => {
+ answer(() => "t|t\n", "t\n");
+ expect(await prepareNativeDatabase(options)).toEqual({});
+ expect(stopNativeProcess).not.toHaveBeenCalled();
+ expect(setAsideLegacyData).not.toHaveBeenCalled();
+ expect(startNativeProcess).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/local-installation/src/native-database.ts b/packages/local-installation/src/native-database.ts
index b07b3f86..cfe65708 100644
--- a/packages/local-installation/src/native-database.ts
+++ b/packages/local-installation/src/native-database.ts
@@ -8,7 +8,12 @@ import {
type Instance,
} from "./instance.js";
import { removeRetrying, renameRetrying } from "./fs-retry.js";
-import { inspectNativeProcess, startNativeProcess } from "./native-process.js";
+import {
+ inspectNativeProcess,
+ startNativeProcess,
+ stopNativeProcess,
+} from "./native-process.js";
+import { preLingerSchema, setAsideLegacyData } from "./legacy-database.js";
import { runProcess } from "./process.js";
import { parseEnv } from "node:util";
@@ -40,13 +45,16 @@ export async function windowsElevated(
);
}
+// Prepares the instance's private PostgreSQL. A database from before Linger
+// is set aside with its data for a fresh one, and `legacyBackup` names the
+// folder it went to.
export async function prepareNativeDatabase(options: {
instance: Instance;
postgresBin: string;
env: NodeJS.ProcessEnv;
signal: AbortSignal;
onOutput: (chunk: string) => void;
-}): Promise<void> {
+}): Promise<{ legacyBackup?: string }> {
const { instance, postgresBin, signal } = options;
if (process.getuid?.() === 0)
throw new Error(
@@ -66,32 +74,6 @@ export async function prepareNativeDatabase(options: {
(await readPrivate(path.join(instance.root, "services.env")))!,
).LINGER_POSTGRES_PASSWORD!;
await atomicPrivate(passwordFile, `${password}\n`);
- let initialized = false;
- try {
- const version = path.join(data, "PG_VERSION");
- const info = await lstat(version);
- if (
- !info.isFile() ||
- info.isSymbolicLink() ||
- (await readFile(version, "utf8")).trim() !== "17"
- )
- throw new Error(
- "This native instance contains an unsupported PostgreSQL data directory.",
- );
- // Only a started postmaster writes postmaster.opts; initdb does not. A
- // directory without it never served a connection and holds no data, as
- // when an earlier initdb was killed after writing PG_VERSION, so it is
- // made again rather than left to fail every start.
- initialized = await lstat(path.join(data, "postmaster.opts")).then(
- () => true,
- (error: NodeJS.ErrnoException) => {
- if (error.code !== "ENOENT") throw error;
- return false;
- },
- );
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
- }
const env = { ...options.env, PGPASSWORD: password, PGCONNECT_TIMEOUT: "3" };
const command = async (name: string, args: string[], timeoutMs = 60_000) => {
const result = await runProcess(postgresProgram(postgresBin, name), args, {
@@ -106,101 +88,153 @@ export async function prepareNativeDatabase(options: {
);
return result;
};
- if (!initialized) {
- // A forced kill (Windows ends the tree on timeout or cancel) leaves
- // initdb no time to clean up, so it builds aside and its directory
- // becomes the data directory only once it succeeded.
- const pending = `${data}.partial`;
- await removeRetrying(pending);
- await privateDirectory(pending);
- await command(
- "initdb",
- [
- "--pgdata",
- pending,
- "--username",
- "simplexai",
- "--pwfile",
- passwordFile,
- "--auth-host",
- "scram-sha-256",
- "--auth-local",
- "scram-sha-256",
- "--encoding",
- "UTF8",
- "--no-locale",
+ const open = async () => {
+ let initialized = false;
+ try {
+ const version = path.join(data, "PG_VERSION");
+ const info = await lstat(version);
+ if (
+ !info.isFile() ||
+ info.isSymbolicLink() ||
+ (await readFile(version, "utf8")).trim() !== "17"
+ )
+ throw new Error(
+ "This native instance contains an unsupported PostgreSQL data directory.",
+ );
+ // Only a started postmaster writes postmaster.opts; initdb does not. A
+ // directory without it never served a connection and holds no data, as
+ // when an earlier initdb was killed after writing PG_VERSION, so it is
+ // made again rather than left to fail every start.
+ initialized = await lstat(path.join(data, "postmaster.opts")).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ return false;
+ },
+ );
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ if (!initialized) {
+ // A forced kill (Windows ends the tree on timeout or cancel) leaves
+ // initdb no time to clean up, so it builds aside and its directory
+ // becomes the data directory only once it succeeded.
+ const pending = `${data}.partial`;
+ await removeRetrying(pending);
+ await privateDirectory(pending);
+ await command(
+ "initdb",
+ [
+ "--pgdata",
+ pending,
+ "--username",
+ "simplexai",
+ "--pwfile",
+ passwordFile,
+ "--auth-host",
+ "scram-sha-256",
+ "--auth-local",
+ "scram-sha-256",
+ "--encoding",
+ "UTF8",
+ "--no-locale",
+ ],
+ // Antivirus scanning of the new files can make it take minutes.
+ 10 * 60_000,
+ );
+ await removeRetrying(data);
+ await renameRetrying(pending, data, { signal });
+ }
+ await startNativeProcess({
+ root: instance.root,
+ name: "postgres",
+ executable: postgresProgram(postgresBin, "postgres"),
+ args: [
+ "-D",
+ data,
+ "-h",
+ "127.0.0.1",
+ "-p",
+ String(port),
+ "-k",
+ "",
+ "-c",
+ "max_connections=100",
+ "-c",
+ "shared_buffers=128MB",
+ "-c",
+ "jit=off",
],
- // Antivirus scanning of the new files can make it take minutes.
- 10 * 60_000,
- );
- await removeRetrying(data);
- await renameRetrying(pending, data, { signal });
- }
- await startNativeProcess({
- root: instance.root,
- name: "postgres",
- executable: postgresProgram(postgresBin, "postgres"),
- args: [
- "-D",
- data,
- "-h",
- "127.0.0.1",
- "-p",
- String(port),
- "-k",
- "",
- "-c",
- "max_connections=100",
- "-c",
- "shared_buffers=128MB",
- "-c",
- "jit=off",
- ],
- cwd: instance.root,
- env,
- signal,
- redactions: [password],
- });
- const connection = [
- "--host",
- "127.0.0.1",
- "--port",
- String(port),
- "--username",
- "simplexai",
- "--dbname",
- "postgres",
- ];
- const deadline = Date.now() + 30_000;
- for (;;) {
- signal.throwIfAborted();
- if (!(await inspectNativeProcess(instance.root, "postgres")).running)
- throw new Error("Native PostgreSQL stopped; inspect its instance log.");
- const ready = await runProcess(
- postgresProgram(postgresBin, "pg_isready"),
- connection,
- { env, signal, timeoutMs: 5_000 },
- );
- if (ready.code === 0) break;
- if (Date.now() >= deadline)
- throw new Error("Native PostgreSQL did not become ready.");
- await delay(200, undefined, { signal });
- }
- const present = await command("psql", [
- ...connection,
- "--tuples-only",
- "--no-align",
- "--command",
- "SELECT 1 FROM pg_database WHERE datname='simplexai'",
- ]);
- if (present.stdout.trim() !== "1")
- await command("createdb", [
+ cwd: instance.root,
+ env,
+ signal,
+ redactions: [password],
+ });
+ const connection = [
"--host",
"127.0.0.1",
"--port",
String(port),
"--username",
"simplexai",
- "simplexai",
+ "--dbname",
+ "postgres",
+ ];
+ const deadline = Date.now() + 30_000;
+ for (;;) {
+ signal.throwIfAborted();
+ if (!(await inspectNativeProcess(instance.root, "postgres")).running)
+ throw new Error("Native PostgreSQL stopped; inspect its instance log.");
+ const ready = await runProcess(
+ postgresProgram(postgresBin, "pg_isready"),
+ connection,
+ { env, signal, timeoutMs: 5_000 },
+ );
+ if (ready.code === 0) break;
+ if (Date.now() >= deadline)
+ throw new Error("Native PostgreSQL did not become ready.");
+ await delay(200, undefined, { signal });
+ }
+ const present = await command("psql", [
+ ...connection,
+ "--tuples-only",
+ "--no-align",
+ "--command",
+ "SELECT 1 FROM pg_database WHERE datname='simplexai'",
]);
+ if (present.stdout.trim() !== "1")
+ await command("createdb", [
+ "--host",
+ "127.0.0.1",
+ "--port",
+ String(port),
+ "--username",
+ "simplexai",
+ "simplexai",
+ ]);
+ };
+ await open();
+ const query = async (sql: string) =>
+ (
+ await command("psql", [
+ "--host",
+ "127.0.0.1",
+ "--port",
+ String(port),
+ "--username",
+ "simplexai",
+ "--dbname",
+ "simplexai",
+ "--tuples-only",
+ "--no-align",
+ "--command",
+ sql,
+ ])
+ ).stdout;
+ if (!(await preLingerSchema(query))) return {};
+ await stopNativeProcess(instance.root, "postgres");
+ const legacyBackup = await setAsideLegacyData(instance.root, signal);
+ await privateDirectory(data);
+ await open();
+ return { legacyBackup };
}
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index 39e6f027..03e8cbca 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -130,6 +130,7 @@ async function fixture() {
});
vi.mocked(prepareNativeDatabase).mockImplementation(async () => {
running.add("postgres");
+ return {};
});
vi.stubGlobal(
"fetch",
@@ -245,6 +246,44 @@ test("only TeamHub's process gets the server identity key", async () => {
);
expect(events.join("\n")).not.toContain(key);
});
+test("a database from before Linger is reported and the installation goes on", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const backup = path.join(f.home, "instances/native-legacy/simplex-backup-x");
+ vi.mocked(prepareNativeDatabase).mockImplementation(async () => {
+ f.running.add("postgres");
+ return { legacyBackup: backup };
+ });
+ const events: InstallerEvent[] = [];
+ const result = await installNativeSource({
+ home: f.home,
+ repo: f.repo,
+ name: "native-legacy",
+ setupChoice: "pi",
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ expect(result.code).toBe(0);
+ const notice = events.findIndex(
+ (event) => event.kind === "log" && event.message.includes(backup),
+ );
+ expect(events[notice]).toMatchObject({
+ stage: "services",
+ message: expect.stringContaining("earlier Simplex app"),
+ });
+ const migrate = vi
+ .mocked(runProcess)
+ .mock.calls.findIndex((row) => row[1].includes("migrate"));
+ expect(
+ vi.mocked(runProcess).mock.invocationCallOrder[migrate],
+ ).toBeGreaterThan(
+ vi.mocked(prepareNativeDatabase).mock.invocationCallOrder[0]!,
+ );
+});
test("a new identity key restarts TeamHub alone", 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.ts
index 1917f0cc..de06c2c7 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -771,13 +771,19 @@ async function runNativeSource(
// Mark before startup so a failed init/readiness step can stop a process
// it managed to create without touching a previously running cluster.
if (!postgresWasRunning) started.push("postgres");
- await prepareNativeDatabase({
+ const { legacyBackup } = await prepareNativeDatabase({
instance: current,
postgresBin: tools.postgresBin,
env,
signal,
onOutput: (chunk) => output.write(chunk),
});
+ if (legacyBackup)
+ emit({
+ kind: "log",
+ 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");
await runtime;
signal.throwIfAborted();