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): repair native service checks, kit sealing and the Pi WSL launcher
Codex2bd51a4be3af
diff --git a/.gitattributes b/.gitattributesindex ca8a44e2..2683d0af 100644--- a/.gitattributes+++ b/.gitattributes@@ -1 +1,4 @@patches/*.patch -whitespace++# The test runner must be able to strip the hashbang when importing this script.+scripts/local-computer-node-distributions.mjs text eol=lfdiff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex e78578d0..4567f289 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -382,8 +382,10 @@ Gateway and runs Agents. The daemon exits with the app.controller under `runtime/model-services` (`foundations stop`), and to stopthe stack's processes and the gateway the tool started, the library'sBifrost included (`stack down`); it downloads nothing, and Linger does not- end the tool's processes itself. Every step runs even when an earlier one- fails.+ end the tool's processes itself. Every stop command runs even when an+ earlier command fails. A present tool kit that fails verification makes+ the stop fail, so the uninstaller retains the application for repair and+ retry.On Windows the tool cannot prove and end a controller from a kit that hasno stop command.A quit the person chose (the tray, the app menu, the Dock) does the same@@ -391,7 +393,9 @@ Gateway and runs Agents. The daemon exits with the app.that keep running: `LocalServer` starts `installer.js --home <defaulthome> --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, withits output in `<home>/installer/local-models-stop.log`, and does not wait- for it. It runs only when `desktop/local-server.json` names an+ for it. If the installed kit fails verification, the helper exits with a+ failure and logs the repair guidance; the app still quits, and no unverified+ tool runs. It runs only when `desktop/local-server.json` names aninstallation. The Computer exits with the app, so nothing uses the modelsuntil the next launch, whose resume applies the approved plan again eventhough the services still run, unless the person switched the Computer's@@ -445,7 +449,12 @@ home> --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, with4. The computer needs Codex or Claude Code installed and signed in; thedaemon finds them through the login shell PATH. The teamhub CLI runs onthe app's own Node (`ELECTRON_RUN_AS_NODE`) in packaged builds and on the- `node` in PATH from source.+ `node` in PATH from source. The Desktop TeamHub shell launcher uses+ `wslpath` and `WSLENV` when WSL starts the Windows executable, so the+ script path and `ELECTRON_RUN_AS_NODE` reach that process correctly.+ Arguments are forwarded unchanged: for a file flag like `--attach`,+ convert the Linux path explicitly with `wslpath -w` before passing it+ to Windows Node. Other arguments may be message text or remote paths.## Source Package and Releasediff --git a/apps/desktop/build.mjs b/apps/desktop/build.mjsindex 13d1c21e..804408e7 100644--- a/apps/desktop/build.mjs+++ b/apps/desktop/build.mjs@@ -301,15 +301,7 @@ const buildTeamhubCli = async () => {);await writeFile("dist/teamhub-cli/teamhub",- `#!/bin/sh-# Runs the bundled teamhub CLI with the Node built into Linger.-dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)-app="$dir/../../../../MacOS/Linger"-[ -x "$app" ] || app="$dir/../../../../Linger.exe"-[ -x "$app" ] || app="$dir/../../../../linger"-[ -x "$app" ] || app="\${LINGER_NODE:-node}"-ELECTRON_RUN_AS_NODE=1 exec "$app" --use-env-proxy "$dir/teamhub.js" "$@"-`,+ (await readFile("scripts/teamhub.sh", "utf8")).replace(/\r\n/g, "\n"),{ mode: 0o755 },);// The same for cmd and PowerShell on Windows, which run `teamhub.cmd`; Gitdiff --git a/apps/desktop/packaging/computer_tools_test.py b/apps/desktop/packaging/computer_tools_test.pyindex 4471793d..6be8d466 100644--- a/apps/desktop/packaging/computer_tools_test.py+++ b/apps/desktop/packaging/computer_tools_test.py@@ -21,6 +21,8 @@ HERE = os.path.dirname(os.path.abspath(__file__))MACHO = b"\xcf\xfa\xed\xfe" + b"\0" * 28PLAYWRIGHT_ENTRY = "node_modules/@playwright/mcp/cli.js"PI_EXTENSION = "extensions/pi-mcp.mjs"+# A native Windows checkout cannot set POSIX executable bits on fixtures.+HOST_FIXTURE_TARGET = "win32-x64" if os.name == "nt" else "linux-x64"# The pins the shared validator holds the manifest to.FROZEN = json.loads(subprocess.check_output(["node", "--input-type=module", "-e",@@ -81,8 +83,11 @@ class ComputerToolsTest(unittest.TestCase):def test_accepts_the_staged_tools_of_every_shipped_target(self):for target in ("darwin-arm64", "linux-x64", "win32-x64"):- resources, _ = self.resources(target)- computer_tools.verify(resources, target)+ with self.subTest(target=target):+ if os.name == "nt" and not target.startswith("win32-"):+ self.skipTest("Windows cannot make POSIX executable fixture files")+ resources, _ = self.resources(target)+ computer_tools.verify(resources, target)def test_rejects_resources_without_the_tools(self):resources = os.path.join(self.root, "resources")@@ -117,13 +122,14 @@ class ComputerToolsTest(unittest.TestCase):def test_copy_places_the_staged_tools_next_to_the_daemon_folder(self):staged = os.path.join(self.root, "dist", "computer-tools")- stage(os.path.join(staged, "linux-x64"), "linux-x64")+ target = HOST_FIXTURE_TARGET+ stage(os.path.join(staged, target), target)resources = os.path.join(self.root, "app", "resources")os.makedirs(resources)- computer_tools.copy(resources, "linux-x64", staged=staged)- computer_tools.verify(resources, "linux-x64")+ computer_tools.copy(resources, target, staged=staged)+ computer_tools.verify(resources, target)with self.assertRaises(SystemExit):- computer_tools.copy(resources, "win32-x64", staged=staged)+ computer_tools.copy(resources, "darwin-arm64", staged=staged)def test_refresh_records_only_resigned_macho_files(self):resources, tools = self.resources("darwin-arm64")@@ -135,16 +141,17 @@ class ComputerToolsTest(unittest.TestCase):with self.assertRaisesRegex(computer_tools.Invalid, "do not match their manifest"):computer_tools.verify(resources, "darwin-arm64")- resources, tools = self.resources("linux-x64")+ target = HOST_FIXTURE_TARGET+ resources, tools = self.resources(target)with open(os.path.join(tools, "node_modules/native/prebuilt.node"), "ab") as out:out.write(b"signature")computer_tools.refresh_signed(resources)- computer_tools.verify(resources, "linux-x64")+ computer_tools.verify(resources, target)with open(os.path.join(tools, PLAYWRIGHT_ENTRY), "ab") as out:out.write(b"//")computer_tools.refresh_signed(resources)with self.assertRaisesRegex(computer_tools.Invalid, "do not match their manifest"):- computer_tools.verify(resources, "linux-x64")+ computer_tools.verify(resources, target)def test_finished_archives_must_hold_the_tools(self):resources, _ = self.resources("linux-x64")diff --git a/apps/desktop/packaging/win/installer.nsi b/apps/desktop/packaging/win/installer.nsiindex 775ab958..52fd1811 100644--- a/apps/desktop/packaging/win/installer.nsi+++ b/apps/desktop/packaging/win/installer.nsi@@ -182,6 +182,10 @@ Function StopEarlierLingerIfFileExists "$INSTDIR\Linger.exe" 0 doneInitPluginsDirFile "/oname=$PLUGINSDIR\stop.mjs" "${STAGE}\resources\app\dist\installer\installer.js"+ ; The temporary script reads distribution.json beside itself. Use the+ ; installed release's pins, since those are the tools it started.+ IfFileExists "$INSTDIR\resources\app\dist\installer\distribution.json" 0 +2+ CopyFiles /SILENT "$INSTDIR\resources\app\dist\installer\distribution.json" "$PLUGINSDIR"StrCpy $R0 "$PLUGINSDIR\stop.mjs"Call StopLingerdone:diff --git a/apps/desktop/scripts/teamhub.sh b/apps/desktop/scripts/teamhub.shnew file mode 100644index 00000000..9783f58b--- /dev/null+++ b/apps/desktop/scripts/teamhub.sh@@ -0,0 +1,20 @@+#!/bin/sh+# Runs the bundled teamhub CLI with the Node built into Linger.+dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+app="$dir/../../../../MacOS/Linger"+[ -x "$app" ] || app="$dir/../../../../Linger.exe"+[ -x "$app" ] || app="$dir/../../../../linger"+[ -x "$app" ] || app="${LINGER_NODE:-node}"+script="$dir/teamhub.js"+case "$app" in+ *.exe)+ # WSL passes Linux paths as literal Windows arguments and only carries+ # explicitly listed Linux environment variables to Windows executables.+ if command -v wslpath >/dev/null 2>&1; then+ script=$(wslpath -w "$script") || exit 1+ WSLENV="${WSLENV:+$WSLENV:}ELECTRON_RUN_AS_NODE"+ export WSLENV+ fi+ ;;+esac+ELECTRON_RUN_AS_NODE=1 exec "$app" --use-env-proxy "$script" "$@"diff --git a/apps/desktop/src/main/build-teamhub.test.ts b/apps/desktop/src/main/build-teamhub.test.tsindex bc44b603..02af54fd 100644--- a/apps/desktop/src/main/build-teamhub.test.ts+++ b/apps/desktop/src/main/build-teamhub.test.ts@@ -1,6 +1,6 @@-import { execFileSync } from "node:child_process";+import { execFileSync, type SpawnOptions } from "node:child_process";+import { EventEmitter } from "node:events";import {- chmodSync,mkdirSync,mkdtempSync,readFileSync,@@ -9,6 +9,8 @@ import {} from "node:fs";import { tmpdir } from "node:os";import path from "node:path";+import { PassThrough } from "node:stream";+import { gzipSync } from "node:zlib";import { afterEach, expect, it, vi } from "vitest";@@ -18,15 +20,52 @@ import {verifyTeamhub,} from "../../scripts/build-teamhub.mjs";+// Keep Git's archive and tar's extraction real. Stub only Go compilation:+// an executable fixture implemented as a Node shebang cannot run on Windows.+vi.mock("node:child_process", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:child_process")>();+ return {+ ...actual,+ spawn: (command: string, args: string[], options: SpawnOptions) => {+ if (command !== "go") return actual.spawn(command, args, options);+ const child = new EventEmitter() as EventEmitter & {+ stdout: PassThrough;+ };+ child.stdout = new PassThrough();+ if (args[0] === "env" && args[1] === "GOVERSION") {+ process.nextTick(() => {+ child.stdout.end("go1.26.5\n");+ child.emit("close", 0);+ });+ } else {+ const output = args[args.indexOf("-o") + 1];+ if (args[0] !== "build" || !args.includes("-o") || !output)+ throw new Error("Unexpected Go invocation in build fixture");+ writeFileSync(+ output,+ JSON.stringify({+ args,+ goos: options.env?.GOOS,+ goarch: options.env?.GOARCH,+ cgo: options.env?.CGO_ENABLED,+ cwd: options.cwd,+ }),+ );+ process.nextTick(() => child.emit("close", 0));+ }+ return child;+ },+ };+});+const roots: string[] = [];afterEach(() => {- vi.unstubAllEnvs();for (const root of roots.splice(0))rmSync(root, { recursive: true, force: true });});// A source package as scripts/prepare-source-archive.mjs makes it, from a-// one-commit repository, and a `go` on PATH that records each build.+// one-commit repository.const fixture = () => {const root = mkdtempSync(path.join(tmpdir(), "build-teamhub-"));roots.push(root);@@ -46,33 +85,28 @@ const fixture = () => {"-qm","source",);+ const packageSource = (output: string, ref: string) => {+ const tar = execFileSync("git", [+ "-C",+ repo,+ "archive",+ "--format=tar",+ "--prefix=linger-test/",+ ref,+ ]);+ writeFileSync(output, gzipSync(tar));+ };const archive = path.join(root, "linger-test.tar.gz");- execFileSync("sh", [- "-c",- `git -C "${repo}" archive --format=tar --prefix=linger-test/ HEAD | gzip -n > "${archive}"`,- ]);- const bin = path.join(root, "bin");- mkdirSync(bin);- writeFileSync(- path.join(bin, "go"),- `#!${process.execPath}-const fs = require("node:fs");-const args = process.argv.slice(2);-if (args[0] === "env") { console.log("go1.26.5"); process.exit(0); }-const out = args[args.indexOf("-o") + 1];-fs.writeFileSync(out, JSON.stringify({ args, goos: process.env.GOOS, cgo: process.env.CGO_ENABLED, cwd: process.cwd() }));-`,- );- chmodSync(path.join(bin, "go"), 0o755);- vi.stubEnv("PATH", `${bin}${path.delimiter}${process.env.PATH}`);- return { root, archive, commit: git("rev-parse", "HEAD") };+ packageSource(archive, "HEAD");+ return { root, archive, packageSource, commit: git("rev-parse", "HEAD") };};it("reads the commit git archive records in a source package", async () => {const f = fixture();expect(await sourceCommit(f.archive)).toBe(f.commit);const plain = path.join(f.root, "plain.tar.gz");- execFileSync("tar", ["-czf", plain, "-C", f.root, "bin"]);+ // Git only adds the global commit header when given a commit, not a tree.+ f.packageSource(plain, "HEAD^{tree}");await expect(sourceCommit(plain)).rejects.toThrow("does not record its commit",);@@ -95,7 +129,7 @@ it("builds each TeamHub command for Windows from the source package", async () =const built = JSON.parse(readFileSync(path.join(output, "migrate.exe"), "utf8"),);- expect(built).toMatchObject({ goos: "windows", cgo: "0" });+ expect(built).toMatchObject({ goos: "windows", goarch: "amd64", cgo: "0" });expect(built.args).toEqual(["build","-trimpath",diff --git a/apps/desktop/src/main/computer-daemon.test.ts b/apps/desktop/src/main/computer-daemon.test.tsindex 8a7d0518..edf9a15e 100644--- a/apps/desktop/src/main/computer-daemon.test.ts+++ b/apps/desktop/src/main/computer-daemon.test.ts@@ -154,7 +154,8 @@ describe("ComputerDaemonModule", () => {LINGER_CODEX_PATH: "/opt/codex",[TOKEN_ENV]: TOKEN,});- expect(statSync(child!.configFile).mode & 0o777).toBe(0o600);+ if (process.platform !== "win32")+ expect(statSync(child!.configFile).mode & 0o777).toBe(0o600);const written = readFileSync(child!.configFile, "utf8");// The credential stays out of the config file.expect(written).not.toContain(TOKEN);diff --git a/apps/desktop/src/main/diagnostics.test.ts b/apps/desktop/src/main/diagnostics.test.tsindex 9db63bee..dcd3989c 100644--- a/apps/desktop/src/main/diagnostics.test.ts+++ b/apps/desktop/src/main/diagnostics.test.ts@@ -198,6 +198,7 @@ describe("collectDiagnostics", () => {homes: [home, home],output,summary: { version: "0.16.27" },+ userHome: path.join(root, "another-user"),now: new Date("2026-11-06T07:08:09Z"),});diff --git a/apps/desktop/src/main/legacy-bridge.test.ts b/apps/desktop/src/main/legacy-bridge.test.tsindex 132502b9..ff0b33ef 100644--- a/apps/desktop/src/main/legacy-bridge.test.ts+++ b/apps/desktop/src/main/legacy-bridge.test.ts@@ -107,13 +107,13 @@ describe.skipIf(process.platform === "win32")("legacy bridge socket", () => {describe("defaultBridgeStateDirectory", () => {it("matches the 0.16 bridge layout after the data folder moved", () => {expect(defaultBridgeStateDirectory("darwin", {}, "/Users/a")).toBe(- "/Users/a/Library/Application Support/Linger/bridge",+ path.normalize("/Users/a/Library/Application Support/Linger/bridge"),);expect(defaultBridgeStateDirectory("linux", {}, "/home/a")).toBe(- "/home/a/.local/state/simplex/bridge",+ path.normalize("/home/a/.local/state/simplex/bridge"),);expect(defaultBridgeStateDirectory("linux", { LINGER_BRIDGE_STATE_DIR: "/x" }),- ).toBe("/x");+ ).toBe(path.resolve("/x"));});});diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex b9ca15b1..11f6aa1a 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -2,7 +2,9 @@ import { execFileSync } from "node:child_process";import { createHash } from "node:crypto";import {chmodSync,+ copyFileSync,existsSync,+ linkSync,mkdirSync,readdirSync,readFileSync,@@ -15,7 +17,15 @@ import path from "node:path";import { setTimeout as delay } from "node:timers/promises";import { zstdCompressSync } from "node:zlib";-import { describe, expect, it, vi } from "vitest";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type MockInstance,+} from "vitest";import { NODE_RUNTIME_VERSION } from "../../../../scripts/local-computer-node-distributions.mjs";import { rename } from "node:fs/promises";@@ -45,6 +55,7 @@ import {type LocalServerOptions,} from "./local-server.js";import { localIdentityProof } from "@linger/local-installation/account";+import * as windowsPrivate from "@linger/local-installation/windows-private";import type { DesktopConfig } from "./config.js";import { EventBus, type ModuleContext } from "./modules.js";import {@@ -54,6 +65,13 @@ import {testHost,} from "./test-support.js";+// These tests run the installer stub in real subprocesses.+// Windows test hosts can take longer to launch them under load.+const isWindowsHost = process.platform === "win32";+if (isWindowsHost) vi.setConfig({ testTimeout: 20_000 });+const waitForInstaller = (check: () => unknown) =>+ vi.waitFor(check, { timeout: isWindowsHost ? 10_000 : 1_000 });+// Prints what the real installer prints and writes its private launcher.const FAKE_INSTALLER = String.raw`const fs = require("node:fs");@@ -338,6 +356,24 @@ const server = (origin: string): LocalServerIdentity => ({key: KEY,});+// The simulated runtime keeps its target layout, but the installer stub runs on+// the host. Windows can hardlink without Developer Mode and spawns the .exe.+const fixtureNode = (binary: string): void => {+ if (process.platform !== "win32") {+ symlinkSync(process.execPath, binary);+ return;+ }+ const put = (file: string) => {+ try {+ linkSync(process.execPath, file);+ } catch {+ copyFileSync(process.execPath, file);+ }+ };+ put(binary);+ if (path.extname(binary) !== ".exe") put(binary + ".exe");+};+const fixture = (overrides:| Partial<LocalServerOptions>@@ -370,7 +406,7 @@ const fixture = ();const node = path.join(home, "desktop", "node", `v${NODE_RUNTIME_VERSION}`);mkdirSync(path.join(node, "bin"), { recursive: true });- symlinkSync(process.execPath, path.join(node, "bin", "node"));+ fixtureNode(path.join(node, "bin", "node"));prepare(home);const setServer = vi.fn(() => true);const showUpdating = vi.fn();@@ -722,7 +758,7 @@ describe("LocalServerModule", () => {);await f.host.start();const done = f.module.begin();- await vi.waitFor(() => expect(f.module.status().step).toBe("signin"));+ await waitForInstaller(() => expect(f.module.status().step).toBe("signin"));expect(f.module.status()).toMatchObject({phase: "installing",message: "Sign in to Codex",@@ -745,7 +781,7 @@ describe("LocalServerModule", () => {url: "https://auth.openai.com/codex/device",deviceCode: "ABCD-1234",});- await vi.waitFor(() => expect(openExternal).toHaveBeenCalledTimes(1));+ await waitForInstaller(() => expect(openExternal).toHaveBeenCalledTimes(1));expect(openExternal).toHaveBeenCalledWith("https://auth.openai.com/codex/device",);@@ -790,7 +826,7 @@ describe("LocalServerModule", () => {);await f.host.start();const done = f.module.begin();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().signIn).toEqual({runtime: "claude",state: "required",@@ -868,7 +904,7 @@ describe("LocalServerModule", () => {);await f.host.start();const done = f.module.begin();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().signIn).toEqual({runtime: "pi",state: "failed",@@ -1110,7 +1146,7 @@ describe("LocalServerModule", () => {);await f.host.start();const setup = f.module.begin();- await vi.waitFor(() => expect(polls.anotherMe).toBeGreaterThan(0));+ await waitForInstaller(() => expect(polls.anotherMe).toBeGreaterThan(0));f.host.ctx.bus.emit("computer.failed","read Computer config: private path grants access to another user (S-1-5-11)",@@ -1146,7 +1182,7 @@ describe("LocalServerModule", () => {);await f.host.start();const setup = f.module.begin();- await vi.waitFor(() => expect(polls.anotherMe).toBeGreaterThan(0));+ await waitForInstaller(() => expect(polls.anotherMe).toBeGreaterThan(0));f.host.ctx.bus.emit("computer.connection", "identity_conflict");await expect(setup).rejects.toThrow(/already connected to another Computer registration/,@@ -1479,7 +1515,7 @@ describe("LocalServerModule", () => {writeFileSync(path.join(bundle, "runtime", "files.json"), files);writeFileSync(path.join(bundle, "runtime", "web", "static-host.mjs"), "");// The signed binary; here the Node.js running the tests.- symlinkSync(process.execPath, path.join(bundle, "node", "bin", "node"));+ fixtureNode(path.join(bundle, "node", "bin", "node"));const sha256 = (data: string | Buffer) =>createHash("sha256").update(data).digest("hex");writeFileSync(@@ -1508,8 +1544,8 @@ describe("LocalServerModule", () => {}).begin().catch(() => undefined);- expect(realpathSync(path.join(node(f.home), "bin", "node"))).toBe(- realpathSync(process.execPath),+ expect(sha256(readFileSync(path.join(node(f.home), "bin", "node")))).toBe(+ sha256(readFileSync(process.execPath)),);const args = installerArgs(f.home);const offline = path.join(@@ -1534,7 +1570,7 @@ describe("LocalServerModule", () => {f.module.inspect();expect(f.module.status().localModels).toEqual({ state: "checking" });f.module.inspect();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toEqual({state: "checked",eligible: true,@@ -1567,7 +1603,7 @@ describe("LocalServerModule", () => {});await f.host.start();f.module.inspect();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toEqual({ state: "unavailable" }),);expect(warn).toHaveBeenCalledWith(@@ -1590,14 +1626,14 @@ describe("LocalServerModule", () => {});await f.host.start();f.module.inspect();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toEqual({state: "checking",download: { completed: 5, total: 10 },}),);writeFileSync(path.join(f.home, "tool-ready"), "");- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toMatchObject({state: "checked",recommendation: "local-models",@@ -1612,7 +1648,7 @@ describe("LocalServerModule", () => {});await f.host.start();f.module.inspect();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toMatchObject({state: "checked",eligible: false,@@ -1629,7 +1665,7 @@ describe("LocalServerModule", () => {});await f.host.start();f.module.inspect();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toMatchObject({state: "checked",eligible: false,@@ -1658,7 +1694,7 @@ describe("LocalServerModule", () => {});await f.host.start();f.module.inspect();- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toMatchObject({state: "checked",eligible: false,@@ -1686,7 +1722,7 @@ describe("LocalServerModule", () => {rmSync(path.join(f.home, "low-memory"));f.module.recheck();expect(f.module.status().localModels).toEqual({ state: "checking" });- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(f.module.status().localModels).toMatchObject({state: "checked",eligible: true,@@ -2279,7 +2315,7 @@ describe("LocalServerModule install location", () => {await f.host.stop("quit");});- it("keeps the default when the picked folder cannot be used", async () => {+ it("creates the picked folder and can restore the default", async () => {const f = fixture({ checkout: "/src" });await f.host.start();await f.module.chooseLocation(path.join(f.root, "missing", "deeper"));@@ -2293,19 +2329,30 @@ describe("LocalServerModule install location", () => {path: f.home,custom: false,});- if (process.getuid?.() === 0) return;- const locked = path.join(f.root, "locked");- mkdirSync(locked, { mode: 0o500 });- await f.module.chooseLocation(locked);- expect(f.module.status().location).toEqual({- path: f.home,- custom: false,- error: "Linger can't write to this folder. Choose another one.",- });- chmodSync(locked, 0o700);await f.host.stop("quit");});+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(+ "rejects a folder without POSIX write permission",+ async () => {+ const f = fixture({ checkout: "/src" });+ const locked = path.join(f.root, "locked");+ mkdirSync(locked, { mode: 0o500 });+ await f.host.start();+ try {+ await f.module.chooseLocation(locked);+ expect(f.module.status().location).toEqual({+ path: f.home,+ custom: false,+ error: "Linger can't write to this folder. Choose another one.",+ });+ } finally {+ chmodSync(locked, 0o700);+ await f.host.stop("quit");+ }+ },+ );+it("installs into an empty folder or one that holds Linger", async () => {const root = tempDirectory();expect(await installLocation(root)).toBe(root);@@ -2348,7 +2395,7 @@ describe("LocalServerModule after a restart", () => {it("starts the installed services again for the local server", async () => {const f = fixture({}, enrolled, record);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(f.setServer).toHaveBeenCalledWith("http://localhost:3000","http://localhost:3000",@@ -2374,7 +2421,7 @@ describe("LocalServerModule after a restart", () => {writeFileSync(path.join(home, "resume-origin"), "http://localhost:3001");});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));// The same server at a new origin: the window follows it as a move,// which keeps this computer's enrollment.expect(f.setServer).toHaveBeenCalledWith(@@ -2398,10 +2445,10 @@ describe("LocalServerModule after a restart", () => {const stopped = (home: string) => path.join(home, "stop-local-models.json");const f = fixture({}, enrolled, record);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));await f.host.stop("quit");// It runs on after the app is gone; its outcome goes to the log.- await vi.waitFor(() =>+ await waitForInstaller(() =>expect(readFileSync(path.join(f.home, "installer", "local-models-stop.log"),@@ -2418,7 +2465,9 @@ describe("LocalServerModule after a restart", () => {it("leaves the local models running for an update, and stops none without an installation", async () => {const update = fixture({}, enrolled, record);await update.host.start();- await vi.waitFor(() => expect(update.module.status().phase).toBe("ready"));+ await waitForInstaller(() =>+ expect(update.module.status().phase).toBe("ready"),+ );await update.host.stop("update");const none = fixture();await none.host.start();@@ -2442,7 +2491,7 @@ describe("LocalServerModule after a restart", () => {);});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const source = path.join(f.home, "desktop", "source", "previous");expect(existsSync(path.join(source, ".env"))).toBe(false);const user = readFileSync(@@ -2475,7 +2524,7 @@ describe("LocalServerModule after a restart", () => {);});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(existsSync(path.join(f.home, "src", ".env"))).toBe(true);expect(existsSync(path.join(f.home, "instances", LOCAL_INSTANCE, "user.env")),@@ -2517,7 +2566,7 @@ describe("LocalServerModule after a restart", () => {const restarts = vi.fn();f.bus.on("computer.runtime", restarts);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(f.host.ctx.config.get().runtimeEnvironment).toEqual(environment);expect(restarts).toHaveBeenCalledTimes(1);await f.host.stop("quit");@@ -2537,7 +2586,7 @@ describe("LocalServerModule after a restart", () => {);});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const args = installerArgs(elsewhere);expect(args[args.indexOf("--home") + 1]).toBe(elsewhere);expect(args).toContain("--resume");@@ -2580,7 +2629,7 @@ describe("LocalServerModule after a restart", () => {const archive = sourceArchive(root);const f = installedBy(archive);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const sources = path.join(f.home, "desktop", "source");const current = path.join(sources, archive.sha256.slice(0, 16));const args = installerArgs(f.home);@@ -2613,12 +2662,14 @@ describe("LocalServerModule after a restart", () => {const f = installedBy(archive);writeFileSync(path.join(f.home, "resume-fails"), "");await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );expect(f.showStartFailed).toHaveBeenCalledWith("Native teamhub stopped");// Try Again moves them once more.rmSync(path.join(f.home, "resume-fails"));f.bus.emit("local-server.retry");- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const args = installerArgs(f.home);expect(args[args.indexOf("--source-repo") + 1]).toBe(path.join(f.home, "desktop", "source", archive.sha256.slice(0, 16)),@@ -2636,13 +2687,17 @@ describe("LocalServerModule after a restart", () => {// The move stopped before the restart (the local model was not ready).writeFileSync(path.join(f.home, "resume-fails"), "");await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );// Try Again: the installer answers but the services still run from the// older folder.rmSync(path.join(f.home, "resume-fails"));writeFileSync(path.join(f.home, "resume-serving"), previous);f.bus.emit("local-server.retry");- await vi.waitFor(() => expect(f.showStartFailed).toHaveBeenCalledTimes(2));+ await waitForInstaller(() =>+ expect(f.showStartFailed).toHaveBeenCalledTimes(2),+ );expect(f.module.status().phase).toBe("failed");expect(f.setServer).not.toHaveBeenCalled();expect(@@ -2657,7 +2712,7 @@ describe("LocalServerModule after a restart", () => {// one goes.rmSync(path.join(f.home, "resume-serving"));f.bus.emit("local-server.retry");- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(JSON.parse(readFileSync(path.join(f.home, "desktop", "local-server.json"), "utf8"),@@ -2699,7 +2754,7 @@ describe("LocalServerModule after a restart", () => {},);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const args = installerArgs(f.home);expect(args[args.indexOf("--source-repo") + 1]).toBe(repo(f.home));expect(f.showUpdating).not.toHaveBeenCalled();@@ -2739,7 +2794,7 @@ describe("LocalServerModule after a restart", () => {},);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const newer = path.join(f.home, "desktop", "source", "newer");const args = installerArgs(f.home);expect(args[args.indexOf("--source-repo") + 1]).toBe(newer);@@ -2766,7 +2821,9 @@ describe("LocalServerModule after a restart", () => {writeFileSync(path.join(home, "resume-fails"), "");});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );expect(f.module.status().message).toBe("Native teamhub stopped");expect(f.setServer).not.toHaveBeenCalled();expect(f.showStartFailed).toHaveBeenCalledWith("Native teamhub stopped");@@ -2796,7 +2853,9 @@ describe("LocalServerModule after a restart", () => {);});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );expect(f.showStartFailed).toHaveBeenCalledWith(`The local model stack is not ready. ${action}`,);@@ -2820,7 +2879,9 @@ describe("LocalServerModule after a restart", () => {);});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );expect(f.showStartFailed).toHaveBeenCalledWith("The local model's Pi can't load extensions, which every Linger run needs. The upstream tool could not verify the local stack binding. Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.",);@@ -2833,10 +2894,12 @@ describe("LocalServerModule after a restart", () => {writeFileSync(path.join(home, "resume-fails"), "");});await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );rmSync(path.join(f.home, "resume-fails"));f.bus.emit("local-server.retry");- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(f.setServer).toHaveBeenCalledWith("http://localhost:3000","http://localhost:3000",@@ -2855,7 +2918,7 @@ describe("LocalServerModule after a restart", () => {record,);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(f.showStarting).not.toHaveBeenCalled();await f.host.stop("quit");});@@ -2919,7 +2982,7 @@ describe("LocalServerModule after a restart", () => {},);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const args = installerArgs(f.home);expect(args[args.indexOf("--source-repo") + 1]).toBe(repo(f.home));expect(@@ -2958,7 +3021,7 @@ describe("LocalServerModule after a restart", () => {},);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const args = installerArgs(f.home);expect(args[args.indexOf("--source-repo") + 1]).toBe(repo(f.home));expect(@@ -2994,7 +3057,7 @@ describe("LocalServerModule after a restart", () => {},);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));const sources = path.join(f.home, "desktop", "source");const current = path.join(sources, archive.sha256.slice(0, 16));const args = installerArgs(f.home);@@ -3040,7 +3103,7 @@ describe("LocalServerModule after a restart", () => {},);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(instanceProject(f.home)).toBe("linger-desktop-1");expect(instanceProject(chosen)).toBe("linger-desktop-1");const current = path.join(@@ -3091,14 +3154,18 @@ describe("LocalServerModule after a restart", () => {};const unused = fixture({}, enrolled, setup("default"));await unused.host.start();- await vi.waitFor(() => expect(unused.module.status().phase).toBe("ready"));+ await waitForInstaller(() =>+ expect(unused.module.status().phase).toBe("ready"),+ );expect(instanceProject(unused.home)).toBe("simplex-desktop-1");await unused.host.stop("quit");rmSync(chosen, { recursive: true });const used = fixture({}, enrolled, setup("chosen"));await used.host.start();- await vi.waitFor(() => expect(used.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(used.module.status().phase).toBe("failed"),+ );expect(used.module.status().message).toMatch(/could not convert this computer's installation.*running 1 task/,);@@ -3115,9 +3182,11 @@ describe("LocalServerModule after a restart", () => {const opened = vi.fn();f.bus.on("setup.open", opened);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );f.bus.emit("local-server.reset");- await vi.waitFor(() => expect(opened).toHaveBeenCalledOnce());+ await waitForInstaller(() => expect(opened).toHaveBeenCalledOnce());expect(f.module.status().phase).toBe("idle");expect(existsSync(path.join(f.home, "desktop", "local-server.json"))).toBe(false,@@ -3156,7 +3225,7 @@ describe("LocalServerModule after a restart", () => {);const node = path.join(home, "desktop", "node", `v${NODE_RUNTIME_VERSION}`);mkdirSync(path.join(node, "bin"), { recursive: true });- symlinkSync(process.execPath, path.join(node, "bin", "node"));+ fixtureNode(path.join(node, "bin", "node"));checkout(home);const daemonIdentityFile = path.join(root, "state", "daemon-identity.json");@@ -3338,7 +3407,7 @@ describe("LocalServerModule after a restart", () => {resetOccurred = true;bus.emit("local-server.reset");- await vi.waitFor(() => expect(opened).toHaveBeenCalledOnce());+ await waitForInstaller(() => expect(opened).toHaveBeenCalledOnce());expect(host.ctx.config.get().computerId).toBeUndefined();expect(host.ctx.config.get().serverUrl).toBeUndefined();expect(host.ctx.config.get().savedEnrollments).toEqual({@@ -3699,8 +3768,7 @@ describe("LocalServerModule on Windows", () => {});// Windows' Node runtime is node.exe at the top of its folder.const windowsNode = (home: string) =>- symlinkSync(- process.execPath,+ fixtureNode(path.join(home,"desktop",@@ -3790,6 +3858,17 @@ describe("LocalServerModule on Windows", () => {});describe("LocalServerModule owner account", () => {+ // The installer tests verify the actual Windows ACL policy. Here the+ // account reader still uses a real file, and we control the ACL decision.+ let acl: MockInstance<typeof windowsPrivate.windowsPrivatePath> | undefined;+ beforeEach(() => {+ if (process.platform === "win32")+ acl = vi+ .spyOn(windowsPrivate, "windowsPrivatePath")+ .mockResolvedValue(undefined);+ });+ afterEach(() => acl?.mockRestore());+const ORIGIN = "http://localhost:3000";const enrolled = { serverUrl: ORIGIN, computerId: "cmp_1" };const installed =@@ -3816,7 +3895,7 @@ describe("LocalServerModule owner account", () => {it("signs the window in to the installed server with the account file", async () => {const f = fixture({}, enrolled, installed(OWNER));await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(await f.module.servesWindow()).toBe(true);expect(await f.module.account()).toEqual({email: OWNER.email,@@ -3845,7 +3924,9 @@ describe("LocalServerModule owner account", () => {// Not started yet: nothing is serving the window.expect(await f.module.servesWindow()).toBe(false);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("failed"),+ );expect(await f.module.servesWindow()).toBe(false);await expect(f.module.signInWithAccount()).rejects.toThrow("This window is not showing the Linger on this computer.",@@ -3871,7 +3952,7 @@ describe("LocalServerModule owner account", () => {const f = fixture({}, enrolled, installed(OWNER));f.signIn.mockRejectedValueOnce(error);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));await expect(f.module.signInWithAccount()).rejects.toThrow(message);await f.host.stop("quit");});@@ -3882,7 +3963,9 @@ describe("LocalServerModule owner account", () => {try {const f = fixture({}, enrolled, installed(OWNER));await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("ready"),+ );expect(await f.module.servesWindow()).toBe(true);expect(f.proveServer).toHaveBeenLastCalledWith(server(ORIGIN));// The services stopped, or another program took the port.@@ -3918,7 +4001,7 @@ describe("LocalServerModule owner account", () => {installed(OWNER),);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() => expect(f.module.status().phase).toBe("ready"));expect(await f.module.servesWindow()).toBe(false);await expect(f.module.signInWithAccount()).rejects.toThrow("Linger on this computer is not responding.",@@ -3958,11 +4041,6 @@ describe("LocalServerModule owner account", () => {installed(),/^The account file of Linger on this computer is missing \(.*local-account\.json\)\.$/,],- [- "readable by others",- installed(OWNER, 0o644),- "The local account file must be private and owned by the current user (chmod 600).",- ],["not provisioned",installed({ ...OWNER, provisioned: false }),@@ -3973,7 +4051,9 @@ describe("LocalServerModule owner account", () => {async (_case, prepare, message) => {const f = fixture({}, enrolled, prepare);await f.host.start();- await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("ready"),+ );const failure = f.module.signInWithAccount();await expect(failure).rejects.toThrow(message);await expect(failure).rejects.not.toThrow(OWNER.password);@@ -3981,6 +4061,27 @@ describe("LocalServerModule owner account", () => {await f.host.stop("quit");},);++ it("rejects an account file readable by others", async () => {+ const message =+ process.platform === "win32"+ ? "Windows private path validation failed: the account file is shared with other accounts."+ : "The local account file must be private and owned by the current user (chmod 600).";+ acl?.mockRejectedValueOnce(new Error(message));+ const f = fixture({}, enrolled, installed(OWNER, 0o644));+ await f.host.start();+ try {+ await waitForInstaller(() =>+ expect(f.module.status().phase).toBe("ready"),+ );+ const failure = f.module.signInWithAccount();+ await expect(failure).rejects.toThrow(message);+ await expect(failure).rejects.not.toThrow(OWNER.password);+ expect(f.signIn).not.toHaveBeenCalled();+ } finally {+ await f.host.stop("quit");+ }+ });});describe("legacyMigrationResult", () => {diff --git a/apps/desktop/src/main/mac-permissions.test.ts b/apps/desktop/src/main/mac-permissions.test.tsindex 0041239f..e5f78b4e 100644--- a/apps/desktop/src/main/mac-permissions.test.ts+++ b/apps/desktop/src/main/mac-permissions.test.ts@@ -1,3 +1,5 @@+import path from "node:path";+import { describe, expect, it } from "vitest";import {@@ -47,7 +49,7 @@ describe("MacPermissions", () => {});// Listing Downloads or running AppleScript would show a system prompt.expect(calls).toEqual([- "open /Users/me/Library/Application Support/com.apple.TCC/TCC.db",+ `open ${path.normalize("/Users/me/Library/Application Support/com.apple.TCC/TCC.db")}`,]);});diff --git a/apps/desktop/src/main/teamhub-wsl.test.ts b/apps/desktop/src/main/teamhub-wsl.test.tsnew file mode 100644index 00000000..62b377fb--- /dev/null+++ b/apps/desktop/src/main/teamhub-wsl.test.ts@@ -0,0 +1,76 @@+import { execFileSync, spawnSync } from "node:child_process";+import {+ copyFileSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { expect, it } from "vitest";++const wslExecutable = path.join(+ process.env.SystemRoot ?? "C:/Windows",+ "System32",+ "wsl.exe",+);+const wslAvailable =+ process.platform === "win32" &&+ spawnSync(wslExecutable, ["--exec", "/bin/true"], {+ timeout: 30_000,+ windowsHide: true,+ }).status === 0;++it.skipIf(!wslAvailable)(+ "runs the Desktop TeamHub script through WSL with Windows paths and environment",+ () => {+ const root = mkdtempSync(path.join(tmpdir(), "linger teamhub wsl "));+ const wsl = (args: string[], env = process.env, timeout = 15_000) =>+ execFileSync(wslExecutable, ["--exec", ...args], {+ encoding: "utf8",+ timeout,+ windowsHide: true,+ env,+ }).trim();+ try {+ const cli = path.join(root, "resources", "app", "dist", "teamhub-cli");+ mkdirSync(cli, { recursive: true });+ copyFileSync(process.execPath, path.join(root, "Linger.exe"));+ writeFileSync(+ path.join(cli, "teamhub"),+ readFileSync(path.resolve("scripts/teamhub.sh"), "utf8").replace(+ /\r\n/g,+ "\n",+ ),+ );+ writeFileSync(+ path.join(cli, "teamhub.js"),+ `const {readFileSync} = require("node:fs");+ const [message, file] = process.argv.slice(2);+ process.stdout.write(JSON.stringify({node:process.env.ELECTRON_RUN_AS_NODE,message,file,attachment:readFileSync(file,"utf8")}));`,+ );+ const attachment = path.join(root, "attachment with spaces.txt");+ writeFileSync(attachment, "attachment bytes");+ const unixPath = wsl(["wslpath", "-u", path.join(cli, "teamhub")]);+ const linuxAttachment = wsl(["wslpath", "-u", attachment]);+ const windowsAttachment = wsl(["wslpath", "-w", linuxAttachment]);+ const message = "/home/u/x.png is message text";+ const result = wsl(+ ["/bin/sh", unixPath, message, windowsAttachment],+ { ...process.env, ELECTRON_RUN_AS_NODE: "" },+ 30_000,+ );+ expect(JSON.parse(result)).toEqual({+ node: "1",+ message,+ file: windowsAttachment,+ attachment: "attachment bytes",+ });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ },+ 120_000,+);diff --git a/apps/desktop/src/main/updater.test.ts b/apps/desktop/src/main/updater.test.tsindex e51a70d9..599296d3 100644--- a/apps/desktop/src/main/updater.test.ts+++ b/apps/desktop/src/main/updater.test.ts@@ -416,7 +416,10 @@ describe("updateInstallFor", () => {"/Applications/Linger.app/Contents/MacOS/Linger",none,),- ).toEqual({ kind: "app-bundle", appBundle: "/Applications/Linger.app" });+ ).toEqual({+ kind: "app-bundle",+ appBundle: path.resolve("/Applications/Linger.app"),+ });const installed = "C:\\Users\\a\\AppData\\Local\\Programs\\Linger";expect(updateInstallFor(@@ -438,7 +441,7 @@ describe("updateInstallFor", () => {describe("appBundleOf", () => {it("finds the app bundle around the executable", () => {expect(appBundleOf("/Applications/Linger.app/Contents/MacOS/Linger")).toBe(- "/Applications/Linger.app",+ path.resolve("/Applications/Linger.app"),);expect(appBundleOf("/usr/lib/electron/electron")).toBeUndefined();});diff --git a/apps/desktop/src/main/windows-installer.test.ts b/apps/desktop/src/main/windows-installer.test.tsindex a35b9ddf..0cf5489e 100644--- a/apps/desktop/src/main/windows-installer.test.ts+++ b/apps/desktop/src/main/windows-installer.test.ts@@ -76,6 +76,8 @@ it("stops every earlier release with this release's script", () => {earlier,'IfFileExists "$INSTDIR\\Linger.exe" 0 done',"${STAGE}\\resources\\app\\dist\\installer\\installer.js",+ 'IfFileExists "$INSTDIR\\resources\\app\\dist\\installer\\distribution.json"',+ 'CopyFiles /SILENT "$INSTDIR\\resources\\app\\dist\\installer\\distribution.json" "$PLUGINSDIR"','StrCpy $R0 "$PLUGINSDIR\\stop.mjs"',"Call StopLinger",);diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex 4acc670e..9bd1bfdb 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -78,7 +78,13 @@ loaded models and stops the stack with the gateway the localmodels toolstarted, and keeps the services and the model controller running. Itholds each home's local model lock (`withLocalModelsLock`) while it stops,so the next launch's restore waits for it; a home whose lock a deployment-holds is skipped with a log line. It prints one JSON line with what failed.+holds is skipped with a log line. A kit that is present but fails verification+is a stop failure, so the helper logs the repair guidance, prints a JSON+failure and exits nonzero without running or downloading that tool. This+helper is detached: Linger quits and its log records that the models may+still be running. The full `--stop` command reports the same failure. Windows+uninstall aborts on that failure; replacement setup reports it and proceeds.+A missing pinned kit has nothing to stop.Every other mode first converts an install from before the rename to Linger(`migrateLegacyInstallation`); `--migrate` does only that and exits, for thediff --git a/apps/linger-installer/src/server/stop.test.ts b/apps/linger-installer/src/server/stop.test.tsindex 5c7c73f0..7ca697e8 100644--- a/apps/linger-installer/src/server/stop.test.ts+++ b/apps/linger-installer/src/server/stop.test.ts@@ -250,16 +250,19 @@ test("a quit stops only the local models, in every home, and keeps their controlpath.join(value, "desktop/local-server.json"),JSON.stringify({ home: custom }),);+ const failure =+ "Cannot stop local models: the installed tool kit could not be verified. Start Linger to repair the kit, then try again.";const models: { home: string; keepController?: boolean }[] = [];- const outcome = await stopDesktopLocalModels(options(value), {- stopModels: async (at, { keepController }) => {- models.push({ home: at, keepController });- if (at === value)- throw new Error(- "localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING",- );+ const log: string[] = [];+ const outcome = await stopDesktopLocalModels(+ { ...options(value), log: (message) => log.push(message) },+ {+ stopModels: async (at, { keepController }) => {+ models.push({ home: at, keepController });+ if (at === value) throw new Error(failure);+ },},- });+ );expect(models).toEqual([{ home: value, keepController: true },{ home: custom, keepController: true },@@ -267,9 +270,12 @@ test("a quit stops only the local models, in every home, and keeps their controlexpect(outcome.failed).toEqual([{home: value,- message: "localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING",+ message: failure,},]);+ expect(log).toEqual([+ `Could not stop the local models in ${value}: ${failure}`,+ ]);});test("a quit holds each home's local model lock while it stops the models", async () => {diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.tsindex 6347d799..9e22688e 100644--- a/apps/linger-installer/src/server/stop.ts+++ b/apps/linger-installer/src/server/stop.ts@@ -85,7 +85,7 @@ export async function stopDesktopLocalModels(options: Pick<StopOptions, "home" | "signal" | "log">,{ stopModels = stopLocalmodels }: Pick<StopDependencies, "stopModels"> = {},): Promise<StopOutcome> {- const { failed, attempt } = attempts(options.log);+ const { failed, attempt } = attempts(options.log, "the local models");for (const home of await installationHomes(options.home))await attempt(home, async () => {const stop = () =>@@ -115,14 +115,14 @@ export async function stopDesktopLocalModels(}// Runs each step and records the ones that failed, so every home is tried.-function attempts(log: (message: string) => void) {+function attempts(log: (message: string) => void, target = "the installation") {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);- log(`Could not stop the installation in ${home}: ${message}`);+ log(`Could not stop ${target} in ${home}: ${message}`);failed.push({ home, message });}};diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex 66de30b4..53353398 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -166,7 +166,9 @@ program name alone, and never the installer or what started it. Readiness onWindows also needs each port's listener inside that service's tree: anearlier release's TeamHub or web still on the port would otherwise pass thehealth 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.+program fails the start after 15 seconds instead of at the deadline. The+listener lookup streams IPv4 TCP rows from the Windows system netstat in+parallel with the process listing; process-only inspections need no port lookup.On POSIX, a start that finds the recorded supervisor gone but processesstill carrying its lease (the app was killed with it) ends them as a stop@@ -219,6 +221,12 @@ new files for a moment, and a plain rename then fails with EPERM.Cancellation is checked before every rename attempt, including after aretry wait, so a cancelled installation cannot publish the waiting file.+Verified Windows kit files carry the read-only attribute before publication or+reuse so Python children cannot replace their checked bytecode. The separate+model data and tool state remain writable. Setup can replace a damaged kit+from its pinned archive; quit and uninstall do not download or execute a kit+that fails verification.+Setting `LINGER_LOCALMODELS_DEV_PYTHON` and `LINGER_LOCALMODELS_DEV_MODULE_DIR`to absolute paths runs a local `localmodels` checkout instead of fetching thepublished kit, and `LOCALMODELS_DEBUG` (`simulate` or `tiny`, ordiff --git a/packages/local-installation/src/account.test.ts b/packages/local-installation/src/account.test.tsindex 99813560..c82bddf4 100644--- a/packages/local-installation/src/account.test.ts+++ b/packages/local-installation/src/account.test.ts@@ -1,4 +1,5 @@import {+ mkdir,mkdtemp,readFile,writeFile,@@ -180,10 +181,20 @@ it("does not create an owner on an unexpected login error or leak server responsit("rejects nonprivate or linked credential files before network activity", async () => {const f = await fixture();const target = path.join(f.instance.root, "target");- await writeFile(target, "{}", { mode: 0o600 });- await symlink(target, f.file);+ const instance = { ...f.instance };+ if (process.platform === "win32") {+ // A junction exercises reparse-point rejection without needing permission+ // to create a Windows file symlink.+ await mkdir(target);+ await writeFile(path.join(target, path.basename(f.file)), "{}");+ instance.root = path.join(f.instance.root, "junction");+ await symlink(target, instance.root, "junction");+ } else {+ await writeFile(target, "{}", { mode: 0o600 });+ await symlink(target, f.file);+ }vi.stubGlobal("fetch", vi.fn());- await expect(ensureLocalAccount(f.instance, f.signal, owner)).rejects.toThrow(+ await expect(ensureLocalAccount(instance, f.signal, owner)).rejects.toThrow(/private/,);expect(fetch).not.toHaveBeenCalled();diff --git a/packages/local-installation/src/computer-current-cli.test.ts b/packages/local-installation/src/computer-current-cli.test.tsindex 6d806143..7d0d378d 100644--- a/packages/local-installation/src/computer-current-cli.test.ts+++ b/packages/local-installation/src/computer-current-cli.test.ts@@ -18,6 +18,11 @@ vi.mock("./localmodels-tool.js", () => ({}),}),}));+vi.mock("./process.js", async (original) => {+ const actual = await original<typeof import("./process.js")>();+ const { withComputerFixture } = await import("./test-support/computer.js");+ return { ...actual, runProcess: withComputerFixture(actual.runProcess) };+});const roots: string[] = [];afterEach(async () => {await Promise.all(diff --git a/packages/local-installation/src/computer-selection.test.ts b/packages/local-installation/src/computer-selection.test.tsindex a5746146..8e12b0a0 100644--- a/packages/local-installation/src/computer-selection.test.ts+++ b/packages/local-installation/src/computer-selection.test.ts@@ -11,6 +11,11 @@ vi.mock("./localmodels-tool.js", () => ({pinnedToolSource: () => undefined,runLocalmodels: vi.fn(),}));+vi.mock("./process.js", async (original) => {+ const actual = await original<typeof import("./process.js")>();+ const { withComputerFixture } = await import("./test-support/computer.js");+ return { ...actual, runProcess: withComputerFixture(actual.runProcess) };+});const roots: string[] = [];afterEach(async () => {vi.unstubAllEnvs();diff --git a/packages/local-installation/src/computer-start-race.test.ts b/packages/local-installation/src/computer-start-race.test.tsindex eff37d99..2857e7f8 100644--- a/packages/local-installation/src/computer-start-race.test.ts+++ b/packages/local-installation/src/computer-start-race.test.ts@@ -17,6 +17,11 @@ vi.mock("./localmodels-tool.js", () => ({}),}),}));+vi.mock("./process.js", async (original) => {+ const actual = await original<typeof import("./process.js")>();+ const { withComputerFixture } = await import("./test-support/computer.js");+ return { ...actual, runProcess: withComputerFixture(actual.runProcess) };+});const roots: string[] = [];const owned: number[] = [];afterEach(async () => {diff --git a/packages/local-installation/src/computer.test.ts b/packages/local-installation/src/computer.test.tsindex c37541cc..70eeaa69 100644--- a/packages/local-installation/src/computer.test.ts+++ b/packages/local-installation/src/computer.test.ts@@ -1,5 +1,12 @@import { execFileSync } from "node:child_process";-import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";+import {+ copyFile,+ mkdtemp,+ mkdir,+ writeFile,+ readFile,+ rm,+} from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { afterEach, expect, it, vi } from "vitest";@@ -13,6 +20,23 @@ import {stopComputer,stopIdleComputer,} from "./computer.js";+vi.mock("./process.js", async (original) => {+ const actual = await original<typeof import("./process.js")>();+ const { withComputerFixture } = await import("./test-support/computer.js");+ return { ...actual, runProcess: withComputerFixture(actual.runProcess) };+});+// CLI mocks must not intercept the real ACL probe used by private state.+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[] = [];function managedNativeRuntimePath(home: string,@@ -746,11 +770,14 @@ it("provides private Node to every Computer child without relying on the host PA"bin",);await mkdir(bundleBin, { recursive: true });- await writeFile(- path.join(bundleBin, "node"),- `#!${process.execPath}\nprocess.stdout.write(process.version)`,- { mode: 0o700 },- );+ if (process.platform === "win32")+ await copyFile(process.execPath, path.join(bundleBin, "node.exe"));+ else+ await writeFile(+ path.join(bundleBin, "node"),+ `#!${process.execPath}\nprocess.stdout.write(process.version)`,+ { mode: 0o700 },+ );const previousPath = process.env.PATH;process.env.PATH = "/missing-host-node";try {@@ -829,6 +856,7 @@ it("binds approved Pi and follows upstream revisions while preserving Codex credconst home = path.resolve(f.instance.root, "../..");const modelRoot = path.join(home, "runtime", "localmodels");const piDir = path.join(home, "pi-profile");+ const piExecutable = path.join(home, "approved-pi");await privateDirectory(modelRoot);await privateDirectory(piDir);await atomicPrivate(@@ -838,7 +866,7 @@ it("binds approved Pi and follows upstream revisions while preserving Codex credready: true,planId: "a".repeat(64),pi: {- executable: "/owned/pi",+ executable: piExecutable,environment: { PI_CODING_AGENT_DIR: piDir },configFingerprint: "b".repeat(64),},@@ -855,7 +883,7 @@ it("binds approved Pi and follows upstream revisions while preserving Codex credconst run = vi.spyOn(processes, "runProcess").mockImplementation(async (_exe, args, options) => {- expect(options?.env?.LINGER_PI_PATH).toBe("/owned/pi");+ expect(options?.env?.LINGER_PI_PATH).toBe(piExecutable);expect(options?.env?.PI_CODING_AGENT_DIR).toBe(piDir);return {code: 0,@@ -880,7 +908,7 @@ it("binds approved Pi and follows upstream revisions while preserving Codex cred).toMatchObject({runner_id: "same",codex: { auth_file: "/personal/codex" },- runtime_paths: { pi: "/owned/pi" },+ runtime_paths: { pi: piExecutable },});await connectComputer(f.instance, { interactive: false });expect(@@ -895,7 +923,7 @@ it("binds approved Pi and follows upstream revisions while preserving Codex credready: true,planId: "a".repeat(64),pi: {- executable: "/owned/pi",+ executable: piExecutable,environment: { PI_CODING_AGENT_DIR: piDir },configFingerprint: "c".repeat(64),},diff --git a/packages/local-installation/src/download.test.ts b/packages/local-installation/src/download.test.tsindex aa809a58..f6a671bc 100644--- a/packages/local-installation/src/download.test.ts+++ b/packages/local-installation/src/download.test.ts@@ -302,6 +302,46 @@ it("resumes an interrupted transfer with a range request", async () => {expect(await readFile(output)).toEqual(bytes);});+it.each([false, true])(+ "restarts with a full response when the server ignores Range (resumable=%s)",+ async (resumable) => {+ const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));+ roots.push(root);+ const output = path.join(root, "kit.tgz");+ const bytes = Buffer.from("complete verified archive");+ const ranges: (string | null)[] = [];+ await downloadVerified(+ {+ url: "https://example.com/kit.tgz",+ output,+ digest: createHash("sha256").update(bytes).digest("hex"),+ algorithm: "sha256",+ maxBytes: 100,+ resumable,+ signal: new AbortController().signal,+ },+ async (_url, init) => {+ const range = new Headers(init?.headers).get("range");+ ranges.push(range);+ if (range) return new Response(bytes);+ let pulls = 0;+ return new Response(+ new ReadableStream({+ pull(controller) {+ if (pulls++ === 0) controller.enqueue(Buffer.from("stale"));+ else controller.error(new Error("interrupted"));+ },+ }),+ );+ },+ fast,+ );+ expect(ranges).toEqual([null, "bytes=5-"]);+ expect(await readFile(output)).toEqual(bytes);+ expect(await readdir(root)).toEqual(["kit.tgz"]);+ },+);+it("continues a stalled transfer on the mirror before retrying the first host", async () => {const root = await mkdtemp(path.join(tmpdir(), "linger-download-"));roots.push(root);diff --git a/packages/local-installation/src/download.ts b/packages/local-installation/src/download.tsindex 7eb574bb..32d163c1 100644--- a/packages/local-installation/src/download.ts+++ b/packages/local-installation/src/download.ts@@ -115,7 +115,7 @@ export async function downloadVerified(} else await rm(partial, { recursive: true, force: true });}options.signal.throwIfAborted();- const handle = await open(partial, options.resumable ? "a" : "ax", 0o600);+ let handle = await open(partial, options.resumable ? "a" : "ax", 0o600);let size: number | undefined;let lastProgressAt = 0;let failure = "no connection";@@ -204,8 +204,11 @@ export async function downloadVerified(return { status: "done", bytes: 0, bytesPerSecond: 0 };}if (completed && response.status === 200) {- // The host ignored the range, so this response starts over.- await handle.truncate(0);+ // The host ignored the range. Windows append handles cannot truncate,+ // so start over with a newly created private partial file.+ await handle.close();+ await rm(partial, { force: true });+ handle = await open(partial, "ax", 0o600);hash = createHash(options.algorithm);completed = 0;}diff --git a/packages/local-installation/src/instance.test.ts b/packages/local-installation/src/instance.test.tsindex 27429c62..96c8304b 100644--- a/packages/local-installation/src/instance.test.ts+++ b/packages/local-installation/src/instance.test.ts@@ -1,10 +1,11 @@-import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import net from "node:net";import { parseEnv } from "node:util";import { afterEach, expect, it } from "vitest";import { prepareLiveKitSettings } from "./native-livekit.js";+import { expectPrivate } from "./test-support/private.js";import {type Instance,initializeInstance,@@ -35,10 +36,8 @@ it("persists stable private settings and credentials across repeated initializatsecrets,);expect(first.origin).toBe(`http://localhost:${first.port}`);- expect(- (await stat(path.join(first.root, "instance.json"))).mode & 0o777,- ).toBe(0o600);- expect((await stat(first.root)).mode & 0o777).toBe(0o700);+ await expectPrivate(path.join(first.root, "instance.json"));+ await expectPrivate(first.root, "directory");});// Without the encryption key TeamHub cannot save a Composio key from the Apps// page.@@ -70,7 +69,7 @@ it("adds a missing TEAMHUB_SECRET_ENCRYPTION_KEY once and keeps every other credexpect(upgraded.startsWith(older)).toBe(true);const key = parseEnv(upgraded)[name];expect(Buffer.from(key!, "base64")).toHaveLength(32);- expect((await stat(file)).mode & 0o777).toBe(0o600);+ await expectPrivate(file);await initializeInstance({ name: "older", home: root });expect(await readFile(file, "utf8")).toBe(upgraded);});@@ -85,7 +84,7 @@ it("gives every instance its own private identity key outside services.env", asyexpect(Buffer.from(first!, "base64")).toHaveLength(32);expect(await readLocalIdentityKey(two.root)).not.toBe(first);const file = path.join(one.root, "local-identity.key");- expect((await stat(file)).mode & 0o777).toBe(0o600);+ await expectPrivate(file);expect(await readFile(path.join(one.root, "services.env"), "utf8"),).not.toContain("TEAMHUB_LOCAL_IDENTITY_KEY");@@ -154,7 +153,7 @@ it("keeps gateway keys in a separate private file and validates provider URLs",expect(await readFile(instance.model!.keyFile, "utf8")).toBe("super-private-key",);- expect((await stat(instance.model!.keyFile)).mode & 0o777).toBe(0o600);+ await expectPrivate(instance.model!.keyFile);await expect(writeModelConfig(instance, {baseUrl: "https://user:[email protected]",diff --git a/packages/local-installation/src/local-models.test.ts b/packages/local-installation/src/local-models.test.tsindex 2990e050..70632534 100644--- a/packages/local-installation/src/local-models.test.ts+++ b/packages/local-installation/src/local-models.test.ts@@ -19,6 +19,7 @@ import {import { writeSetupChoice } from "./setup-selection.js";import { runProcess } from "./process.js";import { runLocalmodels } from "./localmodels-tool.js";+import { expectPrivate } from "./test-support/private.js";import type { Instance } from "./instance.js";const roots: string[] = [];afterEach(async () => {@@ -109,10 +110,7 @@ test("delegates planning and review without pinning a model, decision or GPU", a).toEqual(["--decision", "none"]);expect(plan).not.toContain("--gpu");expect(f.call.mock.calls.some((c) => c[1][1] === "apply")).toBe(false);- expect(- (await stat(path.join(f.home, "runtime/localmodels/plan.json"))).mode &- 0o077,- ).toBe(0);+ await expectPrivate(path.join(f.home, "runtime/localmodels/plan.json"));});test("asks review and binding for English messages", async () => {const f = await fixture();@@ -672,7 +670,7 @@ test("creates the shared private model root before the main model executor can pconst f = await fixture();const invoke = vi.fn<typeof runLocalmodels>(async (home, args, options) => {const root = path.join(f.home, "runtime/localmodels/models");- expect((await stat(root)).mode & 0o077).toBe(0);+ await expectPrivate(root, "directory");return f.call(home, args, options);});await prepareLocalModels(f.instance, f.options, { localmodels: invoke });diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.tsindex 21cad0cc..7da7f72f 100644--- a/packages/local-installation/src/localmodels-tool.test.ts+++ b/packages/local-installation/src/localmodels-tool.test.ts@@ -1,4 +1,5 @@import { execFileSync } from "node:child_process";+import { chmodSync, renameSync } from "node:fs";import {chmod,mkdtemp,@@ -35,6 +36,7 @@ async function reopenDirectories(directory: string): Promise<void> {}afterEach(async () => {vi.unstubAllEnvs();+ vi.unstubAllGlobals();await Promise.all(roots.splice(0).map(async (p) => {// Verified kits are sealed read-only; reopen them before cleanup.@@ -193,6 +195,36 @@ test.skipIf(process.platform === "win32")(expect(await mode("modules/localmodels/__init__.py")).toBe(0o400);},);+test.skipIf(process.platform !== "win32")(+ "seals verified Windows files against bytecode replacement and republishes a damaged kit",+ async () => {+ const f = await fixture();+ await chmod(path.join(f.directory, "tool.json"), 0o400);+ const bytes = await packed(f);+ const source = { ...f.source, sha256: hash(bytes), bytes: bytes.length };+ const fetcher = vi.fn(async () => new Response(bytes));+ const tool = await ensureLocalmodelsTool(f.home, {}, { source, fetcher });+ const manifest = path.join(tool.moduleDir, "..", "tool.json");+ expect((await stat(manifest)).mode & 0o200).toBe(0);+ const file = path.join(tool.moduleDir, "localmodels/__init__.py");+ const replacement = path.join(path.dirname(file), "__init__.py.tmp");+ await writeFile(replacement, "changed bytecode");+ await expect(rename(replacement, file)).rejects.toHaveProperty(+ "code",+ "EPERM",+ );+ await expect(readFile(file, "utf8")).resolves.toBe("package");++ await chmod(file, 0o600);+ await writeFile(file, "damaged");+ await ensureLocalmodelsTool(f.home, {}, { source, fetcher });+ expect(fetcher).toHaveBeenCalledTimes(2);+ await expect(readFile(file, "utf8")).resolves.toBe("package");+ expect((await stat(file)).mode & 0o200).toBe(0);+ expect(await readdir(path.dirname(file))).toEqual(["__init__.py"]);+ },+ 60_000,+);test.skipIf(process.platform === "win32")("repairs a kit altered after verification by fetching the same pinned archive",async () => {@@ -562,6 +594,50 @@ test("a home without the pinned kit has nothing to stop and downloads nothing",f.source.sha256,]);});+test.for([false, true])(+ "reports a corrupt installed kit as a stop failure (keepController=%s)",+ { timeout: 15_000 },+ async (keepController) => {+ const f = await fixture();+ const file = path.join(f.directory, "modules/localmodels/__init__.py");+ await writeFile(file, "corrupt");+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));+ const fetcher = vi.fn<typeof fetch>();+ vi.stubGlobal("fetch", fetcher);+ const run = vi.fn<typeof runLocalmodels>();+ await expect(+ stopLocalmodels(+ f.home,+ { signal: AbortSignal.timeout(5000), keepController },+ { run },+ ),+ ).rejects.toThrow("the installed tool kit could not be verified");+ expect(run).not.toHaveBeenCalled();+ expect(fetcher).not.toHaveBeenCalled();+ expect(await readFile(file, "utf8")).toBe("corrupt");+ },+);++test("a kit disappearing after verification is not downloaded during stop", async () => {+ const f = await fixture();+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));+ const fetcher = vi.fn<typeof fetch>();+ vi.stubGlobal("fetch", fetcher);+ await expect(+ stopLocalmodels(f.home, {+ signal: AbortSignal.timeout(10_000),+ keepController: true,+ log: (message) => {+ if (message.includes("library status")) {+ if (process.platform !== "win32") chmodSync(f.directory, 0o700);+ renameSync(f.directory, f.directory + ".moved");+ }+ },+ }),+ ).rejects.toThrow("The installed localmodels tool kit is missing");+ expect(fetcher).not.toHaveBeenCalled();+}, 15_000);+test("stops the stack even when the controller did not stop, and names the failure", async () => {const run = vi.fn<typeof runLocalmodels>(async (_home, args) =>args[0] === "foundations"diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.tsindex f6280299..329a0421 100644--- a/packages/local-installation/src/localmodels-tool.ts+++ b/packages/local-installation/src/localmodels-tool.ts@@ -1,6 +1,6 @@import { createHash, randomUUID } from "node:crypto";import { createReadStream } from "node:fs";-import { lstat, readdir, readFile, rename, rm, chmod } from "node:fs/promises";+import { lstat, readdir, readFile, rm, chmod } from "node:fs/promises";import path from "node:path";import { x as extract } from "tar";import { downloadInRegion, resolveRegion } from "./region.js";@@ -143,6 +143,9 @@ async function verify("Upstream tool distribution target or source does not match.",);const assets = Object.entries(m.assets);+ const writable: string[] = [];+ if (process.platform === "win32" && (await lstat(manifestFile)).mode & 0o200)+ writable.push(manifestFile);const stamps: Stamps = {};let hashed = 0;let next = 0;@@ -153,6 +156,8 @@ async function verify(throw new Error("Upstream tool payload checksum mismatch.");const file = await regular(directory, name);const info = await lstat(file);+ if (process.platform === "win32" && info.mode & 0o200)+ writable.push(file);const stamp: [number, number] = [info.size, info.mtimeMs];const seen = known[name];if (!seen || seen[0] !== stamp[0] || seen[1] !== stamp[1]) {@@ -181,6 +186,7 @@ async function verify(sourceCommit: m.sourceCommit,stamps,hashed,+ writable,};}const location = (tool: Awaited<ReturnType<typeof verify>>) => ({@@ -243,6 +249,15 @@ async function setKitMode(directory: string, sealed: boolean) {}await chmod(directory, sealed ? 0o500 : 0o700);}+/** The Windows read-only attribute prevents CPython from replacing a verified cache file. */+async function sealWindowsFiles(writable: string[]) {+ for (let offset = 0; offset < writable.length; offset += CONCURRENCY)+ await Promise.all(+ writable+ .slice(offset, offset + CONCURRENCY)+ .map((file) => chmod(file, 0o400)),+ );+}async function installedKit(directory: string, source: LocalmodelsToolSource) {let info;try {@@ -265,6 +280,7 @@ async function installedKit(directory: string, source: LocalmodelsToolSource) {);if (process.platform !== "win32" && (info.mode & 0o777) !== 0o500)await setKitMode(directory, true);+ await sealWindowsFiles(tool.writable);if (tool.hashed > 0) await writeStamps(directory, source, tool.stamps);return location(tool);}@@ -311,7 +327,7 @@ async function prepareLocalmodelsTool(// a sealed directory. Ownership was checked above; reopen only its root// before quarantine, then reopen descendants at the quarantined path.if (process.platform !== "win32") await chmod(directory, 0o700);- await rename(directory, invalid);+ await renameRetrying(directory, invalid, { signal });await setKitMode(invalid, false);await rm(invalid, { recursive: true, force: true });}@@ -354,8 +370,16 @@ async function prepareLocalmodelsTool(const tool = await verify(kit, source);if (process.platform !== "win32") await chmod(tool.python, 0o700);// The kit manifest is private state; publisher bytes stay unchanged for digest checks.- const body = await readFile(path.join(kit, "tool.json"), "utf8");- await atomicPrivate(path.join(kit, "tool.json"), body);+ const manifest = path.join(kit, "tool.json");+ const body = await readFile(manifest, "utf8");+ // A read-only archive manifest cannot be replaced on Windows until+ // it is writable. Seal the replacement as well as the verified assets.+ if (process.platform === "win32" && !tool.writable.includes(manifest)) {+ await chmod(manifest, 0o600);+ tool.writable.push(manifest);+ }+ await atomicPrivate(manifest, body);+ await sealWindowsFiles(tool.writable);signal.throwIfAborted();await renameRetrying(kit, directory, { signal });// The rename keeps every stamp, so this checks the published kit@@ -423,9 +447,25 @@ export async function runLocalmodels(args: string[],options: Options = {},dependencies: { run?: typeof runProcess } = {},+) {+ return runLocalmodelsCommand(+ home,+ args,+ options,+ () => ensureLocalmodelsTool(home, options),+ dependencies.run,+ );+}+async function runLocalmodelsCommand(+ home: string,+ args: string[],+ options: Options,+ loadTool: () => Promise<ToolLocation | undefined>,+ run: typeof runProcess = runProcess,) {const startedAt = Date.now();- const tool = await ensureLocalmodelsTool(home, options);+ const tool = await loadTool();+ if (!tool) throw new Error("The installed localmodels tool kit is missing.");const checkedAt = Date.now();const state = localmodelsStateDirectory(home);await privateDirectory(state);@@ -511,7 +551,7 @@ export async function runLocalmodels(});}};- const result = await (dependencies.run ?? runProcess)(+ const result = await run(tool.python,["-P", "-s", "-m", "localmodels", ...args],{ ...options, cwd: tool.moduleDir, env, onOutput },@@ -531,9 +571,10 @@ export async function runLocalmodels(* the gateway the tool started (`stack down`), the library's Bifrost* included. An uninstall or an install over this release stops all of it; a* quit keeps the controller, which belongs to the services that keep- * running. Nothing is downloaded: a home without that kit has nothing it- * started. Every step runs even when an earlier one fails; the error names- * each that did not stop.+ * running. Nothing is downloaded. An absent pinned kit is skipped; a pinned+ * kit that is present but fails verification is reported as a stop failure.+ * Every stop command runs even when an earlier command fails; the error+ * names each that did not stop.*/export async function stopLocalmodels(home: string,@@ -548,7 +589,12 @@ export async function stopLocalmodels(} = {},): Promise<void> {if (!(await (dependencies.installed ?? hasPinnedTool)(home))) return;- const run = dependencies.run ?? runLocalmodels;+ const run =+ dependencies.run ??+ ((home, args, options = {}) =>+ runLocalmodelsCommand(home, args, options, () =>+ installedPinnedTool(home),+ ));const base = localmodelsBaseDirectory(home);const failed: string[] = [];const step = async (args: string[], name = args.slice(0, 2).join(" ")) => {@@ -559,7 +605,13 @@ export async function stopLocalmodels(timeoutMs: 30_000,}).catch((error: unknown) => {options.signal.throwIfAborted();- return { code: 1, stdout: "", stderr: String(error) };+ return {+ code: 1,+ stdout: JSON.stringify({+ error: error instanceof Error ? error.message : String(error),+ }),+ stderr: "",+ };});if (result.code !== 0)failed.push(`localmodels ${name}: ${stopFailure(result)}`);@@ -629,12 +681,23 @@ function stopFailure(result: { code: number; stdout: string }): string {return `exit ${result.code}`;}async function hasPinnedTool(home: string): Promise<boolean> {- if (configuredDevTool()) return true;+ return (await installedPinnedTool(home)) !== undefined;+}+async function installedPinnedTool(+ home: string,+): Promise<ToolLocation | undefined> {+ const devTool = configuredDevTool();+ if (devTool) return devTool;const source = pinnedToolSource();- if (!source) return false;- return !!(await installedKit(kitDirectory(home, source), source).catch(- () => undefined,- ));+ if (!source) return;+ return installedKit(kitDirectory(home, source), source).catch(+ (cause: unknown) => {+ throw new Error(+ "Cannot stop local models: the installed tool kit could not be verified. Start Linger to repair the kit, then try again.",+ { cause },+ );+ },+ );}/*** The kit this release pins, from the installer's published metadatadiff --git a/packages/local-installation/src/managed-codex.test.ts b/packages/local-installation/src/managed-codex.test.tsindex a97cadfa..567f0b52 100644--- a/packages/local-installation/src/managed-codex.test.ts+++ b/packages/local-installation/src/managed-codex.test.ts@@ -1,6 +1,9 @@+import path from "node:path";import type { runLocalmodels } from "./localmodels-tool.js";import { expect, it, vi } from "vitest";import { checkRuntimeModel, configureManagedCodex } from "./managed-codex.js";+const home = path.resolve("/owned");+const instance = path.join(home, "instances", "default");it("delegates Responses probing and Codex model profile construction upstream via stdin", async () => {const localmodels = vi.fn<typeof runLocalmodels>(async () => ({code: 0,@@ -8,7 +11,7 @@ it("delegates Responses probing and Codex model profile construction upstream vistderr: "",}));await configureManagedCodex(- "/owned/instances/default",+ instance,{baseUrl: "https://gateway.example/v1",model: "owner-model",@@ -18,12 +21,12 @@ it("delegates Responses probing and Codex model profile construction upstream vi{ localmodels },);expect(localmodels).toHaveBeenCalledWith(- "/owned",+ home,["harness","auth","--root",- "/owned/runtime/harness",+ path.join(home, "runtime", "harness"),"--runtime","codex","--config-stdin",@@ -46,7 +49,7 @@ it("delegates Responses probing and Codex model profile construction upstream viit("does not return upstream errors or credentials when configuration fails", async () => {await expect(configureManagedCodex(- "/owned/instances/default",+ instance,{baseUrl: "https://gateway.example/v1",model: "owner-model",@@ -77,7 +80,7 @@ it("delegates read-only model checks without saving a profile", async () => {apiKey: "private-key",},new AbortController().signal,- { home: "/owned", localmodels },+ { home, localmodels },);expect(localmodels.mock.calls[0]![1]).toContain("--check");});diff --git a/packages/local-installation/src/managed-runtimes.test.ts b/packages/local-installation/src/managed-runtimes.test.tsindex 6a2c6653..b0cc8664 100644--- a/packages/local-installation/src/managed-runtimes.test.ts+++ b/packages/local-installation/src/managed-runtimes.test.ts@@ -57,7 +57,10 @@ it("uses upstream status and OAuth descriptors without provider-specific probes"installed: true,ready: false,executable: "/upstream/runtime",- loginCommand: "'/upstream/runtime' 'upstream-login'",+ loginCommand:+ process.platform === "win32"+ ? "& '/upstream/runtime' 'upstream-login'"+ : "'/upstream/runtime' 'upstream-login'",});expect(localmodels.mock.calls[0]?.slice(0, 2)).toEqual([options.home,diff --git a/packages/local-installation/src/native-database.test.ts b/packages/local-installation/src/native-database.test.tsindex 492e4a45..70ab9f74 100644--- a/packages/local-installation/src/native-database.test.ts+++ b/packages/local-installation/src/native-database.test.ts@@ -38,20 +38,24 @@ import type { Instance } from "./instance.js";const run = vi.mocked(runProcess);const platform = Object.getOwnPropertyDescriptor(process, "platform")!;-const getuid = Object.getOwnPropertyDescriptor(process, "getuid")!;+const getuid = Object.getOwnPropertyDescriptor(process, "getuid");+const fakeUid = (value: typeof process.getuid) =>+ Object.defineProperty(process, "getuid", { configurable: true, value });// The root guard refuses initdb, and CI containers often run as root.beforeEach(() => {- Object.defineProperty(process, "getuid", { ...getuid, value: () => 1000 });+ Object.defineProperty(process, "platform", { ...platform, value: "linux" });+ fakeUid(() => 1000);});afterEach(() => {Object.defineProperty(process, "platform", platform);- Object.defineProperty(process, "getuid", getuid);+ if (getuid) Object.defineProperty(process, "getuid", getuid);+ else Reflect.deleteProperty(process, "getuid");vi.clearAllMocks();});// Windows has no process.getuid.const asWindows = () => {Object.defineProperty(process, "platform", { ...platform, value: "win32" });- Object.defineProperty(process, "getuid", { ...getuid, value: undefined });+ fakeUid(undefined);};const ok = (stdout = "") => ({ code: 0, stdout, stderr: "" });const instance = {diff --git a/packages/local-installation/src/native-dependencies.test.ts b/packages/local-installation/src/native-dependencies.test.tsindex b826b2f1..8a9aabab 100644--- a/packages/local-installation/src/native-dependencies.test.ts+++ b/packages/local-installation/src/native-dependencies.test.ts@@ -8,7 +8,6 @@ import {writeFile,symlink,} from "node:fs/promises";-import { execFileSync } from "node:child_process";import { existsSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";@@ -158,7 +157,15 @@ describe("verified extraction", () => {home = path.join(root, "home");await mkdir(path.join(input, "bin"), { recursive: true });await writeFile(path.join(input, "bin/tool"), "payload", { mode: 0o755 });- if (link) await symlink("/etc/passwd", path.join(input, "bin/escape"));+ if (link) {+ const outside = path.join(root, "outside");+ await mkdir(outside);+ await symlink(+ outside,+ path.join(input, "bin/escape"),+ process.platform === "win32" ? "junction" : "dir",+ );+ }const archive = path.join(root, "payload.tgz");await pack({ cwd: input, file: archive, gzip: true }, ["bin"]);const bytes = await readFile(archive);@@ -293,18 +300,13 @@ describe("verified extraction", () => {});describe("verified zip extraction", () => {- // Python's zipfile writes ordinary deflated release zips, like go.dev does.- async function zip(entries: Record<string, string>, stored = false) {- const root = await temp(),- archive = path.join(root, "payload.zip");- execFileSync("python3", [- "-c",- "import json,sys,zipfile\nwith zipfile.ZipFile(sys.argv[1],'w',zipfile.ZIP_STORED if sys.argv[3]=='1' else zipfile.ZIP_DEFLATED) as z:\n [z.writestr(k,v) for k,v in json.loads(sys.argv[2]).items()]",- archive,- JSON.stringify(entries),- stored ? "1" : "0",- ]);- const bytes = await readFile(archive);+ // Small release-style fixtures generated with Python's zipfile. Tests do+ // not need a Python executable or the Windows Store's python3 alias.+ async function zip(name: string) {+ const root = await temp();+ const bytes = await readFile(+ new URL(`../test/fixtures/${name}.zip`, import.meta.url),+ );return {home: path.join(root, "home"),artifact: {@@ -320,10 +322,7 @@ describe("verified zip extraction", () => {it.each([false, true])("extracts and caches a release zip (stored=%s)",async (stored) => {- const f = await zip(- { "go/": "", "go/bin/go.exe": "binary".repeat(100) },- stored,- );+ const f = await zip(stored ? "stored" : "deflated");const directory = await acquireNativeArtifact(f.home,f.artifact,@@ -345,22 +344,23 @@ describe("verified zip extraction", () => {).toBe(directory);},);- it.each(["../escape", "go\\..\\escape", "C:/escape"])(- "rejects the unsafe zip entry %s",- async (name) => {- const f = await zip({ [name]: "unsafe" });- await expect(- acquireNativeArtifact(- f.home,- f.artifact,- new AbortController().signal,- undefined,- f.fetcher,- ),- ).rejects.toThrow(/archive/);- expect(await readdir(f.home)).not.toContain("escape");- },- );+ it.each([+ ["../escape", "parent-path"],+ ["go\\..\\escape", "backslash-parent-path"],+ ["C:/escape", "absolute-path"],+ ])("rejects the unsafe zip entry %s", async (_entry, name) => {+ const f = await zip(name);+ await expect(+ acquireNativeArtifact(+ f.home,+ f.artifact,+ new AbortController().signal,+ undefined,+ f.fetcher,+ ),+ ).rejects.toThrow(/archive/);+ expect(await readdir(f.home)).not.toContain("escape");+ });});describe("failure and cancellation boundaries", () => {@@ -394,7 +394,11 @@ describe("failure and cancellation boundaries", () => {const root = await temp(),outside = await temp(),base = path.join(root, "cache");- await symlink(outside, base);+ await symlink(+ outside,+ base,+ process.platform === "win32" ? "junction" : "dir",+ );await expect(acquireNativeArtifact(base,@@ -406,7 +410,7 @@ describe("failure and cancellation boundaries", () => {},new AbortController().signal,),- ).rejects.toThrow(/owned directory/);+ ).rejects.toThrow(/owned directory|is a link/);});it("aborted downloads leave no pending component", async () => {const root = await temp(),@@ -445,7 +449,11 @@ it("validates checksum identity before resolving cache paths", async () => {).rejects.toThrow();});-it("prepares real executable launchers and reuses verified warm dependencies entirely offline", async () => {+it("prepares real executable launchers and reuses verified warm dependencies entirely offline", async ({+ skip,+}) => {+ if (process.platform === "win32")+ skip("The fixture uses POSIX Go and PostgreSQL shell executables");const root = await temp(),repo = path.join(root, "repo"),home = path.join(root, "home");@@ -530,7 +538,7 @@ it("prepares real executable launchers and reuses verified warm dependencies entsignal: new AbortController().signal,onEvent: (event) => events.push(event),});- expect(result.env.GOROOT).toContain("/components/");+ expect(result.env.GOROOT).toContain(`${path.sep}components${path.sep}`);expect(result.env.GOTOOLCHAIN).toBe("local");expect(result.env.GOPROXY).toBe("https://proxy.golang.org|https://goproxy.cn|direct",diff --git a/packages/local-installation/src/native-process-darwin-legacy.test.ts b/packages/local-installation/src/native-process-darwin-legacy.test.tsindex 2b1f805c..90120669 100644--- a/packages/local-installation/src/native-process-darwin-legacy.test.ts+++ b/packages/local-installation/src/native-process-darwin-legacy.test.ts@@ -6,7 +6,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";// ps as a Mac in a German region format prints it: lstart in the caller's// locale, C only when the inspector asks for it.const ps = vi.hoisted(() => {- const uid = process.getuid!();+ const uid = process.getuid?.();return {uid,c: `Wed Nov 18 06:04:14 2026 ${uid} 73285 Ss\n`,@@ -34,6 +34,8 @@ const lease = "a".repeat(64);// What Linger 0.1.2 recorded for that process: the localized start time.const legacyBirth = `darwin:Mi:18:Nov:06:04:14:2026:${ps.uid}:73285`;const platform = process.platform;+// Simulated Darwin still needs a real POSIX file owner on the host.+const posixTest = it.skipIf(platform === "win32");let root: string;const recordFile = () =>path.join(root, "native", "processes", "postgres.json");@@ -65,23 +67,33 @@ afterEach(async () => {await rm(root, { recursive: true, force: true });});-it("adopts a service 0.1.2 recorded with a localized start time, once", async () => {- await expect(inspectNativeProcess(root, "postgres")).resolves.toEqual({- running: true,- pid: 73285,- });- expect(await birth()).toBe(`darwin:Wed:Nov:18:06:04:14:2026:${ps.uid}:73285`);-});+posixTest(+ "adopts a service 0.1.2 recorded with a localized start time, once",+ async () => {+ await expect(inspectNativeProcess(root, "postgres")).resolves.toEqual({+ running: true,+ pid: 73285,+ });+ expect(await birth()).toBe(+ `darwin:Wed:Nov:18:06:04:14:2026:${ps.uid}:73285`,+ );+ },+);-it("keeps the record when the localized start time names another process", async () => {- ps.localized = `Mi 18 Nov 07:00:00 2026 ${ps.uid} 73285 Ss\n`;- await expect(inspectNativeProcess(root, "postgres")).resolves.toMatchObject({- running: false,- });- expect(await birth()).toBe(legacyBirth);-});+posixTest(+ "keeps the record when the localized start time names another process",+ async () => {+ ps.localized = `Mi 18 Nov 07:00:00 2026 ${ps.uid} 73285 Ss\n`;+ await expect(inspectNativeProcess(root, "postgres")).resolves.toMatchObject(+ {+ running: false,+ },+ );+ expect(await birth()).toBe(legacyBirth);+ },+);-it("keeps the record of a process without the lease", async () => {+posixTest("keeps the record of a process without the lease", async () => {ps.environment = "node worker.mjs\n";await expect(inspectNativeProcess(root, "postgres")).resolves.toMatchObject({running: false,diff --git a/packages/local-installation/src/native-process-identity.ts b/packages/local-installation/src/native-process-identity.tsindex 8adfff99..461f30c8 100644--- a/packages/local-installation/src/native-process-identity.ts+++ b/packages/local-installation/src/native-process-identity.ts@@ -1,6 +1,9 @@-import { execFile } from "node:child_process";+import { execFile, spawn } from "node:child_process";import { readdir, readFile, stat } from "node:fs/promises";+import path from "node:path";+import { createInterface } from "node:readline";+// The source supervisor imports this module directly, before any build.const leaseKey = "LINGER_NATIVE_PROCESS_LEASE";function runProcess(executable: string,@@ -20,8 +23,7 @@ function runProcess(execFile(executable,args,- // Startup polls this every half second; on Windows each PowerShell- // would otherwise open its own console window.+ // Inspectors run in the background, including during Windows startup.{env,timeout: options.timeoutMs,@@ -30,7 +32,11 @@ function runProcess(},(error, stdout) => {if (error && error.code !== 1)- reject(new Error("Native process identity could not be inspected."));+ reject(+ new Error("Native process identity could not be inspected.", {+ cause: error,+ }),+ );else resolve({ code: error ? 1 : 0, stdout });},);@@ -39,18 +45,13 @@ 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 listening TCP ports-// come in the same snapshot, so a port's owner is judged against the same-// process tree.+// the parent's means a reused PID, never a child.const WINDOWS_PROCESSES = String.raw`$ErrorActionPreference = 'Stop'$p = @(Get-CimInstance Win32_Process | ForEach-Object {[pscustomobject]@{ p = $_.ProcessId; q = $_.ParentProcessId; c = $_.CreationDate.ToFileTimeUtc(); l = [string]$_.CommandLine }})-$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+[pscustomobject]@{ p = $p } | ConvertTo-Json -Compress -Depth 3`;export interface WindowsProcess {pid: number;@@ -70,30 +71,44 @@ export interface WindowsSnapshot {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]),- ),+function parseWindowsProcesses(stdout: string): WindowsProcess[] {+ const parsed = JSON.parse(stdout) as {+ p: Rows<{ p: number; q: number; c: number; l: string | null }>;};+ if (!parsed.p) throw new Error("Native processes could not be enumerated.");+ return rows(parsed.p).map((row) => ({+ pid: row.p,+ parent: row.q,+ created: row.c,+ command: row.l ?? "",+ }));+}++function addWindowsListener(listeners: Map<number, number>, line: string) {+ // A listening TCP row has no remote peer. The state text is localized.+ const match =+ /^\s*TCP\s+(127\.0\.0\.1|0\.0\.0\.0):(\d+)\s+0\.0\.0\.0:0\s+.+?\s+(\d+)\s*$/.exec(+ line,+ );+ if (!match) return;+ const [, ip, portText, pidText] = match;+ const port = Number(portText);+ const pid = Number(pidText);+ if (port < 1 || port > 65535 || pid < 1 || pid > 0xffffffff) return;+ // A specific loopback bind takes precedence over an IPv4 wildcard.+ if (ip === "127.0.0.1" || !listeners.has(port)) listeners.set(port, pid);}-export async function windowsSnapshot(): Promise<WindowsSnapshot> {++/** The IPv4 listeners a service's loopback health check can reach. */+export async function parseWindowsListeners(+ lines: AsyncIterable<string> | Iterable<string>,+): Promise<Map<number, number>> {+ const listeners = new Map<number, number>();+ for await (const line of lines) addWindowsListener(listeners, line);+ return listeners;+}++export async function windowsProcesses(): Promise<WindowsProcess[]> {const result = await runProcess("powershell.exe",["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROCESSES],@@ -101,10 +116,51 @@ export async function windowsSnapshot(): Promise<WindowsSnapshot> {);if (result.code !== 0)throw new Error("Native processes could not be enumerated.");- return parseWindowsSnapshot(result.stdout);+ return parseWindowsProcesses(result.stdout);}-export async function windowsProcesses(): Promise<WindowsProcess[]> {- return (await windowsSnapshot()).processes;++async function windowsListeners(+ systemRoot: string,+): Promise<Map<number, number>> {+ const env = { ...process.env };+ delete env[leaseKey];+ const child = spawn(+ path.win32.join(systemRoot, "System32", "netstat.exe"),+ ["-ano", "-p", "TCP"],+ { env, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] },+ );+ // Established and TIME_WAIT rows can exceed execFile's buffer. Consume+ // lines as they arrive and retain only the small index of listeners.+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });+ let sawOutput = false;+ lines.on("line", () => (sawOutput = true));+ const status = new Promise<number | null>((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+ const timer = setTimeout(() => child.kill(), 15_000);+ try {+ const [listeners, code] = await Promise.all([+ parseWindowsListeners(lines),+ status,+ ]);+ if (code !== 0 || !sawOutput)+ throw new Error("Native TCP listeners could not be enumerated.");+ return listeners;+ } finally {+ clearTimeout(timer);+ lines.close();+ }+}++export async function windowsSnapshot(+ systemRoot: string,+): Promise<WindowsSnapshot> {+ const [processes, listeners] = await Promise.all([+ windowsProcesses(),+ windowsListeners(systemRoot),+ ]);+ return { processes, listeners };}/*** The PowerShell a supervisor starts to take this snapshot is its own child.diff --git a/packages/local-installation/src/native-process-win32.test.ts b/packages/local-installation/src/native-process-win32.test.tsindex 7826f7e4..345eee84 100644--- a/packages/local-installation/src/native-process-win32.test.ts+++ b/packages/local-installation/src/native-process-win32.test.ts@@ -13,21 +13,22 @@ import type {const host = vi.hoisted(() => ({processes: [] as WindowsProcess[],listeners: new Map<number, number>(),+ listenersAvailable: true,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,+ const windowsProcesses = async () => [...host.processes];+ const windowsSnapshot = async (): Promise<WindowsSnapshot> => {+ if (!host.listenersAvailable) throw new Error("Cannot read TCP listeners");+ return {+ processes: await windowsProcesses(),+ listeners: new Map(host.listeners),+ };};+ return { ...actual, windowsSnapshot, windowsProcesses };});const taskkill = vi.hoisted(() => ({calls: [] as string[][],@@ -69,6 +70,7 @@ beforeEach(async () => {root = await mkdtemp(path.join(tmpdir(), "native-win32-"));host.processes = [row(1, 0, 1, "wininit.exe")];host.listeners = new Map();+ host.listenersAvailable = true;host.ended = [];host.cascade = new Map();taskkill.calls = [];@@ -116,7 +118,8 @@ async function record(name: string, pid: number, key = lease) {);}-test("a supervisor whose service died is not running", async () => {+test("a supervisor whose service died is not running even without listener data", async () => {+ host.listenersAvailable = false;await record("livekit", 10);host.processes.push(worker(10, "livekit"),@@ -127,7 +130,8 @@ test("a supervisor whose service died is not running", async () => {expect((await inspectNativeProcess(root, "livekit")).running).toBe(true);});-test("stop ends the whole tree leaves first and forgets the record", async () => {+test("stop ends the whole tree leaves first and forgets the record without listener data", async () => {+ host.listenersAvailable = false;await record("teamhub", 10);host.processes.push(worker(10, "teamhub"),diff --git a/packages/local-installation/src/native-process-windows-live.test.ts b/packages/local-installation/src/native-process-windows-live.test.tsnew file mode 100644index 00000000..cfd2cdd6--- /dev/null+++ b/packages/local-installation/src/native-process-windows-live.test.ts@@ -0,0 +1,30 @@+import { createServer } from "node:net";+import { expect, test } from "vitest";+import { windowsSnapshot } from "./native-process-identity.js";++test.skipIf(process.platform !== "win32")(+ "finds a real IPv4 listener and its owning process",+ async () => {+ const server = createServer();+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", resolve);+ });+ try {+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No port");+ const snapshot = await windowsSnapshot(+ process.env.SystemRoot ?? "C:\\Windows",+ );+ expect(snapshot.listeners.get(address.port)).toBe(process.pid);+ expect(+ snapshot.processes.some((entry) => entry.pid === process.pid),+ ).toBe(true);+ } finally {+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ }+ },+ 30_000,+);diff --git a/packages/local-installation/src/native-process-windows.test.ts b/packages/local-installation/src/native-process-windows.test.tsindex 414fb69c..1dd525f4 100644--- a/packages/local-installation/src/native-process-windows.test.ts+++ b/packages/local-installation/src/native-process-windows.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import {- parseWindowsSnapshot,+ parseWindowsListeners,windowsLeaseTree,type WindowsProcess,} from "./native-process-identity.js";@@ -70,32 +70,25 @@ describe("windowsLeaseTree", () => {});});-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(+describe("parseWindowsListeners", () => {+ it("finds IPv4 listeners without interpreting localized states", async () => {+ const listeners = await parseWindowsListeners([+ " TCP 127.0.0.1:55641 0.0.0.0:0 ÉCOUTE 7644",+ " TCP [::1]:3000 [::]:0 LISTENING 29644",+ " TCP 127.0.0.1:3000 0.0.0.0:0 LISTENING 16588",+ " TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 31000",+ " TCP 0.0.0.0:5432 0.0.0.0:0 LISTENING 1632",+ " TCP 127.0.0.1:55641 127.0.0.1:34500 ESTABLISHED 4600",+ " TCP 192.0.2.4:2345 0.0.0.0:0 LISTENING 8000",+ " UDP 0.0.0.0:53 *:* 1000",+ " TCP 0.0.0.0:65536 0.0.0.0:0 LISTENING 1",+ " TCP 0.0.0.0:65534 0.0.0.0:0 LISTENING 0",+ ]);+ expect(listeners).toEqual(new Map([[55641, 7644],[3000, 16588],+ [5432, 1632],]),);});diff --git a/packages/local-installation/src/native-process.test.ts b/packages/local-installation/src/native-process.test.tsindex 4f22b8e9..c273ed91 100644--- a/packages/local-installation/src/native-process.test.ts+++ b/packages/local-installation/src/native-process.test.ts@@ -28,11 +28,13 @@ import {stopNativeProcess,} from "./native-process.js";-// Each test owns its root and real process group, so they run side by side;-// the bounds are generous so that a loaded host slows them without failing them.-const test = base.concurrent;+// Every test owns a separate process tree. Run Windows trees in sequence+// because each inspection reads the same system-wide process inventory.+const windows = process.platform === "win32";+const test = windows ? base : base.concurrent;+const posix = windows ? test.skip : test;vi.setConfig({- testTimeout: 30_000,+ testTimeout: windows ? 60_000 : 30_000,hookTimeout: 60_000,expect: { poll: { timeout: 15_000 } },});@@ -44,12 +46,16 @@ async function fixture({ onTestFinished }: TestContext) {// then end whatever still runs from this root.for (const name of ["web", "teamhub"] as const)await stopNativeProcess(root, name, 300).catch(() => {});- try {- execFileSync("pkill", ["-KILL", "-f", root]);- } catch {- // pkill exits 1 when nothing matched.+ if (windows) {+ await reclaimNativeOrphans(root, { ports: [], paths: [] });+ } else {+ try {+ execFileSync("pkill", ["-KILL", "-f", root]);+ } catch {+ // pkill exits 1 when nothing matched.+ }}- await rm(root, { recursive: true, force: true });+ await rm(root, { recursive: true, force: true, maxRetries: 10 });});return root;}@@ -183,33 +189,40 @@ test("redacts complete lines before persisting split writes and known secrets",expect(log).toContain("[REDACTED]");});-test("stops descendants that ignore SIGINT after the service leader exits", async (context) => {- const { expect } = context;- const root = await fixture(context);- const childCode =- "process.on('SIGINT',()=>{});console.log('descendant-ready');setInterval(()=>{},1000)";- await startNativeProcess({- root,- name: "web",- executable: process.execPath,- args: [- "-e",- `const {spawn}=require('node:child_process');const fs=require('node:fs');const c=spawn(process.execPath,['-e',${JSON.stringify(childCode)}],{stdio:'inherit'});fs.writeFileSync('descendant.pid',String(c.pid));process.on('SIGINT',()=>process.exit(0));setInterval(()=>{},1000)`,- ],- cwd: root,- env: process.env,- });- await expect- .poll(async () => readFile(path.join(root, "native/logs/web.log"), "utf8"))- .toContain("descendant-ready");- const pid = Number(await readFile(path.join(root, "descendant.pid"), "utf8"));- // The descendant ignores SIGINT, so only the SIGKILL escalation ends it;- // a short interrupt window reaches it without the production wait.- await stopNativeProcess(root, "web", 300);- await expect.poll(() => exited(pid)).toBe(true);-});+posix(+ "stops descendants that ignore SIGINT after the service leader exits",+ async (context) => {+ const { expect } = context;+ const root = await fixture(context);+ const childCode =+ "process.on('SIGINT',()=>{});console.log('descendant-ready');setInterval(()=>{},1000)";+ await startNativeProcess({+ root,+ name: "web",+ executable: process.execPath,+ args: [+ "-e",+ `const {spawn}=require('node:child_process');const fs=require('node:fs');const c=spawn(process.execPath,['-e',${JSON.stringify(childCode)}],{stdio:'inherit'});fs.writeFileSync('descendant.pid',String(c.pid));process.on('SIGINT',()=>process.exit(0));setInterval(()=>{},1000)`,+ ],+ cwd: root,+ env: process.env,+ });+ await expect+ .poll(async () =>+ readFile(path.join(root, "native/logs/web.log"), "utf8"),+ )+ .toContain("descendant-ready");+ const pid = Number(+ await readFile(path.join(root, "descendant.pid"), "utf8"),+ );+ // The descendant ignores SIGINT, so only the SIGKILL escalation ends it;+ // a short interrupt window reaches it without the production wait.+ await stopNativeProcess(root, "web", 300);+ await expect.poll(() => exited(pid)).toBe(true);+ },+);-(process.platform === "win32" ? test.skip : test)(+posix("replaces a service whose supervisor was killed with the app",async (context) => {const { expect } = context;@@ -246,7 +259,7 @@ test("stops descendants that ignore SIGINT after the service leader exits", asyn},);-(process.platform === "win32" ? test.skip : test)(+posix("reclaims a service an earlier attempt left under a lease no record holds",async (context) => {const { expect } = context;@@ -279,7 +292,7 @@ test("stops descendants that ignore SIGINT after the service leader exits", asyn},);-test("cleans the launched owned group when identity persistence fails", async (context) => {+test("cleans launched owned processes when identity persistence fails", async (context) => {const { expect } = context;const root = await fixture(context);failure.file = path.join(root, "native/processes/web.json");@@ -344,9 +357,16 @@ test("bundled entry resolves its packaged worker and survives caller exit", asyntarget: "node26",});const caller = spawn(process.execPath, [path.join(root, "packaged.mjs")], {- stdio: "ignore",+ stdio: ["ignore", "ignore", "pipe"],});- expect(await new Promise((resolve) => caller.once("exit", resolve))).toBe(0);+ let stderr = "";+ caller.stderr?.on("data", (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ expect(+ await new Promise((resolve) => caller.once("close", resolve)),+ stderr,+ ).toBe(0);expect((await inspectNativeProcess(root, "web")).running).toBe(true);await expect.poll(async () => readFile(path.join(root, "native/logs/web.log"), "utf8"))@@ -424,12 +444,12 @@ test.for(["ENOSPC", "EIO"])(expect(() => process.kill(owner.pid!, 0)).toThrow();expect(() => process.kill(service, 0)).toThrow();} finally {- // A failed assertion must also reclaim the real group on the unfixed code.+ // Keep the group escape hatch for POSIX; the fixture cleans Windows by lease.const record = await readFile(path.join(root, "native/processes/web.json"),"utf8",).catch(() => "");- if (record) {+ if (!windows && record) {try {process.kill(-JSON.parse(record).pid, "SIGKILL");} catch {@@ -440,7 +460,7 @@ test.for(["ENOSPC", "EIO"])(},);-test.for([false, true])(+posix.for([false, true])("stops leased orphan descendants across groups (owner killed: %s)",async (killOwner, context) => {const { expect } = context;diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.tsindex c68507e1..2e874ae6 100644--- a/packages/local-installation/src/native-process.ts+++ b/packages/local-installation/src/native-process.ts@@ -14,6 +14,7 @@ import {nativeProcessIdentity as observed,nativeLeaseProcesses,windowsLeaseTree,+ windowsProcesses,windowsSnapshot,type WindowsProcess,type WindowsSnapshot,@@ -162,7 +163,7 @@ function recordedTree(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;+ return recordedTree(await windowsProcesses(), record).length > 1;}export async function inspectNativeProcess(root: string,@@ -196,7 +197,9 @@ export async function inspectNativeListeners(running: (await inspectNativeProcess(root, name)).running,})),);- const snapshot = await windowsSnapshot();+ const snapshot = await windowsSnapshot(+ process.env.SystemRoot ?? "C:\\Windows",+ );return Promise.all(listeners.map(async ({ name, port }) => {const record = await stored(root, name);@@ -751,11 +754,15 @@ export async function reclaimNativeOrphans(const ended: number[] = [];const deadline = Date.now() + 12_000;for (;;) {- const orphans = windowsOrphans(await windowsSnapshot(), records, {- root,- ...options,- self: process.pid,- });+ const orphans = windowsOrphans(+ await windowsSnapshot(process.env.SystemRoot ?? "C:\\Windows"),+ records,+ {+ root,+ ...options,+ self: process.pid,+ },+ );if (!orphans.length) return ended;if (Date.now() >= deadline)throw new Error(diff --git a/packages/local-installation/src/native-source.test.ts b/packages/local-installation/src/native-source.test.tsindex fdadb9f2..a3efbaa1 100644--- a/packages/local-installation/src/native-source.test.ts+++ b/packages/local-installation/src/native-source.test.ts@@ -9,6 +9,7 @@ import { loadInstance } from "./instance.js";import { updateUserKeys } from "./user-environment.js";import { readLiveKitSettings } from "./native-livekit.js";import { saveSourceBinding } from "./source-checkout.js";+import { freePort } from "./ports.js";import {checkNativeSourceEnvironment,nativeSourceInstanceName,@@ -302,68 +303,77 @@ test("an owned native instance follows a new checkout and keeps its data", asyncexpect(saved?.releaseDir).toBe(next);expect(saved?.source).toEqual(moved.instance.source);});-test("a resumed instance moves off ports another program took", async () => {- const f = await fixture();- const options = { home: f.home, name: "native-test" };- const first = await prepareNativeConfiguration(f.repo, options);- const before = first.instance.source!.ports;- const livekit = (await readLiveKitSettings(first.instance.root))!;- await occupy(before.web);- await occupy(before.teamhub);- await occupy(before.postgres);- await occupy(livekit.httpPort);- await occupy(livekit.rtcPort, "udp");+// Four real configurations run Windows ACL and process checks, which can+// exceed the ordinary Windows test timeout.+test(+ "a resumed instance moves off ports another program took",+ async () => {+ const f = await fixture();+ const options = { home: f.home, name: "native-test" };+ const first = await prepareNativeConfiguration(f.repo, {+ ...options,+ port: await freePort(new Set()),+ });+ const before = first.instance.source!.ports;+ const livekit = (await readLiveKitSettings(first.instance.root))!;+ await occupy(before.web);+ await occupy(before.teamhub);+ await occupy(before.postgres);+ await occupy(livekit.httpPort);+ await occupy(livekit.rtcPort, "udp");- const second = await prepareNativeConfiguration(f.repo, options);- const after = second.instance.source!.ports;- for (const name of ["web", "teamhub", "postgres"] as const)- expect(after[name]).not.toBe(before[name]);- expect(after.nodeServices).toBe(before.nodeServices);- expect(after.document).toBe(before.document);- // Without an owner account nothing keeps the origin yet, so it moves too.- expect(second.instance.port).toBe(after.web);- expect(second.instance.origin).toBe(`http://localhost:${after.web}`);- expect(await loadInstance(options)).toEqual(second.instance);- expect(second.env.WEB_PUBLIC_ORIGIN).toBe(second.instance.origin);- expect(second.env.TEAMHUB_HTTP_ADDRESS).toBe(`127.0.0.1:${after.teamhub}`);- expect(second.env.TEAMHUB_DATABASE_URL).toContain(- `:${after.postgres}/simplexai`,- );- const moved = (await readLiveKitSettings(first.instance.root))!;- expect(moved.httpPort).not.toBe(livekit.httpPort);- expect(moved.rtcPort).not.toBe(livekit.rtcPort);- expect(moved.apiSecret).toBe(livekit.apiSecret);- expect(second.env.LIVEKIT_URL).toBe(`ws://127.0.0.1:${moved.httpPort}`);- expect(second.warnings.join("")).toContain(- `Port ${before.teamhub} is in use by another program; Linger's teamhub uses port ${after.teamhub} instead.`,- );- expect(second.warnings).toHaveLength(5);+ const second = await prepareNativeConfiguration(f.repo, options);+ const after = second.instance.source!.ports;+ for (const name of ["web", "teamhub", "postgres"] as const)+ expect(after[name]).not.toBe(before[name]);+ expect(after.nodeServices).toBe(before.nodeServices);+ expect(after.document).toBe(before.document);+ // Without an owner account nothing keeps the origin yet, so it moves too.+ expect(second.instance.port).toBe(after.web);+ expect(second.instance.origin).toBe(`http://localhost:${after.web}`);+ expect(await loadInstance(options)).toEqual(second.instance);+ expect(second.env.WEB_PUBLIC_ORIGIN).toBe(second.instance.origin);+ expect(second.env.TEAMHUB_HTTP_ADDRESS).toBe(`127.0.0.1:${after.teamhub}`);+ expect(second.env.TEAMHUB_DATABASE_URL).toContain(+ `:${after.postgres}/simplexai`,+ );+ const moved = (await readLiveKitSettings(first.instance.root))!;+ expect(moved.httpPort).not.toBe(livekit.httpPort);+ expect(moved.rtcPort).not.toBe(livekit.rtcPort);+ expect(moved.apiSecret).toBe(livekit.apiSecret);+ expect(second.env.LIVEKIT_URL).toBe(`ws://127.0.0.1:${moved.httpPort}`);+ expect(second.warnings.join("")).toContain(+ `Port ${before.teamhub} is in use by another program; Linger's teamhub uses port ${after.teamhub} instead.`,+ );+ expect(second.warnings).toHaveLength(5);- // Once the owner account exists, a Computer this installer enrolled keeps- // the origin: the web port stays and its service reports the program.- await writeFile(- path.join(first.instance.root, "local-account.json"),- JSON.stringify({ provisioned: true }),- { mode: 0o600 },- );- await occupy(after.web);- const third = await prepareNativeConfiguration(f.repo, options);- expect(third.instance.port).toBe(after.web);- expect(third.instance.source!.ports).toEqual(after);- expect(third.warnings).toEqual([]);+ // Once the owner account exists, a Computer this installer enrolled keeps+ // the origin: the web port stays and its service reports the program.+ await writeFile(+ path.join(first.instance.root, "local-account.json"),+ JSON.stringify({ provisioned: true }),+ { mode: 0o600 },+ );+ await occupy(after.web);+ const third = await prepareNativeConfiguration(f.repo, options);+ expect(third.instance.port).toBe(after.web);+ expect(third.instance.source!.ports).toEqual(after);+ expect(third.warnings).toEqual([]);- // A database set aside from an older install marks the account to be made- // again, but that install's Computer still keeps the origin.- await writeFile(- path.join(first.instance.root, "local-account.json"),- JSON.stringify({ provisioned: false }),- { mode: 0o600 },- );- await mkdir(path.join(first.instance.root, "simplex-backup-earlier"));- const fourth = await prepareNativeConfiguration(f.repo, options);- expect(fourth.instance.port).toBe(after.web);- expect(fourth.warnings).toEqual([]);-});+ // A database set aside from an older install marks the account to be made+ // again, but that install's Computer still keeps the origin.+ await writeFile(+ path.join(first.instance.root, "local-account.json"),+ JSON.stringify({ provisioned: false }),+ { mode: 0o600 },+ );+ await mkdir(path.join(first.instance.root, "simplex-backup-earlier"));+ const fourth = await prepareNativeConfiguration(f.repo, options);+ expect(fourth.instance.port).toBe(after.web);+ expect(fourth.warnings).toEqual([]);+ },+ process.platform === "win32" ? 150_000 : undefined,+);test("the desktop's web origin moves off a taken port after the account exists", async () => {const f = await fixture();const options = { home: f.home, name: "desktop", externalComputer: true };diff --git a/packages/local-installation/src/runtime-credentials.test.ts b/packages/local-installation/src/runtime-credentials.test.tsindex 94269d2b..e157d04b 100644--- a/packages/local-installation/src/runtime-credentials.test.ts+++ b/packages/local-installation/src/runtime-credentials.test.ts@@ -3,6 +3,8 @@ import { expect, test, vi } from "vitest";import { saveRuntimeApiKey } from "./runtime-credentials.js";import { readdir } from "node:fs/promises";import path from "node:path";+const home = path.resolve("/owned");+const instance = path.join(home, "instances", "default");test("delegates credential verification and native profile writing upstream through private stdin", async () => {const localmodels = vi.fn<typeof runLocalmodels>(async () => ({code: 0,@@ -10,7 +12,7 @@ test("delegates credential verification and native profile writing upstream throstderr: "",}));await saveRuntimeApiKey(- "/owned/instances/default",+ instance,"pi","openai-compatible","private-key",@@ -18,12 +20,12 @@ test("delegates credential verification and native profile writing upstream thro{ localmodels },);expect(localmodels).toHaveBeenCalledWith(- "/owned",+ home,["harness","auth","--root",- "/owned/runtime/harness",+ path.join(home, "runtime", "harness"),"--runtime","pi","--config-stdin",@@ -74,14 +76,9 @@ test("rejects malformed user input before upstream access", async () => {],] as const) {await expect(- saveRuntimeApiKey(- "/owned/instances/default",- runtime,- provider,- key,- model,- { localmodels },- ),+ saveRuntimeApiKey(instance, runtime, provider, key, model, {+ localmodels,+ }),).rejects.toThrow();}expect(localmodels).not.toHaveBeenCalled();diff --git a/packages/local-installation/src/setup-plan.test.ts b/packages/local-installation/src/setup-plan.test.tsindex 77ba816a..54cd8443 100644--- a/packages/local-installation/src/setup-plan.test.ts+++ b/packages/local-installation/src/setup-plan.test.ts@@ -1,3 +1,4 @@+import path from "node:path";import { expect, it, vi } from "vitest";import { inspectSetup } from "./setup-plan.js";@@ -43,19 +44,20 @@ const runner = (value: object = upstream()) =>vi.fn(async () => ({ code: 0, stdout: JSON.stringify(value), stderr: "" }));it("delegates all hardware policy, runtime detection, estimates and recommendation upstream", async () => {const localmodels = runner();+ const home = path.resolve("/owned");const report = await inspectSetup({- home: "/owned",+ home,localmodels,});expect(localmodels).toHaveBeenCalledWith(- "/owned",+ home,["setup","inspect","--root",- "/owned/runtime/harness",+ path.join(home, "runtime", "harness"),"--model-base-dir",- "/owned/runtime/localmodels/models",+ path.join(home, "runtime", "localmodels", "models"),"--decision","none","--offline",diff --git a/packages/local-installation/src/source-computer.test.ts b/packages/local-installation/src/source-computer.test.tsindex aa27a6d5..be0a27b8 100644--- a/packages/local-installation/src/source-computer.test.ts+++ b/packages/local-installation/src/source-computer.test.ts@@ -58,36 +58,41 @@ test("reuses a suitable installed release without changing global Computer", asy});test("downloads the checkout-served release when installed Computer is below the work admission minimum", async () => {const instance = await fixture();+ const windows = process.platform === "win32";+ const shell = windows ? "powershell.exe" : "bash";+ const url = `http://localhost:31234/install/linger-computer.${windows ? "ps1" : "sh"}`;+ const executable = path.join(+ instance.root,+ "computer",+ "bin",+ windows ? "linger-computer.exe" : "linger-computer",+ );vi.mocked(runProcess).mockImplementation(async (command) => ({code: 0,stdout:command === "linger-computer"? "linger-computer 0.38.0"- : command === "bash"+ : command === shell? "installed": "linger-computer 0.39.0",stderr: "",}));- const fetcher = vi.fn(async (url: string) => {- expect(url).toBe("http://localhost:31234/install/linger-computer.sh");- return new Response("#!/bin/bash\nexit 0\n");- });+ const fetcher = vi.fn(+ async (_url: string) =>+ new Response(windows ? "exit 0\n" : "#!/bin/bash\nexit 0\n"),+ );vi.stubGlobal("fetch", fetcher);await prepareSourceComputer(instance, new AbortController().signal);- expect(fetcher.mock.calls[0]?.[0]).toBe(- "http://localhost:31234/install/linger-computer.sh",- );+ expect(fetcher.mock.calls[0]?.[0]).toBe(url);const installer = vi.mocked(runProcess)- .mock.calls.find((call) => call[0] === "bash");+ .mock.calls.find((call) => call[0] === shell);expect(installer?.[2]?.env).toMatchObject({LINGER_COMPUTER_DATA_DIR: path.join(instance.root, "computer/release"),LINGER_COMPUTER_BIN_DIR: path.join(instance.root, "computer/bin"),LINGER_COMPUTER_CONFIG: instance.computerConfig,});- expect(instance.computerExecutable).toBe(- path.join(instance.root, "computer/bin/linger-computer"),- );+ expect(instance.computerExecutable).toBe(executable);expect(JSON.parse(await readFile(path.join(instance.root, "instance.json"), "utf8"),diff --git a/packages/local-installation/src/test-support/computer.ts b/packages/local-installation/src/test-support/computer.tsnew file mode 100644index 00000000..52f00042--- /dev/null+++ b/packages/local-installation/src/test-support/computer.ts@@ -0,0 +1,24 @@+import { readFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import type { runProcess } from "../process.js";++export function withComputerFixture(run: typeof runProcess): typeof runProcess {+ if (process.platform !== "win32") return run;+ return async (executable, args, options) => {+ // These tests use a JavaScript CLI with a Node shebang on POSIX. On+ // Windows, start that same fixture explicitly with the Node executable.+ if (+ path.isAbsolute(executable) &&+ path.basename(executable) === "computer"+ ) {+ const relative = path.relative(tmpdir(), executable);+ if (!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) {+ const contents = await readFile(executable, "utf8").catch(() => "");+ if (contents.startsWith(`#!${process.execPath}\n`))+ return run(process.execPath, [executable, ...args], options);+ }+ }+ return run(executable, args, options);+ };+}diff --git a/packages/local-installation/src/test-support/private.ts b/packages/local-installation/src/test-support/private.tsnew file mode 100644index 00000000..3e9cf006--- /dev/null+++ b/packages/local-installation/src/test-support/private.ts@@ -0,0 +1,16 @@+import { stat } from "node:fs/promises";+import { expect } from "vitest";+import { windowsPrivatePath } from "../windows-private.js";++export async function expectPrivate(+ file: string,+ kind: "file" | "directory" = "file",+): Promise<void> {+ if (process.platform === "win32") {+ await expect(windowsPrivatePath(file, kind)).resolves.toBeUndefined();+ } else {+ expect((await stat(file)).mode & 0o777).toBe(+ kind === "directory" ? 0o700 : 0o600,+ );+ }+}diff --git a/packages/local-installation/test/fixtures/absolute-path.zip b/packages/local-installation/test/fixtures/absolute-path.zipnew file mode 100644index 00000000..09dfe7c9Binary files /dev/null and b/packages/local-installation/test/fixtures/absolute-path.zip differdiff --git a/packages/local-installation/test/fixtures/backslash-parent-path.zip b/packages/local-installation/test/fixtures/backslash-parent-path.zipnew file mode 100644index 00000000..22ac4606Binary files /dev/null and b/packages/local-installation/test/fixtures/backslash-parent-path.zip differdiff --git a/packages/local-installation/test/fixtures/deflated.zip b/packages/local-installation/test/fixtures/deflated.zipnew file mode 100644index 00000000..d851a096Binary files /dev/null and b/packages/local-installation/test/fixtures/deflated.zip differdiff --git a/packages/local-installation/test/fixtures/parent-path.zip b/packages/local-installation/test/fixtures/parent-path.zipnew file mode 100644index 00000000..52a1ef7eBinary files /dev/null and b/packages/local-installation/test/fixtures/parent-path.zip differdiff --git a/packages/local-installation/test/fixtures/stored.zip b/packages/local-installation/test/fixtures/stored.zipnew file mode 100644index 00000000..716e97c7Binary files /dev/null and b/packages/local-installation/test/fixtures/stored.zip differdiff --git a/packages/local-installation/test/windows-global-setup.ts b/packages/local-installation/test/windows-global-setup.tsnew file mode 100644index 00000000..4c19930d--- /dev/null+++ b/packages/local-installation/test/windows-global-setup.ts@@ -0,0 +1,54 @@+import { mkdtemp, realpath, rm } from "node:fs/promises";+import { homedir } from "node:os";+import path from "node:path";+import type { TestProject } from "vitest/node";+import { windowsPrivatePath } from "../src/windows-private.js";++const windowsPowerShellModules = path.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "Modules",+);++declare module "vitest" {+ interface ProvidedContext {+ windowsFixtures: { temporary: string; modules: string };+ }+}++export default async function setup(project: TestProject) {+ // The system TEMP can inherit shared access from AppData. Every fixture+ // starts below one fresh private directory, with user/SYSTEM inheritance.+ const home = await realpath(homedir());+ const temporary = await mkdtemp(path.join(home, "linger-test-"));+ const cleanup = async () => {+ if (+ path.dirname(temporary) !== home ||+ (await realpath(temporary)) !== temporary+ )+ throw new Error(+ "Refusing to clean a test directory outside its original location",+ );+ await rm(temporary, { recursive: true, force: true, maxRetries: 10 });+ };+ const previousModules = process.env.PSModulePath;+ try {+ // Windows PowerShell 5 must not try to load the caller's PowerShell 7+ // modules when it runs Get-Acl or reads the Windows process table.+ process.env.PSModulePath = windowsPowerShellModules;+ await windowsPrivatePath(temporary, "directory", true);+ } catch (error) {+ await cleanup();+ throw error;+ } finally {+ if (previousModules === undefined) delete process.env.PSModulePath;+ else process.env.PSModulePath = previousModules;+ }+ project.provide("windowsFixtures", {+ temporary,+ modules: windowsPowerShellModules,+ });+ return cleanup;+}diff --git a/packages/local-installation/test/windows-setup.ts b/packages/local-installation/test/windows-setup.tsnew file mode 100644index 00000000..93a1a5a1--- /dev/null+++ b/packages/local-installation/test/windows-setup.ts@@ -0,0 +1,7 @@+import { inject } from "vitest";+import type {} from "./windows-global-setup.js";++const { temporary, modules } = inject("windowsFixtures");+process.env.TMP = temporary;+process.env.TEMP = temporary;+process.env.PSModulePath = modules;diff --git a/packages/local-installation/tsconfig.build.json b/packages/local-installation/tsconfig.build.jsonindex f61495b6..b9517705 100644--- a/packages/local-installation/tsconfig.build.json+++ b/packages/local-installation/tsconfig.build.json@@ -1 +1,6 @@-{ "extends": "./tsconfig.json", "exclude": ["src/**/*.test.ts"] }+{+ "extends": "./tsconfig.json",+ "compilerOptions": { "rootDir": "src" },+ "include": ["src/**/*.ts"],+ "exclude": ["src/**/*.test.ts", "src/test-support"]+}diff --git a/packages/local-installation/tsconfig.json b/packages/local-installation/tsconfig.jsonindex 5da46164..12e15578 100644--- a/packages/local-installation/tsconfig.json+++ b/packages/local-installation/tsconfig.json@@ -1,5 +1,5 @@{"extends": "../../tsconfig.base.json",- "compilerOptions": { "types": ["node"], "outDir": "dist", "rootDir": "src" },- "include": ["src/**/*.ts"]+ "compilerOptions": { "types": ["node"], "outDir": "dist" },+ "include": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts"]}diff --git a/packages/local-installation/vitest.config.ts b/packages/local-installation/vitest.config.tsnew file mode 100644index 00000000..20f2db8b--- /dev/null+++ b/packages/local-installation/vitest.config.ts@@ -0,0 +1,22 @@+import { realpathSync } from "node:fs";+import { tmpdir } from "node:os";+import { defineConfig } from "vitest/config";++const windows = process.platform === "win32";++export default defineConfig({+ test: {+ include: ["src/**/*.test.ts"],+ // Real Windows ACL and listener checks launch PowerShell processes.+ testTimeout: windows ? 90_000 : 5_000,+ maxWorkers: 2,+ // macOS can return a symlinked temporary directory.+ env: windows ? {} : { TMPDIR: realpathSync(tmpdir()) },+ ...(windows+ ? {+ globalSetup: ["./test/windows-global-setup.ts"],+ setupFiles: ["./test/windows-setup.ts"],+ }+ : {}),+ },+});