diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 249ad41ba8..6453325734 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -518,7 +518,19 @@ Gateway and runs Agents. The daemon exits with the app. asynchronously after signaling `resume_ready` so removing the previous checkout never delays opening the window; otherwise the older services keep running from their folder, the record keeps naming it, and the start failure - page's Retry moves them again. `LocalServer` marks `localServer: true` in + page's Retry moves them again. When `--resume` starts services cleanly but + reports `runtimeError` or leaves `config.json` without the expected + `localmodels` kit (resolved read-only via `resolveEffectiveToolSource` so a + newer verified `/tools/localmodels/active.json` kit is respected and + never downgraded, and skipped under `LINGER_LOCALMODELS_DEV_*` overrides), + `LocalServer` logs `local_server.resume_runtime_failed` naming the error and + expected vs active kit hashes, keeps `runtimeRefreshPending: true` in + `desktop/local-server.json`, and schedules bounded background retries + (`local_server.runtime_refresh_retry_scheduled` / + `local_server.runtime_refresh_retry_exhausted`, abortable on stop, reset, + `server.changed`, or `suspendRecovery`) without blocking startup, clearing + `runtimeRefreshPending` and logging `local_server.runtime_refresh_recovered` + once adoption succeeds. `LocalServer` marks `localServer: true` in `config.json` when it owns the active server (explicitly set to `false` on `server.changed` to another origin, preserved on `server.moved`, and cleared with `serverUrl` on reset while keeping `preferredRuntime`/`runtimeEnvironment`); diff --git a/apps/desktop/src/main/local-server-resume.test.ts b/apps/desktop/src/main/local-server-resume.test.ts index cba52f14f7..5fbafb57f5 100644 --- a/apps/desktop/src/main/local-server-resume.test.ts +++ b/apps/desktop/src/main/local-server-resume.test.ts @@ -1,3 +1,10 @@ +import { execFileSync } from "node:child_process"; +import { + createHash, + generateKeyPairSync, + sign as cryptoSign, + type KeyObject, +} from "node:crypto"; import { existsSync, mkdirSync, @@ -7,12 +14,18 @@ import { } from "node:fs"; import path from "node:path"; +import { tarCommand } from "@linger/local-installation/archive"; import { atomicPrivate, composeProject, instanceRoot, privateDirectory, } from "@linger/local-installation/instance"; +import { + ACTIVE_KIT_RECORD_SCHEMA, + currentKitTarget, + writeActiveKitRecord, +} from "@linger/local-installation/localmodels-active"; import { describe, expect, it, vi } from "vitest"; import { NODE_RUNTIME_VERSION } from "../../../../scripts/local-computer-node-distributions.mjs"; @@ -84,6 +97,11 @@ function writeAppliedInstance(home: string, applied = true): void { function setupResumeFixture( installerScript: string, options: { + home?: string; + version?: string; + platform?: NodeJS.Platform; + arch?: string; + sourceArchive?: { readonly url: string; readonly sha256: string }; fetch?: typeof fetch; serverIdentity?: ( home: string, @@ -99,10 +117,17 @@ function setupResumeFixture( userEnvironmentPending?: boolean; beforeResume?: () => Promise; initialConfig?: Parameters[0]; + runtimeRefreshRetryDelaysMs?: readonly number[]; + kitPublicKeys?: Readonly>; + onLog?: (entry: { + level: string; + event: string; + fields?: Record; + }) => void; } = {}, ) { const root = tempDirectory(); - const home = path.join(root, "home"); + const home = options.home ?? path.join(root, "home"); const installerDirectory = path.join(root, "installer"); mkdirSync(installerDirectory, { recursive: true }); writeFileSync(path.join(installerDirectory, "installer.js"), installerScript); @@ -110,9 +135,18 @@ function setupResumeFixture( path.join(installerDirectory, "package.json"), '{"type":"commonjs"}', ); + const platform = options.platform ?? "linux"; + const arch = options.arch ?? "x64"; const node = path.join(home, "desktop", "node", `v${NODE_RUNTIME_VERSION}`); - mkdirSync(path.join(node, "bin"), { recursive: true }); - fixtureNode(path.join(node, "bin", "node")); + if (platform === "win32") { + mkdirSync(node, { recursive: true }); + const binary = path.join(node, "node.exe"); + if (!existsSync(binary)) fixtureNode(binary); + } else { + mkdirSync(path.join(node, "bin"), { recursive: true }); + const binary = path.join(node, "bin", "node"); + if (!existsSync(binary)) fixtureNode(binary); + } if (options.withRecord !== false) { mkdirSync(path.join(home, "desktop"), { recursive: true }); writeFileSync( @@ -147,11 +181,12 @@ function setupResumeFixture( const module = new LocalServerModule({ home, - version: "0.16.20", + version: options.version ?? "0.16.20", installerDirectory, - platform: "linux", - arch: "x64", + platform, + arch, pollMs: 10, + ...(options.sourceArchive ? { sourceArchive: options.sourceArchive } : {}), signIn: async () => {}, ...(options.serverIdentity ? { serverIdentity: options.serverIdentity } @@ -169,6 +204,10 @@ function setupResumeFixture( ? { unreachableGraceMs: options.unreachableGraceMs } : {}), ...(options.beforeResume ? { beforeResume: options.beforeResume } : {}), + ...(options.runtimeRefreshRetryDelaysMs !== undefined + ? { runtimeRefreshRetryDelaysMs: options.runtimeRefreshRetryDelaysMs } + : {}), + ...(options.kitPublicKeys ? { kitPublicKeys: options.kitPublicKeys } : {}), }); const host = new ModuleHost( @@ -192,9 +231,21 @@ function setupResumeFixture( config, bus, log: { - info: (event, fields) => logs.push({ level: "info", event, fields }), - warn: (event, fields) => logs.push({ level: "warn", event, fields }), - error: (event, fields) => logs.push({ level: "error", event, fields }), + info: (event, fields) => { + const entry = { level: "info", event, fields }; + logs.push(entry); + options.onLog?.(entry); + }, + warn: (event, fields) => { + const entry = { level: "warn", event, fields }; + logs.push(entry); + options.onLog?.(entry); + }, + error: (event, fields) => { + const entry = { level: "error", event, fields }; + logs.push(entry); + options.onLog?.(entry); + }, }, }, ); @@ -2924,3 +2975,1006 @@ describe("LocalServerModule warm restart fast path", () => { } }); }); + +function sha256Hex(content: string | Buffer): string { + return createHash("sha256").update(content).digest("hex"); +} + +function createSourceArchive(root: string): { + bytes: Buffer; + sha256: string; +} { + const tree = path.join(root, "source-archive-stage", "linger-0.2.2"); + mkdirSync(path.join(tree, "scripts"), { recursive: true }); + writeFileSync(path.join(tree, "scripts", "source-native.mjs"), ""); + writeFileSync( + path.join(tree, "package.json"), + JSON.stringify({ name: "linger", version: "0.2.2" }), + ); + const archivePath = path.join(root, "source.tar.gz"); + execFileSync(tarCommand(), [ + "-czf", + archivePath, + "-C", + path.join(root, "source-archive-stage"), + "linger-0.2.2", + ]); + const bytes = readFileSync(archivePath); + return { bytes, sha256: sha256Hex(bytes) }; +} + +function kitRuntimeEnvironment( + home: string, + sha256: string, +): Record { + const kitDir = path.join(home, "tools", "localmodels", sha256); + const pythonRel = + process.platform === "win32" + ? path.join("python", "python.exe") + : path.join("python", "bin", "python3.12"); + return { + LINGER_LOCALMODELS_PYTHON: path.join(kitDir, pythonRel), + LINGER_LOCALMODELS_MODULE_DIR: path.join(kitDir, "modules"), + LINGER_LOCALMODELS_STATE: path.join( + home, + "runtime", + "localmodels", + "state", + ), + LINGER_LOCALMODELS_BASE_DIR: path.join( + home, + "runtime", + "localmodels", + "models", + ), + }; +} + +function writeDistributionTool( + installerDirectory: string, + tool: { version: string; sha256: string }, +): void { + writeFileSync( + path.join(installerDirectory, "distribution.json"), + JSON.stringify({ + platform: process.platform, + arch: process.arch, + localmodelsTool: { + url: `https://cdn.example/kits/${tool.version}/kit.tgz`, + sha256: tool.sha256, + bytes: 1024, + version: tool.version, + sourceCommit: "a".repeat(40), + manifestSha256: "d".repeat(64), + }, + }), + ); +} + +interface SignedActiveKitFixtureOptions { + keyId: string; + minLingerVersion: string; + activeSha?: string; +} + +interface SignedActiveKitFixture { + activeSha: string; + activeEnv: Record; + toolsRoot: string; + publicKey: KeyObject; +} + +async function writeSignedActiveKitFixture( + home: string, + options: SignedActiveKitFixtureOptions, +): Promise { + const activeSha = options.activeSha ?? "c".repeat(64); + const activeCommit = "e".repeat(40); + const target = currentKitTarget(); + const toolsRoot = path.join(home, "tools", "localmodels"); + const activeKitDir = path.join(toolsRoot, activeSha); + const pythonRel = + process.platform === "win32" + ? "python/python.exe" + : "python/bin/python3.12"; + const pythonBody = "#!/bin/sh\necho ok\n"; + const initBody = "# localmodels\n"; + mkdirSync(path.dirname(path.join(activeKitDir, ...pythonRel.split("/"))), { + recursive: true, + }); + mkdirSync(path.join(activeKitDir, "modules", "localmodels"), { + recursive: true, + }); + writeFileSync(path.join(activeKitDir, ...pythonRel.split("/")), pythonBody, { + mode: 0o700, + }); + writeFileSync( + path.join(activeKitDir, "modules", "localmodels", "__init__.py"), + initBody, + ); + const toolJsonRaw = JSON.stringify({ + schemaVersion: 1, + platform: process.platform, + arch: process.arch, + sourceCommit: activeCommit, + python: pythonRel, + moduleDir: "modules", + assets: { + [pythonRel]: sha256Hex(pythonBody), + "modules/localmodels/__init__.py": sha256Hex(initBody), + }, + }); + const manifestSha256 = sha256Hex(toolJsonRaw); + writeFileSync(path.join(activeKitDir, "tool.json"), toolJsonRaw, { + mode: 0o600, + }); + + const { publicKey, privateKey } = generateKeyPairSync("ed25519"); + const manifestRaw = `${JSON.stringify( + { + schema: 2, + keyId: options.keyId, + channel: "next", + sequence: 115, + publishedAt: "2026-12-06T00:00:00Z", + version: "0.1.0.dev115", + npmVersion: "0.1.0-dev.115", + sourceCommit: activeCommit, + compatibility: { + cliContract: "3.1", + archiveLayout: "npm-package-v1", + minLingerVersion: options.minLingerVersion, + maxLingerVersion: null, + minDaemonVersion: "0.2.0", + kitPythonMinor: "3.12", + maxCatalogModels: 256, + diskSchemas: { + runtimeIndex: "localmodels.runtime-index/v1", + libraryStatus: "localmodels.library-status/v1", + libraryJob: "localmodels.library-job/v1", + speechStatus: "localmodels.speech-status/v1", + ttsStatus: "localmodels.tts-status/v1", + }, + httpContracts: { + speechSidecar: 1, + ttsSidecar: 1, + }, + }, + rollout: { percent: 100, salt: "0.1.0.dev115" }, + runtimeVersions: { + claude: "2.1.290", + codex: "0.170.0", + pi: "1.3.0", + }, + runtimeBaselines: { + claude: "2.1.282", + codex: "0.166.0", + pi: "1.2.0", + }, + kits: { + [target]: { + url: `https://downloads.example.com/kits/0.1.0.dev115/${target}.tgz`, + sha256: activeSha, + bytes: 102400, + sourceCommit: activeCommit, + manifestSha256, + }, + }, + }, + null, + 2, + )}\n`; + const signature = cryptoSign( + null, + Buffer.from(manifestRaw, "utf8"), + privateKey, + ).toString("base64"); + await writeActiveKitRecord(toolsRoot, { + schema: ACTIVE_KIT_RECORD_SCHEMA, + manifestRaw, + signature, + target, + kitDir: activeKitDir, + updatedAt: "2026-12-06T00:00:00Z", + }); + + return { + activeSha, + activeEnv: kitRuntimeEnvironment(home, activeSha), + toolsRoot, + publicKey, + }; +} + +describe("LocalServerModule resume runtime error and localmodels kit refresh", () => { + it("logs runtimeError on upgrade, marks runtimeRefreshPending, and recovers via bounded background retry", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const archive = createSourceArchive(root); + const oldSha = "a".repeat(64); + const newSha = "b".repeat(64); + const oldEnv = kitRuntimeEnvironment(home, oldSha); + const newEnv = kitRuntimeEnvironment(home, newSha); + const gateFile = path.join(root, "allow-retry.flag"); + const counterFile = path.join(root, "runs.txt"); + + const f = setupResumeFixture( + ` + const fs = require("node:fs"); + const args = process.argv.slice(2); + const repo = args[args.indexOf("--source-repo") + 1]; + const count = fs.existsSync(${JSON.stringify(counterFile)}) + ? Number(fs.readFileSync(${JSON.stringify(counterFile)}, "utf8")) + 1 + : 1; + fs.writeFileSync(${JSON.stringify(counterFile)}, String(count)); + if (count === 1) { + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000", source: repo }, + runtimeError: "Download failed for https://cdn.example/kit.tgz?token=secret123#frag", + }) + "\\n"); + } else { + const timer = setInterval(() => { + if (!fs.existsSync(${JSON.stringify(gateFile)})) return; + clearInterval(timer); + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000", source: repo }, + runtime: { + setupChoice: "local-models", + environment: ${JSON.stringify(newEnv)}, + }, + }) + "\\n"); + }, 15); + } + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + sourceArchive: { + url: "https://cdn.example/linger.tar.gz", + sha256: archive.sha256, + }, + fetch: (async (input: string | URL | Request) => { + const url = String(input instanceof Request ? input.url : input); + if (url.startsWith("https://cdn.example/")) + return new Response(new Uint8Array(archive.bytes), { status: 200 }); + return new Response("", { status: 200 }); + }) as typeof fetch, + initialConfig: { runtimeEnvironment: oldEnv }, + runtimeRefreshRetryDelaysMs: [30, 100], + }, + ); + const prevRepo = path.join(home, "desktop", "source", "previous"); + mkdirSync(path.join(prevRepo, "scripts"), { recursive: true }); + writeFileSync(path.join(prevRepo, "scripts", "source-native.mjs"), ""); + writeFileSync( + path.join(home, "desktop", "local-server.json"), + JSON.stringify({ + home, + repo: prevRepo, + origin: "http://localhost:3000", + version: "0.2.1", + }), + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: newSha, + }); + + const runtimeEvents = vi.fn(); + f.bus.on("computer.runtime", runtimeEvents); + + await f.host.start(); + try { + await waitForInstaller(() => + expect(f.module.status().phase).toBe("ready"), + ); + expect(f.showUpdating).toHaveBeenCalledOnce(); + expect(f.showStartFailed).not.toHaveBeenCalled(); + + const runtimeWarn = f.logs.find( + (entry) => entry.event === "local_server.resume_runtime_failed", + ); + expect(runtimeWarn).toEqual({ + level: "warn", + event: "local_server.resume_runtime_failed", + fields: { + error: "Download failed for https://cdn.example/kit.tgz", + expected_kit_sha256: newSha.slice(0, 12), + expected_kit_version: "0.1.0.dev113", + expected_kit_origin: "bundled", + active_kit_sha256: oldSha.slice(0, 12), + kit_mismatch: true, + }, + }); + expect(f.config.get().runtimeEnvironment).toEqual(oldEnv); + expect(runtimeEvents).not.toHaveBeenCalled(); + + const movedRepo = path.join( + home, + "desktop", + "source", + archive.sha256.slice(0, 16), + ); + expect( + JSON.parse( + readFileSync(path.join(home, "desktop", "local-server.json"), "utf8"), + ), + ).toEqual({ + home, + repo: movedRepo, + origin: "http://localhost:3000", + version: "0.2.2", + runtimeRefreshPending: true, + }); + + await waitForInstaller(() => + expect( + f.logs.find( + (entry) => + entry.event === "local_server.runtime_refresh_retry_scheduled", + ), + ).toMatchObject({ + fields: { attempt: 1, max_attempts: 2 }, + }), + ); + + // Unblock the bounded retry so the new kit is adopted. + writeFileSync(gateFile, "go"); + await waitForInstaller(() => + expect(f.config.get().runtimeEnvironment).toEqual(newEnv), + ); + expect(runtimeEvents).toHaveBeenCalledTimes(1); + await waitForInstaller(() => + expect( + JSON.parse( + readFileSync( + path.join(home, "desktop", "local-server.json"), + "utf8", + ), + ), + ).toEqual({ + home, + repo: movedRepo, + origin: "http://localhost:3000", + version: "0.2.2", + }), + ); + expect( + f.logs.find( + (entry) => entry.event === "local_server.runtime_refresh_recovered", + ), + ).toEqual({ + level: "info", + event: "local_server.runtime_refresh_recovered", + fields: { + kit_sha256: newSha.slice(0, 12), + kit_version: "0.1.0.dev113", + kit_origin: "bundled", + }, + }); + } finally { + await f.host.stop("quit"); + } + }); + + it("exhausts bounded retries cleanly and preserves runtimeRefreshPending for the next launch without blocking fast-ready", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const repo = createValidRepo(root); + const oldSha = "a".repeat(64); + const newSha = "b".repeat(64); + const oldEnv = kitRuntimeEnvironment(home, oldSha); + const newEnv = kitRuntimeEnvironment(home, newSha); + const counterFile = path.join(root, "launch1-runs.txt"); + + // Launch 1: initial resume + 2 bounded retries all fail runtime lookup. + const first = setupResumeFixture( + ` + const fs = require("node:fs"); + const count = fs.existsSync(${JSON.stringify(counterFile)}) + ? Number(fs.readFileSync(${JSON.stringify(counterFile)}, "utf8")) + 1 + : 1; + fs.writeFileSync(${JSON.stringify(counterFile)}, String(count)); + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtimeError: "network unreachable", + }) + "\\n"); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + initialConfig: { runtimeEnvironment: oldEnv }, + runtimeRefreshRetryDelaysMs: [15, 15], + }, + ); + writeFileSync( + path.join(home, "desktop", "local-server.json"), + JSON.stringify({ + home, + repo, + origin: "http://localhost:3000", + version: "0.2.2", + }), + ); + writeDistributionTool(first.installerDirectory, { + version: "0.1.0.dev113", + sha256: newSha, + }); + + await first.host.start(); + try { + await waitForInstaller(() => + expect( + first.logs.find( + (entry) => + entry.event === "local_server.runtime_refresh_retry_exhausted", + ), + ).toEqual({ + level: "warn", + event: "local_server.runtime_refresh_retry_exhausted", + fields: { attempts: 2 }, + }), + ); + expect(Number(readFileSync(counterFile, "utf8"))).toBe(3); + expect( + JSON.parse( + readFileSync(path.join(home, "desktop", "local-server.json"), "utf8"), + ), + ).toMatchObject({ runtimeRefreshPending: true }); + } finally { + await first.host.stop("quit"); + } + + // Launch 2: services already answer (warm fast-ready), background reconcile + // adopts the new kit without blocking startup and clears runtimeRefreshPending. + const second = setupResumeFixture( + ` + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtime: { + setupChoice: "local-models", + environment: ${JSON.stringify(newEnv)}, + }, + }) + "\\n"); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + withRecord: false, + fetch: (async () => new Response("", { status: 200 })) as typeof fetch, + serverIdentity: async () => ({ + origin: "http://localhost:3000", + teamhub: "http://127.0.0.1:8080", + key: new Uint8Array(32), + }), + proveServer: async () => {}, + initialConfig: { runtimeEnvironment: oldEnv }, + runtimeRefreshRetryDelaysMs: [15], + }, + ); + writeDistributionTool(second.installerDirectory, { + version: "0.1.0.dev113", + sha256: newSha, + }); + const runtimeEvents = vi.fn(); + second.bus.on("computer.runtime", runtimeEvents); + + await second.host.start(); + try { + await waitForInstaller(() => + expect(second.module.status().phase).toBe("ready"), + ); + expect(second.showStarting).not.toHaveBeenCalled(); + expect( + second.logs.find( + (entry) => entry.event === "local_server.resume_fast_ready", + ), + ).toMatchObject({ + fields: { runtime_refresh_pending: true }, + }); + await waitForInstaller(() => + expect(second.config.get().runtimeEnvironment).toEqual(newEnv), + ); + expect(runtimeEvents).toHaveBeenCalledTimes(1); + await waitForInstaller(() => + expect( + JSON.parse( + readFileSync( + path.join(home, "desktop", "local-server.json"), + "utf8", + ), + ), + ).toEqual({ + home, + repo, + origin: "http://localhost:3000", + version: "0.2.2", + }), + ); + expect( + second.logs.find( + (entry) => entry.event === "local_server.runtime_refresh_recovered", + ), + ).toBeDefined(); + } finally { + await second.host.stop("quit"); + } + }); + + it("detects a stale localmodels kit even when an older installer omits runtime and runtimeError", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const oldSha = "a".repeat(64); + const newSha = "b".repeat(64); + const f = setupResumeFixture( + ` + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + }) + "\\n"); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + initialConfig: { + runtimeEnvironment: kitRuntimeEnvironment(home, oldSha), + }, + runtimeRefreshRetryDelaysMs: [], + }, + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: newSha, + }); + + await f.host.start(); + try { + await waitForInstaller(() => + expect(f.module.status().phase).toBe("ready"), + ); + expect( + f.logs.find( + (entry) => entry.event === "local_server.resume_runtime_failed", + ), + ).toEqual({ + level: "warn", + event: "local_server.resume_runtime_failed", + fields: { + error: + "Resume omitted runtime environment before adopting the expected localmodels kit.", + expected_kit_sha256: newSha.slice(0, 12), + expected_kit_version: "0.1.0.dev113", + expected_kit_origin: "bundled", + active_kit_sha256: oldSha.slice(0, 12), + kit_mismatch: true, + }, + }); + expect( + JSON.parse( + readFileSync(path.join(home, "desktop", "local-server.json"), "utf8"), + ), + ).toMatchObject({ runtimeRefreshPending: true }); + } finally { + await f.host.stop("quit"); + } + }); + + it("respects a newer signed active.json kit and does not warn, retry, or downgrade it", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const bundledSha = "b".repeat(64); + const keyId = "test-ed25519-key"; + const { activeEnv, toolsRoot, publicKey } = + await writeSignedActiveKitFixture(home, { + keyId, + minLingerVersion: "0.2.0", + }); + const f = setupResumeFixture( + ` + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtime: { + setupChoice: "local-models", + environment: ${JSON.stringify(activeEnv)}, + }, + }) + "\\n"); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + initialConfig: { runtimeEnvironment: activeEnv }, + runtimeRefreshRetryDelaysMs: [20], + kitPublicKeys: { [keyId]: publicKey }, + }, + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: bundledSha, + }); + const runtimeEvents = vi.fn(); + f.bus.on("computer.runtime", runtimeEvents); + + await f.host.start(); + try { + await waitForInstaller(() => + expect(f.module.status().phase).toBe("ready"), + ); + expect( + f.logs.find( + (entry) => entry.event === "local_server.resume_runtime_failed", + ), + ).toBeUndefined(); + expect( + f.logs.find( + (entry) => + entry.event === "local_server.runtime_refresh_retry_scheduled", + ), + ).toBeUndefined(); + expect(f.config.get().runtimeEnvironment).toEqual(activeEnv); + expect(runtimeEvents).not.toHaveBeenCalled(); + expect(existsSync(path.join(toolsRoot, "active.json"))).toBe(true); + expect( + JSON.parse( + readFileSync(path.join(home, "desktop", "local-server.json"), "utf8"), + ), + ).not.toHaveProperty("runtimeRefreshPending"); + } finally { + await f.host.stop("quit"); + } + }); + + it("adopts the bundled localmodels kit cleanly on normal resume without warning or pending flag", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const oldSha = "a".repeat(64); + const newSha = "b".repeat(64); + const oldEnv = kitRuntimeEnvironment(home, oldSha); + const newEnv = kitRuntimeEnvironment(home, newSha); + + const f = setupResumeFixture( + ` + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtime: { + setupChoice: "local-models", + environment: ${JSON.stringify(newEnv)}, + }, + }) + "\\n"); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + initialConfig: { runtimeEnvironment: oldEnv }, + runtimeRefreshRetryDelaysMs: [20], + }, + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: newSha, + }); + const runtimeEvents = vi.fn(); + f.bus.on("computer.runtime", runtimeEvents); + + await f.host.start(); + try { + await waitForInstaller(() => + expect(f.module.status().phase).toBe("ready"), + ); + expect(f.config.get().runtimeEnvironment).toEqual(newEnv); + expect(runtimeEvents).toHaveBeenCalledTimes(1); + expect( + f.logs.find( + (entry) => entry.event === "local_server.resume_runtime_failed", + ), + ).toBeUndefined(); + expect( + f.logs.find( + (entry) => + entry.event === "local_server.runtime_refresh_retry_scheduled", + ), + ).toBeUndefined(); + expect( + JSON.parse( + readFileSync(path.join(home, "desktop", "local-server.json"), "utf8"), + ), + ).not.toHaveProperty("runtimeRefreshPending"); + } finally { + await f.host.stop("quit"); + } + }); + + it("skips localmodels kit mismatch checks when LINGER_LOCALMODELS_DEV_* override is active", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const devPython = path.join(root, "dev-python"); + const devModules = path.join(root, "dev-modules"); + vi.stubEnv("LINGER_LOCALMODELS_DEV_PYTHON", devPython); + vi.stubEnv("LINGER_LOCALMODELS_DEV_MODULE_DIR", devModules); + try { + const devEnv = { + LINGER_LOCALMODELS_PYTHON: devPython, + LINGER_LOCALMODELS_MODULE_DIR: devModules, + }; + const f = setupResumeFixture( + ` + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtime: { environment: ${JSON.stringify(devEnv)} }, + }) + "\\n"); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + initialConfig: { runtimeEnvironment: devEnv }, + runtimeRefreshRetryDelaysMs: [20], + }, + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: "b".repeat(64), + }); + + await f.host.start(); + try { + await waitForInstaller(() => + expect(f.module.status().phase).toBe("ready"), + ); + expect( + f.logs.find( + (entry) => entry.event === "local_server.resume_runtime_failed", + ), + ).toBeUndefined(); + expect( + JSON.parse( + readFileSync( + path.join(home, "desktop", "local-server.json"), + "utf8", + ), + ), + ).not.toHaveProperty("runtimeRefreshPending"); + } finally { + await f.host.stop("quit"); + } + } finally { + vi.unstubAllEnvs(); + } + }); + + it("pauses a scheduled runtime refresh retry across suspendRecovery and runs it once resumed", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const oldSha = "a".repeat(64); + const newSha = "b".repeat(64); + const oldEnv = kitRuntimeEnvironment(home, oldSha); + const newEnv = kitRuntimeEnvironment(home, newSha); + const counterFile = path.join(root, "suspend-runs.txt"); + let resolveScheduled!: () => void; + const retryScheduled = new Promise((resolve) => { + resolveScheduled = resolve; + }); + + const f = setupResumeFixture( + ` + const fs = require("node:fs"); + const count = fs.existsSync(${JSON.stringify(counterFile)}) + ? Number(fs.readFileSync(${JSON.stringify(counterFile)}, "utf8")) + 1 + : 1; + fs.writeFileSync(${JSON.stringify(counterFile)}, String(count)); + if (count === 1) { + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtimeError: "temporary kit error", + }) + "\\n"); + } else { + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtime: { + setupChoice: "local-models", + environment: ${JSON.stringify(newEnv)}, + }, + }) + "\\n"); + } + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + initialConfig: { runtimeEnvironment: oldEnv }, + runtimeRefreshRetryDelaysMs: [200], + onLog: (entry) => { + if (entry.event === "local_server.runtime_refresh_retry_scheduled") { + resolveScheduled(); + } + }, + }, + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: newSha, + }); + + await f.host.start(); + try { + await retryScheduled; + const release = await f.module.suspendRecovery("apply:0.2.3"); + try { + await new Promise((resolve) => setTimeout(resolve, 260)); + expect(Number(readFileSync(counterFile, "utf8"))).toBe(1); + } finally { + release(); + } + await waitForInstaller(() => + expect(f.config.get().runtimeEnvironment).toEqual(newEnv), + ); + expect(Number(readFileSync(counterFile, "utf8"))).toBe(2); + await waitForInstaller(() => + expect( + JSON.parse( + readFileSync( + path.join(home, "desktop", "local-server.json"), + "utf8", + ), + ), + ).not.toHaveProperty("runtimeRefreshPending"), + ); + } finally { + await f.host.stop("quit"); + } + }); + + it("clears pending reconcile flag when an in-flight runtime-refresh reconcile is cancelled", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const repo = createValidRepo(root); + const oldSha = "a".repeat(64); + const oldEnv = kitRuntimeEnvironment(home, oldSha); + const startedFile = path.join(root, "reconcile-started.flag"); + const gateFile = path.join(root, "reconcile-gate.flag"); + + const f = setupResumeFixture( + ` + const fs = require("node:fs"); + fs.writeFileSync(${JSON.stringify(startedFile)}, "1"); + const timer = setInterval(() => { + if (!fs.existsSync(${JSON.stringify(gateFile)})) return; + clearInterval(timer); + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + }) + "\\n"); + }, 20); + `, + { + home, + version: "0.2.2", + platform: process.platform, + arch: process.arch, + fetch: (async () => new Response("", { status: 200 })) as typeof fetch, + serverIdentity: async () => ({ + origin: "http://localhost:3000", + teamhub: "http://127.0.0.1:8080", + key: new Uint8Array(32), + }), + proveServer: async () => {}, + initialConfig: { runtimeEnvironment: oldEnv }, + runtimeRefreshRetryDelaysMs: [20], + }, + ); + writeFileSync( + path.join(home, "desktop", "local-server.json"), + JSON.stringify({ + home, + repo, + origin: "http://localhost:3000", + version: "0.2.2", + runtimeRefreshPending: true, + }), + ); + + await f.host.start(); + try { + await waitForInstaller(() => expect(existsSync(startedFile)).toBe(true)); + // Switch to a remote server while the runtime-refresh reconcile is in flight. + f.bus.emit("server.changed", "https://team.example.com"); + const release = await f.module.suspendRecovery("check"); + release(); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect( + f.logs.find( + (entry) => + entry.event === "local_server.runtime_refresh_retry_scheduled", + ), + ).toBeUndefined(); + } finally { + await f.host.stop("quit"); + } + }); + + it("honors LINGER_APP_VERSION environment overrides when checking active.json compatibility", async () => { + const root = tempDirectory(); + const home = path.join(root, "home"); + const bundledSha = "b".repeat(64); + const keyId = "test-ed25519-env-override"; + const { activeEnv, publicKey } = await writeSignedActiveKitFixture(home, { + keyId, + minLingerVersion: "0.2.5", + }); + + vi.stubEnv("LINGER_APP_VERSION", "0.2.6"); + try { + const f = setupResumeFixture( + ` + process.stdout.write(JSON.stringify({ + code: 0, + details: { origin: "http://localhost:3000" }, + runtime: { + setupChoice: "local-models", + environment: ${JSON.stringify(activeEnv)}, + }, + }) + "\\n"); + `, + { + home, + version: "0.2.0", + platform: process.platform, + arch: process.arch, + initialConfig: { runtimeEnvironment: activeEnv }, + runtimeRefreshRetryDelaysMs: [20], + kitPublicKeys: { [keyId]: publicKey }, + }, + ); + writeDistributionTool(f.installerDirectory, { + version: "0.1.0.dev113", + sha256: bundledSha, + }); + + await f.host.start(); + try { + await waitForInstaller(() => + expect(f.module.status().phase).toBe("ready"), + ); + expect( + f.logs.find( + (entry) => entry.event === "local_server.resume_runtime_failed", + ), + ).toBeUndefined(); + expect( + JSON.parse( + readFileSync( + path.join(home, "desktop", "local-server.json"), + "utf8", + ), + ), + ).not.toHaveProperty("runtimeRefreshPending"); + } finally { + await f.host.stop("quit"); + } + } finally { + vi.unstubAllEnvs(); + } + }); +}); diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts index f7e704989c..fe65cc7fb3 100644 --- a/apps/desktop/src/main/local-server.ts +++ b/apps/desktop/src/main/local-server.ts @@ -1,5 +1,10 @@ import { spawn } from "node:child_process"; -import { createHash, randomBytes, randomUUID } from "node:crypto"; +import { + createHash, + randomBytes, + randomUUID, + type KeyObject, +} from "node:crypto"; import { closeSync, createReadStream, @@ -55,10 +60,17 @@ import { foldersInUse, inspectNativeProcess, } from "@linger/local-installation/native-process"; -import { isValidSemver } from "@linger/local-installation/localmodels-active"; +import { + effectiveLingerAppVersion, + isValidSemver, + localmodelsToolsRoot, + resolveEffectiveToolSource, +} from "@linger/local-installation/localmodels-active"; import { bundledToolArchivePath, + configuredDevTool, ensureLocalmodelsTool, + pinnedToolSource, readPublishedTool, } from "@linger/local-installation/localmodels-tool"; import { @@ -110,7 +122,7 @@ import { TEAMHUB_BINARY_DIRECTORY, teamhubBinaryStampsFile, } from "@linger/local-installation/teamhub-binaries"; -import { redact } from "@linger/local-installation/redaction"; +import { redactWithUrlStrip } from "@linger/local-installation/redaction"; import { windowsPrivateLocation, windowsPrivateRefusal, @@ -587,6 +599,13 @@ export interface LocalServerOptions { // services resume (used by V2 ReleaseOrchestrator to complete interrupted // pre-commit upgrade rollback before LocalServer boots services). readonly beforeResume?: () => Promise; + // Backoff delays (ms) for bounded background retries when `--resume` + // starts services cleanly but fails to refresh runtime or localmodels kit + // paths; RUNTIME_REFRESH_RETRY_DELAYS_MS by default. + readonly runtimeRefreshRetryDelaysMs?: readonly number[]; + // Optional Ed25519 public keys for verifying signed active.json kit records; + // production pinned keys by default. + readonly kitPublicKeys?: Readonly>; } // The starter Room the server makes for a new owner, with their Agents. @@ -627,6 +646,11 @@ const UNREACHABLE_PROBE_TIMEOUT_MS = 5_000; // A server that keeps going away is resumed at most this often on its own; // Retry is never held back. const RECOVERY_INTERVAL_MS = 60_000; +// Bounded backoff delays for retrying a failed runtime or localmodels kit +// refresh after `--resume` succeeded in starting services. +const RUNTIME_REFRESH_RETRY_DELAYS_MS: readonly number[] = [ + 30_000, 120_000, 300_000, +]; // Short initial polling interval while fast setup steps settle, before // relaxing back to the caller's steady-state interval. @@ -757,6 +781,9 @@ export class LocalServerModule implements Module { #node: Promise | undefined; #abort = new AbortController(); #reconcileAbort: AbortController | undefined; + #reconcileHasPendingRuntimeRefresh = false; + #runtimeRefreshRetryTimer: ReturnType | undefined; + #runtimeRefreshNeededAfterSuspend = false; #inspectAbort: AbortController | undefined; #pruning: Promise = Promise.resolve(); #preStagedSources = new Map(); @@ -940,6 +967,7 @@ export class LocalServerModule implements Module { }); this.#offServerChanged = ctx.bus.on("server.changed", (serverUrl) => { if (this.#origin && sameOrigin(this.#origin, serverUrl)) return; + this.#runtimeRefreshNeededAfterSuspend = false; this.#cancelBackgroundReconcile(); this.#origin = undefined; if (ctx.config.get().localServer !== false) @@ -973,6 +1001,7 @@ export class LocalServerModule implements Module { // ModuleHost's 5 s module timeout. this.#hadRunningInstallAtStop = this.#hadRunningInstallAtStop || this.#running !== undefined; + this.#runtimeRefreshNeededAfterSuspend = false; this.#cancelPrestage("stopped"); this.#cancelBackgroundReconcile(); this.#recoveryGraceAbort?.abort(); @@ -2723,6 +2752,7 @@ export class LocalServerModule implements Module { const status = this.status(); if (!status.available) throw new Error("Running Linger on this computer is not supported here"); + this.#runtimeRefreshNeededAfterSuspend = false; this.#cancelBackgroundReconcile(); const installAbort = new AbortController(); this.#installAbort = installAbort; @@ -3303,6 +3333,12 @@ export class LocalServerModule implements Module { async suspendRecovery(reason = "release_transition"): Promise<() => void> { this.#recoverySuspendCount += 1; if (this.#recoverySuspendCount === 1) { + if ( + this.#runtimeRefreshRetryTimer || + this.#reconcileHasPendingRuntimeRefresh + ) { + this.#runtimeRefreshNeededAfterSuspend = true; + } this.#recoveryGraceAbort?.abort(); this.#cancelBackgroundReconcile(); this.#ctx?.log.info("local_server.recovery_suspended", { reason }); @@ -3311,6 +3347,12 @@ export class LocalServerModule implements Module { await this.#recoveryPromise.catch(() => undefined); // An already-in-flight resume could finish via fast-ready and spawn a // background reconcile right before settling; cancel it before yielding. + if ( + this.#runtimeRefreshRetryTimer || + this.#reconcileHasPendingRuntimeRefresh + ) { + this.#runtimeRefreshNeededAfterSuspend = true; + } this.#cancelBackgroundReconcile(); } // Also wait boundedly for any in-flight startup/retry resume or aborted @@ -3318,6 +3360,12 @@ export class LocalServerModule implements Module { // before the V2 transition invokes installer commands. await this.#waitForInFlightResume(SUSPEND_RESUME_WAIT_MS); if (this.#activeReconcile) { + if ( + this.#runtimeRefreshRetryTimer || + this.#reconcileHasPendingRuntimeRefresh + ) { + this.#runtimeRefreshNeededAfterSuspend = true; + } this.#cancelBackgroundReconcile(); await this.#waitForInFlightResume(RESUME_ABORT_WAIT_MS); } @@ -3329,6 +3377,15 @@ export class LocalServerModule implements Module { this.#recoverySuspendCount -= 1; if (this.#recoverySuspendCount === 0) { this.#ctx?.log.info("local_server.recovery_resumed", { reason }); + if ( + this.#runtimeRefreshNeededAfterSuspend && + this.#phase === "ready" && + !this.#abort.signal.aborted && + !this.#beforeResumeBlocked + ) { + this.#runtimeRefreshNeededAfterSuspend = false; + this.#scheduleRuntimeRefreshRetry(1); + } } }; } @@ -3342,6 +3399,7 @@ export class LocalServerModule implements Module { */ blockForManualRecovery(reason: string): void { this.#beforeResumeBlocked = true; + this.#runtimeRefreshNeededAfterSuspend = false; this.#recoveryGraceAbort?.abort(); this.#cancelBackgroundReconcile(); this.#set("failed", reason); @@ -5387,17 +5445,125 @@ export class LocalServerModule implements Module { } #cancelBackgroundReconcile(): void { + if (this.#runtimeRefreshRetryTimer) { + clearTimeout(this.#runtimeRefreshRetryTimer); + this.#runtimeRefreshRetryTimer = undefined; + } + this.#reconcileHasPendingRuntimeRefresh = false; this.#reconcileAbort?.abort(); this.#reconcileAbort = undefined; } + #scheduleRuntimeRefreshRetry(attempt: number): void { + if ( + this.#abort.signal.aborted || + this.#phase !== "ready" || + this.#beforeResumeBlocked + ) + return; + const delays = + this.#options.runtimeRefreshRetryDelaysMs ?? + RUNTIME_REFRESH_RETRY_DELAYS_MS; + if (attempt > delays.length) { + this.#ctx?.log.warn("local_server.runtime_refresh_retry_exhausted", { + attempts: delays.length, + }); + return; + } + if (this.#recoverySuspendCount > 0) { + this.#runtimeRefreshNeededAfterSuspend = true; + return; + } + if (this.#runtimeRefreshRetryTimer) { + clearTimeout(this.#runtimeRefreshRetryTimer); + this.#runtimeRefreshRetryTimer = undefined; + } + const delayMs = Math.max(0, delays[attempt - 1]!); + this.#ctx?.log.info("local_server.runtime_refresh_retry_scheduled", { + attempt, + max_attempts: delays.length, + delay_ms: delayMs, + }); + const timer = setTimeout(() => { + if (this.#runtimeRefreshRetryTimer === timer) { + this.#runtimeRefreshRetryTimer = undefined; + } + void this.#runRuntimeRefreshRetry(attempt); + }, delayMs); + timer.unref?.(); + this.#runtimeRefreshRetryTimer = timer; + } + + async #runRuntimeRefreshRetry(attempt: number): Promise { + if ( + this.#abort.signal.aborted || + this.#phase !== "ready" || + this.#resuming || + this.#reconcileAbort || + this.#beforeResumeBlocked + ) + return; + if (this.#recoverySuspendCount > 0) { + this.#runtimeRefreshNeededAfterSuspend = true; + return; + } + const record = await this.#readRecord(); + if ( + !record || + this.#abort.signal.aborted || + this.#phase !== "ready" || + this.#resuming || + this.#reconcileAbort || + this.#beforeResumeBlocked + ) + return; + if (this.#recoverySuspendCount > 0) { + this.#runtimeRefreshNeededAfterSuspend = true; + return; + } + const config = this.#ctx?.config.get(); + if ( + !this.#origin || + !sameOrigin(this.#origin, record.origin) || + !config?.serverUrl || + !sameOrigin(config.serverUrl, record.origin) || + !config.computerId + ) + return; + const reconcileAbort = new AbortController(); + this.#reconcileAbort = reconcileAbort; + const reconcileSignal = AbortSignal.any([ + this.#abort.signal, + reconcileAbort.signal, + ]); + const startedAt = Date.now(); + const reconcileTask = this.#reconcileAfterFastReady( + record, + reconcileAbort, + reconcileSignal, + startedAt, + { retryAttempt: attempt }, + ).finally(() => { + if (this.#activeReconcile === reconcileTask) { + this.#activeReconcile = undefined; + } + }); + this.#activeReconcile = reconcileTask; + await reconcileTask; + } + async #reconcileAfterFastReady( record: LocalRecord, controller: AbortController, signal: AbortSignal, startedAt: number, + options?: { readonly retryAttempt?: number }, ): Promise { let stage = "ensure_node"; + let nextRetryAttempt: number | undefined; + this.#reconcileHasPendingRuntimeRefresh = Boolean( + record.runtimeRefreshPending || options?.retryAttempt !== undefined, + ); try { const serving = await this.#runResume( record, @@ -5415,10 +5581,20 @@ export class LocalServerModule implements Module { record.origin; if (signal.aborted) return; if (!this.#origin || !sameOrigin(this.#origin, record.origin)) return; - if (origin !== record.origin) { - await this.#writeRecord({ ...record, origin }); + const nextRecord = this.#withRuntimeRefreshPending( + { ...record, origin }, + serving.runtimeRefreshPending, + ); + if ( + origin !== record.origin || + Boolean(nextRecord.runtimeRefreshPending) !== + Boolean(record.runtimeRefreshPending) + ) { + await this.#writeRecord(nextRecord); if (signal.aborted) return; if (!this.#origin || !sameOrigin(this.#origin, record.origin)) return; + } + if (origin !== record.origin) { this.#ctx?.log.info("local_server.origin_moved", { from: record.origin, to: origin, @@ -5431,7 +5607,13 @@ export class LocalServerModule implements Module { this.#ctx?.log.info("local_server.resume_succeeded", { total_ms: Date.now() - startedAt, background: true, + ...(options?.retryAttempt !== undefined + ? { runtime_refresh_attempt: options.retryAttempt } + : {}), }); + if (serving.runtimeRefreshPending) { + nextRetryAttempt = (options?.retryAttempt ?? 0) + 1; + } } catch (error) { if (signal.aborted) return; const message = error instanceof Error ? error.message : String(error); @@ -5439,9 +5621,21 @@ export class LocalServerModule implements Module { stage, total_ms: Date.now() - startedAt, error: this.#formatResumeError(message), + ...(options?.retryAttempt !== undefined + ? { runtime_refresh_attempt: options.retryAttempt } + : {}), }); + if (record.runtimeRefreshPending) { + nextRetryAttempt = (options?.retryAttempt ?? 0) + 1; + } } finally { - if (this.#reconcileAbort === controller) this.#reconcileAbort = undefined; + if (this.#reconcileAbort === controller) { + this.#reconcileAbort = undefined; + this.#reconcileHasPendingRuntimeRefresh = false; + } + if (nextRetryAttempt !== undefined) { + this.#scheduleRuntimeRefreshRetry(nextRetryAttempt); + } } } @@ -5460,13 +5654,20 @@ export class LocalServerModule implements Module { async #resumeInner(record: LocalRecord, signal: AbortSignal): Promise { const retryingFromFailed = this.#phase === "failed"; + this.#runtimeRefreshNeededAfterSuspend = false; this.#cancelBackgroundReconcile(); let currentRecord = record; this.#origin = record.origin; this.#resuming = true; + let scheduleRuntimeRefreshRetry = false; const startedAt = Date.now(); let stage = "fast_ready_check"; - this.#ctx?.log.info("local_server.resume_started"); + this.#ctx?.log.info( + "local_server.resume_started", + currentRecord.runtimeRefreshPending + ? { runtime_refresh_pending: true } + : undefined, + ); const windows = this.#ctx?.get("WindowManager"); this.#acquireBusy(); try { @@ -5563,8 +5764,14 @@ export class LocalServerModule implements Module { this.#set("ready", "Linger is running on this computer."); this.#ctx?.log.info("local_server.resume_fast_ready", { ms: Date.now() - startedAt, + ...(currentRecord.runtimeRefreshPending + ? { runtime_refresh_pending: true } + : {}), }); if (this.#recoverySuspendCount > 0) { + if (currentRecord.runtimeRefreshPending) { + this.#runtimeRefreshNeededAfterSuspend = true; + } return; } const reconcileAbort = new AbortController(); @@ -5644,9 +5851,23 @@ export class LocalServerModule implements Module { throw new Error( "Linger could not restart on this version. The earlier version is still installed; try again.", ); - await this.#moved({ ...currentRecord, origin }, repo); - } else if (origin !== currentRecord.origin) - await this.#writeRecord({ ...currentRecord, origin }); + await this.#moved( + { ...currentRecord, origin }, + repo, + serving.runtimeRefreshPending, + ); + } else if ( + origin !== currentRecord.origin || + Boolean(serving.runtimeRefreshPending) !== + Boolean(currentRecord.runtimeRefreshPending) + ) { + await this.#writeRecord( + this.#withRuntimeRefreshPending( + { ...currentRecord, origin }, + serving.runtimeRefreshPending, + ), + ); + } if (origin !== currentRecord.origin) this.#ctx?.log.info("local_server.origin_moved", { from: currentRecord.origin, @@ -5671,6 +5892,7 @@ export class LocalServerModule implements Module { this.#ctx?.log.info("local_server.resume_succeeded", { total_ms: Date.now() - startedAt, }); + scheduleRuntimeRefreshRetry = serving.runtimeRefreshPending; if (repo !== currentRecord.repo) void this.#schedulePruneSources(currentRecord.home, [repo]); } catch (error) { @@ -5686,6 +5908,9 @@ export class LocalServerModule implements Module { } finally { this.#releaseBusy(); this.#resuming = false; + if (scheduleRuntimeRefreshRetry) { + this.#scheduleRuntimeRefreshRetry(1); + } } } @@ -5731,6 +5956,7 @@ export class LocalServerModule implements Module { // Install sets this computer up again in the same location, keeping what // is left of that instance. async #reset(): Promise { + this.#runtimeRefreshNeededAfterSuspend = false; this.#cancelBackgroundReconcile(); const ctx = this.#ctx!; try { @@ -5896,12 +6122,132 @@ export class LocalServerModule implements Module { return true; } - async #moved(record: LocalRecord, repo: string): Promise { - await this.#writeRecord({ - ...record, - repo, - version: this.#options.version, + #withRuntimeRefreshPending( + record: LocalRecord, + pending: boolean, + ): LocalRecord { + const base: LocalRecord = { + home: record.home, + repo: record.repo, + origin: record.origin, + ...(record.version !== undefined ? { version: record.version } : {}), + }; + return pending ? { ...base, runtimeRefreshPending: true } : base; + } + + async #moved( + record: LocalRecord, + repo: string, + runtimeRefreshPending = false, + ): Promise { + await this.#writeRecord( + this.#withRuntimeRefreshPending( + { + ...record, + repo, + version: this.#options.version, + }, + runtimeRefreshPending, + ), + ); + } + + // Resolves the localmodels kit this installation expects (a verified newer + // active.json kit ahead of the bundle's distribution.json baseline), read-only + // so Desktop never mutates active.json or downgrades an independently upgraded + // kit. Returns undefined when a developer localmodels checkout overrides it or + // no distribution kit is configured. + async #expectedLocalmodelsKit( + home: string, + lingerVersionOverride?: string, + ): Promise< + | { + readonly sha256: string; + readonly version?: string; + readonly origin: "active" | "bundled"; + } + | undefined + > { + try { + if (configuredDevTool()) return undefined; + } catch { + return undefined; + } + let bundled: Awaited>; + try { + bundled = pinnedToolSource(); + } catch { + bundled = undefined; + } + if (!bundled) { + bundled = await readPublishedTool( + path.join(this.#options.installerDirectory, "distribution.json"), + ).catch(() => undefined); + } + if (!bundled) return undefined; + const lingerVersion = + lingerVersionOverride ?? (await this.#resolveAppVersion()); + const effective = await resolveEffectiveToolSource(home, bundled, { + retireStale: false, + ...(lingerVersion ? { lingerVersion } : {}), + ...(this.#options.platform ? { platform: this.#options.platform } : {}), + ...(this.#options.arch ? { arch: this.#options.arch } : {}), + ...(this.#options.kitPublicKeys + ? { publicKeys: this.#options.kitPublicKeys } + : {}), }); + if (!effective.source) return undefined; + return { + sha256: effective.source.sha256, + ...(effective.source.version + ? { version: effective.source.version } + : {}), + origin: effective.origin, + }; + } + + async #activeLocalmodelsKitSha256(home: string): Promise<{ + readonly adoptedSha256?: string; + readonly reportedSha256?: string; + }> { + const env = this.#ctx?.config.get().runtimeEnvironment; + const python = env?.LINGER_LOCALMODELS_PYTHON; + const moduleDir = env?.LINGER_LOCALMODELS_MODULE_DIR; + if (!python && !moduleDir) return {}; + const toolsRoot = localmodelsToolsRoot(home); + const roots = new Set([toolsRoot]); + const realHome = await canonicalPath(home); + roots.add(localmodelsToolsRoot(realHome)); + roots.add(await canonicalPath(toolsRoot)); + const rootList = [...roots]; + const resolveSha = async ( + candidate: string | undefined, + ): Promise => { + if (!candidate) return undefined; + for (const root of rootList) { + const direct = kitSha256UnderToolsRoot(root, candidate); + if (direct) return direct; + } + const realCandidate = await canonicalPath(candidate); + if (realCandidate !== candidate) { + for (const root of rootList) { + const resolved = kitSha256UnderToolsRoot(root, realCandidate); + if (resolved) return resolved; + } + } + return undefined; + }; + const [pythonSha, moduleSha] = await Promise.all([ + resolveSha(python), + resolveSha(moduleDir), + ]); + const adoptedSha256 = + pythonSha && moduleSha && pythonSha === moduleSha ? pythonSha : undefined; + const reportedSha256 = adoptedSha256 ?? pythonSha ?? moduleSha; + return { + ...(adoptedSha256 ? { adoptedSha256 } : {}), + ...(reportedSha256 ? { reportedSha256 } : {}), + }; } // Resolves with the source folder the installer reports the services @@ -5913,7 +6259,12 @@ export class LocalServerModule implements Module { signal: AbortSignal, onStage?: (stage: string) => void, options?: { readonly skipAdoptKeys?: boolean }, - ): Promise<{ source?: string; origin?: string; revived: boolean }> { + ): Promise<{ + source?: string; + origin?: string; + revived: boolean; + runtimeRefreshPending: boolean; + }> { if (!options?.skipAdoptKeys) await this.#adoptSourceKeys(record.home); // Resolved while the Node runtime is checked, so a slow PAC script does // not add to the start. @@ -6152,6 +6503,54 @@ export class LocalServerModule implements Module { this.#localModelsDegraded = undefined; } this.#adoptRuntime(outcome.runtime); + const runtimeError = + typeof outcome.runtimeError === "string" && outcome.runtimeError.trim() + ? outcome.runtimeError.trim() + : undefined; + const [expectedKit, activeKit] = await Promise.all([ + this.#expectedLocalmodelsKit(record.home, effectiveLingerAppVersion(env)), + this.#activeLocalmodelsKitSha256(record.home), + ]); + signal.throwIfAborted(); + const kitMismatch = Boolean( + expectedKit && activeKit.adoptedSha256 !== expectedKit.sha256, + ); + const runtimeRefreshPending = Boolean(runtimeError || kitMismatch); + if (runtimeRefreshPending) { + const errorDetail = + runtimeError ?? + (outcome.runtime + ? "Resume returned a different localmodels kit than expected." + : "Resume omitted runtime environment before adopting the expected localmodels kit."); + this.#ctx?.log.warn("local_server.resume_runtime_failed", { + error: this.#formatResumeError(errorDetail), + ...(expectedKit + ? { + expected_kit_sha256: expectedKit.sha256.slice(0, 12), + ...(expectedKit.version + ? { expected_kit_version: expectedKit.version } + : {}), + expected_kit_origin: expectedKit.origin, + } + : {}), + ...(activeKit.reportedSha256 + ? { active_kit_sha256: activeKit.reportedSha256.slice(0, 12) } + : {}), + ...(kitMismatch ? { kit_mismatch: true } : {}), + }); + } else if (record.runtimeRefreshPending) { + this.#ctx?.log.info("local_server.runtime_refresh_recovered", { + ...(expectedKit + ? { + kit_sha256: expectedKit.sha256.slice(0, 12), + ...(expectedKit.version + ? { kit_version: expectedKit.version } + : {}), + kit_origin: expectedKit.origin, + } + : {}), + }); + } const { source, origin } = outcome.details ?? {}; return { ...(typeof source === "string" ? { source } : {}), @@ -6159,14 +6558,12 @@ export class LocalServerModule implements Module { ? { origin } : {}), revived: resumeTimings?.path === "cold", + runtimeRefreshPending, }; } #formatResumeError(message: string): string { - const stripped = message - .replace(/(https?:\/\/[^\s?#]+)\?[^\s#]*/g, "$1") - .replace(/(https?:\/\/[^\s#]+)#[^\s#]*/g, "$1"); - const redacted = redact(stripped); + const redacted = redactWithUrlStrip(message); return redacted.length > 500 ? `${redacted.slice(0, 497)}...` : redacted; } @@ -6267,6 +6664,9 @@ export class LocalServerModule implements Module { ...(typeof value.version === "string" ? { version: value.version } : {}), + ...(value.runtimeRefreshPending === true + ? { runtimeRefreshPending: true } + : {}), } : undefined; } catch { @@ -6356,6 +6756,9 @@ interface ResumeOutcome { localModelsDegraded?: unknown; }; runtime?: InstanceRuntime; + // Why the post-resume runtime lookup failed (for example, downloading the + // pinned localmodels kit failed) while the services themselves resumed. + runtimeError?: unknown; // Resume stderr is not piped (detached services could hold it open), so // the runtime lookup's stage timings ride in the outcome instead. runtimeLookupTimings?: unknown; @@ -6503,6 +6906,29 @@ interface LocalRecord { // The version of the app that unpacked `repo`; a record without one was // written by an app older than any that reads it. readonly version?: string; + // Set when `--resume` started services cleanly but failed to refresh the + // runtime or expected localmodels kit, so later launches keep retrying until + // adoption succeeds. + readonly runtimeRefreshPending?: true; +} + +function kitSha256UnderToolsRoot( + toolsRoot: string, + candidatePath: string, +): string | undefined { + const cleanRoot = path.resolve(toolsRoot); + const cleanCandidate = path.resolve(candidatePath); + const isWin = process.platform === "win32"; + const normalizedRoot = isWin ? cleanRoot.toLowerCase() : cleanRoot; + const normalizedCandidate = isWin + ? cleanCandidate.toLowerCase() + : cleanCandidate; + const rel = path.relative(normalizedRoot, normalizedCandidate); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return undefined; + const segments = rel.split(/[\\/]/).filter(Boolean); + if (segments.length < 2) return undefined; + const sha = segments[0]!; + return /^[a-f0-9]{64}$/.test(sha) ? sha : undefined; } // This computer as the server's Local Computers list reports it. diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md index 599a0c4f04..76992d384e 100644 --- a/apps/linger-installer/AGENTS.md +++ b/apps/linger-installer/AGENTS.md @@ -99,10 +99,12 @@ A failed job's `errorCode` is the runtime's cause when it has one (`RUNTIME_PLAN_REFUSED`, a harness plan refused before anything changed, such as an unusable `SIMPLEX_PI_PATH` or a Windows runtime root too long for Pi without long paths; `RUNTIME_ACTION_FAILED`; -`RUNTIME_EXTENSIONS_FAILED`), otherwise `INSTALL_FAILED`. With -`--external-computer`, a successful outcome carries `runtime`, the same instance runtime as +`RUNTIME_EXTENSIONS_FAILED`), otherwise `INSTALL_FAILED`. 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. The HTTP lookup writes one JSON line to +the desktop's Computer follows them; when `instanceRuntime` throws during +`--resume`, the installer logs the redacted error to both `resume.log` and +`stderr` and includes it as `runtimeError` in the stdout JSON outcome while +still exiting `0` so the resumed services remain usable. The HTTP lookup writes one JSON line to stderr, `{"event":"installer.runtime_lookup_timings","instance",...,"timings"}`, whose `timings` holds `config`, `runtime`, `localModels`, `tool` and `total` in ms; the `--resume` outcome carries the same object as diff --git a/apps/linger-installer/src/main.test.ts b/apps/linger-installer/src/main.test.ts index 128b3cea46..243419112d 100644 --- a/apps/linger-installer/src/main.test.ts +++ b/apps/linger-installer/src/main.test.ts @@ -619,6 +619,180 @@ it("includes resumeTimings in the --resume stdout JSON line alongside runtime fi } }); +it("logs and surfaces redacted runtimeError in --resume stdout JSON while preserving exit 0 when instanceRuntime rejects", async () => { + const home = mkdtempSync(path.join(os.tmpdir(), "installer-resume-err-")); + const migrate = vi.fn().mockResolvedValue([]); + const resumeTimings = { + path: "warm" as const, + probeMs: 8, + totalMs: 14, + }; + const runtimeLookupTimings = { + config: 1, + runtime: 2, + localModels: 1, + tool: 250, + total: 254, + }; + vi.doMock("@linger/local-installation/legacy-migration", () => ({ + migrateLegacyInstallation: migrate, + })); + vi.doMock("./server/resume.js", () => ({ + resumeSourceInstance: vi.fn( + async (opts: { onTimings?: (t: typeof resumeTimings) => void }) => { + opts.onTimings?.(resumeTimings); + return { + code: 0, + state: "ready", + message: "Services are already running.", + }; + }, + ), + })); + vi.doMock("./server/instance-runtime.js", () => ({ + instanceRuntime: vi.fn( + async ( + _home: string, + _name: string, + opts?: { onTimings?: (t: typeof runtimeLookupTimings) => void }, + ) => { + opts?.onTimings?.(runtimeLookupTimings); + throw new Error( + "Download failed for https://cdn.example/kit.tgz?token=secret123#frag with Bearer top-secret-token", + ); + }, + ), + })); + const argv = process.argv; + const stdout = vi.spyOn(process.stdout, "write").mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, "write").mockReturnValue(true); + const exit = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as never); + try { + process.argv = [ + process.execPath, + fileURLToPath(new URL("./main.ts", import.meta.url)), + "--home", + home, + "--source-repo", + "resume-repo", + "--instance", + "desktop", + "--external-computer", + "--resume", + ]; + vi.resetModules(); + await import("./main.js"); + const line = stdout.mock.calls.at(-1)?.[0]; + expect(typeof line).toBe("string"); + const parsed = JSON.parse(String(line)) as Record; + expect(parsed).toEqual({ + code: 0, + state: "ready", + message: "Services are already running.", + runtimeError: + "Download failed for https://cdn.example/kit.tgz with Bearer [REDACTED]", + runtimeLookupTimings, + resumeTimings, + }); + expect(parsed).not.toHaveProperty("runtime"); + const stderrText = stderr.mock.calls + .map(([chunk]) => String(chunk)) + .join(""); + expect(stderrText).toContain( + "Runtime lookup failed: Download failed for https://cdn.example/kit.tgz with Bearer [REDACTED]\n", + ); + expect(stderrText).not.toContain("secret123"); + expect(stderrText).not.toContain("top-secret-token"); + const resumeLog = readFileSync( + path.join(home, "installer", "resume.log"), + "utf8", + ); + expect(resumeLog).toContain( + "Runtime lookup failed: Download failed for https://cdn.example/kit.tgz with Bearer [REDACTED]", + ); + expect(resumeLog).not.toContain("secret123"); + expect(resumeLog).not.toContain("top-secret-token"); + const done = stdout.mock.calls.at(-1)?.[1] as unknown; + if (typeof done === "function") done(); + expect(exit).toHaveBeenCalledWith(0); + } finally { + process.argv = argv; + stdout.mockRestore(); + stderr.mockRestore(); + exit.mockRestore(); + vi.doUnmock("@linger/local-installation/legacy-migration"); + vi.doUnmock("./server/resume.js"); + vi.doUnmock("./server/instance-runtime.js"); + vi.resetModules(); + rmSync(home, { recursive: true, force: true }); + } +}); + +it("surfaces a fallback runtimeError when instanceRuntime rejects with an empty message", async () => { + const home = mkdtempSync(path.join(os.tmpdir(), "installer-resume-empty-")); + vi.doMock("@linger/local-installation/legacy-migration", () => ({ + migrateLegacyInstallation: vi.fn().mockResolvedValue([]), + })); + vi.doMock("./server/resume.js", () => ({ + resumeSourceInstance: vi.fn(async () => ({ + code: 0, + state: "ready", + message: "Services are already running.", + })), + })); + vi.doMock("./server/instance-runtime.js", () => ({ + instanceRuntime: vi.fn(async () => { + throw new Error(""); + }), + })); + const argv = process.argv; + const stdout = vi.spyOn(process.stdout, "write").mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, "write").mockReturnValue(true); + const exit = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as never); + try { + process.argv = [ + process.execPath, + fileURLToPath(new URL("./main.ts", import.meta.url)), + "--home", + home, + "--source-repo", + "resume-repo", + "--instance", + "desktop", + "--external-computer", + "--resume", + ]; + vi.resetModules(); + await import("./main.js"); + const parsed = JSON.parse(String(stdout.mock.calls.at(-1)?.[0])) as Record< + string, + unknown + >; + expect(parsed.code).toBe(0); + expect(parsed.runtimeError).toBe("Failed to resolve instance runtime."); + expect( + readFileSync(path.join(home, "installer", "resume.log"), "utf8"), + ).toContain("Runtime lookup failed: Failed to resolve instance runtime."); + const done = stdout.mock.calls.at(-1)?.[1] as unknown; + if (typeof done === "function") done(); + expect(exit).toHaveBeenCalledWith(0); + } finally { + process.argv = argv; + stdout.mockRestore(); + stderr.mockRestore(); + exit.mockRestore(); + vi.doUnmock("@linger/local-installation/legacy-migration"); + vi.doUnmock("./server/resume.js"); + vi.doUnmock("./server/instance-runtime.js"); + vi.resetModules(); + rmSync(home, { recursive: true, force: true }); + } +}); + it("aborts --inspect gracefully on SIGTERM and removes the listener", async () => { let inspectSignal: AbortSignal | undefined; let inspectStarted!: () => void; diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts index c8a7f2136f..40412679b0 100644 --- a/apps/linger-installer/src/main.ts +++ b/apps/linger-installer/src/main.ts @@ -296,10 +296,12 @@ async function resume(options: ReturnType) { { resumeSourceInstance }, { withLocalmodelsToolCache }, { openResumeLog }, + { redactWithUrlStrip }, ] = await Promise.all([ import("./server/resume.js"), import("@linger/local-installation/localmodels-tool"), import("./server/resume-log.js"), + import("@linger/local-installation/redaction"), ]); const resumeLog = await openResumeLog(options.home); const controller = new AbortController(); @@ -307,7 +309,7 @@ async function resume(options: ReturnType) { let runtimeDescriptors: RuntimeDescriptor[] | undefined; let resumeTimings: ResumeTimings | undefined; let runtimeLookupTimings: RuntimeLookupTimings | undefined; - const { outcome, runtime } = await (async () => { + const { outcome, runtime, runtimeError } = await (async () => { try { return await withLocalmodelsToolCache(async () => { const resumeOutcome = await resumeSourceInstance({ @@ -337,7 +339,9 @@ async function resume(options: ReturnType) { ); // 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. - // The desktop does not read resume stderr, so timings ride in the outcome. + // The desktop does not read resume stderr, so timings and any runtime + // lookup error ride in the outcome. + let runtimeLookupError: string | undefined; const instanceRuntimeResult = resumeOutcome.code === 0 && options.externalComputer ? await import("./server/instance-runtime.js") @@ -349,9 +353,25 @@ async function resume(options: ReturnType) { }, }), ) - .catch(() => undefined) + .catch((error: unknown) => { + const rawMessage = + error instanceof Error ? error.message : String(error); + const sanitized = redactWithUrlStrip(rawMessage) + .trim() + .slice(0, 1500); + runtimeLookupError = + sanitized || "Failed to resolve instance runtime."; + const line = `Runtime lookup failed: ${runtimeLookupError}`; + process.stderr.write(`${line}\n`); + resumeLog.write(line); + return undefined; + }) : undefined; - return { outcome: resumeOutcome, runtime: instanceRuntimeResult }; + return { + outcome: resumeOutcome, + runtime: instanceRuntimeResult, + runtimeError: runtimeLookupError, + }; }); } finally { resumeLog.close(); @@ -362,6 +382,7 @@ async function resume(options: ReturnType) { `${JSON.stringify({ ...outcome, ...(runtime ? { runtime } : {}), + ...(runtimeError ? { runtimeError } : {}), ...(runtimeLookupTimings ? { runtimeLookupTimings } : {}), ...(resumeTimings ? { resumeTimings } : {}), })}\n`, diff --git a/packages/local-installation/src/redaction.test.ts b/packages/local-installation/src/redaction.test.ts new file mode 100644 index 0000000000..0df717f10c --- /dev/null +++ b/packages/local-installation/src/redaction.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { redactWithUrlStrip } from "./redaction.js"; + +describe("redactWithUrlStrip", () => { + it("strips HTTP(S) query strings and fragments and redacts tokens and URL credentials", () => { + const raw = + "Download failed for https://user:pass@cdn.example/kit.tgz?token=secret123#frag with Bearer top-secret-token and api_key=abc123"; + expect(redactWithUrlStrip(raw)).toBe( + "Download failed for https://[REDACTED]@cdn.example/kit.tgz with Bearer [REDACTED] and api_key=[REDACTED]", + ); + }); + + it("strips standalone URL fragments without query strings", () => { + expect( + redactWithUrlStrip("Fetch error at http://cdn.example/kit.tgz#section"), + ).toBe("Fetch error at http://cdn.example/kit.tgz"); + }); +}); diff --git a/packages/local-installation/src/redaction.ts b/packages/local-installation/src/redaction.ts index 7350722191..6fa492bdc4 100644 --- a/packages/local-installation/src/redaction.ts +++ b/packages/local-installation/src/redaction.ts @@ -16,6 +16,13 @@ export function redact(text: string): string { ) ); } +/** Strips URL query strings and fragments before redacting credentials and tokens. */ +export function redactWithUrlStrip(text: string): string { + const stripped = text + .replace(/(https?:\/\/[^\s?#]+)\?[^\s#]*/g, "$1") + .replace(/(https?:\/\/[^\s#]+)#[^\s#]*/g, "$1"); + return redact(stripped); +} /** Caps one line of program output so it cannot fill a status message. */ export function excerptLine(line: string, limit = 240): string { return line.length > limit ? `${line.slice(0, limit - 1)}\u2026` : line;