Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(desktop): fail the Windows uninstall when services keep running

shoudi zheng653ae06bdb64
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 9ab7bda0..cbfa37b7 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -290,9 +290,11 @@ Gateway and runs Agents. The daemon exits with the app.
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).
+ left alone and it gives up after about two minutes. When the stop fails,
+ the uninstaller offers Retry; Cancel (the default when silent) ends it with
+ exit code 1 before anything is removed, so the uninstall can be run again.
+ It keeps `%APPDATA%\Linger` and the Linger home with all their data; a
+ later install starts the services again (resume, or setup's Install).
Setup over an installed release stops it the same way before it replaces
the files, since the services run on `Linger.exe` and hold it open. Setup
always stops them with its own `installer.js`, copied to the plugins
diff --git a/apps/desktop/packaging/win/installer.nsi b/apps/desktop/packaging/win/installer.nsi
index a7405b80..005e7ea5 100644
--- a/apps/desktop/packaging/win/installer.nsi
+++ b/apps/desktop/packaging/win/installer.nsi
@@ -83,8 +83,11 @@ FunctionEnd
; Linger.exe as their Node): a running Linger quits (index.ts), then an
; installer script, 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 script ends on its own after a time limit; setup
-; goes on whatever it reports. Data stays and Linger starts the services again.
+; LiveKit, PostgreSQL). The script ends on its own after a time limit. An
+; install goes on whatever it reports, and Linger starts the services again.
+; An uninstall that cannot stop them asks to retry; cancelled (or silent), it
+; fails with exit code 1 and removes nothing, so it can be run again. Data
+; stays either way.
!define INSTALLER_SCRIPT "$INSTDIR\resources\app\dist\installer\installer.js"
; Written by every install since --quit and --stop: an earlier Linger.exe
; starts on --quit instead of quitting, and its script has no --stop.
@@ -105,6 +108,11 @@ Function ${UN}StopLinger
System::Call 'Kernel32::SetEnvironmentVariable(t "ELECTRON_RUN_AS_NODE", n)'
StrCmp $0 "0" stopped
DetailPrint "Some of Linger's services may still be running."
+!if "${UN}" == "un."
+ MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Linger couldn't stop all of its services. Close Linger and try again." /SD IDCANCEL IDRETRY stop
+ SetErrorLevel 1
+ Abort
+!endif
stopped:
; Only a release that was asked to quit is waited for; a running earlier
; one never exits on its own and CloseLinger asks at once.
diff --git a/packages/local-installation/src/native-process-win32.test.ts b/packages/local-installation/src/native-process-win32.test.ts
index c48e3ef1..7826f7e4 100644
--- a/packages/local-installation/src/native-process-win32.test.ts
+++ b/packages/local-installation/src/native-process-win32.test.ts
@@ -29,6 +29,28 @@ vi.mock("./native-process-identity.js", async (original) => {
windowsProcesses: async () => (await snapshot()).processes,
};
});
+const taskkill = vi.hoisted(() => ({
+ calls: [] as string[][],
+ ends: true,
+}));
+vi.mock("./process.js", async (original) => ({
+ ...(await original<typeof import("./process.js")>()),
+ runProcess: async (_command: string, args: string[]) => {
+ taskkill.calls.push(args);
+ if (taskkill.ends) {
+ const pid = Number(args[1]);
+ const tree = [pid];
+ for (let index = 0; index < tree.length; index++)
+ for (const entry of host.processes)
+ if (entry.parent === tree[index] && !tree.includes(entry.pid))
+ tree.push(entry.pid);
+ host.processes = host.processes.filter(
+ (entry) => !tree.includes(entry.pid),
+ );
+ }
+ return { stdout: "", stderr: "", code: 0 };
+ },
+}));
vi.mock("./instance.js", async (original) => ({
...(await original<typeof import("./instance.js")>()),
readPrivate: (file: string) => readFile(file, "utf8").catch(() => undefined),
@@ -49,6 +71,8 @@ beforeEach(async () => {
host.listeners = new Map();
host.ended = [];
host.cascade = new Map();
+ taskkill.calls = [];
+ taskkill.ends = true;
vi.spyOn(process, "kill").mockImplementation((pid: number) => {
const gone = [pid, ...(host.cascade.get(pid) ?? [])];
host.ended.push(pid);
@@ -171,3 +195,54 @@ test("reclaim ends an earlier release's leftovers on this instance's ports", asy
expect(ended.sort()).toEqual([30, 41, 42]);
expect(host.processes.map((entry) => entry.pid)).toEqual([1, 10, 11, 50]);
});
+
+// TerminateProcess that leaves a process running (access denied to a
+// handle, a process mid-exit) must not end the stop at its deadline.
+function stubbornTree() {
+ host.processes.push(
+ worker(10, "postgres"),
+ row(11, 10, 101, "postgres.exe -D data"),
+ );
+ vi.mocked(process.kill).mockImplementation(() => true);
+ let now = 0;
+ vi.spyOn(Date, "now").mockImplementation(() => (now += 1_000));
+}
+
+test("a tree TerminateProcess left alive is ended with taskkill on the recorded supervisor", async () => {
+ await record("postgres", 10);
+ stubbornTree();
+ await stopNativeProcess(root, "postgres");
+ expect(taskkill.calls).toEqual([["/PID", "10", "/T", "/F"]]);
+ expect(host.processes.map((entry) => entry.pid)).toEqual([1]);
+ await expect(
+ readFile(path.join(root, "native/processes/postgres.json")),
+ ).rejects.toThrow();
+});
+
+test("a tree taskkill cannot end still fails the stop", async () => {
+ await record("postgres", 10);
+ stubbornTree();
+ taskkill.ends = false;
+ await expect(stopNativeProcess(root, "postgres")).rejects.toThrow(
+ "Native postgres did not stop; identity record retained.",
+ );
+ expect(taskkill.calls).toEqual([["/PID", "10", "/T", "/F"]]);
+ await expect(
+ readFile(path.join(root, "native/processes/postgres.json")),
+ ).resolves.toBeTruthy();
+});
+
+test("taskkill never targets a supervisor whose identity no longer matches the record", async () => {
+ await record("postgres", 10);
+ host.processes.push(
+ { ...worker(10, "postgres"), created: 500 },
+ row(11, 10, 501, "postgres.exe -D data"),
+ );
+ vi.mocked(process.kill).mockImplementation(() => true);
+ let now = 0;
+ vi.spyOn(Date, "now").mockImplementation(() => (now += 1_000));
+ await expect(stopNativeProcess(root, "postgres")).rejects.toThrow(
+ "did not stop",
+ );
+ expect(taskkill.calls).toEqual([]);
+});
diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.ts
index 709c3b7c..f5f1b456 100644
--- a/packages/local-installation/src/native-process.ts
+++ b/packages/local-installation/src/native-process.ts
@@ -6,7 +6,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as delay } from "node:timers/promises";
import { atomicPrivate, privateDirectory, readPrivate } from "./instance.js";
-import { runProcess } from "./process.js";
+import { runProcess, windowsTreeTermination } from "./process.js";
import {
linuxProcessStates,
nativeProcessIdentity as observed,
@@ -416,7 +416,7 @@ export async function stopNativeProcess(
const record = await stored(root, name);
if (!record) return;
if (process.platform === "win32") {
- await stopWindowsTree(name, record.lease);
+ await stopWindowsTree(name, record.lease, record);
await rm(paths(root, name).record, { force: true });
return;
}
@@ -518,13 +518,20 @@ export function windowsTerminationOrder(tree: WindowsProcess[]): number[] {
* supervisor, whose command line carries the lease that finds the tree, goes
* only once nothing is left under it.
*/
-async function stopWindowsTree(name: NativeService, lease: string) {
+async function stopWindowsTree(
+ name: NativeService,
+ lease: string,
+ record?: Pick<Lease, "pid" | "birth" | "lease">,
+) {
const deadline = Date.now() + 12_000;
for (;;) {
- const tree = windowsLeaseTree((await windowsSnapshot()).processes, lease);
+ const snapshot = (await windowsSnapshot()).processes;
+ const tree = windowsLeaseTree(snapshot, lease);
if (!tree.length) return;
- if (Date.now() >= deadline)
+ if (Date.now() >= deadline) {
+ if (record && (await endRecordedTree(record, snapshot))) return;
throw new Error(`Native ${name} did not stop; identity record retained.`);
+ }
const order = windowsTerminationOrder(tree);
for (const pid of tree.length > 1 ? order.slice(0, -1) : order)
terminate(pid);
@@ -532,6 +539,40 @@ async function stopWindowsTree(name: NativeService, lease: string) {
}
}
+/**
+ * Last resort when TerminateProcess left part of the tree alive: taskkill /T
+ * ends what Windows still links to the supervisor. Only a supervisor whose
+ * PID and creation time match the record in this very snapshot is targeted,
+ * so a PID Windows has handed to another program is never touched. True when
+ * nothing under the lease is left afterwards.
+ */
+async function endRecordedTree(
+ record: Pick<Lease, "pid" | "birth" | "lease">,
+ snapshot: WindowsProcess[],
+): Promise<boolean> {
+ const owner = recordedTree(snapshot, record)[0];
+ if (!owner) return false;
+ const invocation = windowsTreeTermination({
+ pid: owner.pid,
+ exitCode: null,
+ signalCode: null,
+ });
+ if (!invocation) return false;
+ await runProcess(invocation.command, invocation.args, {
+ timeoutMs: 15_000,
+ }).catch(() => undefined);
+ const deadline = Date.now() + 3_000;
+ for (;;) {
+ const tree = windowsLeaseTree(
+ (await windowsSnapshot()).processes,
+ record.lease,
+ );
+ if (!tree.length) return true;
+ if (Date.now() >= deadline) return false;
+ await delay(100);
+ }
+}
+
const SUPERVISOR = "native-process-worker.mjs";
const comparable = (value: string) => value.replaceAll("/", "\\").toLowerCase();
/**