Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/desktop/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,10 @@ Gateway and runs Agents. The daemon exits with the app.
that keep running: `LocalServer` starts `installer.js --home <default
home> --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, with
its output in `<home>/installer/local-models-stop.log`, and does not wait
for it. If the installed kit fails verification, the helper exits with a
for it. Its steps share one stop budget with reserved time for `stack down`
so slow commands on a busy machine can finish; if a quit-time stop still
fails or is cut short, `<home>/runtime/localmodels/stop-pending.json` remains
and the next launch's `--resume` retries the stop once before resuming. If the installed kit fails verification, the helper exits with a
failure and logs the repair guidance; the app still quits, and no unverified
tool runs. It runs only when `desktop/local-server.json` names an
installation. The Computer exits with the app, so nothing uses the models
Expand Down
10 changes: 8 additions & 2 deletions apps/linger-installer/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,15 @@ and logs durations for the `manager`, `services`, and `localmodels` stop stages.
`--stop-local-models` is the desktop's quit: in the default home and the
location `desktop/local-server.json` names, it cancels the model library's
running loads, unloads its loaded models and stops the stack with the gateway the localmodels tool
started, and keeps the services and the model controller running. It
started, and keeps the services and the model controller running. All steps
share one stop budget (135 s inside the 150 s hard exit) with a reserved slice
for `stack down` instead of a fixed 30 s per-command timeout. It
holds each home's local model lock (`withLocalModelsLock`) while it stops,
so the next launch's restore waits for it; a home whose lock a deployment
records `<home>/runtime/localmodels/stop-pending.json` before stopping and
clears it only on success, so the next launch's resume waits for an in-flight
stop and retries a failed or interrupted stop once before restoring models or
starting services (retiring the marker after a failed retry until a later stop
succeeds so persistently broken stops never stall every launch); a home whose lock a deployment
holds is skipped with a log line. Taking the lock retries a busy lock for up
to 2 s, because the Computer Daemon probes it for a moment after it starts. A kit that is present but fails verification
is a stop failure, so the helper logs the repair guidance, prints a JSON
Expand Down
10 changes: 8 additions & 2 deletions apps/linger-installer/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,8 @@ async function stopInstallation(
options: ReturnType<typeof parseInstallerArguments>,
) {
const { stopDesktopInstallation } = await import("./server/stop.js");
const { DEFAULT_STOP_BUDGET_MS } =
await import("@linger/local-installation/localmodels-tool");
const { recordStopOutcome, stopFailure } =
await import("./server/stop-diagnostics.js");
const failures: ReturnType<typeof stopFailure>[] = [];
Expand All @@ -445,7 +447,8 @@ async function stopInstallation(
const outcome = await stopDesktopInstallation({
home: options.home,
instanceName: options.instanceName!,
signal: AbortSignal.timeout(120_000),
signal: AbortSignal.timeout(DEFAULT_STOP_BUDGET_MS),
budgetMs: DEFAULT_STOP_BUDGET_MS,
log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")),
onFailure: (stage, error) => failures.push(stopFailure(stage, error)),
}).catch((error: unknown) => {
Expand All @@ -472,10 +475,13 @@ async function stopLocalModels(
options: ReturnType<typeof parseInstallerArguments>,
) {
const { stopDesktopLocalModels } = await import("./server/stop.js");
const { QUIT_STOP_BUDGET_MS } =
await import("@linger/local-installation/localmodels-tool");
setTimeout(() => process.exit(1), 150_000).unref();
const outcome = await stopDesktopLocalModels({
home: options.home,
signal: AbortSignal.timeout(120_000),
signal: AbortSignal.timeout(QUIT_STOP_BUDGET_MS),
budgetMs: QUIT_STOP_BUDGET_MS,
log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")),
}).catch((error: unknown) => ({
failed: [
Expand Down
39 changes: 39 additions & 0 deletions apps/linger-installer/src/server/resume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,3 +532,42 @@ test("reports warm and cold resume timings via onTimings and log summary", async
expect(failedTimings?.coldStartMs).toBeGreaterThanOrEqual(0);
expect(failedLogs.join("")).toMatch(/Resume timings \(cold, ms\):/);
});

test("retries a pending local model stop before warm restore and before cold start", async () => {
const warmOrder: string[] = [];
await resumeSourceInstance(options, {
load: async () => instance,
engines: native(vi.fn(), true),
pending: async () => false,
retryPendingStop: async (stopHome) => {
warmOrder.push(`stop:${stopHome}`);
return { retried: true };
},
restore: async () => {
warmOrder.push("restore");
return undefined;
},
restoreByok: async () => {
warmOrder.push("byok");
return undefined;
},
});
expect(warmOrder).toEqual([`stop:${home}`, "restore", "byok"]);

const coldOrder: string[] = [];
await resumeSourceInstance(options, {
load: async () => instance,
engines: native(
vi.fn<ResumeEngine["run"]>(async () => {
coldOrder.push("run");
return { code: 0, state: "ready", message: "ok" };
}),
false,
),
retryPendingStop: async (stopHome) => {
coldOrder.push(`stop:${stopHome}`);
return { retried: true };
},
});
expect(coldOrder).toEqual([`stop:${home}`, "run"]);
});
8 changes: 8 additions & 0 deletions apps/linger-installer/src/server/resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
localModelsDegradedFromOutcome,
restoreByokSource,
restoreLocalModels,
retryPendingLocalModelsStop,
type LocalModelsDegraded,
} from "@linger/local-installation/local-models";
import { userEnvironmentPending } from "@linger/local-installation/user-environment";
Expand Down Expand Up @@ -71,6 +72,7 @@ export async function resumeSourceInstance(
pending = userEnvironmentPending,
restore = restoreLocalModels,
restoreByok = restoreByokSource,
retryPendingStop = retryPendingLocalModelsStop,
} = {},
): Promise<InstallOutcome> {
const startedAt = performance.now();
Expand All @@ -91,6 +93,12 @@ export async function resumeSourceInstance(
totalMs: 0,
};
try {
// If the last quit-time local model stop timed out or failed, finish
// tearing down any lingering engine or gateway before resuming.
await retryPendingStop(path.resolve(instance.root, "../.."), {
signal: options.signal,
log: options.log,
});
// A desktop update ships a new source tree, and a changed user.env new
// keys; running services keep the old ones until they restart.
const repo = await realpath(options.sourceRepo).catch(() =>
Expand Down
147 changes: 146 additions & 1 deletion apps/linger-installer/src/server/stop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@ import path from "node:path";
import { tmpdir } from "node:os";

import { INSTANCE_BUSY } from "@linger/local-installation/instance";
import { withLocalModelsLock } from "@linger/local-installation/local-models";
import {
hasPendingLocalModelsStop,
markLocalModelsStopPending,
withLocalModelsLock,
} from "@linger/local-installation/local-models";
import {
stopLocalmodels,
type runLocalmodels,
} from "@linger/local-installation/localmodels-tool";

import { parseInstallerArguments } from "../main.js";
import { launchInstaller } from "./launch.js";
Expand Down Expand Up @@ -346,3 +354,140 @@ test("passes options.log to stopInstance and logs durations for manager, service
/^Stop timings \(s\): manager [\d.]+, services [\d.]+, localmodels [\d.]+\.$/,
);
});

test("a quit records a stop-pending marker while stopping and keeps it when the stop fails", async () => {
const value = await home();
await mkdir(path.join(value, "runtime/localmodels"), { recursive: true });
let pendingDuringStop = false;
const okOutcome = await stopDesktopLocalModels(
{ ...options(value), budgetMs: 135_000 },
{
stopModels: async (at, opts) => {
pendingDuringStop = await hasPendingLocalModelsStop(at);
expect(opts.budgetMs).toBeGreaterThan(0);
expect(opts.budgetMs).toBeLessThanOrEqual(135_000);
},
},
);
expect(okOutcome.failed).toEqual([]);
expect(pendingDuringStop).toBe(true);
expect(await hasPendingLocalModelsStop(value)).toBe(false);

const failedOutcome = await stopDesktopLocalModels(options(value), {
stopModels: async () => {
throw new Error("localmodels stack down: Command timed out");
},
});
expect(failedOutcome.failed).toHaveLength(1);
expect(await hasPendingLocalModelsStop(value)).toBe(true);
});

test("a full uninstall stop clears any lingering stop-pending marker on success", async () => {
const value = await home();
await markLocalModelsStopPending(value);
const outcome = await stopDesktopInstallation(
{ ...options(value), budgetMs: 120_000 },
{
load: async () => undefined,
stopModels: async (_at, opts) => {
expect(opts.budgetMs).toBeGreaterThan(0);
expect(opts.budgetMs).toBeLessThanOrEqual(120_000);
},
},
);
expect(outcome.failed).toEqual([]);
expect(await hasPendingLocalModelsStop(value)).toBe(false);
});

test("after a slow services stage, uninstall scales localmodels reserves within the outer signal deadline so foundations stop and stack down still run", async () => {
const value = await home();
const runUninstall = async (hangLibraryStatus: boolean) => {
let now = 0;
const outerDeadline = 120_000;
const outerController = new AbortController();
const advance = (ms: number) => {
now += ms;
if (now >= outerDeadline && !outerController.signal.aborted)
outerController.abort(new Error("outer stop deadline reached"));
};
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
const commands: [string, number | undefined][] = [];
const run = vi.fn<typeof runLocalmodels>(async (_home, args, opts) => {
const key = args.slice(0, 2).join(" ");
commands.push([key, opts?.timeoutMs]);
if (key === "library status") {
if (hangLibraryStatus) {
advance(opts?.timeoutMs ?? 0);
opts?.signal?.throwIfAborted();
throw Object.assign(new Error("Command timed out"), {
code: "COMMAND_TIMEOUT",
});
}
advance(2_000);
return {
code: 0,
stdout: JSON.stringify({
schema: "localmodels.library-status/v1",
models: [{ id: "qwen3-8b:Q4_K_M", state: "loaded" }],
}),
stderr: "",
};
}
advance(2_000);
opts?.signal?.throwIfAborted();
return { code: 0, stdout: "{}", stderr: "" };
});
try {
const outcome = await stopDesktopInstallation(
{
...options(value),
signal: outerController.signal,
budgetMs: outerDeadline,
},
{
load: async ({ home: at }) =>
instance(path.join(at!, "instances/desktop")),
stopInstance: async () => {
// Simulate stopping native services taking 80 s of the 120 s budget.
advance(80_000);
},
stopModels: (at, opts) =>
stopLocalmodels(at, opts, {
run,
installed: async () => true,
now: () => now,
}),
},
);
return { outcome, commands, aborted: outerController.signal.aborted };
} finally {
nowSpy.mockRestore();
}
};

// Case 1: slow services (80 s) + healthy localmodels -> every step runs and
// succeeds within the remaining 40 s without skipping anything.
const healthy = await runUninstall(false);
expect(healthy.outcome.failed).toEqual([]);
expect(healthy.aborted).toBe(false);
expect(healthy.commands).toEqual([
["library status", 20_000],
["library unload", 18_000],
["foundations stop", 21_000],
["stack down", 34_000],
]);

// Case 2: slow services (80 s) + hanging library status -> status times out
// at its scaled 20 s cap before the 120 s outer signal fires, so foundations
// stop and stack down still run with their protected tails.
const hung = await runUninstall(true);
expect(hung.aborted).toBe(false);
expect(hung.outcome.failed).toEqual([
{ home: value, message: "localmodels library status: Command timed out" },
]);
expect(hung.commands).toEqual([
["library status", 20_000],
["foundations stop", 5_000],
["stack down", 18_000],
]);
});
Loading