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): skip a leftover Simplex instance instead of blocking Linger
claude-opus-5-5-medium94f5bfb82e30
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex f14e37a4..d1da90cc 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -221,9 +221,12 @@ Gateway and runs Agents. The daemon exits with the app.LocalServer runs `installer.js --migrate` when an instance record stillcarries a `simplex-` project name, before it reads`desktop/local-server.json`- (`packages/local-installation/src/legacy-migration.ts`). A failed migration- puts LocalServer in the failed state with the installer's error, which names- each instance that is still legacy; Retry runs the migration again. There is+ (`packages/local-installation/src/legacy-migration.ts`). Instances the+ installer left unconverted are logged as+ `local_server.legacy_instance_skipped` with their reason and do not hold+ the app back; only when `desktop` itself stayed unconverted, or the+ installer could not run, LocalServer enters the failed state with that+ reason, and Retry runs the migration again. There isno downgrade path: an older build reads neither the converted instances northe moved data folder. The bundle ID andWindows AppUserModelID are `com.simplexai.linger.desktop.preview`. Thediff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex a51be164..14add591 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -29,6 +29,7 @@ import {followHttps,hasNativePostgres,installLocation,+ legacyMigrationResult,parseSetCookie,LocalServerUnverifiedError,localIdentityProof,@@ -2902,3 +2903,49 @@ describe("LocalServerModule owner account", () => {},);});++describe("legacyMigrationResult", () => {+ const skipped = [+ { instance: "default", reason: "Its Computer is running 2 task(s)." },+ ];++ it("only logs instances this app does not use", () => {+ expect(+ legacyMigrationResult(+ { code: 0, output: `${JSON.stringify({ skipped })}\n`, error: "" },+ LOCAL_INSTANCE,+ ),+ ).toEqual({ skipped });+ });++ it("fails with the reason when this app's instance stayed unconverted", () => {+ const own = [+ {+ instance: LOCAL_INSTANCE,+ reason: "Another Linger installer is using it.",+ },+ ];+ expect(+ legacyMigrationResult(+ { code: 0, output: JSON.stringify({ skipped: own }), error: "" },+ LOCAL_INSTANCE,+ ),+ ).toEqual({+ skipped: own,+ failure:+ "Linger could not convert this computer's installation from the earlier Simplex app. Another Linger installer is using it.",+ });+ });++ it("shows every line of an installer that could not start", () => {+ expect(+ legacyMigrationResult(+ { code: 1, output: "", error: "Installer could not start: a\nb: c\n" },+ LOCAL_INSTANCE,+ ),+ ).toEqual({ skipped: [], failure: "Installer could not start: a\nb: c" });+ expect(+ legacyMigrationResult({ code: 0, output: "", error: "" }, LOCAL_INSTANCE),+ ).toEqual({ skipped: [] });+ });+});diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex b8809ab0..67d3fd49 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -33,6 +33,7 @@ import {import { downloadVerified } from "@linger/local-installation/download";import { latestLegacyBackup } from "@linger/local-installation/legacy-database";import { legacyMigrationPending } from "@linger/local-installation/home";+import type { LegacyInstanceSkipped } from "@linger/local-installation/legacy-migration";import {type SetupChoice,setupChoices,@@ -327,6 +328,50 @@ const SERVER_CHECK_TTL_MS = 2_000;// The instance the desktop installs.export const LOCAL_INSTANCE = "desktop";++export interface LegacyMigrationRun {+ code: number | null;+ output: string;+ error: string;+}++/**+ * Reads `installer.js --migrate`: the instances it left unconverted, and why+ * `instance`, the one this app uses, could not be converted, if so.+ */+export function legacyMigrationResult(+ run: LegacyMigrationRun,+ instance: string,+): { failure?: string; skipped: LegacyInstanceSkipped[] } {+ if (run.code !== 0)+ return {+ failure:+ run.error.trim().slice(-1500) ||+ `The installer exited with code ${run.code}.`,+ skipped: [],+ };+ let skipped: LegacyInstanceSkipped[] = [];+ try {+ const parsed = JSON.parse(run.output.trim().split("\n").at(-1) ?? "") as {+ skipped?: unknown;+ };+ if (Array.isArray(parsed.skipped))+ skipped = parsed.skipped.filter(+ (entry): entry is LegacyInstanceSkipped =>+ typeof (entry as LegacyInstanceSkipped)?.instance === "string" &&+ typeof (entry as LegacyInstanceSkipped)?.reason === "string",+ );+ } catch {+ // An installer that answers no list converted everything it could.+ }+ const own = skipped.find((entry) => entry.instance === instance);+ return {+ skipped,+ ...(own && {+ failure: `Linger could not convert this computer's installation from the earlier Simplex app. ${own.reason}`,+ }),+ };+}const NATIVE_TARGETS = new Set(["darwin-arm64", "linux-x64", "win32-x64"]);const MiB = 1024 * 1024;const GiB = 1024 * MiB;@@ -1142,47 +1187,53 @@ export class LocalServerModule implements Module {// An install from before the rename keeps legacy names in its instance// records; the bundled installer converts them once, before a record is- // read. Returns why it failed, for the person to see.+ // read. Returns why this computer's instance stayed unconverted, for the+ // person to see; other instances it left behind are only logged.async #migrateLegacyHome(ctx: ModuleContext): Promise<string | undefined> {if (!(await legacyMigrationPending(this.#options.home)) ||!existsSync(this.#installerScript()))return undefined;- const outcome = await new Promise<{ code: number | null; error: string }>(- (resolve) => {- const child = spawn(- process.execPath,- [this.#installerScript(), "--home", this.#options.home, "--migrate"],- {- stdio: ["ignore", "ignore", "pipe"],- windowsHide: true,- env: {- ...process.env,- ELECTRON_RUN_AS_NODE: "1",- LINGER_HOME: this.#options.home,- },+ const outcome = await new Promise<LegacyMigrationRun>((resolve) => {+ const child = spawn(+ process.execPath,+ [this.#installerScript(), "--home", this.#options.home, "--migrate"],+ {+ stdio: ["ignore", "pipe", "pipe"],+ windowsHide: true,+ env: {+ ...process.env,+ ELECTRON_RUN_AS_NODE: "1",+ LINGER_HOME: this.#options.home,},- );- let error = "";- child.stderr.on("data", (chunk: Buffer) => {- error = (error + chunk.toString("utf8")).slice(-2000);- });- child.once("error", (failure) =>- resolve({ code: null, error: failure.message }),- );- child.once("close", (code) => resolve({ code, error }));- },- );- if (outcome.code === 0) {- ctx.log.info("local_server.home_migrated", {});- return undefined;+ },+ );+ let output = "";+ let error = "";+ child.stdout.on("data", (chunk: Buffer) => {+ output = (output + chunk.toString("utf8")).slice(-20_000);+ });+ child.stderr.on("data", (chunk: Buffer) => {+ error = (error + chunk.toString("utf8")).slice(-2000);+ });+ child.once("error", (failure) =>+ resolve({ code: null, output, error: failure.message }),+ );+ child.once("close", (code) => resolve({ code, output, error }));+ });+ const { failure, skipped } = legacyMigrationResult(outcome, LOCAL_INSTANCE);+ for (const entry of skipped)+ ctx.log.warn("local_server.legacy_instance_skipped", {+ instance: entry.instance,+ reason: entry.reason,+ });+ if (failure) {+ ctx.log.warn("local_server.home_migration_failed", { error: failure });+ return failure;}- const error =- outcome.error.trim().slice(-500) ||- `The installer exited with code ${outcome.code}.`;- ctx.log.warn("local_server.home_migration_failed", { error });- return error;+ ctx.log.info("local_server.home_migrated", {});+ return undefined;}#installerScript(): string {@@ -1779,12 +1830,13 @@ export class LocalServerModule implements Module {},);const log = this.#ctx?.log;- // The installer explains a failed start on stderr; keep its last line.+ // The installer explains a failed start on stderr in one write, which+ // can span lines (one reason per instance); keep the last one whole.let reason = "";child.stderr.on("data", (chunk: Buffer) => {const text = chunk.toString("utf8");- reason = text.trim().split("\n").at(-1)?.slice(0, 500) || reason;- log?.warn("local_server.installer_stderr", { line: text.slice(0, 500) });+ reason = text.trim().slice(0, 1500) || reason;+ log?.warn("local_server.installer_stderr", { line: text.slice(0, 1500) });});const origin = await new Promise<string>((resolve, reject) => {let output = "";diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex 6448a220..8eec2db1 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -32,7 +32,12 @@ setup can run it from a copy on an earlier release's `Linger.exe`.Every other mode first converts an install from before the rename to Linger(`migrateLegacyInstallation`); `--migrate` does only that and exits, for the-desktop client.+desktop client. An instance it could not convert never stops the+installer, and the next start tries again. Only `--migrate` reports them: a+warning naming each and why on stderr, and one JSON line+`{"skipped":[{instance,reason}]}` on stdout. Other modes stay silent, so a+warning is never taken for the reason a start failed, and refuse a skipped+instance when they open it.Run `make check-installer`; verify UI process behavior with an isolatedbrowser context and retain masked evidence. Never stop a user's existing stackdiff --git a/apps/linger-installer/src/main.test.ts b/apps/linger-installer/src/main.test.tsindex e8edd69f..16169360 100644--- a/apps/linger-installer/src/main.test.ts+++ b/apps/linger-installer/src/main.test.ts@@ -92,6 +92,27 @@ it("reports the real start failure and points at permissions only for access err);});+it("keeps every line of a start failure", async () => {+ const { startFailure } = await import("./main.js");+ expect(+ startFailure(new Error("Could not start these instances:\nalpha: why\n")),+ ).toBe(+ "Installer could not start: Could not start these instances:\nalpha: why",+ );+});++it("names a leftover instance it could not convert and why", async () => {+ const { legacySkippedWarning } = await import("./main.js");+ expect(+ legacySkippedWarning({+ instance: "default",+ reason: "Its Computer is running 2 task(s).",+ }),+ ).toBe(+ 'Linger could not convert the instance "default" from the earlier Simplex app and left it as it was; it tries again at the next start. Its Computer is running 2 task(s).',+ );+});+it("saves keys in the instance's user.env without echoing their values", async () => {const { parseInstallerArguments, saveUserKeys } = await import("./main.js");expect(() => parseInstallerArguments(["--user-keys"])).toThrow(diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.tsindex 41f17a5b..12f05386 100644--- a/apps/linger-installer/src/main.ts+++ b/apps/linger-installer/src/main.ts@@ -1,5 +1,6 @@import path from "node:path";import { lingerHome } from "@linger/local-installation/home";+import type { LegacyInstanceSkipped } from "@linger/local-installation/legacy-migration";import { fileURLToPath } from "node:url";import { launchInstaller } from "./server/launch.js";export { startInstallerServer } from "./server/server.js";@@ -90,12 +91,18 @@ export function parseInstallerArguments(args: string[]) {// access error points at permissions.export function startFailure(error: unknown) {const code = (error as { code?: unknown } | undefined)?.code;+ // Every line: a cause can list one reason per line.const reason =- error instanceof Error ? error.message.split("\n")[0]!.slice(0, 300) : "";+ error instanceof Error ? error.message.trim().slice(0, 1500) : "";if (code === "EACCES" || code === "EPERM")return `Installer could not start: ${reason} Check the installation package and home directory permissions.`;return `Installer could not start${typeof code === "string" && code ? ` (${code})` : ""}: ${reason || "unknown error."}`;}+// A leftover instance does not hold Linger back; the person still learns+// which one stayed behind and why.+export function legacySkippedWarning(skipped: LegacyInstanceSkipped): string {+ return `Linger could not convert the instance "${skipped.instance}" from the earlier Simplex app and left it as it was; it tries again at the next start. ${skipped.reason}`;+}const failedToStart = (error: unknown) => {process.stderr.write(`${startFailure(error)}\n`);process.exitCode = 1;@@ -283,17 +290,28 @@ if (// Installs from before the rename move to the Linger home once, before// any mode opens it; --migrate does only that, for the desktop client.// Stopping for an uninstall changes nothing.+ // Only --migrate reports the instances it skipped, as warnings and as one+ // JSON line on stdout: the desktop runs it first, and in the other modes a+ // warning on stderr would read as the reason a start failed. A skipped+ // instance is refused with its own error when a mode opens it.+ let skipped: LegacyInstanceSkipped[] = [];if (options && !options.stop)await import("@linger/local-installation/legacy-migration")- .then(({ migrateLegacyInstallation }) =>- migrateLegacyInstallation({ home: options!.home }),- )+ .then(async ({ migrateLegacyInstallation }) => {+ skipped = await migrateLegacyInstallation({ home: options!.home });+ if (options?.migrate)+ for (const entry of skipped)+ process.stderr.write(`${legacySkippedWarning(entry)}\n`);+ }).catch((error: unknown) => {failedToStart(error);options = undefined;});if (options?.stop) await stopInstallation(options);- else if (options?.migrate) process.exit(0);+ else if (options?.migrate)+ process.stdout.write(`${JSON.stringify({ skipped })}\n`, () =>+ process.exit(0),+ );else if (options?.userKeys) await userKeys(options);else if (options?.inspect) await inspect(options);else if (options?.resume) await resume(options);diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex e5a4283b..250a2993 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -37,9 +37,18 @@ it stops the instance's Computer and native services, renames `SIMPLEX_*`keys in the generated env files, and gives the instance its`linger-<name>-<hash>` project name. The legacy project name in`instance.json` marks an instance as not yet converted, so it is written last-and a rerun after a crash converges. A damaged record is skipped, and a-failing instance does not stop the others; the migration then throws one-error naming each failed instance, and the installer does not start. The+and a rerun after a crash converges. A damaged record is skipped. An+instance that fails keeps its legacy names and is returned with its reason;+it does not stop the others or the installer, and the next start tries it+again. `loadInstance` refuses such an instance with an error that says so.+Only something still running keeps an instance unconverted: work its+Computer reports, or a native service that will not stop. A stop that fails+because its program or runtime left with the earlier app (an unreadable+Computer status, a failed idle stop, a recorded PID now owned by another+program, an old gateway's tools) counts as stopped. A Docker-mode record+(`mode` "source" or "release") is never converted or counted as pending:+`loadInstance` refuses it, and its compose project name removes its+containers. Thecache markers `.simplex-files.json` and `.simplex-model-package.json` keeptheir names.diff --git a/packages/local-installation/src/computer.test.ts b/packages/local-installation/src/computer.test.tsindex d89ba47b..a4c1c07f 100644--- a/packages/local-installation/src/computer.test.ts+++ b/packages/local-installation/src/computer.test.ts@@ -11,6 +11,7 @@ import {inspectComputer,startComputer,stopComputer,+ stopIdleComputer,} from "./computer.js";const roots: string[] = [];function managedNativeRuntimePath(@@ -271,6 +272,17 @@ it("refuses to stop busy Computer and only stops this config when idle", async ().toContain("--if-idle");});+it("stops an instance already found idle without reading its status again", async () => {+ const f = await fixture();+ await writeFile(f.instance.computerConfig, "{}");+ await stopIdleComputer(f.instance);+ const calls = await f.readCalls();+ expect(calls.map((args) => args.slice(0, 2).join(" "))).toEqual([+ "daemon stop",+ ]);+ expect(calls[0]).toContain("--if-idle");+});+it("treats an already stopped instance as idle for repeated down", async () => {const f = await fixture({ stopped: true });await writeFile(f.instance.computerConfig, "{}");diff --git a/packages/local-installation/src/computer.ts b/packages/local-installation/src/computer.tsindex ef5d1500..9f42d1ff 100644--- a/packages/local-installation/src/computer.ts+++ b/packages/local-installation/src/computer.ts@@ -435,6 +435,17 @@ export async function stopComputer(throw new Error("Instance busy: active operations are running or operation state is unavailable",);+ await stopIdleComputer(instance, options);+}+/**+ * Asks an instance's daemon to stop, for a caller that already found it+ * idle; the daemon itself still refuses while it runs work.+ */+export async function stopIdleComputer(+ instance: Instance,+ options: { signal?: AbortSignal } = {},+): Promise<void> {+ if (!(await configured(instance))) return;const stopped = await invoke(instance,["daemon", "stop", "--if-idle"],diff --git a/packages/local-installation/src/home.ts b/packages/local-installation/src/home.tsindex 2da04ec9..b42d05a6 100644--- a/packages/local-installation/src/home.ts+++ b/packages/local-installation/src/home.ts@@ -6,6 +6,10 @@ import path from "node:path";// the rest, so they never make a migration pending.export const INSTANCE_NAME = /^[a-z][a-z0-9-]{0,39}$/;+// The project name prefix of instances installed while the product was named+// Simplex; it marks an instance legacy-migration.ts has not converted yet.+export const LEGACY_PROJECT_PREFIX = "simplex-";+/** The installation home: LINGER_HOME, else ~/.simplexai. */export function lingerHome(environment: NodeJS.ProcessEnv = process.env,@@ -16,6 +20,24 @@ export function lingerHome();}+/**+ * An instance record from before the rename that Linger converts. One from a+ * Docker-mode install (mode "source" or "release") is left as it is: Linger+ * no longer runs it, says so when it is opened, and its compose project+ * name is what removes its containers.+ */+export function convertibleLegacyRecord(value: unknown): boolean {+ const { project, mode } = (value ?? {}) as {+ project?: unknown;+ mode?: unknown;+ };+ return (+ typeof project === "string" &&+ project.startsWith(LEGACY_PROJECT_PREFIX) &&+ mode !== "source" &&+ mode !== "release"+ );+}/*** Whether an instance under `home` still carries the project name of an* install from before the rename, so legacy-migration.ts has work to do.@@ -37,16 +59,15 @@ export async function legacyMigrationPending(home: string): Promise<boolean> {"utf8",).catch(() => undefined);if (record === undefined) continue;- let project: unknown;+ let value: unknown;try {- project = (JSON.parse(record) as { project?: unknown }).project;+ value = JSON.parse(record);} catch {// A damaged record is not the migration's to judge; the installer// reports it when it reads the instance.continue;}- if (typeof project === "string" && project.startsWith("simplex-"))- return true;+ if (convertibleLegacyRecord(value)) return true;}return false;}diff --git a/packages/local-installation/src/instance.ts b/packages/local-installation/src/instance.tsindex f8f76019..250a366b 100644--- a/packages/local-installation/src/instance.ts+++ b/packages/local-installation/src/instance.ts@@ -7,7 +7,7 @@ import {privateDirectory,readPrivate,} from "./private-files.js";-import { lingerHome } from "./home.js";+import { LEGACY_PROJECT_PREFIX, lingerHome } from "./home.js";import path from "node:path";import { DatabaseSync } from "node:sqlite";import { parseEnv } from "node:util";@@ -100,6 +100,12 @@ export async function loadInstance(options: {throw new Error(`The Linger installation in ${root} ran in Docker, which Linger no longer supports. Remove that folder and install again; Linger now runs natively.`,);+ // The installer converts it before it starts; `--migrate` reports why not,+ // and the desktop runs that and shows the reason for its own instance.+ if (value.project?.startsWith(LEGACY_PROJECT_PREFIX))+ throw new Error(+ `The installation in ${root} still has its names from the earlier Simplex app because it could not be converted. Run the installer with --migrate to see why, fix that, then start Linger again.`,+ );if (value.schemaVersion !== 1 ||value.name !== options.name ||@@ -298,6 +304,8 @@ async function writeLocalIdentityKey(root: string): Promise<void> {`${randomBytes(32).toString("base64")}\n`,);}+/** The error code when another process holds an instance's lock. */+export const INSTANCE_BUSY = "INSTANCE_BUSY";export async function withInstanceLock<T>(instance: Instance,callback: () => Promise<T>,@@ -325,7 +333,9 @@ export async function withInstanceLock<T>(} catch (error) {database.close();if (error instanceof Error && error.message.includes("database is locked"))- throw new Error("Instance busy", { cause: error });+ throw Object.assign(new Error("Instance busy", { cause: error }), {+ code: INSTANCE_BUSY,+ });throw error;}try {diff --git a/packages/local-installation/src/legacy-migration.test.ts b/packages/local-installation/src/legacy-migration.test.tsindex 98be2b22..e037ea68 100644--- a/packages/local-installation/src/legacy-migration.test.ts+++ b/packages/local-installation/src/legacy-migration.test.ts@@ -2,13 +2,46 @@ import { createHash } from "node:crypto";import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { inspectComputer, stopIdleComputer } from "./computer.js";import { loadInstance, withInstanceLock, type Instance } from "./instance.js";import { migrateLegacyInstallation } from "./legacy-migration.js";import { legacyMigrationPending } from "./home.js";+import { stopModelGateway } from "./model-gateway.js";+import {+ NATIVE_PROCESS_REPLACED,+ stopNativeProcess,+} from "./native-process.js";++vi.mock("./computer.js", async (original) => ({+ ...(await original<typeof import("./computer.js")>()),+ inspectComputer: vi.fn(),+ stopIdleComputer: vi.fn(),+}));+vi.mock("./native-process.js", async (original) => ({+ ...(await original<typeof import("./native-process.js")>()),+ stopNativeProcess: vi.fn(),+}));+vi.mock("./model-gateway.js", async (original) => ({+ ...(await original<typeof import("./model-gateway.js")>()),+ stopModelGateway: vi.fn(),+}));const roots: string[] = [];+beforeEach(() => {+ vi.mocked(inspectComputer).mockResolvedValue({+ state: "offline",+ detail: "",+ runtimes: [],+ activeOperations: 0,+ connected: false,+ });+ vi.mocked(stopIdleComputer).mockResolvedValue(undefined);+ vi.mocked(stopNativeProcess).mockResolvedValue(undefined);+ vi.mocked(stopModelGateway).mockResolvedValue(undefined);+});afterEach(async () => {+ vi.clearAllMocks();await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),);@@ -114,7 +147,7 @@ describe("migrateLegacyInstallation", () => {);});- it("converts the other instances when one fails, then names it", async () => {+ it("converts the other instances when one fails, names it and retries it later", async () => {const home = await temporary();await legacyInstance(home, "alpha");await legacyInstance(home, "beta");@@ -123,9 +156,12 @@ describe("migrateLegacyInstallation", () => {throw new Error("Instance busy: active operations are running");});- await expect(- migrateLegacyInstallation({ home, stopInstance }),- ).rejects.toThrow(/alpha: Instance busy: active operations are running/);+ expect(await migrateLegacyInstallation({ home, stopInstance })).toEqual([+ {+ instance: "alpha",+ reason: "Instance busy: active operations are running",+ },+ ]);expect(stopInstance).toHaveBeenCalledTimes(2);expect((await loadInstance({ name: "beta", home }))!.project).toMatch(@@ -146,12 +182,17 @@ describe("migrateLegacyInstallation", () => {const instance = await legacyInstance(home, "desktop");const stopInstance = vi.fn(async () => {});- await withInstanceLock(instance, () =>- expect(migrateLegacyInstallation({ home, stopInstance })).rejects.toThrow(- /desktop: Instance busy/,- ),+ const skipped = await withInstanceLock(instance, () =>+ migrateLegacyInstallation({ home, stopInstance }),);+ expect(skipped).toEqual([+ {+ instance: "desktop",+ reason: expect.stringMatching(/^Another Linger installer is using it/),+ },+ ]);+expect(stopInstance).not.toHaveBeenCalled();expect(await legacyMigrationPending(home)).toBe(true);});@@ -188,4 +229,151 @@ describe("migrateLegacyInstallation", () => {await put(path.join(home, "instances", "broken", "instance.json"), "{");expect(await legacyMigrationPending(home)).toBe(false);});++ it("explains an instance it has not converted when the installer loads it", async () => {+ const home = await temporary();+ await legacyInstance(home, "desktop");+ await expect(loadInstance({ name: "desktop", home })).rejects.toThrow(+ /still has its names from the earlier Simplex app.*--migrate to see why/,+ );+ });+});++describe("stopping a legacy instance", () => {+ it("converts an instance whose Computer status cannot be read", async () => {+ const home = await temporary();+ await legacyInstance(home, "default");+ vi.mocked(inspectComputer).mockResolvedValueOnce({+ state: "action_required",+ detail: "Computer status could not be inspected.",+ runtimes: [],+ activeOperations: -1,+ connected: false,+ });++ expect(await migrateLegacyInstallation({ home })).toEqual([]);++ expect(stopIdleComputer).not.toHaveBeenCalled();+ expect((await loadInstance({ name: "default", home }))!.project).toMatch(+ /^linger-default-/,+ );+ });++ it("stops an idle Computer, and leaves one running tasks as it was", async () => {+ const home = await temporary();+ await legacyInstance(home, "default");+ const status = {+ state: "offline" as const,+ detail: "",+ runtimes: [],+ connected: false,+ };+ vi.mocked(inspectComputer).mockResolvedValueOnce({+ ...status,+ activeOperations: 2,+ });++ expect(await migrateLegacyInstallation({ home })).toEqual([+ {+ instance: "default",+ reason:+ "Its Computer is running 2 task(s). Let them finish or stop them, then start Linger again.",+ },+ ]);+ expect(stopIdleComputer).not.toHaveBeenCalled();++ vi.mocked(inspectComputer).mockResolvedValueOnce({+ ...status,+ activeOperations: 0,+ });+ expect(await migrateLegacyInstallation({ home })).toEqual([]);+ expect(stopIdleComputer).toHaveBeenCalledTimes(1);+ expect(await legacyMigrationPending(home)).toBe(false);+ });++ it("converts an instance whose Computer runtime is gone", async () => {+ const home = await temporary();+ await legacyInstance(home, "default");+ vi.mocked(inspectComputer).mockRejectedValueOnce(+ new Error("Managed runtime is not installed"),+ );++ expect(await migrateLegacyInstallation({ home })).toEqual([]);+ expect(stopIdleComputer).not.toHaveBeenCalled();+ expect(await legacyMigrationPending(home)).toBe(false);+ });++ it("converts an idle instance whose stops find nothing to stop", async () => {+ const home = await temporary();+ await legacyInstance(home, "default-current");+ vi.mocked(inspectComputer).mockResolvedValueOnce({+ state: "offline",+ detail: "",+ runtimes: [],+ activeOperations: 0,+ connected: false,+ });+ vi.mocked(stopIdleComputer).mockRejectedValueOnce(+ new Error("Could not stop instance Computer; run linger-computer doctor"),+ );+ vi.mocked(stopNativeProcess).mockRejectedValueOnce(+ Object.assign(new Error("Native postgres process identity changed"), {+ code: NATIVE_PROCESS_REPLACED,+ }),+ );+ vi.mocked(stopModelGateway).mockRejectedValueOnce(+ new Error("The owned model gateway could not be stopped."),+ );++ expect(await migrateLegacyInstallation({ home })).toEqual([]);+ expect(await legacyMigrationPending(home)).toBe(false);+ });++ it("skips an instance whose service is still running, saying so", async () => {+ const home = await temporary();+ await legacyInstance(home, "default");+ await legacyInstance(home, "desktop");+ vi.mocked(stopNativeProcess).mockImplementation(async (root, name) => {+ if (root.endsWith(`${path.sep}default`) && name === "postgres")+ throw new Error(+ "Native postgres did not stop; identity record retained.",+ );+ });++ const skipped = await migrateLegacyInstallation({ home });++ expect(skipped).toEqual([+ {+ instance: "default",+ reason:+ "Its postgres service is still running and could not be stopped (Native postgres did not stop; identity record retained.). Restart this computer, then start Linger again.",+ },+ ]);+ expect(skipped[0]!.reason).not.toMatch(/stop any task/i);+ expect((await loadInstance({ name: "desktop", home }))!.project).toMatch(+ /^linger-desktop-/,+ );+ });++ it("leaves an install from the Docker era as it was", async () => {+ const home = await temporary();+ const root = path.join(home, "instances", "default");+ const record = JSON.stringify({+ name: "default",+ mode: "release",+ root,+ project: "simplex-default-0123456789ab",+ });+ await put(path.join(root, "instance.json"), record);++ expect(await legacyMigrationPending(home)).toBe(false);+ expect(await migrateLegacyInstallation({ home })).toEqual([]);+ expect(inspectComputer).not.toHaveBeenCalled();+ expect(await readFile(path.join(root, "instance.json"), "utf8")).toBe(+ record,+ );+ await expect(loadInstance({ name: "default", home })).rejects.toThrow(+ /ran in Docker/,+ );+ });});diff --git a/packages/local-installation/src/legacy-migration.ts b/packages/local-installation/src/legacy-migration.tsindex ae726c63..f0c0a22b 100644--- a/packages/local-installation/src/legacy-migration.ts+++ b/packages/local-installation/src/legacy-migration.ts@@ -1,17 +1,23 @@import { readdir } from "node:fs/promises";import path from "node:path";-import { stopComputer } from "./computer.js";-import { INSTANCE_NAME, lingerHome } from "./home.js";-import { composeProject, withInstanceLock, type Instance } from "./instance.js";+import { inspectComputer, stopIdleComputer } from "./computer.js";+import { INSTANCE_NAME, convertibleLegacyRecord, lingerHome } from "./home.js";+import {+ composeProject,+ INSTANCE_BUSY,+ withInstanceLock,+ type Instance,+} from "./instance.js";import { stopModelGateway } from "./model-gateway.js";-import { stopNativeProcess } from "./native-process.js";+import {+ NATIVE_PROCESS_REPLACED,+ stopNativeProcess,+} from "./native-process.js";import { nativeServices } from "./native-source.js";import { atomicPrivate, readPrivate } from "./private-files.js";-// Names that installs made while the product was named Simplex still carry.-// They identify what this one-time migration converts; nothing reads them-// after it.-const LEGACY_PROJECT_PREFIX = "simplex-";+// Environment keys that installs made while the product was named Simplex+// still carry; nothing reads them after this one-time migration.const LEGACY_ENVIRONMENT_PREFIX = /^SIMPLEX_/gm;// Generated instance files whose keys carried the legacy prefix. user.env is// the person's own file and never held them.@@ -24,19 +30,26 @@ export interface LegacyMigrationOptions {readonly stopInstance?: (instance: Instance) => Promise<void>;}+/** An instance this run left with its legacy names, and why. */+export interface LegacyInstanceSkipped {+ readonly instance: string;+ readonly reason: string;+}+/*** Converts an installation made while the product was named Simplex, once:* each instance gets its Linger project name and LINGER_* environment keys.- * An instance that fails does not hold back the others; one error at the end- * names every instance that is still legacy and why.+ * An instance that fails keeps its legacy names, does not hold back the+ * others or Linger's start, and is tried again on the next run; the result+ * names each one and why.*/export async function migrateLegacyInstallation(options: LegacyMigrationOptions = {},-): Promise<void> {+): Promise<LegacyInstanceSkipped[]> {const home = path.resolve(options.home ?? lingerHome());const stop = options.stopInstance ?? stopLegacyInstance;const directory = path.join(home, "instances");- const failures: string[] = [];+ const skipped: LegacyInstanceSkipped[] = [];for (const name of await children(directory)) {if (!INSTANCE_NAME.test(name)) continue;const root = path.join(directory, name);@@ -48,15 +61,18 @@ export async function migrateLegacyInstallation(migrateInstance(root, name, stop),);} catch (error) {- failures.push(- `${name}: ${error instanceof Error ? error.message : String(error)}`,- );+ skipped.push({+ instance: name,+ reason:+ (error as { code?: unknown }).code === INSTANCE_BUSY+ ? "Another Linger installer is using it. Close other Linger windows and installer pages, then start Linger again."+ : error instanceof Error+ ? error.message+ : String(error),+ });}}- if (failures.length > 0)- throw new Error(- `Could not convert these instances to Linger names. Stop any task running in them and start Linger again.\n${failures.join("\n")}`,- );+ return skipped;}async function children(directory: string): Promise<string[]> {@@ -79,15 +95,38 @@ async function readInstance(root: string): Promise<Instance | undefined> {}function isLegacy(instance: Instance | undefined): instance is Instance {- return instance?.project?.startsWith(LEGACY_PROJECT_PREFIX) ?? false;+ return convertibleLegacyRecord(instance);}-/** Stops what an instance runs from its folder, using its stored settings. */+/**+ * Stops what an instance runs from its folder, using its stored settings.+ * Only something still running holds the conversion back: a stop that fails+ * because the program or runtime that would do it left with the earlier app+ * finds nothing to stop, and nothing that keeps running reads the names+ * that change here.+ */async function stopLegacyInstance(instance: Instance): Promise<void> {- await stopComputer(instance);+ // A Computer whose status cannot be read takes no stop request either.+ const activeOperations = await inspectComputer(instance).then(+ (status) => status.activeOperations,+ () => -1,+ );+ if (activeOperations > 0)+ throw new Error(+ `Its Computer is running ${activeOperations} task(s). Let them finish or stop them, then start Linger again.`,+ );+ if (activeOperations === 0)+ await stopIdleComputer(instance).catch(() => undefined);for (const name of nativeServices)- await stopNativeProcess(instance.root, name);- await stopModelGateway(instance, undefined);+ await stopNativeProcess(instance.root, name).catch((error: unknown) => {+ if ((error as { code?: unknown }).code === NATIVE_PROCESS_REPLACED)+ return;+ throw new Error(+ `Its ${name} service is still running and could not be stopped (${error instanceof Error ? error.message : String(error)}). Restart this computer, then start Linger again.`,+ );+ });+ // Only earlier releases started this gateway, with tools that may be gone.+ await stopModelGateway(instance, undefined).catch(() => undefined);}async function migrateInstance(diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.tsindex 515bbaaa..75a19148 100644--- a/packages/local-installation/src/native-process.ts+++ b/packages/local-installation/src/native-process.ts@@ -327,6 +327,11 @@ export async function startNativeProcess(options: {}}+/**+ * Marks a stop refused because the recorded PID now belongs to another+ * program: none of the service's own processes are left.+ */+export const NATIVE_PROCESS_REPLACED = "NATIVE_PROCESS_REPLACED";export async function stopNativeProcess(root: string,name: NativeService,@@ -337,8 +342,11 @@ export async function stopNativeProcess(let owned = await nativeLeaseProcesses(record.lease);if (current !== record.birth && !owned.length) {if ((await stillLive(record.pid)) || (await groupLive(record.pid)))- throw new Error(- `Native ${name} process identity changed; refusing to signal this PID.`,+ throw Object.assign(+ new Error(+ `Native ${name} process identity changed; refusing to signal this PID.`,+ ),+ { code: NATIVE_PROCESS_REPLACED },);await rm(paths(root, name).record, { force: true });return;