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(windows): retain unverifiable live service records and handle exiting services

Codexc04ea4292df8
diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.html
index 109de925..1f6464ec 100644
--- a/apps/desktop/src/shell/setup.html
+++ b/apps/desktop/src/shell/setup.html
@@ -2230,7 +2230,7 @@
const ALL_STEPS = [
["prepare", () => "Checking this computer"],
["download", () => "Downloading Linger " + state.version],
- ["services", () => "Starting services"],
+ ["services", () => "Setting up AI and local services"],
["workspace", () => "Setting up your account"],
[
"signin",
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 53353398..dcb15afd 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -162,8 +162,14 @@ 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
+program name alone, and never the installer or what started it. If the
+recorded PID and creation time still exist but the command line is missing,
+stop checks a fresh process listing: CIM can report that incomplete row once
+for an exiting process. If the same process remains without a matching lease,
+stop fails without signalling it and keeps the record. A start cannot replace
+it, and a PID reused by another process does not prevent discarding a stale
+record. 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. The
diff --git a/packages/local-installation/src/account.test.ts b/packages/local-installation/src/account.test.ts
index c82bddf4..1c06da3c 100644
--- a/packages/local-installation/src/account.test.ts
+++ b/packages/local-installation/src/account.test.ts
@@ -3,7 +3,6 @@ import {
mkdtemp,
readFile,
writeFile,
- stat,
rm,
symlink,
} from "node:fs/promises";
@@ -12,6 +11,10 @@ import path from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { ensureLocalAccount, localIdentityProof } from "./account.js";
import type { Instance } from "./instance.js";
+import {
+ expectPrivateFixtureFile,
+ shareFixtureFile,
+} from "./test-support/private-files.js";
const provisionOwner =
vi.fn<(email: string, password: string) => Promise<void>>();
@@ -86,7 +89,7 @@ it("creates the owner through stdin, confirms login and logs out before reusing
const saved = JSON.parse(await readFile(f.file, "utf8"));
expect(saved.password.length).toBeGreaterThanOrEqual(24);
expect(saved.provisioned).toBe(true);
- expect((await stat(f.file)).mode & 0o777).toBe(0o600);
+ await expectPrivateFixtureFile(f.file);
expect(requests).toEqual([
"/v0/auth/login",
"/v0/auth/login",
@@ -249,8 +252,7 @@ it("provides credentials only through a validated private login read", async ()
password: "a-private-password",
});
- const { chmod } = await import("node:fs/promises");
- await chmod(f.file, 0o644);
+ await shareFixtureFile(f.file);
await expect(readLocalLogin(f.instance)).rejects.toThrow(/private/);
});
it("rejects invalid custom credentials before writing or calling the account service", async () => {
@@ -311,8 +313,7 @@ it("reads the server identity from the private instance files", async () => {
teamhub: "http://127.0.0.1:4100",
key,
});
- const { chmod } = await import("node:fs/promises");
- await chmod(keyFile, 0o644);
+ await shareFixtureFile(keyFile);
await expect(readLocalIdentity(f.instance)).rejects.toThrow(/private/);
});
diff --git a/packages/local-installation/src/computer.test.ts b/packages/local-installation/src/computer.test.ts
index 70eeaa69..25683d00 100644
--- a/packages/local-installation/src/computer.test.ts
+++ b/packages/local-installation/src/computer.test.ts
@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import * as processes from "./process.js";
+import * as windowsPrivacy from "./windows-private.js";
import { writeSetupChoice } from "./setup-selection.js";
import { initializeInstance } from "./instance.js";
import {
@@ -382,18 +383,19 @@ it("waits through two connecting observations after one start without repeating
});
it("preserves cancellation while waiting for the started Computer Gateway", async () => {
- const f = await connectingFixture(() => "connecting");
const controller = new AbortController();
- const connecting = connectComputer(f.instance, {
- interactive: false,
- signal: controller.signal,
- });
- const assertion = expect(connecting).rejects.toMatchObject({
- name: "AbortError",
+ const f = await connectingFixture((call) => {
+ // The first observation precedes daemon start. Abort during the next one.
+ if (call === 2) controller.abort();
+ return "connecting";
});
- await vi.waitFor(() => expect(f.statuses()).toBeGreaterThanOrEqual(2));
- controller.abort();
- await assertion;
+ await expect(
+ connectComputer(f.instance, {
+ interactive: false,
+ signal: controller.signal,
+ }),
+ ).rejects.toMatchObject({ name: "AbortError" });
+ expect(f.statuses()).toBe(2);
expect(
f.process.mock.calls.filter(
([, args]) => args.slice(0, 2).join(" ") === "daemon start",
@@ -516,6 +518,10 @@ it("reports the actual Gateway connection separately when disconnected", async (
});
it("refreshes an idle instance after a private runtime is installed and preserves its identity", async () => {
+ // This test exercises the refresh and credential-binding logic through a
+ // mocked CLI. Keep real ACL coverage in the Windows private-state tests.
+ if (process.platform === "win32")
+ vi.spyOn(windowsPrivacy, "windowsPrivatePath").mockResolvedValue();
const f = await fixture();
const personalAuth = path.join(f.instance.root, "personal-auth.json");
await writeFile(personalAuth, "unchanged-personal-credentials", {
diff --git a/packages/local-installation/src/local-enrollment.test.ts b/packages/local-installation/src/local-enrollment.test.ts
index 03b9954e..459fe4ca 100644
--- a/packages/local-installation/src/local-enrollment.test.ts
+++ b/packages/local-installation/src/local-enrollment.test.ts
@@ -1,10 +1,11 @@
-import { mkdtemp, readFile, writeFile, stat, rm } from "node:fs/promises";
+import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { createHash } from "node:crypto";
import { afterEach, expect, it, vi } from "vitest";
import type { Instance } from "./instance.js";
import { prepareLocalEnrollment } from "./local-enrollment.js";
+import { expectPrivateFixtureFile } from "./test-support/private-files.js";
const roots: string[] = [];
afterEach(async () => {
vi.unstubAllGlobals();
@@ -88,7 +89,7 @@ it("authorizes through the local owner session, persists one private PKCE token,
expect(token.origin).toBe(f.instance.origin);
expect(token.tenant_id).toBe("tenant-one");
expect(token.code_verifier).toHaveLength(43);
- expect((await stat(file)).mode & 0o777).toBe(0o600);
+ await expectPrivateFixtureFile(file);
const enrollment = requests.find((r) =>
r.url.endsWith("/local-computer-enrollments"),
)!;
diff --git a/packages/local-installation/src/native-process-win32.test.ts b/packages/local-installation/src/native-process-win32.test.ts
index 345eee84..4ef2b7b7 100644
--- a/packages/local-installation/src/native-process-win32.test.ts
+++ b/packages/local-installation/src/native-process-win32.test.ts
@@ -12,6 +12,7 @@ import type {
// object ends along with it) from the next snapshot.
const host = vi.hoisted(() => ({
processes: [] as WindowsProcess[],
+ exiting: [] as WindowsProcess[],
listeners: new Map<number, number>(),
listenersAvailable: true,
ended: [] as number[],
@@ -20,7 +21,10 @@ const host = vi.hoisted(() => ({
vi.mock("./native-process-identity.js", async (original) => {
const actual =
await original<typeof import("./native-process-identity.js")>();
- const windowsProcesses = async () => [...host.processes];
+ const windowsProcesses = async () => [
+ ...host.processes,
+ ...host.exiting.splice(0),
+ ];
const windowsSnapshot = async (): Promise<WindowsSnapshot> => {
if (!host.listenersAvailable) throw new Error("Cannot read TCP listeners");
return {
@@ -69,6 +73,7 @@ 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.exiting = [];
host.listeners = new Map();
host.listenersAvailable = true;
host.ended = [];
@@ -150,6 +155,43 @@ test("stop ends the whole tree leaves first and forgets the record without liste
).rejects.toThrow();
});
+test.each([
+ ["a different lease", () => worker(10, "web", "c".repeat(64))],
+ ["an unreadable command line", () => row(10, 1, 100)],
+])(
+ "stop retains the live record with %s and signals nothing",
+ async (_, supervisor) => {
+ await record("web", 10);
+ host.processes.push(supervisor(), row(11, 10, 101, "web.exe"));
+ const file = path.join(root, "native/processes/web.json");
+ const original = await readFile(file, "utf8");
+
+ await expect(stopNativeProcess(root, "web")).rejects.toThrow(
+ /identity cannot be verified.*record retained/i,
+ );
+ expect(host.ended).toEqual([]);
+ expect(taskkill.calls).toEqual([]);
+ await expect(readFile(file, "utf8")).resolves.toBe(original);
+ },
+);
+
+test("stop verifies that an exiting supervisor's incomplete CIM row disappears", async () => {
+ await record("web", 10);
+ const supervisor = worker(10, "web");
+ host.processes.push(supervisor);
+ vi.mocked(process.kill).mockImplementationOnce((pid) => {
+ host.ended.push(pid);
+ host.processes = host.processes.filter((entry) => entry.pid !== pid);
+ host.exiting.push({ ...supervisor, command: "" });
+ return true;
+ });
+
+ await stopNativeProcess(root, "web");
+ expect(host.ended).toEqual([10]);
+ expect(taskkill.calls).toEqual([]);
+ expect((await inspectNativeProcess(root, "web")).pid).toBeUndefined();
+});
+
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"));
diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.ts
index 2e874ae6..219158af 100644
--- a/packages/local-installation/src/native-process.ts
+++ b/packages/local-installation/src/native-process.ts
@@ -580,6 +580,36 @@ function terminate(pid: number) {
export function windowsTerminationOrder(tree: WindowsProcess[]): number[] {
return tree.map((candidate) => candidate.pid).reverse();
}
+async function windowsStopSnapshot(
+ name: NativeService,
+ lease: string,
+ record?: Pick<Lease, "pid" | "birth">,
+): Promise<{ snapshot: WindowsProcess[]; tree: WindowsProcess[] }> {
+ const read = async () => {
+ const snapshot = await windowsProcesses();
+ const tree = windowsLeaseTree(snapshot, lease);
+ const unverified =
+ record && tree[0]?.pid !== record.pid
+ ? snapshot.find(
+ ({ pid, created }) =>
+ pid === record.pid && `win32:${pid}:${created}` === record.birth,
+ )
+ : undefined;
+ return { snapshot, tree, unverified };
+ };
+ let current = await read();
+ // If a process exits during CIM enumeration, its PID and birth can still
+ // appear in that snapshot even though its command line could not be read.
+ // A fresh snapshot distinguishes that from a live, unverifiable process.
+ if (current.unverified?.command === "") current = await read();
+ if (current.unverified) {
+ throw new Error(
+ `Native ${name} process identity cannot be verified; identity record retained.`,
+ );
+ }
+ return current;
+}
+
/**
* 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
@@ -596,11 +626,10 @@ async function stopWindowsTree(
) {
const deadline = Date.now() + 12_000;
for (;;) {
- const snapshot = (await windowsSnapshot()).processes;
- const tree = windowsLeaseTree(snapshot, lease);
+ const { snapshot, tree } = await windowsStopSnapshot(name, lease, record);
if (!tree.length) return;
if (Date.now() >= deadline) {
- if (record && (await endRecordedTree(record, snapshot))) return;
+ if (record && (await endRecordedTree(name, record, snapshot))) return;
throw new Error(`Native ${name} did not stop; identity record retained.`);
}
const order = windowsTerminationOrder(tree);
@@ -618,6 +647,7 @@ async function stopWindowsTree(
* nothing under the lease is left afterwards.
*/
async function endRecordedTree(
+ name: NativeService,
record: Pick<Lease, "pid" | "birth" | "lease">,
snapshot: WindowsProcess[],
): Promise<boolean> {
@@ -634,10 +664,7 @@ async function endRecordedTree(
}).catch(() => undefined);
const deadline = Date.now() + 3_000;
for (;;) {
- const tree = windowsLeaseTree(
- (await windowsSnapshot()).processes,
- record.lease,
- );
+ const { tree } = await windowsStopSnapshot(name, record.lease, record);
if (!tree.length) return true;
if (Date.now() >= deadline) return false;
await delay(100);
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index 2c40150d..b9cf7919 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -1245,6 +1245,66 @@ async function bundledRuntime(repo: string) {
return directory;
}
+test("native timings count only Runtime work that outlasts PostgreSQL", async () => {
+ const f = await fixture();
+ let clock = 0;
+ let startRuntime!: () => void;
+ let finishRuntime!: () => void;
+ const runtimeStarted = new Promise<void>((resolve) => {
+ startRuntime = resolve;
+ });
+ const runtimeFinished = new Promise<void>((resolve) => {
+ finishRuntime = resolve;
+ });
+ vi.mocked(prepareRuntime).mockImplementation(async (_runtime, options) => {
+ options.onEvent?.({
+ kind: "stage",
+ stage: "runtime",
+ state: "running",
+ message: "Preparing Pi…",
+ });
+ startRuntime();
+ await runtimeFinished;
+ return { code: 0, state: "ready", message: "ready" };
+ });
+ vi.mocked(prepareNativeDatabase).mockImplementation(async () => {
+ await runtimeStarted;
+ clock += 3000;
+ f.running.add("postgres");
+ // Let the install reach its Runtime wait before completing the probe.
+ setImmediate(() => {
+ clock += 7000;
+ finishRuntime();
+ });
+ return {};
+ });
+ const run = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) clock += 2000;
+ return run(command, args, options);
+ });
+ const runtimeStages: InstallerEvent["state"][] = [];
+ const result = await installNativeSource(
+ {
+ ...f,
+ name: "native-timings",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: (event) => {
+ if (event.kind === "stage" && event.stage === "runtime")
+ runtimeStages.push(event.state);
+ },
+ },
+ () => clock,
+ );
+ expect(result).toMatchObject({
+ code: 0,
+ details: { timings: { services: 5, runtime: 7 } },
+ });
+ expect(runtimeStages).toEqual(["running", "succeeded"]);
+});
+
test("bundled services that verify install no packages and record stage times", async () => {
const f = await fixture();
await bundledRuntime(f.repo);
@@ -1295,6 +1355,7 @@ test("bundled services that verify install no packages and record stage times",
expect.arrayContaining(["preflight", "release", "images", "services"]),
);
expect(Object.values(timings).every((seconds) => seconds > 0)).toBe(true);
+ expect(timings).not.toHaveProperty("runtime");
expect(
logs.some((line) => line.startsWith("Native install timings (s): ")),
).toBe(true);
diff --git a/packages/local-installation/src/native-source.test.ts b/packages/local-installation/src/native-source.test.ts
index a3efbaa1..b66d74ff 100644
--- a/packages/local-installation/src/native-source.test.ts
+++ b/packages/local-installation/src/native-source.test.ts
@@ -79,18 +79,30 @@ test("native checkout identities are stable", async () => {
expect(first.env.TEAMHUB_DATABASE_URL).toContain(
`:${first.instance.source!.ports.postgres}/simplexai`,
);
- const text = await readFile(
- path.join(first.instance.root, "native.env"),
- "utf8",
- );
+ const nativeFile = path.join(first.instance.root, "native.env");
+ const previous = parseEnv(await readFile(nativeFile, "utf8"));
const second = await prepareNativeConfiguration(f.repo, {
home: f.home,
name: "native-test",
});
expect(second.instance).toEqual(first.instance);
- expect(
- await readFile(path.join(first.instance.root, "native.env"), "utf8"),
- ).toBe(text);
+
+ // LiveKit is stopped in this fixture. Its unbound port can be taken between
+ // preparations without changing the instance's identity or credentials.
+ const liveKit = (await readLiveKitSettings(second.instance.root))!;
+ const expected: Record<string, string> = {
+ ...previous,
+ LIVEKIT_URL: `ws://127.0.0.1:${liveKit.httpPort}`,
+ LIVEKIT_API_URL: `http://127.0.0.1:${liveKit.httpPort}`,
+ };
+ if (expected.LIVEKIT_URL !== previous.LIVEKIT_URL)
+ expect(second.warnings).toContain(
+ `Port ${new URL(previous.LIVEKIT_URL!).port} is in use by another program; Linger's livekit uses port ${liveKit.httpPort} instead.\n`,
+ );
+ const current = parseEnv(await readFile(nativeFile, "utf8"));
+ const keys = new Set([...Object.keys(expected), ...Object.keys(current)]);
+ // Only name changed fields on failure; native.env also contains secrets.
+ expect([...keys].filter((key) => current[key] !== expected[key])).toEqual([]);
});
test.each(["O'Neil", "O'Neil`files"])(
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index e4f26399..85c0562a 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -479,6 +479,7 @@ async function runNativeSource(
const started: NativeService[] = [];
let runtimeOutcome: InstallOutcome | undefined;
let runtimeError: unknown;
+ let runtimePending = true;
const runtime = (async () => {
try {
if (options.byok) {
@@ -549,6 +550,8 @@ async function runNativeSource(
} catch (error) {
runtimeError = error;
controller.abort();
+ } finally {
+ runtimePending = false;
}
})();
try {
@@ -856,8 +859,11 @@ async function runNativeSource(
});
// The runtime is ready before the checkout's migrations run: when it is
// not, services still running from an earlier checkout keep the
- // schema they know.
+ // schema they know. Count only the wait beyond the parallel work and
+ // keep the progress events that the runtime itself reports.
+ if (runtimePending) timer.enter("runtime");
await runtime;
+ timer.enter("services");
signal.throwIfAborted();
await command("migrate");
step("services", "Starting native collaboration services…");
diff --git a/packages/local-installation/src/source-computer.test.ts b/packages/local-installation/src/source-computer.test.ts
index be0a27b8..f9fd3fea 100644
--- a/packages/local-installation/src/source-computer.test.ts
+++ b/packages/local-installation/src/source-computer.test.ts
@@ -6,6 +6,18 @@ import type { Instance } from "./instance.js";
import { runProcess } from "./process.js";
import { prepareSourceComputer } from "./source-computer.js";
vi.mock("./process.js", () => ({ runProcess: vi.fn() }));
+// Fake the Computer CLI and its installer, not Windows' private-path probe.
+vi.mock("./windows-private.js", async (original) => {
+ const actual = await original<typeof import("./windows-private.js")>();
+ const { runProcess } =
+ await vi.importActual<typeof import("./process.js")>("./process.js");
+ const windowsPrivatePath: typeof actual.windowsPrivatePath = (
+ file,
+ kind,
+ repair,
+ ) => actual.windowsPrivatePath(file, kind, repair, runProcess);
+ return { ...actual, windowsPrivatePath };
+});
const roots: string[] = [];
afterEach(async () => {
vi.resetAllMocks();
diff --git a/packages/local-installation/src/test-support/private-files.ts b/packages/local-installation/src/test-support/private-files.ts
new file mode 100644
index 00000000..8f971d81
--- /dev/null
+++ b/packages/local-installation/src/test-support/private-files.ts
@@ -0,0 +1,49 @@
+import { chmod, stat } from "node:fs/promises";
+import path from "node:path";
+import { expect } from "vitest";
+import { runProcess } from "../process.js";
+import { windowsPrivatePath } from "../windows-private.js";
+
+export async function expectPrivateFixtureFile(file: string): Promise<void> {
+ if (process.platform === "win32") {
+ await expect(windowsPrivatePath(file, "file")).resolves.toBeUndefined();
+ } else {
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ }
+}
+
+export async function shareFixtureFile(file: string): Promise<void> {
+ if (process.platform !== "win32") {
+ await chmod(file, 0o644);
+ return;
+ }
+ // Windows chmod only controls the read-only attribute. Grant another
+ // identity access to the synthetic fixture to test the actual DACL check.
+ const script = String.raw`
+$ErrorActionPreference = 'Stop'
+$env:PSModulePath = Join-Path $PSHOME 'Modules'
+[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
+$file = [Console]::In.ReadToEnd()
+$acl = Get-Acl -LiteralPath $file
+$everyone = [Security.Principal.SecurityIdentifier]::new('S-1-1-0')
+$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($everyone, 'Read', 'Allow'))
+[IO.FileInfo]::new($file).SetAccessControl($acl)
+`;
+ const result = await runProcess(
+ path.win32.join(
+ process.env.SystemRoot ?? "C:\\Windows",
+ "System32",
+ "WindowsPowerShell",
+ "v1.0",
+ "powershell.exe",
+ ),
+ [
+ "-NoProfile",
+ "-NonInteractive",
+ "-EncodedCommand",
+ Buffer.from(script, "utf16le").toString("base64"),
+ ],
+ { input: file, timeoutMs: 30_000 },
+ );
+ expect(result.code, result.stderr).toBe(0);
+}