Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(local-installation): apply the approved local model plan again when the stack is not ready

Dongdong Chen40b06c1429ce
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index b82fc3cf..5d73b0b4 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -185,7 +185,12 @@ Gateway and runs Agents. The daemon exits with the app.
from their folder, the record keeps naming it, and the start failure page's
Retry moves them again. An app older than the recorded version
(a downgrade) leaves the services on their newer source and logs
- `local_server.source_newer_than_app`. A Quick Install that stopped
+ `local_server.source_newer_than_app`. When the local model stops a resume,
+ the start failure names the stack's first known binding reason code
+ (`details.reasons`, such as `pi-extensions-unavailable`) in its own words
+ and, by `details.code`, the action that works: Try Again for
+ `LOCAL_MODELS_RECOVERY_REQUIRED` (the resume applies the approved plan
+ again), Set Up Again to review a new plan or choose another runtime. A Quick Install that stopped
before the computer enrolled is not resumed: setup shows again and Install
finishes it, reusing a finished job only while its origin answers (a stopped
server gets a new job, which starts the services again). The start failure
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index 65b421c0..7e8cf16d 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -134,7 +134,10 @@ if (args.includes("--resume")) {
const repo = args[args.indexOf("--source-repo") + 1];
const servingFile = path.join(home, "resume-serving");
const source = fs.existsSync(servingFile) ? fs.readFileSync(servingFile, "utf8") : fs.existsSync(repo) ? fs.realpathSync(repo) : repo;
- process.stdout.write("noise\n" + JSON.stringify({ code, message: code ? "Native teamhub stopped" : "ok", details: { source }, ...(runtime ? { runtime } : {}) }) + "\n");
+ // resume-fails may hold the failed outcome's message and details.
+ const failure = code ? fs.readFileSync(path.join(home, "resume-fails"), "utf8").trim() : "";
+ const outcome = failure ? JSON.parse(failure) : { message: code ? "Native teamhub stopped" : "ok", details: { source } };
+ process.stdout.write("noise\n" + JSON.stringify({ code, ...outcome, ...(runtime ? { runtime } : {}) }) + "\n");
process.exit(code);
}
const origin = "http://127.0.0.1:4321";
@@ -2659,6 +2662,60 @@ describe("LocalServerModule after a restart", () => {
await f.host.stop("quit");
});
+ it.each([
+ [
+ "LOCAL_MODELS_RECOVERY_REQUIRED",
+ "Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.",
+ ],
+ [
+ "LOCAL_MODELS_APPROVAL_REQUIRED",
+ "Set Up Again to review the local model plan or choose another AI runtime.",
+ ],
+ ])(
+ "names the action that works when the local model stops a restart (%s)",
+ async (code, action) => {
+ const f = fixture({}, enrolled, (home) => {
+ record(home);
+ writeFileSync(
+ path.join(home, "resume-fails"),
+ JSON.stringify({
+ message: "The local model stack is not ready.",
+ details: { code },
+ }),
+ );
+ });
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));
+ expect(f.showStartFailed).toHaveBeenCalledWith(
+ `The local model stack is not ready. ${action}`,
+ );
+ await f.host.stop("quit");
+ },
+ );
+
+ it("says why the local model stack is not ready, from its reason code", async () => {
+ const f = fixture({}, enrolled, (home) => {
+ record(home);
+ writeFileSync(
+ path.join(home, "resume-fails"),
+ JSON.stringify({
+ message:
+ "The upstream tool could not verify the local stack binding.",
+ details: {
+ code: "LOCAL_MODELS_RECOVERY_REQUIRED",
+ reasons: ["pi-extensions-unavailable", "gateway-unavailable"],
+ },
+ }),
+ );
+ });
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("failed"));
+ expect(f.showStartFailed).toHaveBeenCalledWith(
+ "The local model's Pi can't load extensions, which every Linger run needs. The upstream tool could not verify the local stack binding. Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.",
+ );
+ await f.host.stop("quit");
+ });
+
it("starts the services again when the person tries again", async () => {
const f = fixture({}, enrolled, (home) => {
record(home);
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index d69e59d1..fe3c4b11 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -2326,7 +2326,7 @@ export class LocalServerModule implements Module {
const outcome = await new Promise<{
code: number;
message: string;
- details?: { source?: unknown };
+ details?: { source?: unknown; code?: unknown; reasons?: unknown };
runtime?: InstanceRuntime;
}>((resolve, reject) => {
const child = spawn(
@@ -2363,7 +2363,7 @@ export class LocalServerModule implements Module {
JSON.parse(last) as {
code: number;
message: string;
- details?: { source?: unknown };
+ details?: { source?: unknown; code?: unknown; reasons?: unknown };
runtime?: InstanceRuntime;
},
);
@@ -2372,8 +2372,29 @@ export class LocalServerModule implements Module {
}
});
});
- if (outcome.code !== 0)
- throw new Error(outcome.message || "The installation stopped");
+ if (outcome.code !== 0) {
+ const { code, reasons } = outcome.details ?? {};
+ const action =
+ typeof code === "string" && Object.hasOwn(RESUME_ACTIONS, code)
+ ? RESUME_ACTIONS[code]
+ : undefined;
+ const reason = Array.isArray(reasons)
+ ? reasons.find(
+ (item): item is string =>
+ typeof item === "string" &&
+ Object.hasOwn(LOCAL_MODEL_NOT_READY, item),
+ )
+ : undefined;
+ throw new Error(
+ [
+ reason && LOCAL_MODEL_NOT_READY[reason],
+ outcome.message || "The installation stopped",
+ action,
+ ]
+ .filter(Boolean)
+ .join(" "),
+ );
+ }
this.#adoptRuntime(outcome.runtime);
const source = outcome.details?.source;
return typeof source === "string" ? source : undefined;
@@ -2667,6 +2688,31 @@ const LOCAL_MODEL_FAILURES = new Set([
"GPU_SHARING_REVOCATION_FAILED",
]);
+// What works from the start-failure page when the local model stops a
+// restart: a restart applies the approved plan again, but only setup can
+// approve a new one or switch the runtime.
+const RESUME_ACTIONS: Record<string, string> = {
+ LOCAL_MODELS_RECOVERY_REQUIRED:
+ "Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.",
+ LOCAL_MODELS_APPROVAL_REQUIRED:
+ "Set Up Again to review the local model plan or choose another AI runtime.",
+};
+
+// Why the local model stack was not ready, by the reason code localmodels'
+// setup binding gives.
+const LOCAL_MODEL_NOT_READY: Record<string, string> = {
+ "pi-extensions-unavailable":
+ "The local model's Pi can't load extensions, which every Linger run needs.",
+ "deployment-unavailable": "The local model service isn't running.",
+ "acceptance-unavailable": "The local model stack hasn't passed its checks.",
+ "gateway-ownership": "The local model gateway isn't running.",
+ "gateway-unavailable": "The local model gateway isn't running.",
+ "pi-model-unavailable": "Pi can't reach the local model.",
+ "pi-config-changed": "Pi's settings changed while they were checked.",
+ "plan-invalid": "The approved local model plan can't be read.",
+ "binding-unavailable": "The local model stack couldn't be checked.",
+};
+
export interface Reconnect {
readonly windowMs: number;
readonly maxBackoffMs: number;
diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md
index 21e94437..61146daa 100644
--- a/apps/linger-installer/AGENTS.md
+++ b/apps/linger-installer/AGENTS.md
@@ -28,7 +28,18 @@ once its services are ready on it: until then `instance.json` keeps naming the
checkout they run from, the new checkout's migrations run only after the
runtime (the local model, for one) is ready, and a run that stops earlier
leaves the running services and their schema as they were. A successful
-outcome's `details.source` names the checkout the services serve from. With
+outcome's `details.source` names the checkout the services serve from. A
+local model stack whose saved binding is no longer ready (any setup binding
+reason, `pi-extensions-unavailable` from a Pi an earlier localmodels
+installed without extension support included) gets its approved plan applied
+again when the saved plan inputs still match the current choices; only a
+plan the person approved is ever applied, and a stack still not ready ends
+`LOCAL_MODELS_RECOVERY_REQUIRED` with the binding's reason codes in
+`details.reasons`. 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
`GET /api/instances/{name}/runtime` (runtime and localmodels tool paths), so
the desktop's Computer follows them.
diff --git a/apps/linger-installer/src/server/jobs.test.ts b/apps/linger-installer/src/server/jobs.test.ts
index 4ce9094f..0b263b9f 100644
--- a/apps/linger-installer/src/server/jobs.test.ts
+++ b/apps/linger-installer/src/server/jobs.test.ts
@@ -257,6 +257,26 @@ test.each([
},
);
+test.each([
+ ["RUNTIME_PLAN_REFUSED", "RUNTIME_PLAN_REFUSED"],
+ ["RUNTIME_ACTION_FAILED", "RUNTIME_ACTION_FAILED"],
+ ["RUNTIME_EXTENSIONS_FAILED", "RUNTIME_EXTENSIONS_FAILED"],
+ ["NATIVE_SOURCE_INSTALLATION_FAILED", "INSTALL_FAILED"],
+])(
+ "a failed installation with runtime cause %s reports it as %s",
+ async (code, errorCode) => {
+ const { jobs } = await setup(async () => ({
+ code: 5,
+ state: "failed",
+ message: "The runtime could not be installed.",
+ details: { code, stage: "runtime" },
+ }));
+ const job = await jobs.start({ instance: "default" });
+ await jobs.wait(job.id);
+ expect(jobs.get(job.id)).toMatchObject({ state: "failed", errorCode });
+ },
+);
+
const localPlan = {
planId: "a".repeat(64),
gpuIndex: 1,
diff --git a/apps/linger-installer/src/server/jobs.ts b/apps/linger-installer/src/server/jobs.ts
index 84165a33..84972d2d 100644
--- a/apps/linger-installer/src/server/jobs.ts
+++ b/apps/linger-installer/src/server/jobs.ts
@@ -417,7 +417,14 @@ export class JobManager {
"LOCAL_MODELS_UNAVAILABLE",
"LOCAL_MODELS_APPROVAL_REQUIRED",
"LOCAL_MODELS_RECOVERY_REQUIRED",
- ].includes(String(details.code))
+ ].includes(String(details.code)) ||
+ // Why the runtime could not be installed, in place of INSTALL_FAILED.
+ (record.job.state === "failed" &&
+ [
+ "RUNTIME_PLAN_REFUSED",
+ "RUNTIME_ACTION_FAILED",
+ "RUNTIME_EXTENSIONS_FAILED",
+ ].includes(String(details.code)))
) {
record.job.errorCode = String(details.code);
if (details.code === "LOCAL_MODELS_APPROVAL_REQUIRED") {
diff --git a/packages/local-installation/src/dependencies.test.ts b/packages/local-installation/src/dependencies.test.ts
index 26a9d0be..18ac3817 100644
--- a/packages/local-installation/src/dependencies.test.ts
+++ b/packages/local-installation/src/dependencies.test.ts
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { prepareDependencies } from "./dependencies.js";
@@ -66,3 +66,40 @@ it("returns Runtime timeout category and stage through dependency preparation",
details: { code: "COMMAND_TIMEOUT", stage: "runtime" },
});
});
+it.each([
+ ["plan", "RUNTIME_ACTION_FAILED", "RUNTIME_PLAN_REFUSED"],
+ ["apply", "RUNTIME_ACTION_FAILED", "RUNTIME_ACTION_FAILED"],
+ ["apply", "RUNTIME_EXTENSIONS_FAILED", "RUNTIME_EXTENSIONS_FAILED"],
+])(
+ "returns the harness %s failure %s as %s through dependency preparation",
+ async (step, upstream, code) => {
+ const options = { ...(await fixture()), dependency: "pi" as const };
+ const localmodels = vi.fn(async (_home: string, args: string[]) => {
+ if (args[1] === "plan" && step !== "plan")
+ await writeFile(
+ args[args.indexOf("--out") + 1]!,
+ JSON.stringify({
+ schema: "localmodels.harness-plan/v1",
+ id: "a".repeat(64),
+ runtime: "pi",
+ }),
+ );
+ const failed = args[1] === step;
+ return {
+ code: failed ? 1 : 0,
+ stdout: failed
+ ? JSON.stringify({
+ schema: "localmodels.harness-error/v1",
+ code: upstream,
+ message: "Runtime action failed: upstream cause.",
+ })
+ : "",
+ stderr: "",
+ };
+ });
+ expect(await prepareDependencies(options, { localmodels })).toMatchObject({
+ state: "failed",
+ details: { code, stage: "runtime" },
+ });
+ },
+);
diff --git a/packages/local-installation/src/dependencies.ts b/packages/local-installation/src/dependencies.ts
index de9a226a..6ef89773 100644
--- a/packages/local-installation/src/dependencies.ts
+++ b/packages/local-installation/src/dependencies.ts
@@ -5,6 +5,7 @@ import { privateDirectory } from "./instance.js";
import type { InstallOutcome, InstallerEvent } from "./events.js";
import {
installNativeRuntime,
+ runtimeFailureCode,
runtimeVersionFailure,
type RuntimeDependencies,
} from "./managed-runtimes.js";
@@ -61,12 +62,9 @@ export async function prepareDependencies(
emit("failed", message);
const code =
versionFailure?.code ??
- (error &&
- typeof error === "object" &&
- "code" in error &&
- (error.code === "LOCALMODELS_RUNTIME_UNAVAILABLE" ||
- error.code === "COMMAND_TIMEOUT")
- ? error.code
+ runtimeFailureCode(error) ??
+ ((error as { code?: unknown } | null)?.code === "COMMAND_TIMEOUT"
+ ? "COMMAND_TIMEOUT"
: undefined);
return {
code: 5,
diff --git a/packages/local-installation/src/local-models.test.ts b/packages/local-installation/src/local-models.test.ts
index 98dbf118..8a23f16b 100644
--- a/packages/local-installation/src/local-models.test.ts
+++ b/packages/local-installation/src/local-models.test.ts
@@ -279,7 +279,8 @@ test("replanning requires a separate review and never silently approves", async
).toMatchObject({ details: { code: "LOCAL_MODELS_APPROVAL_REQUIRED" } });
expect(f.call.mock.calls.some((c) => c[1][1] === "apply")).toBe(false);
});
-test("saved binding needs fresh upstream health before reuse", async () => {
+// A deployed stack whose binding is ready, then observed not ready once.
+async function deployedThenNotReady(reason: string) {
const f = await fixture();
await prepareLocalModels(f.instance, f.options, { localmodels: f.call });
await prepareLocalModels(
@@ -287,11 +288,118 @@ test("saved binding needs fresh upstream health before reuse", async () => {
{ ...f.options, localModelsApproval: f.id },
{ localmodels: f.call },
);
+ const ready = structuredClone(f.binding);
f.binding.ready = false;
f.binding.pi = null as never;
+ f.binding.reasons = [{ code: reason, message: "upstream text" }] as never;
+ f.call.mockClear();
+ return { ...f, ready };
+}
+test.each(["deployment-unavailable", "pi-extensions-unavailable"])(
+ "a saved binding observed not ready (%s) applies the approved plan again",
+ async (reason) => {
+ const f = await deployedThenNotReady(reason);
+ const original = f.call.getMockImplementation()!;
+ f.call.mockImplementation(async (...a) => {
+ // stack apply brings the stack and its Pi back.
+ if (a[1][1] === "apply") Object.assign(f.binding, f.ready);
+ return original(...a);
+ });
+ expect(
+ await prepareLocalModels(f.instance, f.options, { localmodels: f.call }),
+ ).toBeUndefined();
+ const stack = f.call.mock.calls
+ .map(([, args]) => args)
+ .filter((args) => args[0] === "stack");
+ expect(stack).toEqual([
+ [
+ "stack",
+ "apply",
+ path.join(f.home, "runtime/localmodels/plan.json"),
+ "--approve",
+ f.id,
+ "--jsonl",
+ ],
+ ]);
+ expect(
+ JSON.parse(
+ await readFile(
+ path.join(f.home, "runtime/localmodels/binding.json"),
+ "utf8",
+ ),
+ ),
+ ).toEqual(f.ready);
+ expect(f.options.onEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ kind: "log",
+ stage: "runtime",
+ message: expect.stringContaining(reason),
+ }),
+ );
+ },
+);
+test("a stack still not ready after applying the approved plan again asks for recovery", async () => {
+ const f = await deployedThenNotReady("gateway-unavailable");
+ const result = await prepareLocalModels(f.instance, f.options, {
+ localmodels: f.call,
+ });
+ expect(result).toMatchObject({
+ state: "action_required",
+ details: {
+ code: "LOCAL_MODELS_RECOVERY_REQUIRED",
+ reasons: ["gateway-unavailable"],
+ },
+ });
+ expect(
+ f.call.mock.calls.filter(([, args]) => args[1] === "apply"),
+ ).toHaveLength(1);
+ // The earlier ready binding is never replaced by one not verified.
+ expect(
+ JSON.parse(
+ await readFile(
+ path.join(f.home, "runtime/localmodels/binding.json"),
+ "utf8",
+ ),
+ ),
+ ).toEqual(f.ready);
+});
+test("a failed re-apply of the approved plan reports the upstream cause", async () => {
+ const f = await deployedThenNotReady("deployment-unavailable");
+ const original = f.call.getMockImplementation()!;
+ f.call.mockImplementation(async (...a) => {
+ if (a[1][1] !== "apply") return original(...a);
+ a[2]!.onOutput!("stack: port 8080 is held by another program\n");
+ return { code: 1, stdout: "", stderr: "" };
+ });
expect(
await prepareLocalModels(f.instance, f.options, { localmodels: f.call }),
- ).toMatchObject({ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" } });
+ ).toMatchObject({
+ state: "action_required",
+ // What made it apply the plan again.
+ details: {
+ code: "LOCAL_MODELS_RECOVERY_REQUIRED",
+ reasons: ["deployment-unavailable"],
+ },
+ message: expect.stringContaining(
+ "stack: port 8080 is held by another program",
+ ),
+ });
+});
+test("a not-ready binding is never re-applied once resource choices changed", async () => {
+ const f = await deployedThenNotReady("deployment-unavailable");
+ const result = await prepareLocalModels(
+ f.instance,
+ { ...f.options, shareGpu: false },
+ { localmodels: f.call },
+ );
+ expect(result).toMatchObject({
+ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" },
+ });
+ expect(
+ f.call.mock.calls.some(
+ ([, args]) => args[0] === "stack" && ["plan", "apply"].includes(args[1]!),
+ ),
+ ).toBe(false);
});
test("cancellation propagates without pretending to finish", async () => {
const f = await fixture();
diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.ts
index cabc2020..c1fac212 100644
--- a/packages/local-installation/src/local-models.ts
+++ b/packages/local-installation/src/local-models.ts
@@ -39,6 +39,8 @@ interface Binding {
environment: Record<string, string>;
configFingerprint: string;
} | null;
+ // Why the stack is not ready, such as pi-extensions-unavailable.
+ reasons?: { code?: unknown; message?: unknown }[];
}
interface Options {
shareGpu?: boolean;
@@ -182,6 +184,22 @@ function binding(value: unknown, id?: string): Binding {
throw new Error("Invalid upstream Pi binding.");
return b;
}
+// The binding's reason codes, such as pi-extensions-unavailable.
+function reasonCodes(observed: Binding | null): string[] {
+ return (observed?.reasons ?? []).flatMap((reason) =>
+ typeof reason?.code === "string" &&
+ /^[a-z][a-z0-9-]{0,63}$/.test(reason.code)
+ ? [reason.code]
+ : [],
+ );
+}
+// The first reason's upstream message, for display only.
+function reasonText(observed: Binding | null): string {
+ const message = observed?.reasons?.[0]?.message;
+ return typeof message === "string" && message.trim()
+ ? `: ${message.trim().replace(/\s+/g, " ").slice(0, 300)}`
+ : "";
+}
export async function localModelsEnvironment(
instance: Instance,
): Promise<NodeJS.ProcessEnv> {
@@ -235,6 +253,8 @@ export async function prepareLocalModels(
dependencies: Dependencies = {},
): Promise<InstallOutcome | undefined> {
options.signal.throwIfAborted();
+ // Why the binding was not ready, for the client to word; set once observed.
+ let reasons: string[] = [];
const action = (
code: string,
message: string,
@@ -243,7 +263,11 @@ export async function prepareLocalModels(
code: 4,
state: "action_required",
message,
- details: { code, ...(summary ? { localModelsPlan: summary } : {}) },
+ details: {
+ code,
+ ...(summary ? { localModelsPlan: summary } : {}),
+ ...(reasons.length ? { reasons } : {}),
+ },
});
if (options.localModelsReplan && options.localModelsApproval)
return action(
@@ -399,23 +423,10 @@ export async function prepareLocalModels(
"--json",
]);
if (result.code !== 0) return null;
- return binding(JSON.parse(result.stdout), summary.planId);
+ const observed = binding(JSON.parse(result.stdout), summary.planId);
+ reasons = observed.ready ? [] : reasonCodes(observed);
+ return observed;
};
- if (
- previous &&
- !options.localModelsReplan &&
- binding(JSON.parse(previous)).planId === summary.planId
- ) {
- const observed = await observe();
- if (observed?.ready) {
- await atomicPrivate(bindFile, JSON.stringify(observed));
- return;
- }
- return action(
- "LOCAL_MODELS_RECOVERY_REQUIRED",
- "The upstream stack is not ready. Review an updated plan; existing resources were preserved.",
- );
- }
let inputs:
| { planId?: unknown; shareGpu?: unknown; decision?: unknown }
| undefined;
@@ -425,24 +436,51 @@ export async function prepareLocalModels(
} catch {
// A damaged or incomplete approval binding cannot authorize deployment.
}
- if (
- inputs?.planId !== summary.planId ||
- inputs?.shareGpu !== shareGpu ||
- inputs?.decision !== false
- )
- return action(
- "LOCAL_MODELS_RECOVERY_REQUIRED",
- "Local model resource choices changed or their approval binding is unavailable. Review a new plan; existing resources were preserved.",
- );
- if (
- options.localModelsApproval !== summary.planId ||
- options.localModelsReplan
- )
- return action(
- "LOCAL_MODELS_APPROVAL_REQUIRED",
- "Review the upstream local model plan before installing.",
- summary,
- );
+ const approvedInputs =
+ inputs?.planId === summary.planId &&
+ inputs?.shareGpu === shareGpu &&
+ inputs?.decision === false;
+ // A binding saved for this plan means it was approved and deployed once.
+ const deployed =
+ !!previous &&
+ !options.localModelsReplan &&
+ binding(JSON.parse(previous)).planId === summary.planId;
+ if (deployed) {
+ const observed = await observe();
+ if (observed?.ready) {
+ await atomicPrivate(bindFile, JSON.stringify(observed));
+ return;
+ }
+ if (!approvedInputs)
+ return action(
+ "LOCAL_MODELS_RECOVERY_REQUIRED",
+ "The local model stack is not ready, and its resource choices changed since its plan was approved. Review a new plan; existing resources were preserved.",
+ );
+ // Whatever stopped the approved stack (a stopped or adopted
+ // deployment, a Pi without extension support from an earlier
+ // localmodels), applying the same plan again restores it; the
+ // approval it was deployed under still holds.
+ options.onEvent({
+ kind: "log",
+ stage: "runtime",
+ message: `The local model stack is not ready (${reasons.join(", ") || "unknown"}); applying its approved plan again.\n`,
+ });
+ } else {
+ if (!approvedInputs)
+ return action(
+ "LOCAL_MODELS_RECOVERY_REQUIRED",
+ "Local model resource choices changed or their approval binding is unavailable. Review a new plan; existing resources were preserved.",
+ );
+ if (
+ options.localModelsApproval !== summary.planId ||
+ options.localModelsReplan
+ )
+ return action(
+ "LOCAL_MODELS_APPROVAL_REQUIRED",
+ "Review the upstream local model plan before installing.",
+ summary,
+ );
+ }
const applied = await command([
"stack",
"apply",
@@ -462,7 +500,7 @@ export async function prepareLocalModels(
if (!observed?.ready)
return action(
"LOCAL_MODELS_RECOVERY_REQUIRED",
- "The upstream tool could not verify the local stack binding. Existing resources were preserved.",
+ `The upstream tool could not verify the local stack binding${reasonText(observed)}. Existing resources were preserved.`,
);
await atomicPrivate(bindFile, JSON.stringify(observed));
options.onEvent({
diff --git a/packages/local-installation/src/managed-runtimes.test.ts b/packages/local-installation/src/managed-runtimes.test.ts
index 0423a51e..6a2c6653 100644
--- a/packages/local-installation/src/managed-runtimes.test.ts
+++ b/packages/local-installation/src/managed-runtimes.test.ts
@@ -371,3 +371,64 @@ it("does not retry once the install is cancelled during the wait", async () => {
).rejects.toThrow();
expect(applies(localmodels)).toHaveLength(1);
});
+
+// A harness command that fails at `step` with one harness-error/v1 line.
+function harnessFailing(step: "plan" | "apply", code: string, message = "") {
+ return vi.fn(async (_home: string, args: string[]) => {
+ if (args[1] === "plan" && step !== "plan")
+ await writeFile(
+ args[args.indexOf("--out") + 1]!,
+ JSON.stringify({
+ schema: "localmodels.harness-plan/v1",
+ id: "a".repeat(64),
+ runtime: "pi",
+ }),
+ );
+ const failed = args[1] === step;
+ return {
+ code: failed ? 1 : 0,
+ stdout: failed
+ ? JSON.stringify({
+ schema: "localmodels.harness-error/v1",
+ code,
+ message,
+ })
+ : "",
+ stderr: "",
+ };
+ });
+}
+
+it("reports a plan the harness refused, such as a Windows runtime root too long for Pi", async () => {
+ const options = await fixture();
+ const localmodels = harnessFailing(
+ "plan",
+ "RUNTIME_ACTION_FAILED",
+ "Runtime action failed: The runtime root is 120 characters; Pi's dependency tree fits below a root of at most 90 on Windows unless long paths are enabled. Inspect the plan and retry.",
+ );
+ const failure = await installNativeRuntime("pi", options, {
+ localmodels,
+ }).catch((error: Error & { code: string }) => error);
+ expect(failure).toMatchObject({ code: "RUNTIME_PLAN_REFUSED" });
+ expect((failure as Error).message).toContain(
+ "The runtime root is 120 characters",
+ );
+ expect(localmodels.mock.calls.some(([, args]) => args[1] === "apply")).toBe(
+ false,
+ );
+});
+
+it.each(["RUNTIME_ACTION_FAILED", "RUNTIME_EXTENSIONS_FAILED"])(
+ "keeps the harness apply failure %s as its code",
+ async (code) => {
+ const options = await fixture();
+ const failure = await installNativeRuntime("pi", options, {
+ localmodels: harnessFailing(
+ "apply",
+ code,
+ "Runtime action failed: pi is still not usable after apply. Inspect the plan and retry.",
+ ),
+ }).catch((error: Error & { code: string }) => error);
+ expect(failure).toMatchObject({ code });
+ },
+);
diff --git a/packages/local-installation/src/managed-runtimes.ts b/packages/local-installation/src/managed-runtimes.ts
index 634c5fa1..54733872 100644
--- a/packages/local-installation/src/managed-runtimes.ts
+++ b/packages/local-installation/src/managed-runtimes.ts
@@ -53,6 +53,25 @@ export function runtimeVersionFailure(
? { code, message: versionFailures[code]! }
: undefined;
}
+/**
+ * The failures this module reports with their own code: a harness plan
+ * refused before anything changed (an unusable SIMPLEX_PI_PATH, a Windows
+ * runtime root too long for Pi without long paths), an apply that left the
+ * runtime unusable, a Pi that cannot load extensions, and any other
+ * localmodels failure.
+ */
+const runtimeFailures = new Set([
+ "RUNTIME_PLAN_REFUSED",
+ "RUNTIME_ACTION_FAILED",
+ "RUNTIME_EXTENSIONS_FAILED",
+ "LOCALMODELS_RUNTIME_UNAVAILABLE",
+]);
+export function runtimeFailureCode(error: unknown): string | undefined {
+ const code = (error as { code?: unknown } | null)?.code;
+ return typeof code === "string" && runtimeFailures.has(code)
+ ? code
+ : undefined;
+}
type LocalmodelsResult = Awaited<ReturnType<typeof runLocalmodels>>;
function unavailable(failed?: {
args: string[];
@@ -75,9 +94,25 @@ function unavailable(failed?: {
} catch {
/* Non-JSON output is read below as redacted diagnostics. */
}
- const { cause, log } = localmodelsFailure(failed.args, failed.result);
+ const { code, cause, log } = localmodelsFailure(failed.args, failed.result);
for (const message of log)
failed.onEvent?.({ kind: "log", stage: "runtime", message });
+ if (code === "RUNTIME_EXTENSIONS_FAILED")
+ return Object.assign(
+ new Error(
+ "Pi cannot load extensions, which Linger needs on every run. If you installed Pi yourself, update or remove it, then try again.",
+ ),
+ { code },
+ );
+ if (code === "RUNTIME_ACTION_FAILED") {
+ const planned = failed.args[1] === "plan";
+ return Object.assign(
+ new Error(
+ `The localmodels Runtime ${planned ? "plan was refused" : "operation failed"}${cause ? `: ${cause}` : "."}`,
+ ),
+ { code: planned ? "RUNTIME_PLAN_REFUSED" : code },
+ );
+ }
if (cause)
return Object.assign(
new Error(`The localmodels Runtime operation failed: ${cause}`),
@@ -141,11 +176,7 @@ export async function inspectRuntimeDescriptors(
const failure = runtimeVersionFailure(error);
if (failure)
throw Object.assign(new Error(failure.message), { code: failure.code });
- if (
- error instanceof Error &&
- (error as { code?: string }).code === "LOCALMODELS_RUNTIME_UNAVAILABLE"
- )
- throw error;
+ if (error instanceof Error && runtimeFailureCode(error)) throw error;
throw unavailable();
}
}
@@ -296,11 +327,7 @@ export async function installNativeRuntime(
const failure = runtimeVersionFailure(error);
if (failure)
throw Object.assign(new Error(failure.message), { code: failure.code });
- if (
- error instanceof Error &&
- (error as { code?: string }).code === "LOCALMODELS_RUNTIME_UNAVAILABLE"
- )
- throw error;
+ if (error instanceof Error && runtimeFailureCode(error)) throw error;
throw unavailable();
} finally {
await rm(temporary, { recursive: true, force: true });