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): stop the local services when Linger is uninstalled on Windows
claude-opus-5-5-medium32b29841de41
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 4a73cafd..63122781 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -223,6 +223,15 @@ Gateway and runs Agents. The daemon exits with the app.Windows setup installs into `%LOCALAPPDATA%\Programs\Linger`; on upgrade itcloses and removes `%LOCALAPPDATA%\Programs\Simplex` and moves the"Open at login" Run value from `ai.simplex.desktop.preview` to the new id.+ The uninstaller (per-user, like the setup) first runs `Linger.exe --quit`,+ which a running Linger obeys without asking, then the bundled+ `installer.js --instance desktop --stop` under `ELECTRON_RUN_AS_NODE`. That+ stops the installation manager the desktop started (cancelling a running+ job) and the `desktop` instance's services in the default home and in the+ location `desktop/local-server.json` names; services already stopped are+ left alone and it gives up after about two minutes. It keeps+ `%APPDATA%\Linger` and the Linger home with all their data and asks nothing;+ a later install starts the services again (resume, or setup's Install).- `src/main/legacy-migration.ts`: on start, stops a bridge an older versionleft running and moves its credential and the Desktop 0.16 daemon identityinto the daemon layout, so the computer keeps its id.diff --git a/apps/desktop/packaging/win/installer.nsi b/apps/desktop/packaging/win/installer.nsiindex 7092a99d..58e07288 100644--- a/apps/desktop/packaging/win/installer.nsi+++ b/apps/desktop/packaging/win/installer.nsi@@ -93,8 +93,43 @@ Section "Linger"WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1SectionEnd+; Uninstalling stops what Linger runs, so nothing keeps running or holds a+; file: a running Linger quits (index.ts), then the bundled installer, run by+; the app's own Node, stops the installation manager and the services of the+; local installation (TeamHub, web, node-services, LiveKit, PostgreSQL). The+; installer ends on its own after a time limit; the uninstall goes on whatever+; it reports. Data stays and a new install starts the services again.+!define INSTALLER_SCRIPT "$INSTDIR\resources\app\dist\installer\installer.js"+Function un.StopLinger+ IfFileExists "$INSTDIR\Linger.exe" 0 done+ ; Without a running Linger this exits at once.+ ExecWait '"$INSTDIR\Linger.exe" --quit'+ IfFileExists "${INSTALLER_SCRIPT}" 0 closing+ DetailPrint "Stopping Linger on this computer..."+ System::Call 'Kernel32::SetEnvironmentVariable(t "ELECTRON_RUN_AS_NODE", t "1")'+ nsExec::ExecToLog '"$INSTDIR\Linger.exe" "${INSTALLER_SCRIPT}" --instance desktop --stop'+ Pop $0+ System::Call 'Kernel32::SetEnvironmentVariable(t "ELECTRON_RUN_AS_NODE", n)'+ StrCmp $0 "0" closing+ DetailPrint "Some of Linger's services may still be running."+ closing:+ ; The app takes a moment to quit; un.CloseLinger asks after that.+ StrCpy $1 0+ wait:+ ClearErrors+ Delete "$INSTDIR\Linger.exe"+ IfErrors 0 done+ IntOp $1 $1 + 1+ IntCmp $1 20 done+ Sleep 500+ Goto wait+ done:+FunctionEnd+Section "Uninstall"- ; Settings, sign-in and logs stay in %APPDATA%\Linger.+ ; Settings, sign-in and logs stay in %APPDATA%\Linger, and the local+ ; installation (%USERPROFILE%\.simplexai) with its data.+ Call un.StopLingerCall un.CloseLingerDelete "$SMPROGRAMS\Linger.lnk"RMDir /r "$INSTDIR"diff --git a/apps/desktop/src/main/app-window.test.ts b/apps/desktop/src/main/app-window.test.tsindex 75d2f426..ae200695 100644--- a/apps/desktop/src/main/app-window.test.ts+++ b/apps/desktop/src/main/app-window.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { appWindow } from "./app-window.js";+import { appWindow, quitRequested } from "./app-window.js";describe("appWindow", () => {it("brings back setup that was closed before this computer connected", () => {@@ -15,3 +15,10 @@ describe("appWindow", () => {expect(appWindow({ enrolled: true, setupOpen: false })).toBe("main");});});++describe("quitRequested", () => {+ it("quits for the uninstaller, as the second instance or the only one", () => {+ expect(quitRequested(["Linger.exe", "--quit"])).toBe(true);+ expect(quitRequested(["Linger.exe", "--background"])).toBe(false);+ });+});diff --git a/apps/desktop/src/main/app-window.ts b/apps/desktop/src/main/app-window.tsindex b8e53121..5f26adec 100644--- a/apps/desktop/src/main/app-window.ts+++ b/apps/desktop/src/main/app-window.ts@@ -9,3 +9,9 @@ export function appWindow(state: {}): "setup" | "main" {return state.setupOpen || !state.enrolled ? "setup" : "main";}++// The uninstaller runs `Linger.exe --quit` before it stops the local+// services and removes the app.+export function quitRequested(argv: readonly string[]): boolean {+ return argv.includes("--quit");+}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 045c8944..70c6111c 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -17,6 +17,7 @@ import {import { lingerHome } from "@linger/local-installation/home";+import { quitRequested } from "./app-window.js";import { CredentialStore } from "./computer-credential.js";import {ComputerDaemonModule,@@ -86,7 +87,9 @@ else if (app.isPackaged) {const APP_USER_MODEL_ID = "com.simplexai.linger.desktop.preview";if (process.platform === "win32") app.setAppUserModelId(APP_USER_MODEL_ID);-if (!app.requestSingleInstanceLock()) {+// `--quit` (the uninstaller) asks a running Linger to quit, and starts+// nothing when none runs.+if (!app.requestSingleInstanceLock() || quitRequested(process.argv)) {app.quit();} else {registerAppScheme();@@ -312,7 +315,11 @@ async function main(): Promise<void> {const host = new ModuleHost(modules, { config, log, bus: new EventBus() });const showApp = (): void => setup.showApp();- app.on("second-instance", showApp);+ app.on("second-instance", (_event, argv) => {+ // Without asking: the uninstaller is removing the app.+ if (quitRequested(argv)) app.quit();+ else showApp();+ });app.on("activate", showApp);// Closing the window only hides it; the tray keeps the app running.app.on("window-all-closed", () => {});diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex 07328003..7437e723 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -21,7 +21,12 @@ after a reboot and reads the outcome from the single JSON line on stdout. Italso restarts running services when the instance's `user.env` no longermatches the configuration they started with.-Every mode first converts an install from before the rename to Linger+`--stop` (with `--instance`) is the desktop uninstall's: it stops the+manager the desktop started for that instance (its `/api/stop` cancels a+running job) and the instance's services, deletes nothing, and prints one+JSON line with what failed.++Every other mode first converts an install from before the rename to Linger(`migrateLegacyInstallation`); `--migrate` does only that and exits, for thedesktop client.diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.tsindex db553351..e83e7419 100644--- a/apps/linger-installer/src/main.ts+++ b/apps/linger-installer/src/main.ts@@ -16,6 +16,7 @@ export function parseInstallerArguments(args: string[]) {inspect?: boolean;userKeys?: boolean;migrate?: boolean;+ stop?: boolean;} = {home: lingerHome(),};@@ -37,6 +38,10 @@ export function parseInstallerArguments(args: string[]) {options.migrate = true;continue;}+ if (flag === "--stop") {+ options.stop = true;+ continue;+ }if (flag === "--user-keys") {options.userKeys = true;continue;@@ -69,13 +74,16 @@ export function parseInstallerArguments(args: string[]) {!options.sourceRepo &&!options.inspect &&!options.userKeys &&- !options.migrate+ !options.migrate &&+ !options.stop)throw new Error("The installer needs a source checkout (--source-repo).");if (options.resume && !options.instanceName)throw new Error("Resume needs a source checkout and an instance.");if (options.userKeys && !options.instanceName)throw new Error("Keys need an instance.");+ if (options.stop && !options.instanceName)+ throw new Error("Stop needs an instance.");return options;}// The desktop client shows this line, so it carries the real cause; only an@@ -191,6 +199,30 @@ async function userKeys(options: ReturnType<typeof parseInstallerArguments>) {process.exit("error" in outcome ? 1 : 0),);}+// Headless stop for the desktop's uninstall: the outcome as one JSON line on+// stdout. The uninstall waits for it, so it ends on its own after a while.+async function stopInstallation(+ options: ReturnType<typeof parseInstallerArguments>,+) {+ const { stopDesktopInstallation } = await import("./server/stop.js");+ setTimeout(() => process.exit(1), 150_000).unref();+ const outcome = await stopDesktopInstallation({+ home: options.home,+ instanceName: options.instanceName!,+ signal: AbortSignal.timeout(120_000),+ log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")),+ }).catch((error: unknown) => ({+ failed: [+ {+ home: options.home,+ message: error instanceof Error ? error.message : String(error),+ },+ ],+ }));+ process.stdout.write(`${JSON.stringify(outcome)}\n`, () =>+ process.exit(outcome.failed.length ? 1 : 0),+ );+}async function serve(options: ReturnType<typeof parseInstallerArguments>) {const server = await launchInstaller({...options,@@ -245,7 +277,8 @@ 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.- if (options)+ // Stopping for an uninstall changes nothing.+ if (options && !options.stop)await import("@linger/local-installation/legacy-migration").then(({ migrateLegacyInstallation }) =>migrateLegacyInstallation({ home: options!.home }),@@ -254,7 +287,8 @@ if (failedToStart(error);options = undefined;});- if (options?.migrate) process.exit(0);+ if (options?.stop) await stopInstallation(options);+ else if (options?.migrate) 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/apps/linger-installer/src/server/server.ts b/apps/linger-installer/src/server/server.tsindex 091261f1..a1a70ffc 100644--- a/apps/linger-installer/src/server/server.ts+++ b/apps/linger-installer/src/server/server.ts@@ -203,6 +203,18 @@ export async function startInstallerServer(options: ServerOptions) {setImmediate(() => void close());return;}+ // The desktop's uninstall: closing cancels a running job, which keeps+ // the account and data.+ if (url.pathname === "/api/stop" && method === "POST") {+ const input = (await body(req)) as { token?: unknown };+ if (input.token !== controlToken) {+ error(res, 401, "UNAUTHORIZED", "Open the installer again.");+ return;+ }+ json(res, 200, { ok: true });+ setImmediate(() => void close());+ return;+ }if (url.pathname === "/api/session" && method === "POST") {const input = (await body(req)) as { token?: unknown };if (diff --git a/apps/linger-installer/src/server/stop.test.ts b/apps/linger-installer/src/server/stop.test.tsnew file mode 100644index 00000000..bb4b055b--- /dev/null+++ b/apps/linger-installer/src/server/stop.test.ts@@ -0,0 +1,203 @@+import { afterEach, expect, test, vi } from "vitest";+import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import path from "node:path";+import { tmpdir } from "node:os";++import { parseInstallerArguments } from "../main.js";+import { launchInstaller } from "./launch.js";+import { privateDirectory, privateWrite } from "./storage.js";+import { stopDesktopInstallation, type StopDependencies } from "./stop.js";++const clean: Array<() => Promise<unknown>> = [];+afterEach(async () => {+ for (const fn of clean.splice(0).reverse()) await fn();+});++const home = async () => {+ const value = await mkdtemp(path.join(tmpdir(), "installer-stop-"));+ clean.push(() => rm(value, { recursive: true, force: true }));+ return value;+};+const exists = (file: string) =>+ access(file).then(+ () => true,+ () => false,+ );+const options = (value: string) => ({+ home: value,+ instanceName: "desktop",+ signal: AbortSignal.timeout(10_000),+ log: () => {},+});+const instance = (root: string) =>+ ({ name: "desktop", root }) as unknown as NonNullable<+ Awaited<ReturnType<NonNullable<StopDependencies["load"]>>>+ >;++test("the uninstall stop needs only the instance", () => {+ expect(+ parseInstallerArguments(["--instance", "desktop", "--stop"]),+ ).toMatchObject({ stop: true, instanceName: "desktop" });+ expect(() => parseInstallerArguments(["--stop"])).toThrow(/instance/);+});++test("stops the desktop's manager while a job runs, then the instance's services", async () => {+ const value = await home();+ let cancelled = false;+ const manager = await launchInstaller({+ home: value,+ sourceRepo: "/source/one",+ externalComputer: true,+ instanceName: "desktop",+ noOpen: true,+ dependencies: {+ run: async (_input: unknown, signal: AbortSignal) => {+ await new Promise<void>((resolve) =>+ signal.addEventListener("abort", () => resolve(), { once: true }),+ );+ cancelled = true;+ return { state: "cancelled", code: 130, message: "Cancelled" };+ },+ },+ });+ clean.push(manager.close);+ const session = await fetch(`${manager.origin}/api/session`, {+ method: "POST",+ headers: { Origin: manager.origin, "Content-Type": "application/json" },+ body: JSON.stringify({ token: manager.bootstrapToken }),+ });+ const cookie = session.headers.get("set-cookie")!.split(";")[0]!;+ await fetch(`${manager.origin}/api/jobs`, {+ method: "POST",+ headers: {+ Origin: manager.origin,+ "Content-Type": "application/json",+ Cookie: cookie,+ },+ body: JSON.stringify({ instance: "desktop" }),+ });+ const stopped: string[] = [];+ const outcome = await stopDesktopInstallation(options(value), {+ load: async ({ home: at }) => instance(path.join(at!, "instances/desktop")),+ stopInstance: async (target) => {+ stopped.push(target.root);+ },+ });+ expect(outcome.failed).toEqual([]);+ await manager.closed;+ expect(cancelled).toBe(true);+ expect(await exists(path.join(value, "installer/session.json"))).toBe(false);+ expect(stopped).toEqual([path.join(value, "instances/desktop")]);+});++test("leaves a manager the person opened for another installation", async () => {+ const value = await home();+ const manager = await launchInstaller({+ home: value,+ sourceRepo: "/source/one",+ instanceName: "default",+ noOpen: true,+ });+ clean.push(manager.close);+ const outcome = await stopDesktopInstallation(options(value), {+ load: async () => undefined,+ });+ expect(outcome.failed).toEqual([]);+ expect(await exists(path.join(value, "installer/session.json"))).toBe(true);+});++test("an uninstall with nothing running or installed stops nothing", async () => {+ const value = await home();+ // The session of a manager that ended without removing it.+ await privateDirectory(path.join(value, "installer"));+ await privateWrite(path.join(value, "installer/session.json"), {+ origin: "http://127.0.0.1:9",+ controlToken: "x".repeat(43),+ externalComputer: true,+ instanceName: "desktop",+ });+ const stopInstance = vi.fn(async () => {});+ const outcome = await stopDesktopInstallation(options(value), {+ load: async () => undefined,+ stopInstance,+ fetch: (async () => {+ throw Object.assign(new TypeError("fetch failed"), {+ cause: { code: "ECONNREFUSED" },+ });+ }) as typeof fetch,+ });+ expect(outcome.failed).toEqual([]);+ expect(stopInstance).not.toHaveBeenCalled();+});++test("stops the services even when the manager refuses to stop", async () => {+ const value = await home();+ // An earlier release's manager, or another server on a stale session's port.+ await privateDirectory(path.join(value, "installer"));+ await privateWrite(path.join(value, "installer/session.json"), {+ origin: "http://127.0.0.1:9",+ controlToken: "x".repeat(43),+ externalComputer: true,+ instanceName: "desktop",+ });+ const stopped: string[] = [];+ const outcome = await stopDesktopInstallation(options(value), {+ load: async ({ home: at }) => instance(path.join(at!, "instances/desktop")),+ stopInstance: async (target) => {+ stopped.push(target.root);+ },+ fetch: (async () => new Response("", { status: 404 })) as typeof fetch,+ });+ expect(stopped).toEqual([path.join(value, "instances/desktop")]);+ expect(outcome.failed).toEqual([+ { home: value, message: "The installation manager refused (404)." },+ ]);+});++test("also stops the installation in the location chosen under Customize, even when another fails", async () => {+ const value = await home();+ const custom = await home();+ await mkdir(path.join(value, "desktop"), { recursive: true });+ await writeFile(+ path.join(value, "desktop/local-server.json"),+ JSON.stringify({+ home: custom,+ repo: "/r",+ origin: "http://localhost:3000",+ }),+ );+ const stopped: string[] = [];+ const outcome = await stopDesktopInstallation(options(value), {+ load: async ({ home: at }) => instance(at!),+ stopInstance: async (target) => {+ if (target.root === value)+ throw new Error("Native postgres still has live descendants");+ stopped.push(target.root);+ },+ });+ expect(stopped).toEqual([custom]);+ expect(outcome.failed).toEqual([+ { home: value, message: "Native postgres still has live descendants" },+ ]);+});++test("gives up on a stop that does not finish in time", async () => {+ const value = await home();+ const controller = new AbortController();+ const outcome = await stopDesktopInstallation(+ { ...options(value), signal: controller.signal },+ {+ load: async ({ home: at }) => instance(at!),+ stopInstance: (_target, signal) =>+ new Promise((_resolve, reject) => {+ signal.addEventListener("abort", () => reject(signal.reason), {+ once: true,+ });+ controller.abort(new Error("The stop timed out"));+ }),+ },+ );+ expect(outcome.failed).toEqual([+ { home: value, message: "The stop timed out" },+ ]);+});diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.tsnew file mode 100644index 00000000..8b63d47e--- /dev/null+++ b/apps/linger-installer/src/server/stop.ts@@ -0,0 +1,143 @@+import { access, readFile } from "node:fs/promises";+import path from "node:path";++import { loadInstance } from "@linger/local-installation/instance";+import { stopNativeSource } from "@linger/local-installation/native-source";++import { privateRead } from "./storage.js";++type Instance = NonNullable<Awaited<ReturnType<typeof loadInstance>>>;++export interface StopOptions {+ // The default home; the desktop records a custom install location in it.+ home: string;+ instanceName: string;+ signal: AbortSignal;+ log: (message: string) => void;+}++export interface StopOutcome {+ failed: { home: string; message: string }[];+}++export interface StopDependencies {+ load?: typeof loadInstance;+ stopInstance?: (instance: Instance, signal: AbortSignal) => Promise<void>;+ fetch?: typeof fetch;+}++/**+ * Stops what the desktop's installation runs, for its uninstall: the+ * installation manager it owns (a running job is cancelled) and the+ * instance's services. Nothing is deleted, and stopped services are left as+ * they are. Every home is tried even when one fails.+ */+export async function stopDesktopInstallation(+ options: StopOptions,+ {+ load = loadInstance,+ stopInstance = stopNativeSource,+ fetch: fetcher = fetch,+ }: StopDependencies = {},+): Promise<StopOutcome> {+ const failed: StopOutcome["failed"] = [];+ const attempt = async (home: string, step: () => Promise<void>) => {+ try {+ await step();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ options.log(`Could not stop the installation in ${home}: ${message}`);+ failed.push({ home, message });+ }+ };+ for (const home of await installationHomes(options.home)) {+ // The services stop even when the manager could not: an earlier release's+ // manager has no /api/stop, and a stale session may name another server.+ await attempt(home, () => stopManager(home, options, fetcher));+ await attempt(home, async () => {+ const instance = await load({ name: options.instanceName, home });+ if (!instance) return;+ options.log(`Stopping the services in ${instance.root}.`);+ await stopInstance(instance, options.signal);+ });+ }+ return { failed };+}++// The default home and the install location the desktop chose under+// Customize (desktop/local-server.json).+async function installationHomes(home: string): Promise<string[]> {+ try {+ const record = JSON.parse(+ await readFile(path.join(home, "desktop", "local-server.json"), "utf8"),+ ) as { home?: unknown };+ if (+ typeof record.home === "string" &&+ path.isAbsolute(record.home) &&+ path.resolve(record.home) !== path.resolve(home)+ )+ return [home, path.resolve(record.home)];+ } catch {+ // No record: nothing was installed elsewhere.+ }+ return [home];+}++// Only a manager the desktop started for this instance; one the person+// opened for another installation keeps running.+async function stopManager(+ home: string,+ options: StopOptions,+ fetcher: typeof fetch,+): Promise<void> {+ const file = path.join(home, "installer", "session.json");+ if (!(await exists(file))) return;+ const session = (await privateRead(file)) as {+ origin?: unknown;+ controlToken?: unknown;+ externalComputer?: unknown;+ instanceName?: unknown;+ };+ if (+ session.externalComputer !== true ||+ session.instanceName !== options.instanceName ||+ typeof session.origin !== "string" ||+ !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}$/.test(session.origin) ||+ typeof session.controlToken !== "string"+ )+ return;+ options.log("Stopping the installation manager.");+ try {+ const response = await fetcher(`${session.origin}/api/stop`, {+ method: "POST",+ headers: { Origin: session.origin, "Content-Type": "application/json" },+ body: JSON.stringify({ token: session.controlToken }),+ redirect: "error",+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(10_000)]),+ });+ if (!response.ok)+ throw new Error(`The installation manager refused (${response.status}).`);+ } catch (error) {+ options.signal.throwIfAborted();+ // Nothing listens: the session is left from a manager that ended.+ if (connectionRefused(error)) return;+ throw error;+ }+ // It removes its session once its job is cancelled and its files closed.+ while (await exists(file)) {+ options.signal.throwIfAborted();+ await new Promise((resolve) => setTimeout(resolve, 200));+ }+}++function connectionRefused(error: unknown): boolean {+ const cause = (error as { cause?: { code?: unknown } } | undefined)?.cause;+ return cause?.code === "ECONNREFUSED";+}++async function exists(file: string): Promise<boolean> {+ return access(file).then(+ () => true,+ () => false,+ );+}