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.
feat(desktop): give the desktop's Computer the localmodels tool
Dongdong Chend3193294b262
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex d436fbcd..555f3c07 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -368,7 +368,12 @@ building a package.variables do not reach the daemon. The config's`runtimeEnvironment` (the local server's runtime: these paths plus`CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `PI_CODING_AGENT_DIR`) replaces them,- names compared case-insensitively for Windows.+ names compared case-insensitively for Windows. Its four+ `LINGER_LOCALMODELS_*` paths become the daemon config's `local_models`+ section, which the daemon's model library runs. Every `--resume` reports+ the runtime again; a change updates `runtimeEnvironment` and restarts the+ daemon once its tasks end (`computer.runtime`), so an install from before+ the daemon knew the tool gains it.- `LINGER_LOCALMODELS_DEV_PYTHON`, `LINGER_LOCALMODELS_DEV_MODULE_DIR`:absolute Python and module directory for running a local `localmodels`checkout in Quick Install and the Desktop Computer without fetching thediff --git a/apps/desktop/src/main/computer-daemon.test.ts b/apps/desktop/src/main/computer-daemon.test.tsindex 6ff479b8..fd7958eb 100644--- a/apps/desktop/src/main/computer-daemon.test.ts+++ b/apps/desktop/src/main/computer-daemon.test.ts@@ -215,6 +215,36 @@ describe("ComputerDaemonModule", () => {expect(written.preferred_runtime).toBe("pi");});+ it("names the localmodels tool and restarts when the installer reports it", async () => {+ const { daemon, ctx, bus, config, children } = setup();+ await daemon.start(ctx);+ bus.emit("computer.changed", "computer-1");+ await vi.waitFor(() => expect(children).toHaveLength(2));+ expect(+ JSON.parse(readFileSync(children[1]!.configFile, "utf8")).local_models,+ ).toBeUndefined();+ config.update({+ runtimeEnvironment: {+ LINGER_LOCALMODELS_PYTHON:+ "/home/me/.linger/tools/localmodels/kit/python3",+ LINGER_LOCALMODELS_MODULE_DIR: "/home/me/.linger/tools/localmodels/kit",+ LINGER_LOCALMODELS_STATE: "/home/me/.linger/runtime/localmodels/state",+ LINGER_LOCALMODELS_BASE_DIR:+ "/home/me/.linger/runtime/localmodels/models",+ },+ });+ bus.emit("computer.runtime");+ await vi.waitFor(() => expect(children).toHaveLength(3));+ expect(+ JSON.parse(readFileSync(children[2]!.configFile, "utf8")).local_models,+ ).toEqual({+ python: "/home/me/.linger/tools/localmodels/kit/python3",+ module_directory: "/home/me/.linger/tools/localmodels/kit",+ state_directory: "/home/me/.linger/runtime/localmodels/state",+ base_directory: "/home/me/.linger/runtime/localmodels/models",+ });+ });+it("takes Windows runtime paths and replaces inherited names in any case", () => {const env = daemonEnvironment({diff --git a/apps/desktop/src/main/computer-daemon.ts b/apps/desktop/src/main/computer-daemon.tsindex 14ec5ac4..0af2c876 100644--- a/apps/desktop/src/main/computer-daemon.ts+++ b/apps/desktop/src/main/computer-daemon.ts@@ -10,6 +10,11 @@ import path from "node:path";import { createInterface } from "node:readline";import { finished } from "node:stream";+import {+ localModelsConfig,+ localmodelsToolFromEnvironment,+} from "@linger/local-installation/localmodels-computer";+import type { RuntimeState } from "../shared/api.js";import type {ComputerCredential,@@ -156,6 +161,7 @@ export const daemonConfig = (const value = options.env?.[name];if (value && platformPath.isAbsolute(value)) runtimePaths[runtime] = value;}+ const localModels = localmodelsToolFromEnvironment(options.env, platformPath);return {runner_id: credential.computerId,display_name:@@ -179,6 +185,7 @@ export const daemonConfig = (desktop: options.teamhubCliDirectory? { teamhub_cli_directory: options.teamhubCliDirectory }: {},+ ...(localModels ? { local_models: localModelsConfig(localModels) } : {}),};};@@ -240,6 +247,7 @@ export class ComputerDaemonModule implements Module {// cancelling them.ctx.bus.on("grants.changed", () => this.#requestRestart(true)),ctx.bus.on("computer.renamed", () => this.#requestRestart(true)),+ ctx.bus.on("computer.runtime", () => this.#requestRestart(true)),);const env = this.#options.env ?? {};const protect = this.#protect();diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex 88909902..b214a0aa 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -108,7 +108,9 @@ if (args.includes("--inspect")) {}if (args.includes("--resume")) {const code = fs.existsSync(path.join(home, "resume-fails")) ? 1 : 0;- process.stdout.write("noise\n" + JSON.stringify({ code, message: code ? "Native teamhub stopped" : "ok" }) + "\n");+ const runtimeFile = path.join(home, "resume-runtime.json");+ const runtime = fs.existsSync(runtimeFile) ? JSON.parse(fs.readFileSync(runtimeFile, "utf8")) : undefined;+ process.stdout.write("noise\n" + JSON.stringify({ code, message: code ? "Native teamhub stopped" : "ok", ...(runtime ? { runtime } : {}) }) + "\n");process.exit(code);}const origin = "http://127.0.0.1:4321";@@ -2168,6 +2170,46 @@ describe("LocalServerModule after a restart", () => {await f.host.stop("quit");});+ it("takes the runtime and localmodels paths a resume reports, restarting the Computer once", async () => {+ const tool = {+ LINGER_LOCALMODELS_PYTHON:+ "/home/u/.linger/tools/localmodels/kit/python3",+ LINGER_LOCALMODELS_MODULE_DIR: "/home/u/.linger/tools/localmodels/kit",+ LINGER_LOCALMODELS_STATE: "/home/u/.linger/runtime/localmodels/state",+ LINGER_LOCALMODELS_BASE_DIR: "/home/u/.linger/runtime/localmodels/models",+ };+ const environment = { LINGER_PI_PATH: "/home/u/.linger/pi", ...tool };+ const f = fixture(+ {},+ {+ ...enrolled,+ runtimeEnvironment: { LINGER_PI_PATH: "/home/u/.linger/pi" },+ },+ (home) => {+ mkdirSync(path.join(home, "desktop"), { recursive: true });+ writeFileSync(+ path.join(home, "desktop", "local-server.json"),+ JSON.stringify({+ home,+ repo: "/source",+ origin: "http://localhost:3000",+ }),+ );+ writeFileSync(+ path.join(home, "resume-runtime.json"),+ JSON.stringify({ setupChoice: "local-models", environment }),+ );+ },+ );+ const restarts = vi.fn();+ f.bus.on("computer.runtime", restarts);+ await f.host.start();+ await vi.waitFor(() => 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");+ });+it("starts the services again in the folder they were installed in", async () => {const elsewhere = path.join(tempDirectory(), "Linger");const f = fixture({}, enrolled, (home) => {diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex 8b9b7e91..8b3c2577 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -20,6 +20,7 @@ import {writeFile,} from "node:fs/promises";import path from "node:path";+import { isDeepStrictEqual } from "node:util";import { createInterface } from "node:readline";import type { Readable } from "node:stream";import { pipeline } from "node:stream/promises";@@ -2148,47 +2149,85 @@ export class LocalServerModule implements Module {): Promise<void> {await this.#adoptSourceKeys(record.home);const node = await this.#ensureNode(signal);- const outcome = await new Promise<{ code: number; message: string }>(- (resolve, reject) => {- const child = spawn(- node,- [- this.#installerScript(),- "--home",- record.home,- "--source-repo",- repo,- "--external-computer",- "--instance",- LOCAL_INSTANCE,- "--resume",- ],- {- stdio: ["ignore", "pipe", "ignore"],- // The pinned Node is a console program; without this Windows- // opens a console window for it.- windowsHide: true,- env: { ...process.env, LINGER_HOME: record.home },- signal,- },- );- let output = "";- child.stdout.on("data", (chunk: Buffer) => {- output += chunk.toString("utf8");- });- child.once("error", reject);- child.once("close", (code) => {- try {- const last = output.trim().split("\n").at(-1) ?? "";- resolve(JSON.parse(last) as { code: number; message: string });- } catch {- reject(new Error(`The installer exited with code ${code}`));- }- });- },- );+ const outcome = await new Promise<{+ code: number;+ message: string;+ runtime?: InstanceRuntime;+ }>((resolve, reject) => {+ const child = spawn(+ node,+ [+ this.#installerScript(),+ "--home",+ record.home,+ "--source-repo",+ repo,+ "--external-computer",+ "--instance",+ LOCAL_INSTANCE,+ "--resume",+ ],+ {+ stdio: ["ignore", "pipe", "ignore"],+ // The pinned Node is a console program; without this Windows+ // opens a console window for it.+ windowsHide: true,+ env: { ...process.env, LINGER_HOME: record.home },+ signal,+ },+ );+ let output = "";+ child.stdout.on("data", (chunk: Buffer) => {+ output += chunk.toString("utf8");+ });+ child.once("error", reject);+ child.once("close", (code) => {+ try {+ const last = output.trim().split("\n").at(-1) ?? "";+ resolve(+ JSON.parse(last) as {+ code: number;+ message: string;+ runtime?: InstanceRuntime;+ },+ );+ } catch {+ reject(new Error(`The installer exited with code ${code}`));+ }+ });+ });if (outcome.code !== 0)throw new Error(outcome.message || "The installation stopped");+ this.#adoptRuntime(outcome.runtime);+ }++ // Every resume reports the runtime and localmodels tool paths, so an+ // install from before the Computer knew one gains it. A change restarts+ // the Computer once its running tasks end.+ #adoptRuntime(runtime: InstanceRuntime | undefined): void {+ const ctx = this.#ctx;+ if (+ !ctx ||+ !runtime?.environment ||+ typeof runtime.environment !== "object" ||+ Object.values(runtime.environment).some(+ (value) => typeof value !== "string",+ )+ )+ return;+ if (+ isDeepStrictEqual(+ ctx.config.get().runtimeEnvironment ?? {},+ runtime.environment,+ )+ )+ return;+ ctx.config.update({ runtimeEnvironment: runtime.environment });+ ctx.log.info("local_server.runtime", {+ runtime: runtime.setupChoice,+ keys: Object.keys(runtime.environment),+ });+ ctx.bus.emit("computer.runtime");}// Kept in the default home, wherever the installation went.diff --git a/apps/desktop/src/main/modules.ts b/apps/desktop/src/main/modules.tsindex 58461299..068053ef 100644--- a/apps/desktop/src/main/modules.ts+++ b/apps/desktop/src/main/modules.ts@@ -19,6 +19,8 @@ export interface BusEvents {// Why the Computer service keeps exiting at start, or undefined once it ran."computer.failed": [reason: string | undefined];"computer.renamed": [];+ // The local server's installer reported new runtime or localmodels paths.+ "computer.runtime": [];"diagnostics.changed": [];"grants.changed": [];"local-server.changed": [];diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex 8eec2db1..5e3dbb05 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -22,7 +22,10 @@ on stderr for the desktop to show.stopped services headless, reusing its saved choices; the desktop client runs itafter a reboot and reads the outcome from the single JSON line on stdout. Italso restarts running services when the instance's `user.env` no longer-matches the configuration they started with.+matches the configuration they started with. With `--external-computer`, a+successful outcome carries `runtime`, the same instance runtime as+`GET /api/instances/{name}/runtime` (runtime and localmodels tool paths), so+the desktop's Computer follows them.`--stop` (with `--instance`) is the desktop uninstall's and Windows setup's: it stops themanager the desktop started for that instance (its `/api/stop` cancels adiff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.tsindex 12f05386..0865a4b7 100644--- a/apps/linger-installer/src/main.ts+++ b/apps/linger-installer/src/main.ts@@ -126,9 +126,20 @@ async function resume(options: ReturnType<typeof parseInstallerArguments>) {message: error instanceof Error ? error.message : String(error),details: undefined,}));+ // The desktop's own Computer takes the runtime and localmodels tool paths+ // from every resume, so an install from before it knew one gains it.+ const runtime =+ outcome.code === 0 && options.externalComputer+ ? await import("./server/instance-runtime.js")+ .then(({ instanceRuntime }) =>+ instanceRuntime(options.home, options.instanceName!),+ )+ .catch(() => undefined)+ : undefined;// Detached service processes may keep handles open; exit once flushed.- process.stdout.write(`${JSON.stringify(outcome)}\n`, () =>- process.exit(outcome.code),+ process.stdout.write(+ `${JSON.stringify({ ...outcome, ...(runtime ? { runtime } : {}) })}\n`,+ () => process.exit(outcome.code),);}// Headless check of this computer for the desktop client: the setup reportdiff --git a/apps/linger-installer/src/server/core-gateway.test.ts b/apps/linger-installer/src/server/core-gateway.test.tsindex 7ade37ff..01161b2b 100644--- a/apps/linger-installer/src/server/core-gateway.test.ts+++ b/apps/linger-installer/src/server/core-gateway.test.ts@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({start: vi.fn(),managedEnvironment: vi.fn(),localModelsEnvironment: vi.fn(),+ localmodelsTool: vi.fn(),}));vi.mock("@linger/local-installation/managed-codex", () => ({managedRuntimeEnvironment: mocks.managedEnvironment,@@ -22,6 +23,13 @@ vi.mock("@linger/local-installation/managed-codex", () => ({vi.mock("@linger/local-installation/local-models", () => ({localModelsEnvironment: mocks.localModelsEnvironment,}));+vi.mock(+ "@linger/local-installation/localmodels-computer",+ async (original) => ({+ ...(await original<object>()),+ localmodelsComputerTool: mocks.localmodelsTool,+ }),+);vi.mock("@linger/local-installation/model-gateway", () => ({prepareModelGateway: mocks.prepare,stopModelGateway: mocks.stopGateway,@@ -169,3 +177,26 @@ it("reports the local model's Pi for local models", async () => {},});});++it("reports the localmodels tool for the desktop Computer's model library", async () => {+ mocks.runtime = "codex";+ mocks.managedEnvironment.mockResolvedValue({});+ mocks.localModelsEnvironment.mockResolvedValue({});+ mocks.localmodelsTool.mockResolvedValueOnce({+ python: "/test/tools/localmodels/kit/python3",+ moduleDirectory: "/test/tools/localmodels/kit",+ stateDirectory: "/test/runtime/localmodels/state",+ baseDirectory: "/test/runtime/localmodels/models",+ });+ await expect(+ coreAdapter("/test", "/checkout").runtime("default"),+ ).resolves.toEqual({+ setupChoice: "codex",+ environment: {+ LINGER_LOCALMODELS_PYTHON: "/test/tools/localmodels/kit/python3",+ LINGER_LOCALMODELS_MODULE_DIR: "/test/tools/localmodels/kit",+ LINGER_LOCALMODELS_STATE: "/test/runtime/localmodels/state",+ LINGER_LOCALMODELS_BASE_DIR: "/test/runtime/localmodels/models",+ },+ });+});diff --git a/apps/linger-installer/src/server/core.ts b/apps/linger-installer/src/server/core.tsindex 39242868..ad9d86fb 100644--- a/apps/linger-installer/src/server/core.ts+++ b/apps/linger-installer/src/server/core.ts@@ -27,20 +27,9 @@ import { inspectComputer } from "@linger/local-installation/computer";import type { components } from "@linger/wire-contracts/linger-installer/types";import { publicComputer } from "./public.js";import { prepareDependencies } from "@linger/local-installation/dependencies";-import {- managedRuntimeEnvironment,- readManagedModel,-} from "@linger/local-installation/managed-codex";-import { localModelsEnvironment } from "@linger/local-installation/local-models";+import { readManagedModel } from "@linger/local-installation/managed-codex";import type { RunInstallation } from "./jobs.js";-const RUNTIME_ENVIRONMENT = [- "LINGER_CODEX_PATH",- "LINGER_CLAUDE_PATH",- "LINGER_PI_PATH",- "CODEX_HOME",- "CLAUDE_CONFIG_DIR",- "PI_CODING_AGENT_DIR",-] as const;+import { instanceRuntime } from "./instance-runtime.js";export function coreAdapter(home: string,sourceRepo: string,@@ -187,25 +176,10 @@ export function coreAdapter(businessVerification: "not_run",};},- // What an external Computer (the desktop's) needs to find the runtime- // this installer manages: the paths the CLI's Computer gets in its- // environment, without the rest of that environment.- async runtime(+ runtime(name: string,): Promise<components["schemas"]["InstanceRuntime"] | undefined> {- const value = await instance(name);- if (!value) return undefined;- const setupChoice = await readSetupChoice({ name, home });- const found = {- ...(await managedRuntimeEnvironment(home, value.root)),- ...(await localModelsEnvironment(value)),- };- const environment: Record<string, string> = {};- for (const key of RUNTIME_ENVIRONMENT) {- const entry = found[key];- if (entry && path.isAbsolute(entry)) environment[key] = entry;- }- return { ...(setupChoice ? { setupChoice } : {}), environment };+ return instanceRuntime(home, name);},async login(name: string) {const value = await instance(name);diff --git a/apps/linger-installer/src/server/instance-runtime.ts b/apps/linger-installer/src/server/instance-runtime.tsnew file mode 100644index 00000000..0ba145c6--- /dev/null+++ b/apps/linger-installer/src/server/instance-runtime.ts@@ -0,0 +1,49 @@+import path from "node:path";+import { loadInstance } from "@linger/local-installation/instance";+import { localModelsEnvironment } from "@linger/local-installation/local-models";+import {+ LOCALMODELS_TOOL_ENVIRONMENT,+ localmodelsComputerTool,+ localmodelsToolEnvironment,+} from "@linger/local-installation/localmodels-computer";+import { pinnedToolSource } from "@linger/local-installation/localmodels-tool";+import { managedRuntimeEnvironment } from "@linger/local-installation/managed-codex";+import { readSetupChoice } from "@linger/local-installation/setup-selection";+import type { components } from "@linger/wire-contracts/linger-installer/types";++const RUNTIME_ENVIRONMENT = [+ "LINGER_CODEX_PATH",+ "LINGER_CLAUDE_PATH",+ "LINGER_PI_PATH",+ "CODEX_HOME",+ "CLAUDE_CONFIG_DIR",+ "PI_CODING_AGENT_DIR",+ ...LOCALMODELS_TOOL_ENVIRONMENT,+];++/**+ * What an external Computer (the desktop's) needs to find the runtime and+ * the localmodels tool this installer manages: the paths the CLI's Computer+ * gets, without the rest of its environment.+ */+export async function instanceRuntime(+ home: string,+ name: string,+): Promise<components["schemas"]["InstanceRuntime"] | undefined> {+ const value = await loadInstance({ name, home });+ if (!value) return undefined;+ const setupChoice = await readSetupChoice({ name, home });+ const found: Record<string, string | undefined> = {+ ...(await managedRuntimeEnvironment(home, value.root)),+ ...(await localModelsEnvironment(value)),+ ...localmodelsToolEnvironment(+ await localmodelsComputerTool(home, pinnedToolSource()),+ ),+ };+ const environment: Record<string, string> = {};+ for (const key of RUNTIME_ENVIRONMENT) {+ const entry = found[key];+ if (entry && path.isAbsolute(entry)) environment[key] = entry;+ }+ return { ...(setupChoice ? { setupChoice } : {}), environment };+}