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(desktop): stop the local models and their gateway on quit, uninstall and setup

Dongdong Chend7f4126b19ae
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 5d73b0b4..78e6c21a 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -331,12 +331,25 @@ Gateway and runs Agents. The daemon exits with the app.
on `--quit`, so setup skips `--quit` for it (CloseLinger asks the person to
quit a running app). Retry in that prompt runs the stop again. Nothing running: the stop finds nothing and setup goes on. The
stop also asks the pinned localmodels kit, when that kit is installed in the
- home, to end its foundations controller under `runtime/model-services`
- (`foundations stop`) and the stack's processes (`stack down`); it downloads
- nothing, and Linger does not end the tool's processes itself.
+ home, to unload every model its model library loaded (`library status`,
+ then `library unload` for each `loaded` model), to end its foundations
+ controller under `runtime/model-services` (`foundations stop`), and to stop
+ the stack's processes and the gateway the tool started, the library's
+ Bifrost included (`stack down`); it downloads nothing, and Linger does not
+ end the tool's processes itself. Every step runs even when an earlier one
+ fails.
On Windows the tool cannot prove and end a controller from a kit that has
no stop command.
- The tool refuses the chat stack on Windows, so no engine runs there.
+ A quit the person chose (the tray, the app menu, the Dock) does the same
+ for the local models, except the controller, which serves the services
+ 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. It runs only when `desktop/local-server.json` names an
+ installation. The Computer exits with the app, so nothing uses the models
+ until the next launch, whose resume applies the approved plan again. A
+ quit for an update or a relaunch, and the `--quit` of setup or the
+ uninstaller (which stop the models themselves right after), leave them.
- `src/main/legacy-migration.ts`: on start, stops a bridge an older version
left running and moves its credential and the Desktop 0.16 daemon identity
into the daemon layout, so the computer keeps its id.
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 837acaf8..b1220d56 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -326,10 +326,14 @@ async function main(): Promise<void> {
const host = new ModuleHost(modules, { config, log, bus: new EventBus() });
const showApp = (): void => setup.showApp();
+ // The uninstaller, or setup replacing this release, asked to quit.
+ let replacing = false;
app.on("second-instance", (_event, argv) => {
// Without asking: the uninstaller is removing the app.
- if (quitRequested(argv)) app.quit();
- else showApp();
+ if (quitRequested(argv)) {
+ replacing = true;
+ app.quit();
+ } else showApp();
});
app.on("activate", showApp);
// Closing the window only hides it; the tray keeps the app running.
@@ -340,10 +344,14 @@ async function main(): Promise<void> {
if (quitting) return;
quitting = true;
event.preventDefault();
- void host.stop(relaunch || updating ? "update" : "quit").finally(() => {
- if (relaunch) app.relaunch();
- app.exit(0);
- });
+ // Setup and the uninstaller stop the services and the local models
+ // themselves right after --quit; a stop from here would race theirs.
+ void host
+ .stop(relaunch || updating || replacing ? "update" : "quit")
+ .finally(() => {
+ if (relaunch) app.relaunch();
+ app.exit(0);
+ });
});
// Tasks run in the app, so quitting takes the computer offline; ask first
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts
index 7e8cf16d..362c8eb0 100644
--- a/apps/desktop/src/main/local-server.test.ts
+++ b/apps/desktop/src/main/local-server.test.ts
@@ -76,6 +76,12 @@ if (args.includes("--user-keys")) {
process.stdout.write(JSON.stringify({ saved: names }) + "\n");
process.exit(0);
}
+if (args.includes("--stop-local-models")) {
+ // The quit's stop of the local models; its output goes to a log file.
+ fs.writeFileSync(path.join(home, "stop-local-models.json"), JSON.stringify({ args, runAsNode: process.env.ELECTRON_RUN_AS_NODE }));
+ process.stdout.write(JSON.stringify({ failed: [] }) + "\n");
+ process.exit(0);
+}
if (args.includes("--migrate")) {
// Converts every legacy instance record, except a "desktop" that
// migrate-skips holds back.
@@ -2321,6 +2327,40 @@ describe("LocalServerModule after a restart", () => {
await f.host.stop("quit");
});
+ it("stops the local models when the person quits, without waiting for them", async () => {
+ const stopped = (home: string) => path.join(home, "stop-local-models.json");
+ const f = fixture({}, enrolled, record);
+ await f.host.start();
+ await vi.waitFor(() => expect(f.module.status().phase).toBe("ready"));
+ await f.host.stop("quit");
+ // It runs on after the app is gone; its outcome goes to the log.
+ await vi.waitFor(() =>
+ expect(
+ readFileSync(
+ path.join(f.home, "installer", "local-models-stop.log"),
+ "utf8",
+ ),
+ ).toBe('{"failed":[]}\n'),
+ );
+ expect(JSON.parse(readFileSync(stopped(f.home), "utf8"))).toEqual({
+ args: ["--home", f.home, "--stop-local-models"],
+ runAsNode: "1",
+ });
+ });
+
+ it("leaves the local models running for an update, and stops none without an installation", async () => {
+ const update = fixture({}, enrolled, record);
+ await update.host.start();
+ await vi.waitFor(() => expect(update.module.status().phase).toBe("ready"));
+ await update.host.stop("update");
+ const none = fixture();
+ await none.host.start();
+ await none.host.stop("quit");
+ await delay(300);
+ for (const home of [update.home, none.home])
+ expect(existsSync(path.join(home, "stop-local-models.json"))).toBe(false);
+ });
+
it("moves the keys of the unpacked source's .env into the instance's user.env once", async () => {
const f = fixture({}, enrolled, (home) => {
const source = path.join(home, "desktop", "source", "previous");
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index fe3c4b11..b5d71e4e 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -1,6 +1,12 @@
import { spawn } from "node:child_process";
import { createHash, randomBytes, randomUUID } from "node:crypto";
-import { createReadStream, existsSync, readFileSync } from "node:fs";
+import {
+ closeSync,
+ createReadStream,
+ existsSync,
+ openSync,
+ readFileSync,
+} from "node:fs";
import {
constants as fsConstants,
cp,
@@ -59,7 +65,7 @@ import {
nodeRuntimeDownloadUrls,
} from "../../../../scripts/local-computer-node-distributions.mjs";
import type { Logger } from "./log.js";
-import type { Module, ModuleContext } from "./modules.js";
+import type { Module, ModuleContext, StopReason } from "./modules.js";
import { sameOrigin } from "./navigation.js";
import { humanTenant, type EnrollmentModule } from "./enrollment.js";
import { compareVersions } from "./update-manifest.js";
@@ -502,7 +508,7 @@ export class LocalServerModule implements Module {
});
}
- async stop(): Promise<void> {
+ async stop(reason: StopReason): Promise<void> {
this.#offRetry?.();
this.#offReset?.();
this.#offDaemon?.();
@@ -511,6 +517,64 @@ export class LocalServerModule implements Module {
// The installer manager keeps running a started installation; it exits
// by itself once idle.
this.#abort.abort();
+ if (reason === "quit") await this.#stopLocalModels();
+ }
+
+ // The Computer exits with the app, so after a quit nothing uses the local
+ // models: the bundled installer unloads the model library's models and
+ // stops the stack with the gateway the localmodels tool started, which
+ // would otherwise keep their memory and ports until the next reboot. The
+ // services and the model controller keep running, as after every quit;
+ // the next launch brings the approved stack up again. The stop runs on
+ // after the app is gone, its output in the installer's folder. An update
+ // or an uninstall stops the models with the services instead.
+ async #stopLocalModels(): Promise<void> {
+ if (!(await this.#readRecord()) || !existsSync(this.#installerScript()))
+ return;
+ const directory = path.join(this.#options.home, "installer");
+ let output: number;
+ try {
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ output = openSync(
+ path.join(directory, "local-models-stop.log"),
+ "w",
+ 0o600,
+ );
+ } catch (error) {
+ this.#ctx?.log.warn("local_server.local_models_stop_failed", {
+ error: String(error),
+ });
+ return;
+ }
+ try {
+ const child = spawn(
+ process.execPath,
+ [
+ this.#installerScript(),
+ "--home",
+ this.#options.home,
+ "--stop-local-models",
+ ],
+ {
+ detached: true,
+ // A detached Windows process otherwise opens its own console window.
+ windowsHide: true,
+ stdio: ["ignore", output, output],
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
+ },
+ );
+ child.once("error", (error) =>
+ this.#ctx?.log.warn("local_server.local_models_stop_failed", {
+ error: String(error),
+ }),
+ );
+ child.unref();
+ this.#ctx?.log.info("local_server.local_models_stopping", {
+ home: this.#options.home,
+ });
+ } finally {
+ closeSync(output);
+ }
}
status(): LocalServerStatus {
diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md
index 61146daa..4be37c4f 100644
--- a/apps/linger-installer/AGENTS.md
+++ b/apps/linger-installer/AGENTS.md
@@ -48,7 +48,16 @@ the desktop's Computer follows them.
manager the desktop started for that instance (its `/api/stop` cancels a
running job) and the instance's services, deletes nothing, and prints one
JSON line with what failed. It needs nothing beside `installer.js`, so
-setup can run it from a copy on an earlier release's `Linger.exe`.
+setup can run it from a copy on an earlier release's `Linger.exe`. It also
+stops what the pinned localmodels kit runs for each home: the model
+library's loaded models, the model controller, and the stack with its
+gateway (`stopLocalmodels`).
+
+`--stop-local-models` is the desktop's quit: in the default home and the
+location `desktop/local-server.json` names, it unloads the model library's
+loaded models and stops the stack with the gateway the localmodels tool
+started, and keeps the services and the model controller running. It
+prints one JSON line with what failed.
Every other mode first converts an install from before the rename to Linger
(`migrateLegacyInstallation`); `--migrate` does only that and exits, for the
diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts
index b99d8abd..cdf294a3 100644
--- a/apps/linger-installer/src/main.ts
+++ b/apps/linger-installer/src/main.ts
@@ -19,6 +19,7 @@ export function parseInstallerArguments(args: string[]) {
userKeys?: boolean;
migrate?: boolean;
stop?: boolean;
+ stopLocalModels?: boolean;
} = {
home: lingerHome(),
};
@@ -48,6 +49,10 @@ export function parseInstallerArguments(args: string[]) {
options.stop = true;
continue;
}
+ if (flag === "--stop-local-models") {
+ options.stopLocalModels = true;
+ continue;
+ }
if (flag === "--user-keys") {
options.userKeys = true;
continue;
@@ -82,7 +87,8 @@ export function parseInstallerArguments(args: string[]) {
!options.checkByok &&
!options.userKeys &&
!options.migrate &&
- !options.stop
+ !options.stop &&
+ !options.stopLocalModels
)
throw new Error("The installer needs a source checkout (--source-repo).");
if (options.resume && !options.instanceName)
@@ -273,6 +279,29 @@ async function stopInstallation(
process.exit(outcome.failed.length ? 1 : 0),
);
}
+// Headless stop of the local models for the desktop's quit: the outcome as
+// one JSON line on stdout. The desktop does not wait for it to finish.
+async function stopLocalModels(
+ options: ReturnType<typeof parseInstallerArguments>,
+) {
+ const { stopDesktopLocalModels } = await import("./server/stop.js");
+ setTimeout(() => process.exit(1), 150_000).unref();
+ const outcome = await stopDesktopLocalModels({
+ home: options.home,
+ signal: AbortSignal.timeout(120_000),
+ log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")),
+ }).catch((error: unknown) => ({
+ failed: [
+ {
+ home: options.home,
+ message: error instanceof Error ? error.message : String(error),
+ },
+ ],
+ }));
+ process.stdout.write(`${JSON.stringify(outcome)}\n`, () =>
+ process.exit(outcome.failed.length ? 1 : 0),
+ );
+}
async function serve(options: ReturnType<typeof parseInstallerArguments>) {
const server = await launchInstaller({
...options,
@@ -327,13 +356,13 @@ if (
}
// Installs from before the rename move to the Linger home once, before
// any mode opens it; --migrate does only that, for the desktop client.
- // Stopping for an uninstall changes nothing.
+ // Stopping for an uninstall or a quit changes nothing.
// Only --migrate reports the instances it skipped, as warnings and as one
// JSON line on stdout: the desktop runs it first, and in the other modes a
// warning on stderr would read as the reason a start failed. A skipped
// instance is refused with its own error when a mode opens it.
let skipped: LegacyInstanceSkipped[] = [];
- if (options && !options.stop)
+ if (options && !options.stop && !options.stopLocalModels)
await import("@linger/local-installation/legacy-migration")
.then(async ({ migrateLegacyInstallation }) => {
skipped = await migrateLegacyInstallation({ home: options!.home });
@@ -346,6 +375,7 @@ if (
options = undefined;
});
if (options?.stop) await stopInstallation(options);
+ else if (options?.stopLocalModels) await stopLocalModels(options);
else if (options?.migrate)
process.stdout.write(`${JSON.stringify({ skipped })}\n`, () =>
process.exit(0),
diff --git a/apps/linger-installer/src/server/stop.test.ts b/apps/linger-installer/src/server/stop.test.ts
index 9f108bad..49c274d2 100644
--- a/apps/linger-installer/src/server/stop.test.ts
+++ b/apps/linger-installer/src/server/stop.test.ts
@@ -6,7 +6,11 @@ import { tmpdir } from "node:os";
import { parseInstallerArguments } from "../main.js";
import { launchInstaller } from "./launch.js";
import { privateDirectory, privateWrite } from "./storage.js";
-import { stopDesktopInstallation, type StopDependencies } from "./stop.js";
+import {
+ stopDesktopInstallation,
+ stopDesktopLocalModels,
+ type StopDependencies,
+} from "./stop.js";
const clean: Array<() => Promise<unknown>> = [];
afterEach(async () => {
@@ -41,6 +45,12 @@ test("the uninstall stop needs only the instance", () => {
expect(() => parseInstallerArguments(["--stop"])).toThrow(/instance/);
});
+test("the quit's local model stop needs no instance or source", () => {
+ expect(parseInstallerArguments(["--stop-local-models"])).toMatchObject({
+ stopLocalModels: true,
+ });
+});
+
test("stops the desktop's manager while a job runs, then the instance's services", async () => {
const value = await home();
let cancelled = false;
@@ -228,3 +238,33 @@ test("stops the local models in every home, even where the services did not stop
{ home: custom, message: "localmodels stack down: gateway still running" },
]);
});
+
+test("a quit stops only the local models, in every home, and keeps their controller", async () => {
+ const value = await home();
+ const custom = await home();
+ await mkdir(path.join(value, "desktop"), { recursive: true });
+ await writeFile(
+ path.join(value, "desktop/local-server.json"),
+ JSON.stringify({ home: custom }),
+ );
+ const models: { home: string; keepController?: boolean }[] = [];
+ const outcome = await stopDesktopLocalModels(options(value), {
+ stopModels: async (at, { keepController }) => {
+ models.push({ home: at, keepController });
+ if (at === value)
+ throw new Error(
+ "localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING",
+ );
+ },
+ });
+ expect(models).toEqual([
+ { home: value, keepController: true },
+ { home: custom, keepController: true },
+ ]);
+ expect(outcome.failed).toEqual([
+ {
+ home: value,
+ message: "localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING",
+ },
+ ]);
+});
diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.ts
index 4ea0753f..63b35790 100644
--- a/apps/linger-installer/src/server/stop.ts
+++ b/apps/linger-installer/src/server/stop.ts
@@ -26,7 +26,11 @@ export interface StopDependencies {
stopInstance?: (instance: Instance, signal: AbortSignal) => Promise<void>;
stopModels?: (
home: string,
- options: { signal: AbortSignal; log: (message: string) => void },
+ options: {
+ signal: AbortSignal;
+ log: (message: string) => void;
+ keepController?: boolean;
+ },
) => Promise<void>;
fetch?: typeof fetch;
}
@@ -47,16 +51,7 @@ export async function stopDesktopInstallation(
fetch: fetcher = fetch,
}: StopDependencies = {},
): Promise<StopOutcome> {
- const failed: StopOutcome["failed"] = [];
- const attempt = async (home: string, step: () => Promise<void>) => {
- try {
- await step();
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- options.log(`Could not stop the installation in ${home}: ${message}`);
- failed.push({ home, message });
- }
- };
+ const { failed, attempt } = attempts(options.log);
for (const home of await installationHomes(options.home)) {
// The services stop even when the manager could not: an earlier release's
// manager has no /api/stop, and a stale session may name another server.
@@ -74,6 +69,44 @@ export async function stopDesktopInstallation(
return { failed };
}
+/**
+ * Stops the local models a quit leaves nothing to use: the model library's
+ * loaded models and the stack with the gateway the localmodels tool started,
+ * in every home the desktop installed to. The services and the model
+ * controller keep running, as the services do after a quit; the next launch
+ * brings the approved stack up again.
+ */
+export async function stopDesktopLocalModels(
+ options: Pick<StopOptions, "home" | "signal" | "log">,
+ { stopModels = stopLocalmodels }: Pick<StopDependencies, "stopModels"> = {},
+): Promise<StopOutcome> {
+ const { failed, attempt } = attempts(options.log);
+ for (const home of await installationHomes(options.home))
+ await attempt(home, () =>
+ stopModels(home, {
+ signal: options.signal,
+ log: options.log,
+ keepController: true,
+ }),
+ );
+ return { failed };
+}
+
+// Runs each step and records the ones that failed, so every home is tried.
+function attempts(log: (message: string) => void) {
+ const failed: StopOutcome["failed"] = [];
+ const attempt = async (home: string, step: () => Promise<void>) => {
+ try {
+ await step();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log(`Could not stop the installation in ${home}: ${message}`);
+ failed.push({ home, message });
+ }
+ };
+ return { failed, attempt };
+}
+
// The default home and the install location the desktop chose under
// Customize (desktop/local-server.json).
async function installationHomes(home: string): Promise<string[]> {
diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts
index 7c3df438..c4c47454 100644
--- a/packages/local-installation/src/localmodels-tool.test.ts
+++ b/packages/local-installation/src/localmodels-tool.test.ts
@@ -354,16 +354,36 @@ test("invokes the verified upstream module with isolated module and state paths"
"sourceCommit",
);
});
-test("stops the controller and the stack through the installed pinned kit", async () => {
+// What `library status` prints, cut to the fields the stop reads.
+const libraryStatus = (models: { id: string; state: string }[]) => ({
+ code: 0,
+ stdout: JSON.stringify({ schema: "localmodels.library-status/v1", models }),
+ stderr: "",
+});
+test("unloads the library's models, then stops the controller and the stack through the installed pinned kit", async () => {
const f = await fixture();
vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));
- const run = vi.fn<typeof runLocalmodels>(async () => ({
- code: 0,
- stdout: "{}",
- stderr: "",
- }));
+ const base = path.join(f.home, "runtime/localmodels/models");
+ const run = vi.fn<typeof runLocalmodels>(async (_home, args) =>
+ args[1] === "status"
+ ? libraryStatus([
+ { id: "qwen3-8b:Q4_K_M", state: "loaded" },
+ { id: "lfm3-1.7b:Q8_0", state: "idle" },
+ { id: "gemma4-4b:Q4_K_M", state: "loaded" },
+ ])
+ : { code: 0, stdout: "{}", stderr: "" },
+ );
await stopLocalmodels(f.home, { signal: AbortSignal.timeout(5000) }, { run });
expect(run.mock.calls.map(([home, args]) => [home, args])).toEqual([
+ [f.home, ["library", "status", "--base-dir", base, "--json"]],
+ [
+ f.home,
+ ["library", "unload", "qwen3-8b:Q4_K_M", "--base-dir", base, "--json"],
+ ],
+ [
+ f.home,
+ ["library", "unload", "gemma4-4b:Q4_K_M", "--base-dir", base, "--json"],
+ ],
[
f.home,
[
@@ -377,6 +397,70 @@ test("stops the controller and the stack through the installed pinned kit", asyn
[f.home, ["stack", "down", "--json"]],
]);
});
+test("a quit keeps the controller and stops only the library's models and the stack", async () => {
+ const run = vi.fn<typeof runLocalmodels>(async (_home, args) =>
+ args[1] === "status"
+ ? libraryStatus([{ id: "qwen3-8b:Q4_K_M", state: "loaded" }])
+ : { code: 0, stdout: "{}", stderr: "" },
+ );
+ await stopLocalmodels(
+ "/home",
+ { signal: AbortSignal.timeout(5000), keepController: true },
+ { run, installed: async () => true },
+ );
+ expect(run.mock.calls.map(([, args]) => args.slice(0, 2))).toEqual([
+ ["library", "status"],
+ ["library", "unload"],
+ ["stack", "down"],
+ ]);
+});
+test("stops the stack even when the library could not be read or a model did not unload, and names each failure", async () => {
+ const unloadFailed = vi.fn<typeof runLocalmodels>(async (_home, args) =>
+ args[1] === "status"
+ ? libraryStatus([{ id: "qwen3-8b:Q4_K_M", state: "loaded" }])
+ : args[1] === "unload"
+ ? {
+ code: 1,
+ stdout: JSON.stringify({
+ schema: "localmodels.library-event/v1",
+ event: "error",
+ ok: false,
+ code: "JOB_RUNNING",
+ detail: "a download is running",
+ }),
+ stderr: "",
+ }
+ : { code: 0, stdout: "{}", stderr: "" },
+ );
+ await expect(
+ stopLocalmodels(
+ "/home",
+ { signal: AbortSignal.timeout(5000), keepController: true },
+ { run: unloadFailed, installed: async () => true },
+ ),
+ ).rejects.toThrow("localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING");
+ expect(unloadFailed.mock.calls.at(-1)?.[1]).toEqual([
+ "stack",
+ "down",
+ "--json",
+ ]);
+ const statusFailed = vi.fn<typeof runLocalmodels>(async (_home, args) =>
+ args[1] === "status"
+ ? { code: 1, stdout: "", stderr: "error: library status failed" }
+ : { code: 0, stdout: "{}", stderr: "" },
+ );
+ await expect(
+ stopLocalmodels(
+ "/home",
+ { signal: AbortSignal.timeout(5000), keepController: true },
+ { run: statusFailed, installed: async () => true },
+ ),
+ ).rejects.toThrow("localmodels library status: exit 1");
+ expect(statusFailed.mock.calls.map(([, args]) => args[1])).toEqual([
+ "status",
+ "down",
+ ]);
+});
test("a home without the pinned kit has nothing to stop and downloads nothing", async () => {
const f = await fixture();
vi.stubEnv(
@@ -413,6 +497,7 @@ test("stops the stack even when the controller did not stop, and names the failu
),
).rejects.toThrow("localmodels foundations stop: controller still running");
expect(run.mock.calls.map(([, args]) => args[0])).toEqual([
+ "library",
"foundations",
"stack",
]);
diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts
index 61cf743a..5ef8ab31 100644
--- a/packages/local-installation/src/localmodels-tool.ts
+++ b/packages/local-installation/src/localmodels-tool.ts
@@ -517,50 +517,110 @@ export async function runLocalmodels(
return result;
}
/**
- * For an uninstall, or an install over this release: stops the model
- * controller under <home>/runtime/model-services and the processes the stack
- * started, through the pinned kit. Nothing is downloaded: a home without that
- * kit has nothing it started. Both requests are made even when one fails; the
- * error names each that did not stop.
+ * Stops what the pinned kit runs for a home, through that kit: first every
+ * model the model library loaded (`library unload`), whose engines `stack
+ * down` leaves running, then, unless `keepController`, the model controller
+ * under <home>/runtime/model-services, and last the stack's processes and
+ * the gateway the tool started (`stack down`), the library's Bifrost
+ * included. An uninstall or an install over this release stops all of it; a
+ * quit keeps the controller, which belongs to the services that keep
+ * running. Nothing is downloaded: a home without that kit has nothing it
+ * started. Every step runs even when an earlier one fails; the error names
+ * each that did not stop.
*/
export async function stopLocalmodels(
home: string,
- options: { signal: AbortSignal; log?: (message: string) => void },
+ options: {
+ signal: AbortSignal;
+ log?: (message: string) => void;
+ keepController?: boolean;
+ },
dependencies: {
run?: typeof runLocalmodels;
installed?: (home: string) => Promise<boolean>;
} = {},
): Promise<void> {
if (!(await (dependencies.installed ?? hasPinnedTool)(home))) return;
- const root = modelServicesRoot(home);
+ const run = dependencies.run ?? runLocalmodels;
+ const base = localmodelsBaseDirectory(home);
const failed: string[] = [];
- for (const args of [
- ["foundations", "stop", "--root", root, "--json"],
- ["stack", "down", "--json"],
- ]) {
+ const step = async (args: string[], name = args.slice(0, 2).join(" ")) => {
options.signal.throwIfAborted();
- options.log?.(
- `Stopping the local models (localmodels ${args[0]} ${args[1]}).`,
- );
- const result = await (dependencies.run ?? runLocalmodels)(home, args, {
+ options.log?.(`Stopping the local models (localmodels ${name}).`);
+ const result = await run(home, args, {
signal: options.signal,
timeoutMs: 30_000,
}).catch((error: unknown) => {
options.signal.throwIfAborted();
return { code: 1, stdout: "", stderr: String(error) };
});
- if (result.code === 0) continue;
- let reason = `exit ${result.code}`;
- try {
- const error = (JSON.parse(result.stdout) as { error?: unknown }).error;
- if (typeof error === "string" && error) reason = error;
- } catch {
- // No report: the exit status is all there is.
- }
- failed.push(`localmodels ${args[0]} ${args[1]}: ${reason}`);
+ if (result.code !== 0)
+ failed.push(`localmodels ${name}: ${stopFailure(result)}`);
+ return result;
+ };
+ const status = await step([
+ "library",
+ "status",
+ "--base-dir",
+ base,
+ "--json",
+ ]);
+ if (status.code === 0) {
+ const loaded = loadedLibraryModels(status.stdout);
+ if (!loaded) failed.push("localmodels library status: no model list");
+ for (const model of loaded ?? [])
+ await step(
+ ["library", "unload", model, "--base-dir", base, "--json"],
+ `library unload ${model}`,
+ );
}
+ if (!options.keepController)
+ await step([
+ "foundations",
+ "stop",
+ "--root",
+ modelServicesRoot(home),
+ "--json",
+ ]);
+ await step(["stack", "down", "--json"]);
if (failed.length) throw new Error(failed.join("; "));
}
+// The ids of the models `library status` reports loaded, or undefined when
+// its output is not a status report.
+function loadedLibraryModels(stdout: string): string[] | undefined {
+ try {
+ const models = (JSON.parse(stdout) as { models?: unknown }).models;
+ if (!Array.isArray(models)) return undefined;
+ return models.flatMap((model: { id?: unknown; state?: unknown }) =>
+ model?.state === "loaded" &&
+ typeof model.id === "string" &&
+ /^[a-z0-9][a-z0-9._-]*:[A-Za-z0-9._-]+$/.test(model.id)
+ ? [model.id]
+ : [],
+ );
+ } catch {
+ return undefined;
+ }
+}
+// A failed step's structured cause: the library's error code, the tool's
+// error, or its exit status.
+function stopFailure(result: { code: number; stdout: string }): string {
+ try {
+ const report = JSON.parse(result.stdout) as {
+ code?: unknown;
+ error?: unknown;
+ };
+ if (
+ typeof report.code === "string" &&
+ /^[A-Z][A-Z_]{0,63}$/.test(report.code)
+ )
+ return report.code;
+ if (typeof report.error === "string" && report.error) return report.error;
+ } catch {
+ // No report: the exit status is all there is.
+ }
+ return `exit ${result.code}`;
+}
async function hasPinnedTool(home: string): Promise<boolean> {
if (configuredDevTool()) return true;
const source = pinnedToolSource();