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(installer): mount a saved BYOK source on Bifrost again on resume
shoudi zheng2bd6a4ca7df2
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 69c57218..b0d73da2 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -302,7 +302,9 @@ Gateway and runs Agents. The daemon exits with the app.hash), and `LocalServer` resume emits `local_server.resume_started`,`local_server.resume_stage` (`stage`, `ms`), `local_server.resume_succeeded`(`total_ms`), and `local_server.resume_failed` (`stage`, `total_ms`,- redacted `error` bounded to 500 chars with query/hash stripped).+ redacted `error` bounded to 500 chars with query/hash stripped). A resume+ whose saved BYOK gateway did not come back still succeeds and logs+ `local_server.byok_gateway_unavailable` (`code`, `message`).- `src/shell/*.html`: app-owned pages (title bar, offline/setup page). Theyhave no network access and talk to the main process via `src/preload/shell.ts`.- `src/preload/index.ts`: the only SPA API, `window.lingerDesktop`. Its@@ -403,7 +405,8 @@ home> --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, withinstallation. 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- model source to a subscription or BYOK. A+ model source to a subscription; a BYOK source gets its gateway mounted+ again instead. Aquit for an update or a relaunch, and the `--quit` of setup or theuninstaller (which stop the models themselves right after), leave them.- `src/main/legacy-migration.ts`: on start, stops a bridge an older versiondiff --git a/apps/desktop/src/main/local-server-resume.test.ts b/apps/desktop/src/main/local-server-resume.test.tsindex e1757852..e755be64 100644--- a/apps/desktop/src/main/local-server-resume.test.ts+++ b/apps/desktop/src/main/local-server-resume.test.ts@@ -131,6 +131,27 @@ describe("LocalServerModule resume coordination", () => {await f.host.stop("quit");});+ it("logs a BYOK gateway that did not come back and still resumes", async () => {+ const f = setupResumeFixture(`+ process.stdout.write(JSON.stringify({ code: 0, details: { origin: "http://localhost:3000", byokGateway: { code: "BYOK_UNREACHABLE", message: "Endpoint did not answer." } } }) + "\\n");+ `);++ await f.host.start();++ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));+ expect(f.showStartFailed).not.toHaveBeenCalled();+ expect(+ f.logs.find(+ (entry) => entry.event === "local_server.byok_gateway_unavailable",+ ),+ ).toEqual({+ level: "warn",+ event: "local_server.byok_gateway_unavailable",+ fields: { code: "BYOK_UNREACHABLE", message: "Endpoint did not answer." },+ });+ await f.host.stop("quit");+ });+it("redacts query, hash, and secrets and bounds resume_failed errors to 500 chars", async () => {const longPadding = "x".repeat(600);const f = setupResumeFixture(`diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex b5f5d4ba..f24b6986 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -2590,6 +2590,22 @@ export class LocalServerModule implements Module {.join(" "),);}+ // The services run without the BYOK gateway; the person switches or+ // fixes the source on the Models page, so this only leaves a trace.+ const byokGateway = outcome.details?.byokGateway as+ | { code?: unknown; message?: unknown }+ | null+ | undefined;+ if (+ byokGateway &&+ typeof byokGateway === "object" &&+ typeof byokGateway.code === "string"+ )+ this.#ctx?.log.warn("local_server.byok_gateway_unavailable", {+ code: byokGateway.code,+ message:+ typeof byokGateway.message === "string" ? byokGateway.message : "",+ });this.#adoptRuntime(outcome.runtime);const { source, origin } = outcome.details ?? {};return {@@ -2722,6 +2738,8 @@ interface ResumeOutcome {origin?: unknown;code?: unknown;reasons?: unknown;+ // Why a saved BYOK source's gateway did not come back: `{ code, message }`.+ byokGateway?: unknown;};runtime?: InstanceRuntime;}diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.mdindex b3d1713c..215f8bec 100644--- a/apps/linger-installer/AGENTS.md+++ b/apps/linger-installer/AGENTS.md@@ -58,7 +58,11 @@ whose Computer still uses the local model source (`model-source.json` says`local` or does not exist yet) has its stack checked once(`restoreLocalModels`), since a quit stops the models but not the services: astack that is not ready gets the same restore, then becomes the model source-again. A source switched to a subscription or BYOK leaves the stack stopped.+again. A source switched to a subscription or BYOK leaves the stack stopped;+a saved BYOK source gets its Bifrost gateway mounted again from the saved+configuration unless it already answers (`restoreByokSource`), and a failure+is logged and reported in the ready outcome's `details.byokGateway`+without failing the resume.A failed installation records the stage that caused it, even when nativecheckout preparation and runtime setup ran in parallel. A BYOK mount failurebelongs to runtime and keeps the redacted provider error in the job.diff --git a/apps/linger-installer/src/server/resume.test.ts b/apps/linger-installer/src/server/resume.test.tsindex f45f8966..35ca6d7c 100644--- a/apps/linger-installer/src/server/resume.test.ts+++ b/apps/linger-installer/src/server/resume.test.ts@@ -7,6 +7,7 @@ const instance = {name: "desktop",mode: "source-native",origin: "http://localhost:3000",+ root: "/home/instances/desktop",source: { repo: "/source" },} as Instance;const options = {@@ -82,6 +83,7 @@ test("leaves running services alone", async () => {engines: native(run, true),pending: async () => false,restore: async () => undefined,+ restoreByok: async () => undefined,}),).toMatchObject({ code: 0, details: { origin: instance.origin } });expect(run).not.toHaveBeenCalled();@@ -96,6 +98,7 @@ test("brings the local models back while the services keep running", async () =>engines: native(run, true),pending: async () => false,restore,+ restoreByok: async () => undefined,}),).toMatchObject({ code: 0, state: "ready" });expect(restore).toHaveBeenCalledWith(@@ -105,6 +108,48 @@ test("brings the local models back while the services keep running", async () =>expect(run).not.toHaveBeenCalled();});+test("mounts a saved BYOK source again after the local models", async () => {+ const order: string[] = [];+ const restore = vi.fn(async () => {+ order.push("restore");+ return undefined;+ });+ const restoreByok = vi.fn(async () => {+ order.push("byok");+ return undefined;+ });+ expect(+ await resumeSourceInstance(options, {+ load: async () => instance,+ engines: native(vi.fn(), true),+ pending: async () => false,+ restore,+ restoreByok,+ }),+ ).toMatchObject({ code: 0, message: "Services are already running." });+ expect(order).toEqual(["restore", "byok"]);+ expect(restoreByok).toHaveBeenCalledWith(+ "/home",+ expect.objectContaining({ signal: options.signal }),+ );+});++test("reports a BYOK gateway that did not come back on a ready resume", async () => {+ const byokGateway = {+ code: "BYOK_UNREACHABLE",+ message: "Endpoint did not answer.",+ };+ expect(+ await resumeSourceInstance(options, {+ load: async () => instance,+ engines: native(vi.fn(), true),+ pending: async () => false,+ restore: async () => undefined,+ restoreByok: async () => byokGateway,+ }),+ ).toMatchObject({ code: 0, state: "ready", details: { byokGateway } });+});+test("reports a local model restore that failed", async () => {const failed = {code: 4,@@ -112,18 +157,22 @@ test("reports a local model restore that failed", async () => {message: "The local model stack is not ready.",details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },};+ const restoreByok = vi.fn(async () => undefined);expect(await resumeSourceInstance(options, {load: async () => instance,engines: native(vi.fn(), true),pending: async () => false,restore: async () => failed,+ restoreByok,}),).toEqual(failed);+ expect(restoreByok).not.toHaveBeenCalled();});test("leaves the local models to a full start", async () => {const restore = vi.fn(async () => undefined);+ const restoreByok = vi.fn(async () => undefined);await resumeSourceInstance(options, {load: async () => instance,engines: native(@@ -135,8 +184,10 @@ test("leaves the local models to a full start", async () => {false,),restore,+ restoreByok,});expect(restore).not.toHaveBeenCalled();+ expect(restoreByok).not.toHaveBeenCalled();});test("restarts running services for a changed user.env", async () => {@@ -200,6 +251,7 @@ test("reports the source the services serve from", async () => {engines: native(vi.fn(), true),pending: async () => false,restore: async () => undefined,+ restoreByok: async () => undefined,}),).toMatchObject({ code: 0, details: { source: "/source" } });// The instance names a new checkout only once its services became readydiff --git a/apps/linger-installer/src/server/resume.ts b/apps/linger-installer/src/server/resume.tsindex fa735f8e..a7f9cab2 100644--- a/apps/linger-installer/src/server/resume.ts+++ b/apps/linger-installer/src/server/resume.ts@@ -2,7 +2,10 @@ import { realpath } from "node:fs/promises";import path from "node:path";import { loadInstance } from "@linger/local-installation/instance";-import { restoreLocalModels } from "@linger/local-installation/local-models";+import {+ restoreByokSource,+ restoreLocalModels,+} from "@linger/local-installation/local-models";import { userEnvironmentPending } from "@linger/local-installation/user-environment";import type { InstallOutcome } from "@linger/local-installation/events";import type { RuntimeDescriptor } from "@linger/local-installation/managed-runtimes";@@ -53,6 +56,7 @@ export async function resumeSourceInstance(engines = ENGINES,pending = userEnvironmentPending,restore = restoreLocalModels,+ restoreByok = restoreByokSource,} = {},): Promise<InstallOutcome> {const instance = await load({@@ -81,20 +85,35 @@ export async function resumeSourceInstance() &&!(await pending(instance))) {- // A quit stops the local models but leaves the services running, so- // they come back here rather than with the services.+ // A quit stops the local models and the Bifrost gateway a BYOK source+ // runs on, but leaves the services running, so they come back here+ // rather than with the services.+ const onEvent = (event: { message?: string }) => {+ if (event.message) options.log(event.message);+ };const restored = await restore(instance, {signal: options.signal,- onEvent: (event) => {- if (event.message) options.log(event.message);- },+ onEvent,});if (restored) return restored;+ // A gateway that did not come back is reported, not a failed resume:+ // the person can still reach the Models page.+ const byokGateway = await restoreByok(+ path.resolve(instance.root, "../.."),+ {+ signal: options.signal,+ onEvent,+ },+ );return {code: 0,state: "ready",message: "Services are already running.",- details: { origin: instance.origin, source: instance.source.repo },+ details: {+ origin: instance.origin,+ source: instance.source.repo,+ ...(byokGateway ? { byokGateway } : {}),+ },};}const outcome = await engine.run({diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex 0c161076..58ba75be 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -142,6 +142,16 @@ its approved plan applied again and the local source set again. Deployments,that check and the quit-time stop share one lock per home(`withLocalModelsLock`); the check waits up to 180 s for it, past the stop's150 s hard exit, then asks to try again.+`restoreByokSource` (`local-models.ts`) brings back a saved BYOK source's+Bifrost gateway on every resume (warm, or a restart from the saved choice,+which then prepares the saved runtime and no other source). Under the same+lock, waiting as the restore check does, it skips a loopback gateway whose+`/health` answers, otherwise runs `source apply` from the kit's saved+configuration, so the key never passes through Node. Each re-mount sends+the kit's one small probe request to the person's endpoint and adds a few+seconds to a launch after a quit. A failure (`LOCAL_MODELS_BUSY` when the+lock never frees) is logged and returned as `details.byokGateway`+(`{ code, message }`) of a successful resume, so Linger still opens.`runProcess` decodes stdout and stderr as separate UTF-8 streams beforecapture and output callbacks, preserving characters split across pipe reads.@@ -255,7 +265,8 @@ services), `migrate`, `services`, and `account` run concurrently with `runtime`,`services`/`account` `succeeded` events and `saveSourceBinding` until bothbranches succeed and aborting and draining both before rollback on failure;upgrades and live re-runs keep `migrate` sequential after `runtime`. When-`resume: true`, `prepareRuntime` inspects the selected runtime once and skips+`resume: true`, `prepareRuntime` inspects the selected runtime (or a saved BYOK+source's runtime) once and skips`harness plan` and `harness apply` when it is already installed (falling back toa full install if missing or unreadable), and passes the inspected descriptorthrough `onRuntimeDescriptors` so callers avoid a second status probe. Withindiff --git a/packages/local-installation/src/byok-source.test.ts b/packages/local-installation/src/byok-source.test.tsindex 868120b5..e1ab2198 100644--- a/packages/local-installation/src/byok-source.test.ts+++ b/packages/local-installation/src/byok-source.test.ts@@ -5,12 +5,15 @@ import { afterEach, describe, expect, it, vi } from "vitest";import {checkByokEndpoint,isAllowedByokUrl,+ prepareByokNativeRuntime,prepareByokRuntime,applyNativeSource,readByokEnvironment,validateByokConfiguration,} from "./byok-source.js";import { atomicPrivate, privateDirectory } from "./instance.js";+import type { prepareRuntime } from "./managed-runtimes.js";+import { restoreByokSource, withLocalModelsLock } from "./local-models.js";const tempDirs: string[] = [];@@ -211,6 +214,7 @@ describe("BYOK localmodels integration", () => {runtime: "pi",runtimeModel: "localmodels-byok",environment: { PI_CODING_AGENT_DIR: "/abs/pi" },+ gatewayUrl: "http://127.0.0.1:18480",});});@@ -303,3 +307,283 @@ describe("BYOK localmodels integration", () => {}});});++async function writeSource(home: string, source: unknown): Promise<void> {+ const state = path.join(home, "runtime", "localmodels", "state");+ await privateDirectory(state);+ await atomicPrivate(+ path.join(state, "model-source.json"),+ typeof source === "string" ? source : JSON.stringify(source),+ );+}++function byokSource(gatewayUrl: string | null = "http://127.0.0.1:18480") {+ return {+ schema: "localmodels.model-source/v1",+ mode: "byok",+ runtime: "pi",+ runtime_model: "localmodels-byok",+ model_label: "vendor/model",+ gateway_url: gatewayUrl,+ environment: {},+ };+}++describe("prepareByokNativeRuntime", () => {+ it("forwards the cold-resume options only when given", async () => {+ const prepareNative = vi.fn<typeof prepareRuntime>(async () => ({+ code: 0,+ state: "ready",+ message: "ok",+ }));+ const base = {+ home: "/home",+ signal: new AbortController().signal,+ onEvent: () => {},+ };+ const onDescriptor = vi.fn();+ await prepareByokNativeRuntime(+ "pi",+ { ...base, reuseInstalled: true, onDescriptor },+ { prepareNative },+ );+ expect(prepareNative.mock.calls[0]?.[1]).toMatchObject({+ reuseInstalled: true,+ onDescriptor,+ });+ await prepareByokNativeRuntime("pi", base, { prepareNative });+ expect(prepareNative.mock.calls[1]?.[1]).not.toHaveProperty(+ "reuseInstalled",+ );+ expect(prepareNative.mock.calls[1]?.[1]).not.toHaveProperty("onDescriptor");+ });+});++describe("restoreByokSource", () => {+ const ok = async () => ({ code: 0, stdout: "{}", stderr: "" });++ it("mounts the saved BYOK source from its saved configuration when the gateway is down", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource());+ const localmodels = vi.fn(ok);+ const fetch = vi.fn(async () => {+ throw new Error("connect ECONNREFUSED");+ });+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ { localmodels, fetch },+ );+ expect(fetch).toHaveBeenCalledWith(+ "http://127.0.0.1:18480/health",+ expect.objectContaining({ redirect: "error" }),+ );+ expect(localmodels).toHaveBeenCalledTimes(1);+ const [, args, options] = localmodels.mock.calls[0] as unknown as [+ string,+ string[],+ Record<string, unknown>,+ ];+ expect(args.slice(0, 6)).toEqual([+ "source",+ "apply",+ "--mode",+ "byok",+ "--runtime",+ "pi",+ ]);+ expect(args.at(-1)).toBe("--json");+ expect(args).not.toContain("--config-stdin");+ expect(options).not.toHaveProperty("input");+ });++ it("leaves a gateway that already answers alone", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource());+ const localmodels = vi.fn(ok);+ const fetch = vi.fn(async () => new Response("ok", { status: 200 }));+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ { localmodels, fetch },+ );+ expect(localmodels).not.toHaveBeenCalled();+ });++ it.each([+ ["local", { ...byokSource(), mode: "local" }],+ ["subscription", { ...byokSource(), mode: "subscription" }],+ ["malformed", "{not json"],+ ["missing", undefined],+ ])("does nothing for a %s source", async (_name, source) => {+ const home = await makeHome();+ if (source !== undefined) await writeSource(home, source);+ const localmodels = vi.fn(ok);+ const fetch = vi.fn(async () => new Response("ok"));+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ { localmodels, fetch },+ );+ expect(localmodels).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();+ });++ it.each([+ "http://10.0.0.5:18480",+ "https://127.0.0.1:18480",+ "http://127.0.0.1",+ "http://user:[email protected]:18480",+ "http://127.0.0.1:18480/?x=1",+ "not a url",+ null,+ ])("never probes the gateway URL %s and applies", async (gatewayUrl) => {+ const home = await makeHome();+ await writeSource(home, byokSource(gatewayUrl));+ const localmodels = vi.fn(ok);+ const fetch = vi.fn(async () => new Response("ok"));+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ { localmodels, fetch },+ );+ expect(fetch).not.toHaveBeenCalled();+ expect(localmodels).toHaveBeenCalledTimes(1);+ });++ it("logs and returns a failed mount without throwing", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource(null));+ const events: { kind: string; message: string }[] = [];+ const failure = await restoreByokSource(+ home,+ {+ signal: new AbortController().signal,+ onEvent: (event) => events.push(event),+ },+ {+ localmodels: vi.fn(async () => ({+ code: 1,+ stdout: JSON.stringify({+ code: "BYOK_UNREACHABLE",+ message: "Endpoint did not answer.",+ }),+ stderr: "",+ })),+ },+ );+ expect(failure).toEqual({+ code: "BYOK_UNREACHABLE",+ message: "Endpoint did not answer.",+ });+ const log = events.find((event) => event.kind === "log");+ expect(log?.message).toContain("Endpoint did not answer.");+ expect(log?.message).toContain("BYOK_UNREACHABLE");++ events.length = 0;+ expect(+ await restoreByokSource(+ home,+ {+ signal: new AbortController().signal,+ onEvent: (event) => events.push(event),+ },+ {+ localmodels: vi.fn(async () => ({+ code: 1,+ stdout: "raw private tool output",+ stderr: "",+ })),+ },+ ),+ ).toMatchObject({ code: "BYOK_GATEWAY_FAILED" });+ expect(JSON.stringify(events)).not.toContain("raw private tool output");+ expect(events.some((event) => event.kind === "log")).toBe(true);+ });++ it("keeps the cause of a tool that could not run", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource(null));+ expect(+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ {+ localmodels: vi.fn(async () => {+ throw new Error("The installed localmodels tool kit is missing.");+ }),+ },+ ),+ ).toEqual({+ code: "BYOK_GATEWAY_FAILED",+ message: "The installed localmodels tool kit is missing.",+ });+ });++ it("waits for a quit-time stop holding the lock, then mounts", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource(null));+ const localmodels = vi.fn(ok);+ let release!: () => void;+ let held!: () => void;+ const holding = new Promise<void>((resolve) => (held = resolve));+ const stop = withLocalModelsLock(home, async () => {+ held();+ await new Promise<void>((resolve) => (release = resolve));+ });+ await holding;+ const restored = restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ { localmodels, lockRetryMs: 5, lockWaitMs: 10_000 },+ );+ await new Promise((resolve) => setTimeout(resolve, 30));+ expect(localmodels).not.toHaveBeenCalled();+ release();+ await stop;+ expect(await restored).toBeUndefined();+ expect(localmodels).toHaveBeenCalledTimes(1);+ });++ it("gives up on a lock that is never released without applying", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource(null));+ const localmodels = vi.fn(ok);+ let release!: () => void;+ let held!: () => void;+ const holding = new Promise<void>((resolve) => (held = resolve));+ const stop = withLocalModelsLock(home, async () => {+ held();+ await new Promise<void>((resolve) => (release = resolve));+ });+ await holding;+ expect(+ await restoreByokSource(+ home,+ { signal: new AbortController().signal, onEvent: () => {} },+ { localmodels, lockRetryMs: 5, lockWaitMs: 30 },+ ),+ ).toMatchObject({ code: "LOCAL_MODELS_BUSY" });+ expect(localmodels).not.toHaveBeenCalled();+ release();+ await stop;+ });++ it("lets a cancel through", async () => {+ const home = await makeHome();+ await writeSource(home, byokSource(null));+ const controller = new AbortController();+ await expect(+ restoreByokSource(+ home,+ { signal: controller.signal, onEvent: () => {} },+ {+ localmodels: vi.fn(async () => {+ controller.abort();+ throw new Error("aborted");+ }),+ },+ ),+ ).rejects.toThrow();+ });+});diff --git a/packages/local-installation/src/byok-source.ts b/packages/local-installation/src/byok-source.tsindex c60e8389..69e0f418 100644--- a/packages/local-installation/src/byok-source.ts+++ b/packages/local-installation/src/byok-source.ts@@ -5,7 +5,11 @@ import {localmodelsStateDirectory,runLocalmodels,} from "./localmodels-tool.js";-import { prepareRuntime, type NativeRuntime } from "./managed-runtimes.js";+import {+ prepareRuntime,+ type NativeRuntime,+ type RuntimeDescriptor,+} from "./managed-runtimes.js";import type { InstallOutcome, InstallerEvent } from "./events.js";export type ByokProtocol = "openai-chat" | "openai-responses" | "anthropic";@@ -268,37 +272,65 @@ function sourceApplyFailure(};}-export async function prepareByokRuntime(- config: ByokConfiguration,+/**+ * Installs the runtime a BYOK source drives. BYOK needs no runtime sign-in,+ * so a pending one is not a failure. Returns the outcome only on failure.+ */+export async function prepareByokNativeRuntime(+ runtime: NativeRuntime,options: {home: string;signal: AbortSignal;onEvent: (event: InstallerEvent) => void;env?: NodeJS.ProcessEnv;+ reuseInstalled?: boolean;+ onDescriptor?: (descriptor: RuntimeDescriptor) => void;},dependencies: {localmodels?: typeof runLocalmodels;prepareNative?: typeof prepareRuntime;} = {},-): Promise<InstallOutcome> {- const validated = validateByokConfiguration(config);- const runtime = validated.runtime ?? "claude";- const nativeOutcome = await (dependencies.prepareNative ?? prepareRuntime)(+): Promise<InstallOutcome | undefined> {+ const outcome = await (dependencies.prepareNative ?? prepareRuntime)(runtime,{home: options.home,signal: options.signal,onEvent: options.onEvent,env: options.env,+ ...(options.reuseInstalled ? { reuseInstalled: true } : {}),+ ...(options.onDescriptor ? { onDescriptor: options.onDescriptor } : {}),},dependencies.localmodels ? { localmodels: dependencies.localmodels } : {},);- if (- nativeOutcome.code !== 0 &&- (nativeOutcome.details as { code?: string } | undefined)?.code !==+ return outcome.code === 0 ||+ (outcome.details as { code?: string } | undefined)?.code ==="RUNTIME_AUTH_REQUIRED"- )- return nativeOutcome;+ ? undefined+ : outcome;+}++export async function prepareByokRuntime(+ config: ByokConfiguration,+ options: {+ home: string;+ signal: AbortSignal;+ onEvent: (event: InstallerEvent) => void;+ env?: NodeJS.ProcessEnv;+ },+ dependencies: {+ localmodels?: typeof runLocalmodels;+ prepareNative?: typeof prepareRuntime;+ } = {},+): Promise<InstallOutcome> {+ const validated = validateByokConfiguration(config);+ const runtime = validated.runtime ?? "claude";+ const nativeFailure = await prepareByokNativeRuntime(+ runtime,+ options,+ dependencies,+ );+ if (nativeFailure) return nativeFailure;options.onEvent({kind: "stage",@@ -386,6 +418,7 @@ export async function readByokEnvironment(home: string): Promise<runtime: NativeRuntime;runtimeModel: string;environment: Record<string, string>;+ gatewayUrl: string | undefined;}| undefined> {@@ -421,8 +454,129 @@ export async function readByokEnvironment(home: string): Promise<runtimeModel:typeof parsed.runtime_model === "string" ? parsed.runtime_model : "",environment,+ gatewayUrl: loopbackGatewayUrl(parsed.gateway_url),};} catch {return undefined;}}++// Only a loopback gateway is probed, so a tampered state file cannot point+// the resume's health check at another host.+function loopbackGatewayUrl(raw: unknown): string | undefined {+ if (typeof raw !== "string") return undefined;+ try {+ const url = new URL(raw);+ if (+ url.protocol !== "http:" ||+ (url.hostname !== "127.0.0.1" && url.hostname !== "localhost") ||+ !url.port ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ )+ return undefined;+ return url.origin + url.pathname.replace(/\/+$/, "");+ } catch {+ return undefined;+ }+}++async function gatewayAnswers(+ gatewayUrl: string,+ signal: AbortSignal,+ fetchImpl: typeof fetch,+): Promise<boolean> {+ try {+ const response = await fetchImpl(`${gatewayUrl}/health`, {+ signal: AbortSignal.any([signal, AbortSignal.timeout(2000)]),+ redirect: "error",+ });+ return response.status === 200;+ } catch {+ return false;+ }+}++/** Why a saved BYOK source's gateway could not be mounted again. */+export interface ByokGatewayFailure {+ code: string;+ message: string;+}++/**+ * Mounts a saved BYOK source on Bifrost again from the configuration+ * localmodels saved, so the key never passes through Node, unless its+ * loopback gateway already answers. The caller holds the local model lock,+ * so a quit-time stop cannot take the gateway down between the check and+ * the decision. Returns why it failed, without throwing, except for the+ * caller's abort.+ */+export async function mountSavedByokSource(+ home: string,+ source: { runtime: NativeRuntime; gatewayUrl: string | undefined },+ options: { signal: AbortSignal; onEvent: (event: InstallerEvent) => void },+ dependencies: {+ localmodels?: typeof runLocalmodels;+ fetch?: typeof fetch;+ } = {},+): Promise<ByokGatewayFailure | undefined> {+ if (+ source.gatewayUrl &&+ (await gatewayAnswers(+ source.gatewayUrl,+ options.signal,+ dependencies.fetch ?? fetch,+ ))+ )+ return undefined;+ options.signal.throwIfAborted();+ options.onEvent({+ kind: "stage",+ stage: "runtime",+ state: "running",+ message: "Mounting the saved BYOK endpoint on the local Bifrost gateway…",+ });+ const fallback = "The BYOK gateway did not start.";+ let failure: InstallOutcome | undefined;+ try {+ // The kit's apply probes the endpoint once (up to about 35 s) before+ // Bifrost starts.+ const result = await applySource(+ home,+ "byok",+ source.runtime,+ { signal: options.signal, timeoutMs: 90_000 },+ dependencies.localmodels ?? runLocalmodels,+ );+ if (result.code !== 0)+ failure = sourceApplyFailure(+ result.stdout,+ fallback,+ "BYOK_GATEWAY_FAILED",+ );+ } catch (error) {+ options.signal.throwIfAborted();+ failure = sourceApplyFailure(+ "",+ error instanceof Error && error.message ? error.message : fallback,+ "BYOK_GATEWAY_FAILED",+ );+ }+ if (!failure) {+ options.onEvent({+ kind: "stage",+ stage: "runtime",+ state: "succeeded",+ message: "BYOK gateway is ready.",+ });+ return undefined;+ }+ return {+ code:+ (failure.details as { code?: string } | undefined)?.code ??+ "BYOK_GATEWAY_FAILED",+ message: failure.message,+ };+}diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.tsindex a284f2f1..316adda2 100644--- a/packages/local-installation/src/local-models.ts+++ b/packages/local-installation/src/local-models.ts@@ -12,7 +12,12 @@ import {type Instance,} from "./instance.js";import type { InstallOutcome, InstallerEvent } from "./events.js";-import { applyNativeSource, readByokEnvironment } from "./byok-source.js";+import {+ applyNativeSource,+ mountSavedByokSource,+ readByokEnvironment,+ type ByokGatewayFailure,+} from "./byok-source.js";import { localmodelsFailure } from "./localmodels-failure.js";import { runLocalmodels } from "./localmodels-tool.js";import {@@ -553,6 +558,62 @@ export async function prepareLocalModels(});});}+// Runs `callback` under the local model lock, waiting for another holder.+// Returns undefined when the wait runs out.+async function waitForLocalModelsLock<T>(+ home: string,+ callback: () => Promise<T>,+ signal: AbortSignal,+ dependencies: RestoreDependencies,+): Promise<{ value: T } | undefined> {+ const deadline = Date.now() + (dependencies.lockWaitMs ?? LOCK_WAIT_MS);+ for (;;) {+ try {+ return { value: await withLocalModelsLock(home, callback) };+ } catch (error) {+ if ((error as { code?: unknown }).code !== INSTANCE_BUSY) throw error;+ if (Date.now() >= deadline) return undefined;+ await sleep(dependencies.lockRetryMs ?? 1000, signal);+ }+ }+}++/**+ * Brings back the Bifrost gateway of a saved BYOK source, which the+ * desktop's quit stops with the stack. A failure is logged and returned,+ * never thrown: failing the resume would block the whole local workspace,+ * including the Models page that switches the source. Returns undefined+ * when there was nothing to do or the gateway is up.+ */+export async function restoreByokSource(+ home: string,+ options: { signal: AbortSignal; onEvent: (e: InstallerEvent) => void },+ dependencies: RestoreDependencies & { fetch?: typeof fetch } = {},+): Promise<ByokGatewayFailure | undefined> {+ const source = await readByokEnvironment(home);+ if (source?.mode !== "byok") return undefined;+ // The quit-time stop holds the lock while it takes the gateway down, so a+ // gateway that answers before it ends is not proof that it stays up.+ const held = await waitForLocalModelsLock(+ home,+ () => mountSavedByokSource(home, source, options, dependencies),+ options.signal,+ dependencies,+ );+ const failure: ByokGatewayFailure | undefined = held+ ? held.value+ : {+ code: "LOCAL_MODELS_BUSY",+ message: "Another local model operation is still running.",+ };+ if (failure)+ options.onEvent({+ kind: "log",+ message: `${failure.message} (${failure.code}) Agents cannot reach the model until the endpoint is reachable and the BYOK source is applied again on the Models page, or Linger restarts.`,+ });+ return failure;+}+/*** Brings back the local model stack of a local-models setup whose services* still run, such as when Linger opens again after a quit stopped the@@ -584,25 +645,21 @@ export async function restoreLocalModels();// A quit-time stop may still hold the lock; checking before it ends would// see a stack it is about to take down.- const deadline = Date.now() + (dependencies.lockWaitMs ?? LOCK_WAIT_MS);- let observed: Binding | null;- for (;;) {- try {- observed = await withLocalModelsLock(home, observe);- break;- } catch (error) {- if ((error as { code?: unknown }).code !== INSTANCE_BUSY) throw error;- if (Date.now() >= deadline)- return {- code: 4,- state: "action_required",- message:- "Another local model operation is still running. Try again once it ends.",- details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },- };- await sleep(dependencies.lockRetryMs ?? 1000, options.signal);- }- }+ const held = await waitForLocalModelsLock(+ home,+ observe,+ options.signal,+ dependencies,+ );+ if (!held)+ return {+ code: 4,+ state: "action_required",+ message:+ "Another local model operation is still running. Try again once it ends.",+ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },+ };+ const observed = held.value;if (observed?.ready) return;// prepareLocalModels takes the lock itself, and the lock is not reentrant.return (diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.tsindex 3ae46e31..1e99000a 100644--- a/packages/local-installation/src/native-source-flow.test.ts+++ b/packages/local-installation/src/native-source-flow.test.ts@@ -53,7 +53,8 @@ import {import { prepareRuntime, type RuntimeDescriptor } from "./managed-runtimes.js";import { managedRuntimeEnvironment } from "./managed-codex.js";import { applyNativeSource, prepareByokRuntime } from "./byok-source.js";-import { prepareLocalModels } from "./local-models.js";+import { atomicPrivate, privateDirectory } from "./instance.js";+import { prepareLocalModels, restoreByokSource } from "./local-models.js";import {inspectNativeListeners,inspectNativeProcess,@@ -90,6 +91,7 @@ vi.mock("./byok-source.js", async (original) => ({vi.mock("./local-models.js", async (original) => ({...(await original<typeof import("./local-models.js")>()),prepareLocalModels: vi.fn(async () => undefined),+ restoreByokSource: vi.fn(async () => undefined),}));vi.mock("./managed-runtimes.js", () => ({runtimeVersionFailure: vi.fn(() => undefined),@@ -323,6 +325,210 @@ test("a restart of local models keeps the model source the person switched to",expect(applyNativeSource).not.toHaveBeenCalled();});+async function saveModelSource(home: string, mode: string, runtime: string) {+ const state = path.join(home, "runtime", "localmodels", "state");+ await privateDirectory(state);+ await atomicPrivate(+ path.join(state, "model-source.json"),+ JSON.stringify({+ schema: "localmodels.model-source/v1",+ mode,+ runtime,+ runtime_model: "model",+ model_label: null,+ gateway_url: "http://127.0.0.1:18480",+ environment: {},+ }),+ );+}++async function restartAfter(+ setupChoice: "codex" | "local-models",+ source: { mode: string; runtime: string },+ restartRuntime?:+ | Awaited<ReturnType<typeof prepareRuntime>>+ | typeof prepareRuntime,+ restartOptions: Partial<Parameters<typeof installNativeSource>[0]> = {},+) {+ const f = await fixture();+ vi.mocked(prepareRuntime).mockResolvedValue({+ code: 0,+ state: "ready",+ message: "ok",+ });+ await installNativeSource({+ home: f.home,+ repo: f.repo,+ name: "native-flow",+ setupChoice,+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ await saveModelSource(f.home, source.mode, source.runtime);+ vi.mocked(applyNativeSource).mockClear();+ vi.mocked(prepareLocalModels).mockClear();+ vi.mocked(prepareRuntime).mockClear();+ vi.mocked(prepareModelGateway).mockClear();+ vi.mocked(restoreByokSource).mockClear();+ if (typeof restartRuntime === "function")+ vi.mocked(prepareRuntime).mockImplementation(restartRuntime);+ else if (restartRuntime)+ vi.mocked(prepareRuntime).mockResolvedValue(restartRuntime);+ const result = await installNativeSource({+ home: f.home,+ repo: f.repo,+ name: "native-flow",+ signal: new AbortController().signal,+ onEvent: () => {},+ ...restartOptions,+ });+ return { f, result };+}++test.each(["codex", "local-models"] as const)(+ "a restart mounts a BYOK source switched to after choosing %s",+ async (setupChoice) => {+ // BYOK needs no runtime sign-in, so a pending one never holds a resume.+ const { f, result } = await restartAfter(+ setupChoice,+ { mode: "byok", runtime: "pi" },+ {+ code: 4,+ state: "action_required",+ message: "sign in later",+ details: { code: "RUNTIME_AUTH_REQUIRED" },+ },+ );+ expect(result.code).toBe(0);+ expect(vi.mocked(prepareRuntime).mock.calls[0]?.[0]).toBe("pi");+ expect(restoreByokSource).toHaveBeenCalledWith(+ path.resolve(f.home),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ expect(applyNativeSource).not.toHaveBeenCalled();+ expect(prepareLocalModels).not.toHaveBeenCalled();+ expect(prepareModelGateway).toHaveBeenCalledWith(+ expect.anything(),+ { runtime: "pi", modelSource: "byok" },+ expect.anything(),+ );+ },+);++test("a restart reports a BYOK gateway that did not come back", async () => {+ const byokGateway = {+ code: "BYOK_UNREACHABLE",+ message: "Endpoint did not answer.",+ };+ vi.mocked(restoreByokSource).mockResolvedValue(byokGateway);+ const { result } = await restartAfter("codex", {+ mode: "byok",+ runtime: "pi",+ });+ expect(result).toMatchObject({ code: 0, details: { byokGateway } });+});++test("a cold resume of a saved BYOK source reuses the installed runtime and forwards its descriptor", async () => {+ const descriptor: RuntimeDescriptor = {+ runtime: "pi",+ executable: "/mock/pi",+ argvPrefix: [],+ installed: true,+ authenticated: true,+ authMode: "api_key",+ loginCommand: null,+ };+ const forwarded: RuntimeDescriptor[][] = [];+ const { f, result } = await restartAfter(+ "codex",+ { mode: "byok", runtime: "pi" },+ async (_runtime, options) => {+ options.onDescriptor?.(descriptor);+ return { code: 0, state: "ready", message: "ok" };+ },+ {+ resume: true,+ onRuntimeDescriptors: (descriptors) => forwarded.push(descriptors),+ },+ );+ expect(result.code).toBe(0);+ const options = vi.mocked(prepareRuntime).mock.calls[0]?.[1];+ expect(options?.reuseInstalled).toBe(true);+ expect(options?.env).toBeUndefined();+ expect(forwarded).toEqual([[descriptor]]);+ expect(restoreByokSource).toHaveBeenCalledWith(+ path.resolve(f.home),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+});++test("a restart of a saved BYOK source without resume prepares the runtime in full", async () => {+ const { result } = await restartAfter("codex", {+ mode: "byok",+ runtime: "pi",+ });+ expect(result.code).toBe(0);+ const options = vi.mocked(prepareRuntime).mock.calls[0]?.[1];+ expect(options?.env).toBeDefined();+ expect(options).not.toHaveProperty("reuseInstalled");+});++test("choosing a subscription again replaces a saved BYOK source", async () => {+ const f = await fixture();+ vi.mocked(prepareRuntime).mockResolvedValue({+ code: 0,+ state: "ready",+ message: "ok",+ });+ await saveModelSource(f.home, "byok", "pi");+ await installNativeSource({+ home: f.home,+ repo: f.repo,+ name: "native-flow",+ setupChoice: "codex",+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ expect(applyNativeSource).toHaveBeenCalledWith(+ path.resolve(f.home),+ "subscription",+ "codex",+ expect.any(AbortSignal),+ );+ expect(restoreByokSource).not.toHaveBeenCalled();+});++test("a restart keeps a saved subscription source as before", async () => {+ const { result } = await restartAfter("codex", {+ mode: "subscription",+ runtime: "codex",+ });+ expect(result.code).toBe(0);+ expect(applyNativeSource).toHaveBeenCalledWith(+ expect.any(String),+ "subscription",+ "codex",+ expect.any(AbortSignal),+ );+ expect(restoreByokSource).not.toHaveBeenCalled();+ expect(prepareModelGateway).toHaveBeenCalledWith(+ expect.anything(),+ "codex",+ expect.anything(),+ );+});++test("a restart keeps a saved local source as before", async () => {+ const { result } = await restartAfter("local-models", {+ mode: "local",+ runtime: "pi",+ });+ expect(result.code).toBe(0);+ expect(prepareLocalModels).toHaveBeenCalled();+ expect(applyNativeSource).not.toHaveBeenCalled();+ expect(restoreByokSource).not.toHaveBeenCalled();+});+test("only TeamHub's process gets the server identity key", async () => {const f = await fixture();vi.mocked(prepareRuntime).mockResolvedValue({diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex ae9bf0f5..43f602b1 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -50,14 +50,20 @@ import {managedRuntimeEnvironment,} from "./managed-codex.js";import { prepareRuntime, runtimeVersionFailure } from "./managed-runtimes.js";-import { applyNativeSource, prepareByokRuntime } from "./byok-source.js";+import {+ applyNativeSource,+ prepareByokNativeRuntime,+ prepareByokRuntime,+ readByokEnvironment,+ type ByokGatewayFailure,+} from "./byok-source.js";import {readSetupChoice,writeGpuSharing,validateSetupChoice,writeSetupChoice,} from "./setup-selection.js";-import { prepareLocalModels } from "./local-models.js";+import { prepareLocalModels, restoreByokSource } from "./local-models.js";import { prepareSourceComputer } from "./source-computer.js";import { connectComputer, stopComputer } from "./computer.js";import { prepareLocalEnrollment } from "./local-enrollment.js";@@ -469,6 +475,14 @@ async function runNativeSource(const current = instance;return await withInstanceLock(current, async () => {const home = path.resolve(current.root, "../..");+ // A restart reads the choice from setup-choice.json, which a source+ // switched since on the Models page does not update, so a saved BYOK+ // source keeps its own runtime and gateway.+ const saved =+ !options.byok && !options.setupChoice+ ? await readByokEnvironment(home)+ : undefined;+ const restoredByok = saved?.mode === "byok" ? saved : undefined;await writeSetupChoice(current, choice);if (options.shareGpu !== undefined)await writeGpuSharing(current, options.shareGpu);@@ -485,9 +499,33 @@ async function runNativeSource(let runtimeError: unknown;let runtimeAborted = false;let runtimePending = true;+ let byokGateway: ByokGatewayFailure | undefined;const runtime = (async () => {try {- if (options.byok) {+ if (restoredByok) {+ runtimeOutcome = await prepareByokNativeRuntime(+ restoredByok.runtime,+ {+ home,+ signal,+ onEvent: emit,+ ...(options.resume+ ? { reuseInstalled: true }+ : {+ env: await managedRuntimeEnvironment(home, current.root),+ }),+ onDescriptor: (descriptor) =>+ options.onRuntimeDescriptors?.([descriptor]),+ },+ );+ // A gateway that does not come back leaves the services usable,+ // so the outcome only reports it.+ if (!runtimeOutcome)+ byokGateway = await restoreByokSource(home, {+ signal,+ onEvent: emit,+ });+ } else if (options.byok) {const byokRuntime =choice === "local-models"? (options.byok.runtime ?? "claude")@@ -1063,9 +1101,13 @@ async function runNativeSource(// sign-in, retires one an earlier release started.await prepareModelGateway(current,- options.byok && choice !== "local-models"- ? { runtime: choice, modelSource: "byok" }- : choice,+ // A restored BYOK source keeps its gateway whatever the saved+ // choice: a local-models choice would require the local stack.+ restoredByok+ ? { runtime: restoredByok.runtime, modelSource: "byok" }+ : options.byok && choice !== "local-models"+ ? { runtime: choice, modelSource: "byok" }+ : choice,{home,signal,@@ -1217,6 +1259,7 @@ async function runNativeSource(activeOperations: 0,},businessVerification: "not_run",+ ...(byokGateway ? { byokGateway } : {}),},};}@@ -1258,6 +1301,7 @@ async function runNativeSource(services: checks,computer,businessVerification: "not_run",+ ...(byokGateway ? { byokGateway } : {}),...(authPending && typeof runtimeOutcome?.details === "object"? runtimeOutcome.details: {}),