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): end every Windows service process on stop and upgrade
Dongdong Chen5715aa50b134
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 31e5720c..43ff741c 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -292,19 +292,19 @@ Gateway and runs Agents. The daemon exits with the app.`%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).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. Each+ 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+ folder, on the old `Linger.exe`: an earlier release's script may not stop+ them (0.1.2's left TeamHub, web and node-services running on Windows). Eachinstall writes `resources\stops-services`; a release without it would start- on `--quit` and has no `--stop`, so setup skips `--quit` (CloseLinger asks- the person to quit a running app) and runs its own `installer.js`, copied to- the plugins folder, on the old `Linger.exe`. Retry in that prompt runs the- stop again. Nothing running: the stop finds nothing and setup goes on. The+ on `--quit`, so setup skips `--quit` for it (CloseLinger asks the person to+ quit a running app). Retry in that prompt runs the stop again. Nothing running: the stop finds nothing and setup goes on. Thestop also asks the pinned localmodels kit, when that kit is installed in thehome, to end its foundations controller under `runtime/model-services`(`foundations stop`) and the stack's processes (`stack down`); it downloadsnothing, and Linger does not end the tool's processes itself.- Setup over a release runs that release's script, so a release from before- this stop leaves its controller running; on Windows the tool cannot prove- and end a controller from a kit that has no stop command either.+ On Windows the tool cannot prove and end a controller from a kit that has+ no stop command.The tool refuses the chat stack on Windows, so no engine runs there.- `src/main/legacy-migration.ts`: on start, stops a bridge an older versionleft running and moves its credential and the Desktop 0.16 daemon identitydiff --git a/apps/desktop/packaging/win/installer.nsi b/apps/desktop/packaging/win/installer.nsiindex d120dc89..a7405b80 100644--- a/apps/desktop/packaging/win/installer.nsi+++ b/apps/desktop/packaging/win/installer.nsi@@ -125,17 +125,16 @@ FunctionEnd!insertmacro STOP_LINGER ""!insertmacro STOP_LINGER "un."-; An earlier release that cannot stop its services is stopped by this-; release's script, run by that release's Linger.exe. A running app of such a-; release is left to CloseLinger.+; An earlier release's services are stopped by this release's script, run+; by that release's Linger.exe: an earlier script may not stop them (one+; before --stop has none; 0.1.2's left TeamHub, web and node-services+; running). A running app of a release without the marker is left to+; CloseLinger.Function StopEarlierLingerIfFileExists "$INSTDIR\Linger.exe" 0 done- StrCpy $R0 "${INSTALLER_SCRIPT}"- IfFileExists "${STOP_MARKER}" stopInitPluginsDirFile "/oname=$PLUGINSDIR\stop.mjs" "${STAGE}\resources\app\dist\installer\installer.js"StrCpy $R0 "$PLUGINSDIR\stop.mjs"- stop:Call StopLingerdone:FunctionEnddiff --git a/apps/desktop/src/main/windows-installer.test.ts b/apps/desktop/src/main/windows-installer.test.tsindex ee418ce7..ad697b6d 100644--- a/apps/desktop/src/main/windows-installer.test.ts+++ b/apps/desktop/src/main/windows-installer.test.ts@@ -68,12 +68,13 @@ it("waits for the app to exit only when it was asked to quit", () => {);});-it("stops a release without --stop with this release's script", () => {+it("stops every earlier release with this release's script", () => {const earlier = block("Function StopEarlierLinger", "FunctionEnd");+ // An earlier release's own script may leave its services running.+ expect(earlier).not.toContain("STOP_MARKER");order(earlier,'IfFileExists "$INSTDIR\\Linger.exe" 0 done',- 'IfFileExists "${STOP_MARKER}" stop',"${STAGE}\\resources\\app\\dist\\installer\\installer.js",'StrCpy $R0 "$PLUGINSDIR\\stop.mjs"',"Call StopLinger",diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex 0b8779f7..5f71874b 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -82,6 +82,28 @@ existing Computer is rebound once on its next connect. A distribution withoutthe tool writes none. External Computers (the Desktop's) get the same paths asthe `LINGER_LOCALMODELS_*` keys of the installer's instance runtime.+Each native service runs under a detached supervisor+(`native-process-worker.mjs`) whose record holds its PID, birth and an+unguessable lease. POSIX finds the service's processes by process group and+the lease in their environment. Windows has neither: the lease is in the+supervisor's command line (its job file name) and the tree follows parent+links (`windowsLeaseTree`), which break when a parent dies first. So on+Windows a stop ends one snapshot of the tree leaves first and the supervisor+last; a supervisor with nothing under it counts as stopped (the PowerShell+of its own process listing does not count as its service); a program file+starts as `source-native.mjs`'s direct child, not through cmd.exe, so it ends+with its supervisor. Before the services start and after a stop, the+installer ends what an earlier run lost track of (`reclaimNativeOrphans`): a+supervisor whose job file is in this instance's process directory under a+lease no serving record holds, and a process on one of this instance's+ports whose command line runs from this installation's folders but belongs+to no recorded service, with its wrappers up to its supervisor. Never by a+program name alone, and never the installer or what started it. Readiness on+Windows also needs each port's listener inside that service's tree: an+earlier release's TeamHub or web still on the port would otherwise pass the+health check for a service that could not bind, and a port held by another+program fails the start after 15 seconds instead of at the deadline.+Move a freshly downloaded or unpacked file or folder into place with`renameRetrying` from `fs-retry.ts`: on Windows antivirus and indexing holdnew files for a moment, and a plain rename then fails with EPERM.diff --git a/packages/local-installation/src/native-livekit.ts b/packages/local-installation/src/native-livekit.tsindex 6fc46904..3d6380a9 100644--- a/packages/local-installation/src/native-livekit.ts+++ b/packages/local-installation/src/native-livekit.ts@@ -5,7 +5,11 @@ import path from "node:path";import { parseEnv } from "node:util";import { setTimeout as delay } from "node:timers/promises";import { atomicPrivate, readPrivate } from "./instance.js";-import { inspectNativeProcess, startNativeProcess } from "./native-process.js";+import {+ inspectNativeListeners,+ inspectNativeProcess,+ startNativeProcess,+} from "./native-process.js";// The LiveKit server Native voice runs, as docker-compose.yml runs it for// Docker: the voice workers and the browser meet there. It listens on@@ -149,7 +153,12 @@ export async function liveKitReady(signal?: AbortSignal,): Promise<boolean> {try {- if (!(await inspectNativeProcess(root, "livekit")).running) return false;+ const [state] = await inspectNativeListeners(root, [+ { name: "livekit", port: settings.httpPort },+ ]);+ // Another process on the port would answer for a LiveKit that cannot+ // listen there.+ if (!state?.running || state.foreign !== undefined) return false;const response = await fetch(`http://127.0.0.1:${settings.httpPort}/`, {redirect: "error",signal: AbortSignal.any([diff --git a/packages/local-installation/src/native-process-identity.ts b/packages/local-installation/src/native-process-identity.tsindex 987c53cf..a05794f6 100644--- a/packages/local-installation/src/native-process-identity.ts+++ b/packages/local-installation/src/native-process-identity.ts@@ -36,12 +36,18 @@ function runProcess(// Windows has no process groups and no readable foreign environment. The// supervisor carries the lease in its command line (the job file name), and// what it starts is found through parent links; a creation time older than-// the parent's means a reused PID, never a child.+// the parent's means a reused PID, never a child. The listening TCP ports+// come in the same snapshot, so a port's owner is judged against the same+// process tree.const WINDOWS_PROCESSES = String.raw`$ErrorActionPreference = 'Stop'-Get-CimInstance Win32_Process | ForEach-Object {+$p = @(Get-CimInstance Win32_Process | ForEach-Object {[pscustomobject]@{ p = $_.ProcessId; q = $_.ParentProcessId; c = $_.CreationDate.ToFileTimeUtc(); l = [string]$_.CommandLine }-} | ConvertTo-Json -Compress+})+$n = @(Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | ForEach-Object {+ [pscustomobject]@{ o = [int]$_.OwningProcess; t = [int]$_.LocalPort; a = [string]$_.LocalAddress }+})+[pscustomobject]@{ p = $p; n = $n } | ConvertTo-Json -Compress -Depth 3`;export interface WindowsProcess {pid: number;@@ -49,7 +55,42 @@ export interface WindowsProcess {created: number;command: string;}-export async function windowsProcesses(): Promise<WindowsProcess[]> {+export interface WindowsSnapshot {+ processes: WindowsProcess[];+ /**+ * Listening TCP port to the owning PID, for the addresses the services+ * bind and check: 127.0.0.1, or every IPv4 address. Another program on+ * ::1 neither blocks them nor answers their health checks.+ */+ listeners: Map<number, number>;+}+type Rows<T> = T | T[] | null | undefined;+const rows = <T>(value: Rows<T>): T[] =>+ value == null ? [] : Array.isArray(value) ? value : [value];+export function parseWindowsSnapshot(stdout: string): WindowsSnapshot {+ const parsed = JSON.parse(stdout || "{}") as {+ p?: Rows<{ p: number; q: number; c: number; l: string | null }>;+ n?: Rows<{ o: number; t: number; a: string }>;+ };+ return {+ processes: rows(parsed.p).map((row) => ({+ pid: row.p,+ parent: row.q,+ created: row.c,+ command: row.l ?? "",+ })),+ listeners: new Map(+ rows(parsed.n)+ .filter((row) => row.a === "127.0.0.1" || row.a === "0.0.0.0")+ // The loopback listener is the one a health check reaches.+ .sort(+ (a, b) => Number(a.a === "127.0.0.1") - Number(b.a === "127.0.0.1"),+ )+ .map((row) => [row.t, row.o]),+ ),+ };+}+export async function windowsSnapshot(): Promise<WindowsSnapshot> {const result = await runProcess("powershell.exe",["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROCESSES],@@ -57,15 +98,22 @@ export async function windowsProcesses(): Promise<WindowsProcess[]> {);if (result.code !== 0)throw new Error("Native processes could not be enumerated.");- const rows = JSON.parse(result.stdout || "[]") as- | { p: number; q: number; c: number; l: string }- | { p: number; q: number; c: number; l: string }[];- return (Array.isArray(rows) ? rows : [rows]).map((row) => ({- pid: row.p,- parent: row.q,- created: row.c,- command: row.l ?? "",- }));+ return parseWindowsSnapshot(result.stdout);+}+export async function windowsProcesses(): Promise<WindowsProcess[]> {+ return (await windowsSnapshot()).processes;+}+/**+ * The PowerShell a supervisor starts to take this snapshot is its own child.+ * Counted as a service process, it kept every Windows supervisor alive after+ * its service died, so the record still claimed a running service. Releases+ * before this one ran the same query, so it is recognized by its script.+ */+function processInspection(candidate: WindowsProcess): boolean {+ return (+ /\bpowershell(?:\.exe)?\b/i.test(candidate.command) &&+ candidate.command.includes("Get-CimInstance Win32_Process")+ );}/** The supervisor holding the lease and everything it started, alive now. */export function windowsLeaseTree(@@ -83,6 +131,7 @@ export function windowsLeaseTree(if (candidate.parent === parent.pid &&candidate.created >= parent.created &&+ !processInspection(candidate) &&!tree.includes(candidate))tree.push(candidate);diff --git a/packages/local-installation/src/native-process-win32.test.ts b/packages/local-installation/src/native-process-win32.test.tsnew file mode 100644index 00000000..c48e3ef1--- /dev/null+++ b/packages/local-installation/src/native-process-win32.test.ts@@ -0,0 +1,173 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import type {+ WindowsProcess,+ WindowsSnapshot,+} from "./native-process-identity.js";++// Windows paths of the native lifecycle on any host: the process snapshot+// is the fixture, and ending a process removes it (with whatever Node's job+// object ends along with it) from the next snapshot.+const host = vi.hoisted(() => ({+ processes: [] as WindowsProcess[],+ listeners: new Map<number, number>(),+ ended: [] as number[],+ cascade: new Map<number, number[]>(),+}));+vi.mock("./native-process-identity.js", async (original) => {+ const actual =+ await original<typeof import("./native-process-identity.js")>();+ const snapshot = async (): Promise<WindowsSnapshot> => ({+ processes: [...host.processes],+ listeners: new Map(host.listeners),+ });+ return {+ ...actual,+ windowsSnapshot: snapshot,+ windowsProcesses: async () => (await snapshot()).processes,+ };+});+vi.mock("./instance.js", async (original) => ({+ ...(await original<typeof import("./instance.js")>()),+ readPrivate: (file: string) => readFile(file, "utf8").catch(() => undefined),+}));+import {+ inspectNativeListeners,+ inspectNativeProcess,+ reclaimNativeOrphans,+ stopNativeProcess,+} from "./native-process.js";++const platform = Object.getOwnPropertyDescriptor(process, "platform")!;+let root = "";+beforeEach(async () => {+ Object.defineProperty(process, "platform", { ...platform, value: "win32" });+ root = await mkdtemp(path.join(tmpdir(), "native-win32-"));+ host.processes = [row(1, 0, 1, "wininit.exe")];+ host.listeners = new Map();+ host.ended = [];+ host.cascade = new Map();+ vi.spyOn(process, "kill").mockImplementation((pid: number) => {+ const gone = [pid, ...(host.cascade.get(pid) ?? [])];+ host.ended.push(pid);+ host.processes = host.processes.filter(+ (entry) => !gone.includes(entry.pid),+ );+ return true;+ });+});+afterEach(async () => {+ Object.defineProperty(process, "platform", platform);+ vi.restoreAllMocks();+ await rm(root, { recursive: true, force: true });+});+const row = (pid: number, parent: number, created: number, command = "") => ({+ pid,+ parent,+ created,+ command,+});+const lease = "a".repeat(64);+const worker = (pid: number, name: string, key = lease) =>+ row(+ pid,+ 1,+ 100,+ `node.exe native-process-worker.mjs ${path.join(root, "native", "processes", `${name}.${key}.job`)}`,+ );+async function record(name: string, pid: number, key = lease) {+ await mkdir(path.join(root, "native", "processes"), { recursive: true });+ await writeFile(+ path.join(root, "native", "processes", `${name}.json`),+ JSON.stringify({+ schemaVersion: 1,+ name,+ pid,+ birth: `win32:${pid}:100`,+ lease: key,+ configuration: "b".repeat(64),+ }),+ );+}++test("a supervisor whose service died is not running", async () => {+ await record("livekit", 10);+ host.processes.push(+ worker(10, "livekit"),+ row(20, 10, 200, "powershell.exe -Command Get-CimInstance Win32_Process"),+ );+ expect((await inspectNativeProcess(root, "livekit")).running).toBe(false);+ host.processes.push(row(11, 10, 101, "livekit-server.exe"));+ expect((await inspectNativeProcess(root, "livekit")).running).toBe(true);+});++test("stop ends the whole tree leaves first and forgets the record", async () => {+ await record("teamhub", 10);+ host.processes.push(+ worker(10, "teamhub"),+ row(11, 10, 101, "node.exe source-native.mjs teamhub"),+ row(12, 11, 102, 'cmd.exe /d /s /c "teamhub.exe"'),+ row(13, 12, 103, "teamhub.exe"),+ );+ // Node's job object ends its direct child with it; TeamHub under cmd.exe+ // was not, and a stop that ended the parents first lost it.+ host.cascade.set(11, [12]);+ await stopNativeProcess(root, "teamhub");+ expect(host.ended).toEqual([13, 12, 11, 10]);+ expect(host.processes.map((entry) => entry.pid)).toEqual([1]);+ await expect(+ readFile(path.join(root, "native/processes/teamhub.json")),+ ).rejects.toThrow();+});++test("stop forgets a record whose PID Windows gave to another program", async () => {+ await record("web", 10);+ host.processes.push(row(10, 1, 900, "notepad.exe"));+ await stopNativeProcess(root, "web");+ expect(host.ended).toEqual([]);+ expect((await inspectNativeProcess(root, "web")).pid).toBeUndefined();+});++test("a port held outside the service's tree is reported as foreign", async () => {+ await record("teamhub", 10);+ host.processes.push(+ worker(10, "teamhub"),+ row(11, 10, 101, "teamhub.exe"),+ row(40, 1, 50, "teamhub.exe from an earlier release"),+ );+ host.listeners.set(55640, 40);+ expect(+ await inspectNativeListeners(root, [{ name: "teamhub", port: 55640 }]),+ ).toEqual([{ running: true, foreign: 40 }]);+ host.listeners.set(55640, 11);+ expect(+ await inspectNativeListeners(root, [{ name: "teamhub", port: 55640 }]),+ ).toEqual([{ running: true }]);+});++test("reclaim ends an earlier release's leftovers on this instance's ports", async () => {+ const home = path.dirname(path.dirname(root));+ await record("postgres", 10);+ host.processes.push(+ worker(10, "postgres"),+ row(11, 10, 101, `${home}\\tools\\postgres.exe -D ${root}`),+ // A LiveKit supervisor whose record a later start replaced.+ worker(30, "livekit", "c".repeat(64)),+ row(41, 99, 120, `cmd.exe /d /s /c "${home}\\source\\teamhub.exe"`),+ row(42, 41, 121, `${home}\\source\\teamhub.exe`),+ row(50, 1, 130, "C:\\other\\server.exe"),+ );+ host.listeners = new Map([+ [55640, 42],+ [55643, 11],+ [8080, 50],+ ]);+ const ended = await reclaimNativeOrphans(root, {+ ports: [55640, 55643, 8080],+ paths: [home],+ });+ expect(ended.sort()).toEqual([30, 41, 42]);+ expect(host.processes.map((entry) => entry.pid)).toEqual([1, 10, 11, 50]);+});diff --git a/packages/local-installation/src/native-process-windows.test.ts b/packages/local-installation/src/native-process-windows.test.tsindex bb04d5cf..414fb69c 100644--- a/packages/local-installation/src/native-process-windows.test.ts+++ b/packages/local-installation/src/native-process-windows.test.ts@@ -1,5 +1,10 @@import { describe, expect, it } from "vitest";-import { windowsLeaseTree } from "./native-process-identity.js";+import {+ parseWindowsSnapshot,+ windowsLeaseTree,+ type WindowsProcess,+} from "./native-process-identity.js";+import { windowsOrphans, windowsTerminationOrder } from "./native-process.js";const lease = "a".repeat(64);const row = (pid: number, parent: number, created: number, command = "") => ({@@ -8,6 +13,13 @@ const row = (pid: number, parent: number, created: number, command = "") => ({created,command,});+const inspection = (pid: number, parent: number, created: number) =>+ row(+ pid,+ parent,+ created,+ `powershell.exe -NoProfile -NonInteractive -Command "$ErrorActionPreference = 'Stop'\nGet-CimInstance Win32_Process | ForEach-Object { }"`,+ );describe("windowsLeaseTree", () => {it("starts at the supervisor whose job carries the lease", () => {@@ -42,4 +54,214 @@ describe("windowsLeaseTree", () => {),).toEqual([]);});++ it("does not count the supervisor's own process inspection as its service", () => {+ // The supervisor whose LiveKit died: only the PowerShell of its own+ // check (and that one's console host) runs under it.+ const tree = windowsLeaseTree(+ [+ row(10, 1, 100, `node native-process-worker.mjs livekit.${lease}.job`),+ inspection(20, 10, 200),+ row(21, 20, 201, "\\??\\C:\\WINDOWS\\system32\\conhost.exe 0xffffffff"),+ ],+ lease,+ );+ expect(tree.map((candidate) => candidate.pid)).toEqual([10]);+ });+});++describe("parseWindowsSnapshot", () => {+ it("reads one process and no listeners as lists", () => {+ const snapshot = parseWindowsSnapshot(+ JSON.stringify({ p: { p: 4, q: 0, c: 1, l: null }, n: [] }),+ );+ expect(snapshot.processes).toEqual([row(4, 0, 1)]);+ expect(snapshot.listeners.size).toBe(0);+ });++ it("maps each listening port to its process", () => {+ const snapshot = parseWindowsSnapshot(+ JSON.stringify({+ p: [{ p: 4, q: 0, c: 1, l: "x" }],+ n: [+ { o: 7644, t: 55641, a: "127.0.0.1" },+ { o: 29644, t: 3000, a: "::1" },+ { o: 16588, t: 3000, a: "127.0.0.1" },+ { o: 31000, t: 3000, a: "0.0.0.0" },+ ],+ }),+ );+ // A development server on ::1:3000 is not the web service's listener.+ expect(snapshot.listeners).toEqual(+ new Map([+ [55641, 7644],+ [3000, 16588],+ ]),+ );+ });+});++it("ends leaves before the processes that started them", () => {+ expect(+ windowsTerminationOrder([+ row(10, 1, 100),+ row(11, 10, 101),+ row(12, 11, 102),+ ]),+ ).toEqual([12, 11, 10]);+});++describe("windowsOrphans", () => {+ const home = "C:\\Users\\Ada\\.simplexai";+ const root = `${home}\\instances\\desktop`;+ const node = `${home}\\desktop\\node\\v26.5.0\\node.exe`;+ const oldSource = `${home}\\desktop\\source\\f1e089bacd8b0bd7`;+ const newSource = `${home}\\desktop\\source\\e91b1008ba80087b`;+ const worker = (name: string, key: string) =>+ `${node} C:\\Users\\Ada\\AppData\\Local\\Programs\\Linger\\resources\\app\\dist\\installer\\native-process-worker.mjs ${root}\\native\\processes\\${name}.${key}.job`;+ const ports = { teamhub: 55640, nodeServices: 55641, web: 3000, pg: 55643 };+ const postgresLease = "c".repeat(64);+ const liveKitLease = "d".repeat(64);+ const strayLease = "e".repeat(64);+ // What WIN-10 left after the 0.1.3 setup stopped 0.1.2: its TeamHub, web+ // and node-services without their supervisors, a LiveKit supervisor whose+ // LiveKit is gone, and a PostgreSQL its supervisor still owns.+ const processes: WindowsProcess[] = [+ row(1, 0, 1, "wininit.exe"),+ row(+ 500,+ 1,+ 50,+ `"C:\\Users\\Ada\\AppData\\Local\\Programs\\Linger\\Linger.exe"`,+ ),+ row(600, 500, 60, `${node} installer.js --home ${home} --resume`),+ row(27876, 1, 100, worker("postgres", postgresLease)),+ row(+ 9324,+ 27876,+ 101,+ `${home}\\tools\\native\\bin\\postgres.exe -D ${root}\\native\\postgres-data`,+ ),+ row(+ 9330,+ 9324,+ 102,+ `"${home}/tools/native/bin/postgres.exe" --forkchild="backend" 5604`,+ ),+ row(31196, 1, 110, worker("livekit", liveKitLease)),+ inspection(38584, 31196, 900),+ row(+ 18248,+ 42964,+ 120,+ `C:\\WINDOWS\\system32\\cmd.exe /d /s /c "${oldSource}\\.simplexai-runtime\\prebuilt\\teamhub.exe"`,+ ),+ row(+ 26340,+ 18248,+ 121,+ `${oldSource}\\.simplexai-runtime\\prebuilt\\teamhub.exe`,+ ),+ row(+ 16588,+ 33136,+ 130,+ `${node} ${oldSource}\\.simplexai-runtime\\offline\\web\\static-host.mjs`,+ ),+ row(+ 41828,+ 38688,+ 140,+ `${node} --conditions=linger-production ${oldSource}\\.simplexai-runtime\\offline\\node-services\\dist\\supervisor.js --compiled`,+ ),+ row(+ 7644,+ 41828,+ 141,+ `${node} --conditions=linger-production ${oldSource}\\.simplexai-runtime\\offline\\node-services\\dist\\main.js`,+ ),+ row(7700, 1, 150, worker("web", strayLease)),+ row(42372, 13172, 160, "C:\\bench\\llama-server.exe --port 18910"),+ row(44444, 1, 170, `${newSource}\\scripts\\source-native.mjs web`),+ ];+ const listeners = new Map([+ [ports.teamhub, 26340],+ [ports.nodeServices, 7644],+ [ports.web, 16588],+ [ports.pg, 9324],+ [18910, 42372],+ ]);+ const records = [+ {+ pid: 27876,+ birth: "win32:27876:100",+ lease: postgresLease,+ },+ { pid: 31196, birth: "win32:31196:110", lease: liveKitLease },+ ];+ const options = {+ root,+ ports: Object.values(ports),+ paths: [home, root, newSource],+ self: 600,+ };++ it("finds what an earlier release left running, deepest first", () => {+ const order = windowsOrphans({ processes, listeners }, records, options);+ // LiveKit's supervisor without LiveKit; a supervisor no record holds.+ expect(order).toEqual(+ expect.arrayContaining([31196, 7700, 26340, 18248, 16588, 7644, 41828]),+ );+ expect(order.indexOf(26340)).toBeLessThan(order.indexOf(18248));+ expect(order.indexOf(7644)).toBeLessThan(order.indexOf(41828));+ // The stale supervisor's inspection ends with it.+ expect(order.indexOf(38584)).toBeLessThan(order.indexOf(31196));+ // The serving PostgreSQL tree, another program on its own port, a+ // process on no port, and the running installer stay.+ for (const kept of [27876, 9324, 9330, 42372, 44444, 600, 500])+ expect(order).not.toContain(kept);+ });++ it("leaves a program outside this installation alone, even on its port", () => {+ const order = windowsOrphans(+ {+ processes: [...processes, row(8080, 1, 180, "C:\\tools\\other.exe")],+ listeners: new Map([[ports.web, 8080]]),+ },+ records,+ options,+ );+ expect(order).not.toContain(8080);+ });++ it("never ends this process or what started it", () => {+ // The installer itself runs from the home and could hold a port.+ const order = windowsOrphans(+ { processes, listeners: new Map([[ports.web, 600]]) },+ [],+ options,+ );+ expect(order).not.toContain(600);+ expect(order).not.toContain(500);+ });++ it("leaves a serving supervisor's tree to its own stop", () => {+ const order = windowsOrphans(+ {+ processes: [+ row(31196, 1, 110, worker("livekit", liveKitLease)),+ row(+ 31668,+ 31196,+ 111,+ `${home}\\tools\\native\\bin\\livekit-server.exe`,+ ),+ ],+ listeners: new Map([[7880, 31668]]),+ },+ [records[1]!],+ { ...options, ports: [7880] },+ );+ expect(order).toEqual([]);+ });});diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.tsindex 75a19148..66faa460 100644--- a/packages/local-installation/src/native-process.ts+++ b/packages/local-installation/src/native-process.ts@@ -11,6 +11,10 @@ import {linuxProcessStates,nativeProcessIdentity as observed,nativeLeaseProcesses,+ windowsLeaseTree,+ windowsSnapshot,+ type WindowsProcess,+ type WindowsSnapshot,} from "./native-process-identity.js";export type NativeService =@@ -110,16 +114,76 @@ async function groupLive(group: number): Promise<boolean> {return Number(pgid) === group && !state?.startsWith("Z");});}+/** The recorded supervisor and what it started, or nothing when it is gone. */+function recordedTree(+ processes: WindowsProcess[],+ record: Pick<Lease, "pid" | "birth" | "lease">,+): WindowsProcess[] {+ const tree = windowsLeaseTree(processes, record.lease);+ const owner = tree[0];+ return owner?.pid === record.pid &&+ `win32:${owner.pid}:${owner.created}` === record.birth+ ? tree+ : [];+}+/**+ * Whether the recorded supervisor still runs its service. On Windows a+ * supervisor left with no process under it serves nothing, and one from an+ * earlier release may never exit on its own; counting it as running kept+ * every start waiting for a service that was gone.+ */+async function serving(record: Lease): Promise<boolean> {+ if (process.platform !== "win32")+ return (await observed(record.pid, record.lease)) === record.birth;+ return recordedTree((await windowsSnapshot()).processes, record).length > 1;+}export async function inspectNativeProcess(root: string,name: NativeService,): Promise<NativeProcessState> {const record = await stored(root, name);if (!record) return { running: false };- return {- running: (await observed(record.pid, record.lease)) === record.birth,- pid: record.pid,- };+ return { running: await serving(record), pid: record.pid };+}+export interface NativeListener {+ name: NativeService;+ port: number;+}+export interface NativeListenerState {+ running: boolean;+ /**+ * Windows only: the PID of a process outside the service's recorded tree+ * that listens on its port. The service cannot serve there, and a health+ * check on that port reaches the other process.+ */+ foreign?: number;+}+/** Whether each service runs and, on Windows, whether its port is its own. */+export async function inspectNativeListeners(+ root: string,+ listeners: NativeListener[],+): Promise<NativeListenerState[]> {+ if (process.platform !== "win32")+ return Promise.all(+ listeners.map(async ({ name }) => ({+ running: (await inspectNativeProcess(root, name)).running,+ })),+ );+ const snapshot = await windowsSnapshot();+ return Promise.all(+ listeners.map(async ({ name, port }) => {+ const record = await stored(root, name);+ const tree = record ? recordedTree(snapshot.processes, record) : [];+ const owner = snapshot.listeners.get(port);+ return {+ running: tree.length > 1,+ ...(owner !== undefined &&+ !tree.some((candidate) => candidate.pid === owner)+ ? { foreign: owner }+ : {}),+ };+ }),+ );}interface NativeConfiguration {executable: string;@@ -144,11 +208,7 @@ export async function nativeConfigurationChanged(options: NativeConfiguration & { root: string; name: NativeService },): Promise<boolean> {const existing = await stored(options.root, options.name);- if (- !existing ||- (await observed(existing.pid, existing.lease)) !== existing.birth- )- return false;+ if (!existing || !(await serving(existing))) return false;return configurationHash(options) !== existing.configuration;}export async function startNativeProcess(options: {@@ -168,10 +228,7 @@ export async function startNativeProcess(options: {const location = paths(options.root, options.name);const configuration = configurationHash(options);const existing = await stored(options.root, options.name);- if (- existing &&- (await observed(existing.pid, existing.lease)) === existing.birth- ) {+ if (existing && (await serving(existing))) {if (configuration !== existing.configuration) {if (!options.restartOnConfigurationChange)throw new Error(@@ -185,7 +242,13 @@ export async function startNativeProcess(options: {}return { running: true, pid: existing.pid };}- if (existing) {+ if (existing && process.platform === "win32") {+ // The lease names the supervisor on its command line, so whatever is+ // still on it, such as a supervisor that outlived its service, is this+ // service's own to end. A recorded PID alone proves nothing on Windows,+ // which reuses PIDs quickly.+ await stopNativeProcess(options.root, options.name);+ } else if (existing) {if ((await stillLive(existing.pid)) ||(await groupLive(existing.pid)) ||@@ -295,6 +358,17 @@ export async function startNativeProcess(options: {return { running: true, pid: child.pid };} catch (error) {// A failed record write must not leave an unmanageable owned group behind.+ if (process.platform === "win32") {+ await stopWindowsTree(options.name, lease).catch((failure: unknown) => {+ throw new Error(+ `Native ${options.name} failed to stop after identity persistence failed.`,+ { cause: failure },+ );+ });+ if (child.connected) child.disconnect();+ child.unref();+ throw error;+ }const deadline = Date.now() + 5_000;for (;;) {const owned = await nativeLeaseProcesses(lease);@@ -338,6 +412,11 @@ export async function stopNativeProcess(): Promise<void> {const record = await stored(root, name);if (!record) return;+ if (process.platform === "win32") {+ await stopWindowsTree(name, record.lease);+ await rm(paths(root, name).record, { force: true });+ return;+ }const current = await observed(record.pid, record.lease);let owned = await nativeLeaseProcesses(record.lease);if (current !== record.birth && !owned.length) {@@ -414,3 +493,173 @@ export async function stopNativeProcess(throw new Error(`Native ${name} did not stop; identity record retained.`);await rm(paths(root, name).record, { force: true });}++function terminate(pid: number) {+ try {+ // Windows has no signals: every kill is TerminateProcess.+ process.kill(pid, "SIGKILL");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;+ }+}+/** Deepest first, so that no process loses the parent that links it here. */+export function windowsTerminationOrder(tree: WindowsProcess[]): number[] {+ return tree.map((candidate) => candidate.pid).reverse();+}+/**+ * Ends the supervisor holding the lease and everything under it. Windows+ * links a child only through its parent's PID, so ending a parent first+ * (as the signal loop for process groups does) cut its children off the+ * tree: TeamHub, web and node-services outlived every stop and kept their+ * ports. Each pass ends one snapshot's processes leaves first; the+ * 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) {+ const deadline = Date.now() + 12_000;+ for (;;) {+ const tree = windowsLeaseTree((await windowsSnapshot()).processes, lease);+ if (!tree.length) return;+ if (Date.now() >= deadline)+ 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);+ await delay(100);+ }+}++const SUPERVISOR = "native-process-worker.mjs";+const comparable = (value: string) => value.replaceAll("/", "\\").toLowerCase();+/**+ * What Windows must end before this instance's services start: processes an+ * earlier run started and lost track of. Each is proved this instance's own+ * by its command line, never by a program name alone:+ * - a supervisor whose job file is in this instance's process directory but+ * whose service is gone or whose lease no record holds any more;+ * - a process listening on one of this instance's ports that runs from one+ * of this installation's folders yet belongs to no recorded service, with+ * its wrappers up to its supervisor (a stop of an earlier release ended+ * the supervisor and left TeamHub, web and node-services running).+ * The result lists PIDs in the order to end them, deepest first.+ */+export function windowsOrphans(+ snapshot: WindowsSnapshot,+ records: Array<Pick<Lease, "pid" | "birth" | "lease">>,+ options: { root: string; ports: number[]; paths: string[]; self: number },+): number[] {+ const { processes } = snapshot;+ const byPid = new Map(processes.map((entry) => [entry.pid, entry]));+ const owned = new Set<number>();+ const leases = new Set<string>();+ for (const record of records) {+ const tree = recordedTree(processes, record);+ if (tree.length < 2) continue;+ leases.add(record.lease);+ for (const entry of tree) owned.add(entry.pid);+ }+ // This process and the ones that started it are never ended.+ const keep = new Set<number>();+ for (+ let entry = byPid.get(options.self);+ entry && !keep.has(entry.pid);+ entry = byPid.get(entry.parent)+ )+ keep.add(entry.pid);+ const children = (parent: WindowsProcess) =>+ processes.filter(+ (entry) => entry.parent === parent.pid && entry.created >= parent.created,+ );+ const order: number[] = [];+ const end = (top: WindowsProcess) => {+ const tree = [top];+ for (let index = 0; index < tree.length; index++)+ for (const child of children(tree[index]!))+ if (!tree.includes(child)) tree.push(child);+ for (const pid of windowsTerminationOrder(tree))+ if (!order.includes(pid) && !owned.has(pid) && !keep.has(pid))+ order.push(pid);+ };+ const jobs =+ comparable(path.join(options.root, "native", "processes")) + "\\";+ for (const entry of processes) {+ const command = comparable(entry.command);+ if (!command.includes(SUPERVISOR) || !command.includes(jobs)) continue;+ const lease = /\.([a-f0-9]{64})\.job\b/.exec(command)?.[1];+ if (lease && !leases.has(lease)) end(entry);+ }+ const folders = options.paths.map((folder) => comparable(folder) + "\\");+ const ours = (entry: WindowsProcess) =>+ !keep.has(entry.pid) &&+ folders.some((folder) => comparable(entry.command).includes(folder));+ for (const port of options.ports) {+ const pid = snapshot.listeners.get(port);+ let top = pid === undefined ? undefined : byPid.get(pid);+ if (!top || owned.has(top.pid) || !ours(top)) continue;+ // A supervisor heads every service tree, at most four links up+ // (node-services: main.js, its supervisor, cmd.exe, source-native.mjs).+ for (+ let depth = 0;+ depth < 4 && !comparable(top.command).includes(SUPERVISOR);+ depth+++ ) {+ const parent = byPid.get(top.parent);+ if (+ !parent ||+ parent.created > top.created ||+ owned.has(parent.pid) ||+ !ours(parent)+ )+ break;+ top = parent;+ }+ end(top);+ }+ return order;+}+/**+ * Ends what `windowsOrphans` finds for this instance; nothing elsewhere.+ * Returns the PIDs it ended.+ */+export async function reclaimNativeOrphans(+ root: string,+ options: { ports: number[]; paths: string[] },+): Promise<number[]> {+ if (process.platform !== "win32") return [];+ const records: Lease[] = [];+ for (const name of services)+ try {+ const record = await stored(root, name as NativeService);+ if (record) records.push(record);+ } catch {+ // A damaged record proves nothing; its supervisor counts as unrecorded.+ }+ const ended: number[] = [];+ const deadline = Date.now() + 12_000;+ for (;;) {+ const orphans = windowsOrphans(await windowsSnapshot(), records, {+ root,+ ...options,+ self: process.pid,+ });+ if (!orphans.length) return ended;+ if (Date.now() >= deadline)+ throw new Error(+ `Processes an earlier Linger started on this computer did not stop (PIDs ${orphans.join(", ")}).`,+ );+ const refused: number[] = [];+ for (const pid of orphans)+ try {+ terminate(pid);+ if (!ended.includes(pid)) ended.push(pid);+ } catch {+ // Such as one started as administrator.+ refused.push(pid);+ }+ if (refused.length === orphans.length)+ throw new Error(+ `Processes an earlier Linger started on this computer could not be ended (PIDs ${refused.join(", ")}). End them in Task Manager, then try again.`,+ );+ await delay(100);+ }+}diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.tsindex 03e8cbca..abd24dcf 100644--- a/packages/local-installation/src/native-source-flow.test.ts+++ b/packages/local-installation/src/native-source-flow.test.ts@@ -40,6 +40,7 @@ import {} from "./teamhub-binaries.js";import { prepareRuntime } from "./managed-runtimes.js";import {+ inspectNativeListeners,inspectNativeProcess,nativeConfigurationChanged,startNativeProcess,@@ -70,12 +71,32 @@ vi.mock("./managed-codex.js", () => ({managedRuntimeEnvironment: vi.fn(async () => ({})),configureManagedCodex: vi.fn(),}));-vi.mock("./native-process.js", () => ({- inspectNativeProcess: vi.fn(),- nativeConfigurationChanged: vi.fn(),- startNativeProcess: vi.fn(),- stopNativeProcess: vi.fn(),-}));+vi.mock("./native-process.js", () => {+ const inspectNativeProcess = vi.fn();+ return {+ inspectNativeProcess,+ // Port ownership is checked only on Windows; elsewhere it is the+ // process state.+ inspectNativeListeners: vi.fn(+ async (root: string, listeners: { name: string; port: number }[]) =>+ Promise.all(+ listeners.map(async ({ name }) => ({+ running: Boolean(+ (+ (await inspectNativeProcess(root, name)) as {+ running?: boolean;+ }+ )?.running,+ ),+ })),+ ),+ ),+ reclaimNativeOrphans: async () => [],+ nativeConfigurationChanged: vi.fn(),+ startNativeProcess: vi.fn(),+ stopNativeProcess: vi.fn(),+ };+});vi.mock("./native-database.js", () => ({ prepareNativeDatabase: vi.fn() }));vi.mock("./source-computer.js", () => ({ prepareSourceComputer: vi.fn() }));vi.mock("./computer.js", () => ({@@ -583,6 +604,43 @@ test("a full disk ends startup at once instead of at the deadline", async () =>);});+test("a port an earlier TeamHub still holds fails startup instead of passing its health check", async () => {+ const f = await fixture();+ vi.mocked(prepareRuntime).mockResolvedValue({+ code: 0,+ state: "ready",+ message: "ready",+ });+ vi.useFakeTimers({ toFake: ["Date"] });+ try {+ // The earlier TeamHub answers /healthz on the port; each probe is ten+ // seconds later.+ vi.mocked(inspectNativeListeners).mockImplementation(+ async (_root, listeners) => {+ vi.setSystemTime(Date.now() + 10_000);+ return listeners.map(({ name }) =>+ name === "teamhub"+ ? { running: true, foreign: 4328 }+ : { running: true },+ );+ },+ );+ const result = await installNativeSource({+ ...f,+ name: "native-flow",+ setupChoice: "pi",+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ expect(result).toMatchObject({ code: 1 });+ expect(result.message).toMatch(+ /Native teamhub cannot listen on port \d+: another program \(PID 4328\) is using it/,+ );+ } finally {+ vi.useRealTimers();+ }+});+// What scripts/source-native.mjs logs when go build fails, as on Windows// before TeamHub had a Windows disk-capacity probe.const failedBuild = [diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex de06c2c7..ecbf9a71 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -29,8 +29,10 @@ import { checkTeamhubBinaries } from "./teamhub-binaries.js";import { npmRegistryEnvironment } from "./npm-registry.js";import { prepareNativeDatabase } from "./native-database.js";import {+ inspectNativeListeners,inspectNativeProcess,nativeConfigurationChanged,+ reclaimNativeOrphans,startNativeProcess,stopNativeProcess,type NativeService,@@ -192,11 +194,19 @@ export async function probeNativeSourceServices(["node-services", "node-services", source.ports.nodeServices, "/readyz"],["document-runtime", "node-services", source.ports.document, "/readyz"],] as const;+ const states = await inspectNativeListeners(+ instance.root,+ endpoints.map(([, name, port]) => ({ name, port })),+ ).catch(() => endpoints.map(() => ({ running: false, foreign: undefined })));return Promise.all(- endpoints.map(async ([service, processName, port, endpoint]) => {+ endpoints.map(async ([service, , port, endpoint], index) => {+ const { running, foreign } = states[index]!;+ // Another process on the port would answer the health check for a+ // service that cannot listen there.+ if (foreign !== undefined)+ return { service, ready: false, foreign, port };try {- if (!(await inspectNativeProcess(instance.root, processName)).running)- return { service, ready: false };+ if (!running) return { service, ready: false };const response = await fetch(`http://127.0.0.1:${port}${endpoint}`, {redirect: "error",signal: AbortSignal.any([@@ -290,10 +300,27 @@ async function waitHealthy() {const deadline = Date.now() + 20 * 60_000;let last = 0;+ const occupied = new Map<string, number>();for (;;) {signal.throwIfAborted();- const checks = await probeNativeSourceServices(instance, signal);- if (checks.every((check) => check.ready)) return checks;+ const probed = await probeNativeSourceServices(instance, signal);+ if (probed.every((check) => check.ready))+ return probed.map(({ service, ready }) => ({ service, ready }));+ // A port another process holds never frees up by waiting; the service+ // that should listen there exits or retries until the deadline.+ for (const check of probed) {+ if (!("foreign" in check)) {+ occupied.delete(check.service);+ continue;+ }+ const since = occupied.get(check.service) ?? Date.now();+ occupied.set(check.service, since);+ if (Date.now() - since >= 15_000)+ throw new Error(+ `Native ${check.service} cannot listen on port ${check.port}: another program (PID ${check.foreign}) is using it. End that program, then try again.`,+ );+ }+ const checks = probed;// A failed build exits the service, so its log explains the stop.const failure = await startupFailure(instance, ends);if (failure) throw new Error(failure);@@ -765,6 +792,7 @@ async function runNativeSource("services","Starting private PostgreSQL and applying migrations…",);+ await reclaimEarlierProcesses(current, home, emit);const postgresWasRunning = (await inspectNativeProcess(current.root, "postgres")).running;@@ -1061,6 +1089,32 @@ async function runNativeSource(output.flush();}}+/**+ * Windows: ends the processes of this instance an earlier run lost track of+ * (an earlier release's stop left them, or their supervisor died), so they+ * neither hold the ports nor answer health checks for the new services.+ */+async function reclaimEarlierProcesses(+ instance: Instance,+ home: string,+ onEvent?: (event: InstallerEvent) => void,+) {+ const source = requireNative(instance);+ const liveKit = await readLiveKitSettings(instance.root);+ const ended = await reclaimNativeOrphans(instance.root, {+ ports: [+ ...Object.values(source.ports),+ ...(liveKit ? [liveKit.httpPort] : []),+ ],+ paths: [home, instance.root, source.repo],+ });+ if (ended.length)+ onEvent?.({+ kind: "log",+ stage: "services",+ message: `Ended ${ended.length} Linger processes an earlier run left behind (PIDs ${ended.join(", ")}).\n`,+ });+}export async function stopNativeSource(instance: Instance,signal?: AbortSignal,@@ -1073,6 +1127,10 @@ export async function stopNativeSource(signal?.throwIfAborted();await stopNativeProcess(instance.root, name);}+ await reclaimEarlierProcesses(+ instance,+ path.resolve(instance.root, "../.."),+ );await stopModelGateway(instance, signal);});}diff --git a/scripts/replace-process.mjs b/scripts/replace-process.mjsindex ac09b095..b9dfd84b 100644--- a/scripts/replace-process.mjs+++ b/scripts/replace-process.mjs@@ -11,20 +11,34 @@ export function windowsCommandLine(command, args) {.join(" ");}+/**+ * How Windows starts the command: a program file directly, anything else+ * (pnpm.cmd and other PATHEXT launchers) through cmd.exe.+ */+export function windowsLaunch(command, args) {+ return /^(?:[a-z]:\\|\\\\).*\.exe$/i.test(command)+ ? { file: command, args, shell: false }+ : { file: windowsCommandLine(command, args), args: [], shell: true };+}+/*** POSIX replaces this process so the caller keeps the command's PID, exit* status and signals. Windows has no execve: run the command as a child and* exit with its status; the supervisor still owns it through the parent link.+ * Node ends the children it starts when it exits, but not their children, so+ * a program file runs as this process's own child: through cmd.exe it+ * outlived its supervisor and kept its port.*/export function replaceProcess(command, args, env, cwd = process.cwd()) {if (process.platform !== "win32") {process.chdir(cwd);process.execve("/usr/bin/env", ["env", command, ...args], env);}- const child = spawn(windowsCommandLine(command, args), {+ const launch = windowsLaunch(command, args);+ const child = spawn(launch.file, launch.args, {cwd,env,- shell: true,+ shell: launch.shell,stdio: "inherit",windowsHide: true,});diff --git a/scripts/replace-process.test.ts b/scripts/replace-process.test.tsindex aea12687..371549ad 100644--- a/scripts/replace-process.test.ts+++ b/scripts/replace-process.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { windowsCommandLine } from "./replace-process.mjs";+import { windowsCommandLine, windowsLaunch } from "./replace-process.mjs";describe("windowsCommandLine", () => {it("quotes paths with spaces and leaves plain arguments alone", () => {@@ -19,3 +19,22 @@ describe("windowsCommandLine", () => {expect(() => windowsCommandLine("pnpm", [value])).toThrow(/Unsupported/);});});++describe("windowsLaunch", () => {+ it("runs a program file as a direct child, so it ends with its supervisor", () => {+ expect(+ windowsLaunch("C:\\Users\\Ada Lovelace\\linger\\teamhub.exe", ["-x"]),+ ).toEqual({+ file: "C:\\Users\\Ada Lovelace\\linger\\teamhub.exe",+ args: ["-x"],+ shell: false,+ });+ });+ it("resolves launchers such as pnpm through cmd.exe", () => {+ expect(windowsLaunch("pnpm", ["dev"])).toEqual({+ file: "pnpm dev",+ args: [],+ shell: true,+ });+ });+});