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.

perf(installer): overlap install and cold-resume stages and log stage timings

shoudi zheng8b8aea78820f
diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md
index f140a786..b3d1713c 100644
--- a/apps/linger-installer/AGENTS.md
+++ b/apps/linger-installer/AGENTS.md
@@ -31,8 +31,13 @@ starting sign-in for the new runtime stops the previous runtime's pending login.
`--resume` (native source with `--instance`) starts an installed instance's
stopped services headless, reusing its saved choices; the desktop client runs it
-after a reboot and reads the outcome from the single JSON line on stdout. It
-also restarts running services when the instance's `user.env` no longer
+after a reboot and reads the outcome from the single JSON line on stdout. Cold
+resumes on the same checkout pass `resume: true` (a resume onto another
+checkout omits it and prepares the runtime in full, sequentially) so an already-installed runtime
+is reused after one status check, runtime/foundation preparation overlaps
+service startup, and inspected runtime descriptors are passed directly to
+`instanceRuntime` without a second status probe. It also restarts running
+services when the instance's `user.env` no longer
matches the configuration they started with, or when `--source-repo` names
another checkout than the instance's. An instance follows a new checkout only
once its services are ready on it: until then `instance.json` keeps naming the
@@ -96,7 +101,10 @@ installer, and the next start tries again. Only `--migrate` reports them: a
warning naming each and why on stderr, and one JSON line
`{"skipped":[{instance,reason}]}` on stdout. Other modes stay silent, so a
warning is never taken for the reason a start failed, and refuse a skipped
-instance when they open it.
+instance when they open it. Fresh native installs overlap `migrate`,
+`services`, and `account` with `runtime` while holding `services`/`account`
+completion until both branches succeed; upgrades and live re-runs keep `migrate`
+sequential after `runtime`.
Run `make check-installer`; verify UI process behavior with an isolated
browser context and retain masked evidence. Never stop a user's existing stack
diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts
index 224a440d..3648753b 100644
--- a/apps/linger-installer/src/main.ts
+++ b/apps/linger-installer/src/main.ts
@@ -1,6 +1,7 @@
import path from "node:path";
import { lingerHome } from "@linger/local-installation/home";
import type { LegacyInstanceSkipped } from "@linger/local-installation/legacy-migration";
+import type { RuntimeDescriptor } from "@linger/local-installation/managed-runtimes";
import { fileURLToPath } from "node:url";
import { launchInstaller } from "./server/launch.js";
export { startInstallerServer } from "./server/server.js";
@@ -125,11 +126,15 @@ async function resume(options: ReturnType<typeof parseInstallerArguments>) {
const { resumeSourceInstance } = await import("./server/resume.js");
const controller = new AbortController();
process.once("SIGTERM", () => controller.abort());
+ let runtimeDescriptors: RuntimeDescriptor[] | undefined;
const outcome = await resumeSourceInstance({
home: options.home,
sourceRepo: options.sourceRepo!,
instanceName: options.instanceName!,
externalComputer: options.externalComputer,
+ onRuntimeDescriptors: (descriptors) => {
+ runtimeDescriptors = descriptors;
+ },
signal: controller.signal,
log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")),
}).catch((error: unknown) => ({
@@ -144,7 +149,9 @@ async function resume(options: ReturnType<typeof parseInstallerArguments>) {
outcome.code === 0 && options.externalComputer
? await import("./server/instance-runtime.js")
.then(({ instanceRuntime }) =>
- instanceRuntime(options.home, options.instanceName!),
+ instanceRuntime(options.home, options.instanceName!, {
+ runtimeDescriptors,
+ }),
)
.catch(() => undefined)
: undefined;
diff --git a/apps/linger-installer/src/server/instance-runtime.test.ts b/apps/linger-installer/src/server/instance-runtime.test.ts
new file mode 100644
index 00000000..ef89e89c
--- /dev/null
+++ b/apps/linger-installer/src/server/instance-runtime.test.ts
@@ -0,0 +1,84 @@
+import { beforeEach, expect, test, vi } from "vitest";
+import type { Instance } from "@linger/local-installation/instance";
+import type { RuntimeDescriptor } from "@linger/local-installation/managed-runtimes";
+
+vi.mock("@linger/local-installation/instance", () => ({
+ loadInstance: vi.fn(),
+}));
+vi.mock("@linger/local-installation/setup-selection", () => ({
+ readSetupChoice: vi.fn(),
+}));
+vi.mock("@linger/local-installation/byok-source", () => ({
+ readByokEnvironment: vi.fn(),
+}));
+vi.mock("@linger/local-installation/local-models", () => ({
+ localModelsEnvironment: vi.fn(),
+}));
+vi.mock("@linger/local-installation/managed-codex", () => ({
+ managedRuntimeEnvironment: vi.fn(),
+}));
+vi.mock("@linger/local-installation/localmodels-computer", () => ({
+ LOCALMODELS_TOOL_ENVIRONMENT: ["LINGER_LOCALMODELS_PYTHON"],
+ localmodelsComputerTool: vi.fn(),
+ localmodelsToolEnvironment: vi.fn(() => ({})),
+}));
+vi.mock("@linger/local-installation/localmodels-tool", () => ({
+ pinnedToolSource: vi.fn(() => undefined),
+}));
+
+import { loadInstance } from "@linger/local-installation/instance";
+import { readSetupChoice } from "@linger/local-installation/setup-selection";
+import { readByokEnvironment } from "@linger/local-installation/byok-source";
+import { localModelsEnvironment } from "@linger/local-installation/local-models";
+import { managedRuntimeEnvironment } from "@linger/local-installation/managed-codex";
+import { instanceRuntime } from "./instance-runtime.js";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(loadInstance).mockResolvedValue({
+ name: "local",
+ root: "/home/instances/local",
+ } as Instance);
+ vi.mocked(readSetupChoice).mockResolvedValue("pi");
+ vi.mocked(readByokEnvironment).mockResolvedValue(undefined);
+ vi.mocked(localModelsEnvironment).mockResolvedValue({});
+ vi.mocked(managedRuntimeEnvironment).mockResolvedValue({
+ LINGER_PI_PATH: "/probed/pi",
+ });
+});
+
+test("reuses inspected runtime descriptors without re-probing managedRuntimeEnvironment", async () => {
+ const descriptor: RuntimeDescriptor = {
+ runtime: "pi",
+ executable: "/reused/pi",
+ argvPrefix: [],
+ installed: true,
+ authenticated: true,
+ authMode: "api_key",
+ loginCommand: null,
+ environment: { PI_CODING_AGENT_DIR: "/home/runtime/pi" },
+ };
+ const result = await instanceRuntime("/home", "local", {
+ runtimeDescriptors: [descriptor],
+ });
+ expect(result).toEqual({
+ setupChoice: "pi",
+ environment: {
+ LINGER_PI_PATH: "/reused/pi",
+ PI_CODING_AGENT_DIR: "/home/runtime/pi",
+ },
+ });
+ expect(managedRuntimeEnvironment).not.toHaveBeenCalled();
+});
+
+test("falls back to managedRuntimeEnvironment when no descriptors are supplied", async () => {
+ const result = await instanceRuntime("/home", "local");
+ expect(result).toEqual({
+ setupChoice: "pi",
+ environment: { LINGER_PI_PATH: "/probed/pi" },
+ });
+ expect(managedRuntimeEnvironment).toHaveBeenCalledWith(
+ "/home",
+ "/home/instances/local",
+ );
+});
diff --git a/apps/linger-installer/src/server/instance-runtime.ts b/apps/linger-installer/src/server/instance-runtime.ts
index 2324b8c0..0d04858d 100644
--- a/apps/linger-installer/src/server/instance-runtime.ts
+++ b/apps/linger-installer/src/server/instance-runtime.ts
@@ -8,6 +8,10 @@ import {
localmodelsToolEnvironment,
} from "@linger/local-installation/localmodels-computer";
import { pinnedToolSource } from "@linger/local-installation/localmodels-tool";
+import {
+ runtimeEnvironmentFromDescriptors,
+ type RuntimeDescriptor,
+} from "@linger/local-installation/managed-runtimes";
import { managedRuntimeEnvironment } from "@linger/local-installation/managed-codex";
import { readSetupChoice } from "@linger/local-installation/setup-selection";
import type { components } from "@linger/wire-contracts/linger-installer/types";
@@ -30,13 +34,18 @@ const RUNTIME_ENVIRONMENT = [
export async function instanceRuntime(
home: string,
name: string,
+ options: { runtimeDescriptors?: RuntimeDescriptor[] } = {},
): Promise<components["schemas"]["InstanceRuntime"] | undefined> {
const value = await loadInstance({ name, home });
if (!value) return undefined;
const setupChoice = await readSetupChoice({ name, home });
const byok = await readByokEnvironment(home);
+ const managedEnv =
+ options.runtimeDescriptors !== undefined
+ ? runtimeEnvironmentFromDescriptors(options.runtimeDescriptors)
+ : await managedRuntimeEnvironment(home, value.root);
const found: Record<string, string | undefined> = {
- ...(await managedRuntimeEnvironment(home, value.root)),
+ ...managedEnv,
...(await localModelsEnvironment(value)),
...(byok?.mode === "byok" ? byok.environment : {}),
...localmodelsToolEnvironment(
diff --git a/apps/linger-installer/src/server/resume.test.ts b/apps/linger-installer/src/server/resume.test.ts
index 866b9161..f45f8966 100644
--- a/apps/linger-installer/src/server/resume.test.ts
+++ b/apps/linger-installer/src/server/resume.test.ts
@@ -42,11 +42,38 @@ test("starts the saved instance again without new input", async () => {
home: "/home",
repo: "/source",
externalComputer: true,
+ resume: true,
}),
);
expect(run.mock.calls[0]![0]).not.toHaveProperty("password");
});
+test("forwards runtime descriptors reported during resume", async () => {
+ const onRuntimeDescriptors = vi.fn();
+ const descriptor = {
+ runtime: "pi" as const,
+ executable: "/mock/pi",
+ argvPrefix: [],
+ installed: true,
+ authenticated: true,
+ authMode: "api_key",
+ loginCommand: null,
+ };
+ const run = vi.fn<typeof installNativeSource>(async (opts) => {
+ opts.onRuntimeDescriptors?.([descriptor]);
+ return { code: 0, state: "ready", message: "ok" };
+ });
+ const outcome = await resumeSourceInstance(
+ { ...options, onRuntimeDescriptors },
+ {
+ load: async () => instance,
+ engines: native(run, false),
+ },
+ );
+ expect(outcome.code).toBe(0);
+ expect(onRuntimeDescriptors).toHaveBeenCalledWith([descriptor]);
+});
+
test("leaves running services alone", async () => {
const run = vi.fn();
expect(
@@ -144,6 +171,28 @@ test("moves running services to a new source tree", async () => {
);
});
+test("prepares the runtime in full when resuming onto another checkout", async () => {
+ const onRuntimeDescriptors = vi.fn();
+ const run = vi.fn<ResumeEngine["run"]>(async () => ({
+ code: 0,
+ state: "ready",
+ message: "ok",
+ }));
+ await resumeSourceInstance(
+ { ...options, onRuntimeDescriptors },
+ {
+ load: async () =>
+ ({ ...instance, source: { repo: "/old-source" } }) as Instance,
+ engines: native(run, false),
+ },
+ );
+ expect(run.mock.calls[0]![0]).not.toHaveProperty("resume");
+ expect(run.mock.calls[0]![0]).toMatchObject({
+ repo: "/source",
+ onRuntimeDescriptors,
+ });
+});
+
test("reports the source the services serve from", async () => {
expect(
await resumeSourceInstance(options, {
diff --git a/apps/linger-installer/src/server/resume.ts b/apps/linger-installer/src/server/resume.ts
index 781c82b3..fa735f8e 100644
--- a/apps/linger-installer/src/server/resume.ts
+++ b/apps/linger-installer/src/server/resume.ts
@@ -5,6 +5,7 @@ import { loadInstance } from "@linger/local-installation/instance";
import { 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";
import {
installNativeSource,
probeNativeSourceServices,
@@ -17,6 +18,7 @@ export interface ResumeOptions {
externalComputer?: boolean;
signal: AbortSignal;
log: (message: string) => void;
+ onRuntimeDescriptors?: (descriptors: RuntimeDescriptor[]) => void;
}
type Instance = NonNullable<Awaited<ReturnType<typeof loadInstance>>>;
@@ -71,8 +73,9 @@ export async function resumeSourceInstance(
);
// The instance names the checkout its services last became ready on, so
// services that still run from an earlier one never count as running.
+ const sameCheckout = instance.source.repo === repo;
if (
- instance.source.repo === repo &&
+ sameCheckout &&
(await engine.probe(instance, options.signal)).every(
(check) => check.ready,
) &&
@@ -99,6 +102,10 @@ export async function resumeSourceInstance(
home: options.home,
repo: options.sourceRepo,
externalComputer: options.externalComputer,
+ // A different checkout may pin newer runtimes, so only a resume on the
+ // same one may reuse the installed runtime as is.
+ ...(sameCheckout ? { resume: true } : {}),
+ onRuntimeDescriptors: options.onRuntimeDescriptors,
signal: options.signal,
onEvent: (event) => {
if (event.message) options.log(event.message);
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index dcb15afd..0c161076 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -238,6 +238,71 @@ to absolute paths runs a local `localmodels` checkout instead of fetching the
published kit, and `LOCALMODELS_DEBUG` (`simulate` or `tiny`, or
`~/.config/localmodels/debug.json`) passes straight through to `localmodels`.
+`installNativeSource` records wall-clock stage seconds (`timings`) in the job's
+`details` and logs `Native install timings (s): ...` in the installer event log
+without adding contract fields. Each wall-clock second counts toward exactly one
+stage on the critical path, so stage durations sum to the total job duration:
+`runtime` runs alongside `release`, `images`, and (on overlapped installs)
+`migrate`, `services`, and `account`, and counts only the wait beyond that
+parallel work, appearing only when the runtime finishes last. LiveKit binds its
+saved port before `prepareFoundationServices` on both paths (before the fork
+when overlapped), because the model controller asks the OS for a free port. On
+fresh installs (`!switchingCheckout`, no
+provisioned account unless a legacy backup was set aside, and no running
+services) and cold resumes (`resume: true`, `!switchingCheckout`, and no running
+services), `migrate`, `services`, and `account` run concurrently with `runtime`,
+`prepareFoundationServices`, and `prepareModelGateway`, holding
+`services`/`account` `succeeded` events and `saveSourceBinding` until both
+branches 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
+`harness plan` and `harness apply` when it is already installed (falling back to
+a full install if missing or unreadable), and passes the inspected descriptor
+through `onRuntimeDescriptors` so callers avoid a second status probe. Within
+`release`, binary and native-runtime bundle checks run in parallel, while
+dependency and voice tool preparations stay sequential on the shared
+native-tools lock; collaboration services start concurrently when `node-services`
+is not pre-stopped for a TeamHub config restart. `runLocalmodels`
+forwards `harness apply` `download:retrying` and `total: null` byte progress
+(without a total), and `prepareByokRuntime` logs elapsed time every 10 s while mounting
+the BYOK gateway (a log line, since the job appends and persists every stage
+event).
+
Run `pnpm --filter @linger/local-installation check` (`make check-packages`
runs it too); `make check-installer` runs its consumer, the installer, and
applies to changes that affect its public behavior.
+
+## Local acceptance
+
+Unit tests mock every process, so a change to install ordering, concurrency,
+rollback, resume, or checkout switching also gets one real run on a
+developer machine. Never touch the machine's own install (`~/.simplexai`,
+`~/Library/Application Support/Linger`) or stop processes the run did not
+start.
+
+- Isolate everything a run writes. `LINGER_HOME` alone is not enough: the
+ localmodels kit defaults to `~/.local/share/localmodels` and Pi to the one
+ on `PATH`, so also set `HOME` to a scratch directory and
+ `PATH=/usr/bin:/bin:/usr/sbin:/sbin`, plus `LINGER_DESKTOP_USER_DATA` and
+ `LINGER_BRIDGE_STATE_DIR` (otherwise the desktop removes the real bridge
+ state). Use real paths: on macOS `/tmp` is a symlink and localmodels
+ refuses it (`Unsafe runtime root`), so use `/private/tmp/...`.
+- Run the desktop from source with `LINGER_CHECKOUT` naming the checkout under
+ test (`apps/desktop/AGENTS.md`); add `--remote-debugging-port` to Electron to
+ drive `app://setup/` over CDP. From source there are no bundled TeamHub
+ binaries, so the installer prepares Go and compiles TeamHub, and its
+ timings are not comparable with a packaged build.
+- `LOCALMODELS_DEBUG=simulate:vram_gb=24` simulates the hardware, but a
+ simulated local model echoes the prompt and fails `stack apply`'s answer
+ check. Exercise a full install through BYOK instead, against the kit's
+ stub endpoint once the installer has unpacked the kit:
+ `PYTHONPATH=$K/modules $K/python/bin/python3.12 -P -s -m localmodels.debug_stub_server --bind 127.0.0.1 --port 18950 --model stub-model`
+ with `K=$LINGER_HOME/tools/localmodels/<kit hash>`, then enter
+ `http://127.0.0.1:18950/v1` and any key in setup. `--stop` leaves the
+ simulated stub servers running; stop them yourself.
+- Scenarios: a fresh install (runtime overlaps services and account in the
+ job's stage timings); `--stop` then `--resume` on the same checkout (logs
+ `Reusing the installed <runtime> runtime.` and overlaps); `--resume` while
+ services run (returns `Services are already running.` with unchanged
+ process IDs); and `--resume --source-repo` on another checkout (full
+ `harness plan`/`apply`, migrations only after runtime preparation).
diff --git a/packages/local-installation/src/byok-source.test.ts b/packages/local-installation/src/byok-source.test.ts
index d008c49a..868120b5 100644
--- a/packages/local-installation/src/byok-source.test.ts
+++ b/packages/local-installation/src/byok-source.test.ts
@@ -213,4 +213,93 @@ describe("BYOK localmodels integration", () => {
environment: { PI_CODING_AGENT_DIR: "/abs/pi" },
});
});
+
+ async function mountWithHeartbeat(settle: "resolve" | "reject") {
+ const home = await makeHome();
+ const events: { kind: string; stage?: string; message: string }[] = [];
+ let resolveApply!: (value: {
+ code: number;
+ stdout: string;
+ stderr: string;
+ }) => void;
+ let rejectApply!: (error: Error) => void;
+ const promise = prepareByokRuntime(
+ {
+ baseUrl: "https://api.example.com/v1",
+ modelId: "gpt-4o",
+ runtime: "codex",
+ },
+ {
+ home,
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ },
+ {
+ prepareNative: async () => ({
+ code: 0,
+ state: "ready",
+ message: "ok",
+ }),
+ localmodels: () =>
+ new Promise((resolve, reject) => {
+ resolveApply = resolve;
+ rejectApply = reject;
+ }),
+ },
+ );
+ await vi.advanceTimersByTimeAsync(9_900);
+ const beforeTen = events.length;
+ await vi.advanceTimersByTimeAsync(200);
+ const heartbeats = events.slice(beforeTen);
+ if (settle === "resolve")
+ resolveApply({ code: 0, stdout: "{}", stderr: "" });
+ else rejectApply(new Error("localmodels crashed"));
+ const outcome = await promise.catch((error: Error) => error);
+ return { events, beforeTen, heartbeats, outcome };
+ }
+
+ it("logs elapsed progress every 10s while mounting the BYOK gateway", async () => {
+ vi.useFakeTimers();
+ try {
+ const { events, beforeTen, heartbeats, outcome } =
+ await mountWithHeartbeat("resolve");
+ expect(outcome).toMatchObject({ state: "ready" });
+ const stages = events.slice(0, beforeTen);
+ expect(stages).toEqual([
+ expect.objectContaining({
+ kind: "stage",
+ message: expect.stringMatching(/^Mounting BYOK endpoint/),
+ }),
+ ]);
+ expect(heartbeats).toEqual([
+ {
+ kind: "log",
+ stage: "runtime",
+ message: "Local BYOK model gateway is starting (10s elapsed).\n",
+ },
+ ]);
+ const count = events.length;
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(events.length).toBe(count);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("stops the BYOK heartbeat when the mount rejects", async () => {
+ vi.useFakeTimers();
+ try {
+ const { events, heartbeats, outcome } =
+ await mountWithHeartbeat("reject");
+ expect(outcome).toBeInstanceOf(Error);
+ expect(heartbeats.map((event) => event.kind)).toEqual(["log"]);
+ const count = events.length;
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(events.length).toBe(count);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/packages/local-installation/src/byok-source.ts b/packages/local-installation/src/byok-source.ts
index 3cc5e480..c60e8389 100644
--- a/packages/local-installation/src/byok-source.ts
+++ b/packages/local-installation/src/byok-source.ts
@@ -306,17 +306,33 @@ export async function prepareByokRuntime(
state: "running",
message: "Mounting BYOK endpoint on local Bifrost gateway…",
});
- const result = await applySource(
- options.home,
- "byok",
- runtime,
- {
- signal: options.signal,
- timeoutMs: 180_000,
- input: byokStdin(validated),
- },
- dependencies.localmodels ?? runLocalmodels,
- );
+ const startedAt = Date.now();
+ // A log line, not a stage event: the job appends and persists every stage
+ // event, and other stages may run concurrently with this one.
+ const heartbeat = setInterval(() => {
+ options.onEvent({
+ kind: "log",
+ stage: "runtime",
+ message: `Local BYOK model gateway is starting (${Math.floor((Date.now() - startedAt) / 1000)}s elapsed).\n`,
+ });
+ }, 10_000);
+ heartbeat.unref?.();
+ let result;
+ try {
+ result = await applySource(
+ options.home,
+ "byok",
+ runtime,
+ {
+ signal: options.signal,
+ timeoutMs: 180_000,
+ input: byokStdin(validated),
+ },
+ dependencies.localmodels ?? runLocalmodels,
+ );
+ } finally {
+ clearInterval(heartbeat);
+ }
if (result.code !== 0)
return sourceApplyFailure(
result.stdout,
diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts
index 7da7f72f..ed2c4001 100644
--- a/packages/local-installation/src/localmodels-tool.test.ts
+++ b/packages/local-installation/src/localmodels-tool.test.ts
@@ -730,6 +730,39 @@ test("forwards real Harness byte progress without forwarding native logs or secr
);
expect(JSON.stringify(onEvent.mock.calls)).not.toContain("hidden");
});
+test("emits download:retrying stage and byte progress without a total when total is null", async () => {
+ const f = await fixture();
+ vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source));
+ const onEvent = vi.fn();
+ const run = vi.fn<typeof import("./process.js").runProcess>(
+ async (_file, _args, options) => {
+ options?.onOutput?.(
+ '{"kind":"stage","stage":"download","state":"retrying"}\n' +
+ '{"kind":"progress","stage":"download","completed":2097152,"total":null,"unit":"bytes"}\n',
+ );
+ return { code: 0, stdout: "{}", stderr: "" };
+ },
+ );
+ await runLocalmodels(
+ f.home,
+ ["harness", "apply", "plan", "--jsonl"],
+ { onEvent },
+ { run },
+ );
+ expect(onEvent).toHaveBeenCalledWith({
+ kind: "stage",
+ stage: "runtime",
+ state: "running",
+ message: "Retrying the Harness download…",
+ });
+ expect(onEvent).toHaveBeenCalledWith({
+ kind: "stage",
+ stage: "runtime",
+ state: "running",
+ message: "Downloading the selected Harness (2.0 MB)…",
+ progress: { completed: 2097152, unit: "bytes" },
+ });
+});
test("forwards safe extraction and verification stages after Harness downloads finish", async () => {
const f = await fixture();
diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts
index 2cafaa52..a8fe4deb 100644
--- a/packages/local-installation/src/localmodels-tool.ts
+++ b/packages/local-installation/src/localmodels-tool.ts
@@ -445,6 +445,11 @@ export function localmodelsStateDirectory(home: string): string {
export function localmodelsBaseDirectory(home: string): string {
return path.join(path.resolve(home), "runtime", "localmodels", "models");
}
+function formatDownloadedBytes(bytes: number): string {
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${bytes} B`;
+}
export async function runLocalmodels(
home: string,
args: string[],
@@ -505,6 +510,7 @@ async function runLocalmodelsCommand(
value?.kind === "stage"
) {
const messages: Record<string, string> = {
+ "download:retrying": "Retrying the Harness download…",
"extract:running":
"Extracting Harness files and applying private permissions…",
"verify:running": "Verifying the installed Harness executable…",
@@ -531,26 +537,36 @@ async function runLocalmodelsCommand(
value.unit !== "bytes" ||
typeof value.completed !== "number" ||
!Number.isSafeInteger(value.completed) ||
- value.completed < 0 ||
- typeof value.total !== "number" ||
- !Number.isSafeInteger(value.total) ||
- value.total <= 0 ||
- value.completed > value.total
+ value.completed < 0
)
continue;
+ const hasTotal = value.total !== null && value.total !== undefined;
+ if (
+ hasTotal &&
+ (typeof value.total !== "number" ||
+ !Number.isSafeInteger(value.total) ||
+ value.total <= 0 ||
+ value.completed > value.total)
+ )
+ continue;
+ const label =
+ args[0] === "gateway"
+ ? "Downloading the application model gateway"
+ : "Downloading the selected Harness";
options.onEvent?.({
kind: "stage",
stage: "runtime",
state: "running",
- message:
- args[0] === "gateway"
- ? "Downloading the application model gateway…"
- : "Downloading the selected Harness…",
- progress: {
- completed: value.completed,
- total: value.total,
- unit: "bytes",
- },
+ message: hasTotal
+ ? `${label}…`
+ : `${label} (${formatDownloadedBytes(value.completed)})…`,
+ progress: hasTotal
+ ? {
+ completed: value.completed,
+ total: value.total as number,
+ unit: "bytes",
+ }
+ : { completed: value.completed, unit: "bytes" },
});
}
};
diff --git a/packages/local-installation/src/managed-runtimes.test.ts b/packages/local-installation/src/managed-runtimes.test.ts
index b0cc8664..366a806c 100644
--- a/packages/local-installation/src/managed-runtimes.test.ts
+++ b/packages/local-installation/src/managed-runtimes.test.ts
@@ -13,6 +13,7 @@ import path from "node:path";
import {
installNativeRuntime,
inspectRuntime,
+ prepareRuntime,
runtimeEnvironmentFromDescriptors,
} from "./managed-runtimes.js";
const roots: string[] = [];
@@ -435,3 +436,90 @@ it.each(["RUNTIME_ACTION_FAILED", "RUNTIME_EXTENSIONS_FAILED"])(
expect(failure).toMatchObject({ code });
},
);
+
+it.each([
+ { authenticated: true, expectedState: "ready", expectedCode: 0 },
+ {
+ authenticated: false,
+ expectedState: "action_required",
+ expectedCode: 4,
+ },
+])(
+ "prepareRuntime with reuseInstalled skips plan and apply when already installed (authenticated=$authenticated)",
+ async ({ authenticated, expectedState, expectedCode }) => {
+ const options = await fixture();
+ const localmodels = vi.fn(async (_home: string, args: string[]) => ({
+ code: 0,
+ stdout:
+ args[1] === "status" ? JSON.stringify(status("pi", authenticated)) : "",
+ stderr: "",
+ }));
+ const descriptors: unknown[] = [];
+ const outcome = await prepareRuntime(
+ "pi",
+ {
+ ...options,
+ reuseInstalled: true,
+ onDescriptor: (descriptor) => descriptors.push(descriptor),
+ },
+ { localmodels },
+ );
+ expect(outcome).toMatchObject({
+ code: expectedCode,
+ state: expectedState,
+ });
+ expect(localmodels.mock.calls.map(([, args]) => args[1])).toEqual([
+ "status",
+ ]);
+ expect(descriptors).toHaveLength(1);
+ expect(descriptors[0]).toMatchObject({ runtime: "pi", installed: true });
+ },
+);
+
+it("prepareRuntime with reuseInstalled falls back to plan and apply when not installed", async () => {
+ const options = await fixture();
+ const id = "c".repeat(64);
+ let statusCalls = 0;
+ const localmodels = vi.fn(async (_home: string, args: string[]) => {
+ if (args[1] === "status") {
+ statusCalls += 1;
+ const body = status("pi", true);
+ if (statusCalls === 1) {
+ body.runtimes[0]!.installed = false;
+ body.runtimes[0]!.authenticated = false;
+ }
+ return { code: 0, stdout: JSON.stringify(body), stderr: "" };
+ }
+ if (args[1] === "plan") {
+ await writeFile(
+ args[args.indexOf("--out") + 1]!,
+ JSON.stringify({
+ schema: "localmodels.harness-plan/v1",
+ id,
+ runtime: "pi",
+ }),
+ );
+ }
+ return { code: 0, stdout: "", stderr: "" };
+ });
+ const descriptors: unknown[] = [];
+ const outcome = await prepareRuntime(
+ "pi",
+ {
+ ...options,
+ reuseInstalled: true,
+ onDescriptor: (descriptor) => descriptors.push(descriptor),
+ },
+ { localmodels },
+ );
+ expect(outcome.state).toBe("ready");
+ expect(localmodels.mock.calls.map(([, args]) => args[1])).toEqual([
+ "status",
+ "plan",
+ "apply",
+ "status",
+ "status",
+ ]);
+ expect(descriptors).toHaveLength(1);
+ expect(descriptors[0]).toMatchObject({ runtime: "pi", installed: true });
+});
diff --git a/packages/local-installation/src/managed-runtimes.ts b/packages/local-installation/src/managed-runtimes.ts
index 54733872..b8f682e9 100644
--- a/packages/local-installation/src/managed-runtimes.ts
+++ b/packages/local-installation/src/managed-runtimes.ts
@@ -378,16 +378,45 @@ export async function inspectRuntime(
}
export async function prepareRuntime(
runtime: NativeRuntime,
- options: RuntimePreparationOptions,
+ options: RuntimePreparationOptions & {
+ reuseInstalled?: boolean;
+ onDescriptor?: (descriptor: RuntimeDescriptor) => void;
+ },
dependencies: RuntimeDependencies = {},
): Promise<InstallOutcome> {
- const { prepareDependencies } = await import("./dependencies.js");
- const installed = await prepareDependencies(
- { ...options, dependency: runtime },
- dependencies,
- );
- if (installed.code !== 0) return installed;
- const state = await inspectRuntime(runtime, options, dependencies);
+ let state: RuntimeInspection | undefined;
+ let fallbackEnv = options.env;
+ if (options.reuseInstalled) {
+ try {
+ const existing = await inspectRuntime(runtime, options, dependencies);
+ if (existing.installed) {
+ options.onEvent({
+ kind: "log",
+ stage: "runtime",
+ message: `Reusing the installed ${runtime} runtime.\n`,
+ });
+ state = existing;
+ } else if (!fallbackEnv) {
+ fallbackEnv = runtimeEnvironmentFromDescriptors([existing.descriptor]);
+ }
+ } catch (error) {
+ if (options.signal.aborted) throw error;
+ }
+ }
+ if (!state) {
+ const { prepareDependencies } = await import("./dependencies.js");
+ const installed = await prepareDependencies(
+ {
+ ...options,
+ ...(fallbackEnv ? { env: fallbackEnv } : {}),
+ dependency: runtime,
+ },
+ dependencies,
+ );
+ if (installed.code !== 0) return installed;
+ state = await inspectRuntime(runtime, options, dependencies);
+ }
+ options.onDescriptor?.(state.descriptor);
if (state.ready)
return {
code: 0,
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index 8d6dcd83..3ae46e31 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -35,7 +35,7 @@ import {
installAppleDeveloperTools,
needsAppleDeveloperTools,
} from "./apple-developer-tools.js";
-import type { InstallerEvent } from "./events.js";
+import type { InstallOutcome, InstallerEvent } from "./events.js";
import {
prepareNativeDependencies,
prepareNativeVoiceTools,
@@ -50,7 +50,8 @@ import {
TEAMHUB_BINARY_DIRECTORY,
TEAMHUB_COMMANDS,
} from "./teamhub-binaries.js";
-import { prepareRuntime } from "./managed-runtimes.js";
+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 {
@@ -1324,6 +1325,9 @@ async function bundledRuntime(repo: string) {
test("native timings count only Runtime work that outlasts PostgreSQL", async () => {
const f = await fixture();
+ // A service still running keeps the install sequential, where the Runtime
+ // wait sits on the critical path between PostgreSQL and the migrations.
+ f.running.add("web");
let clock = 0;
let startRuntime!: () => void;
let finishRuntime!: () => void;
@@ -1382,6 +1386,56 @@ test("native timings count only Runtime work that outlasts PostgreSQL", async ()
expect(runtimeStages).toEqual(["running", "succeeded"]);
});
+test("overlapped timings count Runtime only for the wait beyond services and account", async () => {
+ const f = await fixture();
+ let clock = 0;
+ let ownerRan = false;
+ let timerMoved!: () => void;
+ const runtimeEntered = new Promise<void>((resolve) => {
+ timerMoved = resolve;
+ });
+ // Only the stage timer reads this clock. After the owner command, its next
+ // read is the move to "runtime" once the account branch has settled.
+ const now = () => {
+ if (ownerRan) timerMoved();
+ return clock;
+ };
+ vi.mocked(prepareRuntime).mockImplementation(async () => {
+ await runtimeEntered;
+ clock += 4000;
+ return { code: 0, state: "ready", message: "ready" };
+ });
+ const run = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) clock += 2000;
+ if (args.includes("owner")) {
+ clock += 1000;
+ const result = await run(command, args, options);
+ ownerRan = true;
+ return result;
+ }
+ return run(command, args, options);
+ });
+ // A fresh setup with no services running takes the overlapped path.
+ const result = await installNativeSource(
+ {
+ ...f,
+ name: "native-timings-overlap",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ },
+ now,
+ );
+ expect(result.code, result.message).toBe(0);
+ const timings = (result.details as { timings: Record<string, number> })
+ .timings;
+ expect(timings).toMatchObject({ services: 2, account: 1, runtime: 4 });
+ const total = Object.values(timings).reduce((sum, value) => sum + value, 0);
+ expect(total).toBeCloseTo(clock / 1000, 1);
+});
+
test("bundled services that verify install no packages and record stage times", async () => {
const f = await fixture();
await bundledRuntime(f.repo);
@@ -1615,6 +1669,52 @@ test("LiveKit holds its port before the model controller chooses one", async ()
}
});
+test("an overlapped setup binds LiveKit before the runtime branch prepares foundation services", async () => {
+ const f = await fixture();
+ const actual = await vi.importActual<typeof import("./native-livekit.js")>(
+ "./native-livekit.js",
+ );
+ vi.mocked(readLiveKitSettings).mockImplementation(actual.readLiveKitSettings);
+ vi.mocked(prepareNativeVoiceTools).mockResolvedValue({
+ bin: path.join(f.home, "voice"),
+ livekit: path.join(f.home, "voice", "livekit-server"),
+ });
+ const order: string[] = [];
+ // A slow bind gives a racing runtime branch time to reach the controller.
+ vi.mocked(startNativeLiveKit).mockImplementation(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ f.running.add("livekit");
+ order.push("livekit bound");
+ });
+ vi.mocked(prepareFoundationServices).mockImplementation(async () => {
+ order.push("foundations ensure");
+ });
+ const events: InstallerEvent[] = [];
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ // A fresh setup with no services running takes the overlapped path.
+ const result = await installNativeSource({
+ ...f,
+ name: "native-flow-overlap-livekit",
+ setupChoice: "pi",
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ expect(result.code, result.message).toBe(0);
+ expect(order).toEqual(["livekit bound", "foundations ensure"]);
+ const servicesRunning = events.findIndex(
+ (event) =>
+ event.kind === "stage" &&
+ event.stage === "services" &&
+ event.state === "running" &&
+ event.message === "Starting native collaboration services…",
+ );
+ expect(servicesRunning).toBeGreaterThanOrEqual(0);
+});
+
for (const tools of ["absent", "failed"] as const)
test(`voice stays off and the install continues when voice tools are ${tools}`, async () => {
const { events, services, env } = await installVoice(tools, {
@@ -1644,3 +1744,625 @@ test("a changed voice key leaves the voice setting alone", async () => {
expect(voice(second)).toEqual(voice(first));
expect(second.env("node-services").XAI_API_KEY).toBe("xai-2");
});
+
+test("fresh install overlaps migrate, services, and account with pending runtime while holding succeeded until both finish", async () => {
+ const f = await fixture();
+ let resolveRuntime!: (outcome: InstallOutcome) => void;
+ vi.mocked(prepareRuntime).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveRuntime = resolve;
+ }),
+ );
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ let resolveOwner!: () => void;
+ const ownerCalled = new Promise<void>((resolve) => {
+ resolveOwner = resolve;
+ });
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ const result = await baseRun(command, args, options);
+ if (args.includes("owner")) resolveOwner();
+ return result;
+ });
+ const events: InstallerEvent[] = [];
+ const runPromise = installNativeSource({
+ ...f,
+ name: "native-flow-overlap",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ // migrate, services, and account owner provisioning complete while runtime is still pending.
+ await ownerCalled;
+ expect(
+ events.some(
+ (event) =>
+ event.kind === "stage" &&
+ (event.stage === "services" || event.stage === "account") &&
+ event.state === "succeeded",
+ ),
+ ).toBe(false);
+ resolveRuntime({ code: 0, state: "ready", message: "ready" });
+ const outcome = await runPromise;
+ expect(outcome.code).toBe(0);
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ kind: "stage",
+ stage: "services",
+ state: "succeeded",
+ }),
+ );
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ kind: "stage",
+ stage: "account",
+ state: "succeeded",
+ }),
+ );
+});
+
+test("upgrade keeps migrate sequential after runtime when account is already provisioned", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const firstOutcome = await installNativeSource({
+ ...f,
+ name: "native-flow-upgrade",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(firstOutcome.code).toBe(0);
+
+ let runtimeResolved = false;
+ let resolveRuntime!: (outcome: InstallOutcome) => void;
+ vi.mocked(prepareRuntime).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveRuntime = (outcome) => {
+ runtimeResolved = true;
+ resolve(outcome);
+ };
+ }),
+ );
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ let migrateSawRuntimeResolved = false;
+ let resolveMigrateReached!: () => void;
+ const migrateReached = new Promise<void>((resolve) => {
+ resolveMigrateReached = resolve;
+ });
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) {
+ migrateSawRuntimeResolved = runtimeResolved;
+ resolveMigrateReached();
+ }
+ return baseRun(command, args, options);
+ });
+ const runPromise = installNativeSource({
+ ...f,
+ name: "native-flow-upgrade",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ await vi.waitFor(() => expect(resolveRuntime).toBeTypeOf("function"));
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ resolveRuntime({ code: 0, state: "ready", message: "ready" });
+ await migrateReached;
+ const outcome = await runPromise;
+ expect(outcome.code).toBe(0);
+ expect(migrateSawRuntimeResolved).toBe(true);
+});
+
+test("mid-flight migrate failure aborts runtime and drains both branches before rollback", async () => {
+ const f = await fixture();
+ let runtimeAborted = false;
+ let runtimeSettled = false;
+ vi.mocked(prepareRuntime).mockImplementation(
+ (_choice, options) =>
+ new Promise((_resolve, reject) => {
+ options.signal.addEventListener("abort", () => {
+ runtimeAborted = true;
+ setTimeout(() => {
+ runtimeSettled = true;
+ reject(new Error("aborted"));
+ }, 15);
+ });
+ }),
+ );
+ let settledBeforeStop = false;
+ vi.mocked(stopNativeProcess).mockImplementation(async () => {
+ settledBeforeStop = runtimeSettled;
+ });
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) return { code: 1, stdout: "", stderr: "" };
+ return baseRun(command, args, options);
+ });
+ const failed = await installNativeSource({
+ ...f,
+ name: "native-flow-fail-drain",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(failed).toMatchObject({ code: 1, state: "failed" });
+ expect(failed.message).toContain("Native source migrate failed (exit 1).");
+ expect(runtimeAborted).toBe(true);
+ expect(settledBeforeStop).toBe(true);
+});
+
+test("fresh-install overlap preserves RUNTIME_AUTH_REQUIRED without aborting services", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 4,
+ state: "action_required",
+ message: "auth required",
+ details: {
+ code: "RUNTIME_AUTH_REQUIRED",
+ runtime: "pi",
+ executable: "/pi",
+ loginCommand: "pi login",
+ },
+ });
+ const events: InstallerEvent[] = [];
+ const authOutcome = await installNativeSource({
+ ...f,
+ name: "native-flow-auth-pending",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ expect(authOutcome.code).toBe(0);
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ kind: "stage",
+ stage: "runtime",
+ state: "waiting_user",
+ }),
+ );
+});
+
+for (const failingStep of [
+ "prepareFoundationServices",
+ "prepareModelGateway",
+] as const)
+ test(`fresh-install overlap reports runtime when ${failingStep} fails after account starts`, async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ let resolveOwnerStarted!: () => void;
+ const ownerStarted = new Promise<void>((resolve) => {
+ resolveOwnerStarted = resolve;
+ });
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("owner")) {
+ resolveOwnerStarted();
+ return new Promise((_resolve, reject) => {
+ const abort = () => {
+ try {
+ options?.signal?.throwIfAborted();
+ } catch (error) {
+ reject(error);
+ }
+ };
+ if (options?.signal?.aborted) abort();
+ else options?.signal?.addEventListener("abort", abort);
+ });
+ }
+ return baseRun(command, args, options);
+ });
+ if (failingStep === "prepareFoundationServices") {
+ vi.mocked(prepareFoundationServices).mockImplementation(async () => {
+ await ownerStarted;
+ throw new Error("foundation services failed");
+ });
+ } else {
+ vi.mocked(prepareFoundationServices).mockImplementation(async () => {
+ await ownerStarted;
+ });
+ vi.mocked(prepareModelGateway).mockImplementation(async () => {
+ throw new Error("model gateway failed");
+ });
+ }
+ const events: InstallerEvent[] = [];
+ const failed = await installNativeSource({
+ ...f,
+ name:
+ failingStep === "prepareFoundationServices"
+ ? "native-flow-overlap-foundation"
+ : "native-flow-overlap-gateway",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ expect(failed).toMatchObject({
+ code: 1,
+ state: "failed",
+ details: { stage: "runtime" },
+ });
+ expect(failed.message).toContain(
+ failingStep === "prepareFoundationServices"
+ ? "foundation services failed"
+ : "model gateway failed",
+ );
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ kind: "stage",
+ stage: "runtime",
+ state: "failed",
+ }),
+ );
+ expect(events).not.toContainEqual(
+ expect.objectContaining({
+ kind: "stage",
+ stage: "account",
+ state: "failed",
+ }),
+ );
+ if (failingStep === "prepareModelGateway") {
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ kind: "log",
+ stage: "runtime",
+ message: expect.stringContaining(
+ "Preparing foundation services took",
+ ),
+ }),
+ );
+ }
+ });
+
+test("fresh-install overlap reports account when account provisioning fails", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockImplementation(
+ (_choice, options) =>
+ new Promise((_resolve, reject) => {
+ const abort = () => {
+ try {
+ options.signal.throwIfAborted();
+ } catch (error) {
+ reject(error);
+ }
+ };
+ if (options.signal.aborted) abort();
+ else options.signal.addEventListener("abort", abort);
+ }),
+ );
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("owner")) return { code: 1, stdout: "", stderr: "" };
+ return baseRun(command, args, options);
+ });
+ const events: InstallerEvent[] = [];
+ const failed = await installNativeSource({
+ ...f,
+ name: "native-flow-overlap-account-fail",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ expect(failed).toMatchObject({
+ code: 1,
+ state: "failed",
+ details: { stage: "account" },
+ });
+ expect(failed.message).toContain(
+ "Local account sign-in failed after creation (HTTP 401).",
+ );
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ kind: "stage",
+ stage: "account",
+ state: "failed",
+ }),
+ );
+});
+
+test("cold resume skips pre-inspection env probe, reuses installed runtime, forwards descriptors, and overlaps services", async () => {
+ const f = await fixture();
+ // First install provisions the instance and saved account.
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const initial = await installNativeSource({
+ ...f,
+ name: "native-flow-cold-resume",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(initial.code).toBe(0);
+ const saved = await loadInstance({
+ name: "native-flow-cold-resume",
+ home: f.home,
+ });
+ await stopNativeSource(saved!, new AbortController().signal);
+
+ vi.mocked(managedRuntimeEnvironment).mockClear();
+ let releaseRuntime!: () => void;
+ let migrateStartedBeforeRuntimeDone = false;
+ let runtimeDone = false;
+ const descriptor: RuntimeDescriptor = {
+ runtime: "pi",
+ executable: "/mock/pi",
+ argvPrefix: [],
+ installed: true,
+ authenticated: true,
+ authMode: "api_key",
+ loginCommand: null,
+ };
+ vi.mocked(prepareRuntime).mockImplementationOnce(async (_choice, options) => {
+ expect(options.reuseInstalled).toBe(true);
+ expect(options.env).toBeUndefined();
+ await new Promise<void>((resolve) => {
+ releaseRuntime = resolve;
+ });
+ runtimeDone = true;
+ options.onDescriptor?.(descriptor);
+ return { code: 0, state: "ready", message: "ready" };
+ });
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) {
+ migrateStartedBeforeRuntimeDone = !runtimeDone;
+ releaseRuntime();
+ }
+ return baseRun(command, args, options);
+ });
+
+ const forwarded: RuntimeDescriptor[][] = [];
+ const resumed = await installNativeSource({
+ ...f,
+ name: "native-flow-cold-resume",
+ externalComputer: true,
+ resume: true,
+ onRuntimeDescriptors: (descriptors) => forwarded.push(descriptors),
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(resumed.code).toBe(0);
+ expect(vi.mocked(managedRuntimeEnvironment)).not.toHaveBeenCalled();
+ expect(migrateStartedBeforeRuntimeDone).toBe(true);
+ expect(forwarded).toEqual([[descriptor]]);
+});
+
+test("resume stays sequential when services are already running", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const initial = await installNativeSource({
+ ...f,
+ name: "native-flow-resume-seq",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(initial.code).toBe(0);
+
+ // Services from the initial install are still running, so resume stays sequential.
+ let runtimeDone = false;
+ let migrateSawRuntimeDone = false;
+ vi.mocked(prepareRuntime).mockImplementationOnce(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ runtimeDone = true;
+ return { code: 0, state: "ready", message: "ready" };
+ });
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) {
+ migrateSawRuntimeDone = runtimeDone;
+ }
+ return baseRun(command, args, options);
+ });
+
+ const resumed = await installNativeSource({
+ ...f,
+ name: "native-flow-resume-seq",
+ externalComputer: true,
+ resume: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(resumed.code).toBe(0);
+ expect(migrateSawRuntimeDone).toBe(true);
+});
+
+test("overlap runtime failure returns the runtime outcome and stops started services in reverse order", async () => {
+ const f = await fixture();
+ let failRuntime!: () => void;
+ vi.mocked(prepareRuntime).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ failRuntime = () =>
+ resolve({ code: 1, state: "failed", message: "runtime failed" });
+ }),
+ );
+ const baseStart = vi.mocked(startNativeProcess).getMockImplementation()!;
+ const started: string[] = [];
+ vi.mocked(startNativeProcess).mockImplementation(async (options) => {
+ started.push(options.name);
+ return baseStart(options);
+ });
+ const stopped: string[] = [];
+ vi.mocked(stopNativeProcess).mockImplementation(async (_root, name) => {
+ stopped.push(name);
+ });
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("owner")) failRuntime();
+ return baseRun(command, args, options);
+ });
+ const events: InstallerEvent[] = [];
+ const failed = await installNativeSource({
+ ...f,
+ name: "native-flow-overlap-runtime-fail",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: (event) => events.push(event),
+ });
+ // The Runtime's own outcome is the cause, not the aborted services branch.
+ expect(failed).toMatchObject({
+ code: 1,
+ state: "failed",
+ message: "runtime failed",
+ });
+ expect(events).not.toContainEqual(
+ expect.objectContaining({ stage: "account", state: "failed" }),
+ );
+ expect(started.length).toBeGreaterThan(0);
+ // PostgreSQL starts first through its own path, so it stops last.
+ expect(stopped).toEqual([...started].reverse().concat("postgres"));
+});
+
+test("a service start that fails at once waits for the other starts before rollback", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const baseStart = vi.mocked(startNativeProcess).getMockImplementation()!;
+ const settled = new Set<string>();
+ vi.mocked(startNativeProcess).mockImplementation(async (options) => {
+ if (options.name === "teamhub")
+ throw new Error("teamhub identity cannot be verified");
+ if (options.name === "web" || options.name === "node-services") {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ const result = await baseStart(options);
+ settled.add(options.name);
+ return result;
+ }
+ return baseStart(options);
+ });
+ const stopsBeforeSettled: string[] = [];
+ const stopped: string[] = [];
+ vi.mocked(stopNativeProcess).mockImplementation(async (_root, name) => {
+ if (settled.size < 2) stopsBeforeSettled.push(name);
+ stopped.push(name);
+ f.running.delete(name);
+ });
+ const failed = await installNativeSource({
+ ...f,
+ name: "native-flow-start-settle",
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(failed.code).not.toBe(0);
+ expect(settled).toEqual(new Set(["web", "node-services"]));
+ expect(stopsBeforeSettled).toEqual([]);
+ expect(stopped).toEqual(
+ expect.arrayContaining(["teamhub", "node-services", "web"]),
+ );
+});
+
+for (const variant of ["resume", "setup choice"] as const)
+ test(`a ${variant} onto another checkout keeps migrate after the runtime`, async () => {
+ const f = await fixture();
+ const name = `native-flow-switch-${variant.replace(" ", "-")}`;
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const initial = await installNativeSource({
+ ...f,
+ name,
+ setupChoice: "pi",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ expect(initial.code).toBe(0);
+ const saved = await loadInstance({ name, home: f.home });
+ await stopNativeSource(saved!, new AbortController().signal);
+ // Without a provisioned account a setup choice would overlap too, so
+ // only the checkout switch keeps it sequential.
+ if (variant === "setup choice")
+ await rm(path.join(saved!.root, "local-account.json"));
+ const next = path.join(f.home, "next");
+ await cp(f.repo, next, { recursive: true });
+
+ let runtimeDone = false;
+ let releaseRuntime!: () => void;
+ vi.mocked(prepareRuntime).mockImplementationOnce(async () => {
+ await new Promise<void>((resolve) => {
+ releaseRuntime = resolve;
+ });
+ runtimeDone = true;
+ return { code: 0, state: "ready", message: "ready" };
+ });
+ const baseRun = vi.mocked(runProcess).getMockImplementation()!;
+ let migrateSawRuntimeDone: boolean | undefined;
+ vi.mocked(runProcess).mockImplementation(async (command, args, options) => {
+ if (args.includes("migrate")) migrateSawRuntimeDone = runtimeDone;
+ return baseRun(command, args, options);
+ });
+ const runPromise = installNativeSource({
+ ...f,
+ repo: next,
+ name,
+ externalComputer: true,
+ ...(variant === "resume" ? { resume: true } : { setupChoice: "pi" }),
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ });
+ await vi.waitFor(() => expect(releaseRuntime).toBeTypeOf("function"));
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ expect(migrateSawRuntimeDone).toBeUndefined();
+ releaseRuntime();
+ expect((await runPromise).code).toBe(0);
+ expect(migrateSawRuntimeDone).toBe(true);
+ });
+
+test("a repeated resume after a successful resume succeeds without provisioning the owner again", async () => {
+ const f = await fixture();
+ vi.mocked(prepareRuntime).mockResolvedValue({
+ code: 0,
+ state: "ready",
+ message: "ready",
+ });
+ const input = {
+ ...f,
+ name: "native-flow-resume-twice",
+ externalComputer: true,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ };
+ expect(
+ (await installNativeSource({ ...input, setupChoice: "pi" })).code,
+ ).toBe(0);
+ const saved = await loadInstance({ name: input.name, home: f.home });
+ await stopNativeSource(saved!, new AbortController().signal);
+ const owners = () =>
+ vi.mocked(runProcess).mock.calls.filter((row) => row[1].includes("owner"))
+ .length;
+ expect((await installNativeSource({ ...input, resume: true })).code).toBe(0);
+ const afterFirstResume = owners();
+ expect((await installNativeSource({ ...input, resume: true })).code).toBe(0);
+ expect(owners()).toBe(afterFirstResume);
+});
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index 029e153a..ae9bf0f5 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -14,6 +14,7 @@ import {
type SourceInstallOptions,
} from "./source-checkout.js";
import {
+ loadInstance,
privateDirectory,
readLocalIdentityKey,
withInstanceLock,
@@ -39,7 +40,11 @@ import {
stopNativeProcess,
type NativeService,
} from "./native-process.js";
-import { ensureLocalAccount, validateLocalCredentials } from "./account.js";
+import {
+ ensureLocalAccount,
+ localAccountProvisioned,
+ validateLocalCredentials,
+} from "./account.js";
import {
configureManagedCodex,
managedRuntimeEnvironment,
@@ -478,6 +483,7 @@ async function runNativeSource(
const started: NativeService[] = [];
let runtimeOutcome: InstallOutcome | undefined;
let runtimeError: unknown;
+ let runtimeAborted = false;
let runtimePending = true;
const runtime = (async () => {
try {
@@ -523,7 +529,11 @@ async function runNativeSource(
home,
signal,
onEvent: emit,
- env: await managedRuntimeEnvironment(home, current.root),
+ ...(options.resume
+ ? { reuseInstalled: true }
+ : { env: await managedRuntimeEnvironment(home, current.root) }),
+ onDescriptor: (descriptor) =>
+ options.onRuntimeDescriptors?.([descriptor]),
});
if (
choice !== "pi" &&
@@ -543,12 +553,18 @@ async function runNativeSource(
runtimeOutcome &&
runtimeOutcome.code !== 0 &&
(runtimeOutcome.details as { code?: string } | undefined)?.code !==
- "RUNTIME_AUTH_REQUIRED"
- )
+ "RUNTIME_AUTH_REQUIRED" &&
+ !controller.signal.aborted
+ ) {
+ runtimeAborted = true;
controller.abort();
+ }
} catch (error) {
runtimeError = error;
- controller.abort();
+ if (!controller.signal.aborted) {
+ runtimeAborted = true;
+ controller.abort();
+ }
} finally {
runtimePending = false;
}
@@ -560,24 +576,44 @@ async function runNativeSource(
const timed = async <T>(
what: string,
run: () => Promise<T>,
- detail: (value: T) => string = () => "",
+ timedOptions: {
+ detail?: (value: T) => string;
+ stage?: InstallStage;
+ } = {},
): Promise<T> => {
const startedAt = Date.now();
const value = await run();
+ const detail = timedOptions.detail?.(value) ?? "";
emit({
kind: "log",
- stage,
- message: `${what} took ${((Date.now() - startedAt) / 1000).toFixed(1)}s${detail(value)}.\n`,
+ stage: timedOptions.stage ?? stage,
+ message: `${what} took ${((Date.now() - startedAt) / 1000).toFixed(1)}s${detail}.\n`,
});
return value;
};
- // The desktop puts the TeamHub binaries it ships into the checkout;
- // with them TeamHub needs no Go.
- const binaries = await timed(
- "Checking the bundled TeamHub binaries",
- () => checkTeamhubBinaries(current.source!.repo),
- (state) => ` (${state})`,
- );
+ // The desktop puts the TeamHub binaries it ships into the checkout,
+ // and unpacks the services it built into the checkout.
+ let checked = "";
+ const [binaries, bundled] = await Promise.all([
+ timed(
+ "Checking the bundled TeamHub binaries",
+ () => checkTeamhubBinaries(current.source!.repo),
+ { detail: (state) => ` (${state})` },
+ ),
+ options.externalComputer
+ ? timed(
+ "Checking the bundled Native services",
+ () =>
+ checkNativeRuntime(current.source!.repo, {
+ signal,
+ checked: (how, files) => {
+ checked = `, ${files} files by ${how === "sizes" ? "size" : "sha256"}`;
+ },
+ }),
+ { detail: (state) => ` (${state}${checked})` },
+ )
+ : Promise.resolve(false as const),
+ ]);
signal.throwIfAborted();
if (binaries !== "absent")
emit({
@@ -588,22 +624,6 @@ async function runNativeSource(
? "Using the bundled TeamHub binaries; Go is not needed.\n"
: "The bundled TeamHub binaries do not verify; compiling TeamHub instead.\n",
});
- // The desktop also unpacks the services it built into the checkout;
- // with them (and the Computer it ships) nothing installs packages.
- let checked = "";
- const bundled =
- options.externalComputer &&
- (await timed(
- "Checking the bundled Native services",
- () =>
- checkNativeRuntime(current.source!.repo, {
- signal,
- checked: (how, files) => {
- checked = `, ${files} files by ${how === "sizes" ? "size" : "sha256"}`;
- },
- }),
- (state) => ` (${state}${checked})`,
- ));
if (bundled && bundled !== "absent")
emit({
kind: "log",
@@ -614,6 +634,13 @@ async function runNativeSource(
: "The bundled Native services do not verify; installing the checkout's packages instead.\n",
});
const offline = bundled === "verified";
+ // Voice needs LiveKit and ffmpeg; the desktop ships them for each
+ // computer. They run whether or not a voice key is set, so a key
+ // saved later in the app works without a reinstall. A computer
+ // without them, or a failed preparation, keeps voice off and the
+ // install going; TeamHub then reports voice as unavailable. Both
+ // operations lock the shared native-tools directory, so they run
+ // sequentially here.
const tools = await timed(
"Preparing the private toolchains and PostgreSQL",
() =>
@@ -626,13 +653,12 @@ async function runNativeSource(
packages: !offline,
}),
);
- // Voice needs LiveKit and ffmpeg; the desktop ships them for each
- // computer. They run whether or not a voice key is set, so a key
- // saved later in the app works without a reinstall. A computer
- // without them, or a failed preparation, keeps voice off and the
- // install going; TeamHub then reports voice as unavailable.
const voice = await timed("Preparing the voice tools", () =>
- prepareNativeVoiceTools({ home, signal, onEvent: emit }),
+ prepareNativeVoiceTools({
+ home,
+ signal,
+ onEvent: emit,
+ }),
).catch((error: unknown) => {
if (signal.aborted) throw error;
emit({
@@ -695,17 +721,33 @@ async function runNativeSource(
);
const command = async (
operation: string,
- extraEnv: NodeJS.ProcessEnv = {},
- input?: string,
- sink: { write(chunk: string): void } = output,
- retried = false,
+ commandOptions: {
+ extraEnv?: NodeJS.ProcessEnv;
+ input?: string;
+ sink?: { write(chunk: string): void };
+ stage?: InstallStage;
+ retried?: boolean;
+ } = {},
): Promise<void> => {
+ const {
+ extraEnv = {},
+ input,
+ sink,
+ retried = false,
+ stage: commandStage = stage,
+ } = commandOptions;
const startedAt = Date.now();
+ const ownedSink = sink
+ ? undefined
+ : lineRedactor((message) =>
+ emit({ kind: "log", stage: commandStage, message }),
+ );
+ const activeSink = sink ?? ownedSink!;
const heartbeat = setInterval(
() =>
emit({
kind: "log",
- stage,
+ stage: commandStage,
message: `Native ${operation} is running (${Math.floor((Date.now() - startedAt) / 1000)}s elapsed).\n`,
}),
10_000,
@@ -728,13 +770,14 @@ async function runNativeSource(
input,
capture: false,
onOutput: (chunk) => {
- sink.write(chunk);
+ activeSink.write(chunk);
tail = (tail + chunk).slice(-64_000);
},
},
));
} finally {
clearInterval(heartbeat);
+ ownedSink?.flush();
}
if (code === 0) return;
// Prebuilt binaries cover every native module, but when one has to
@@ -743,7 +786,7 @@ async function runNativeSource(
const installing = "Installing Apple developer tools…";
emit({
kind: "stage",
- stage,
+ stage: commandStage,
state: "running",
message: installing,
});
@@ -752,16 +795,16 @@ async function runNativeSource(
onWaiting: (seconds) =>
emit({
kind: "log",
- stage,
+ stage: commandStage,
message: `${installing} Choose Install in the window macOS opened (${seconds}s elapsed).\n`,
}),
});
emit({
kind: "log",
- stage,
+ stage: commandStage,
message: `Apple developer tools are installed. Running native ${operation} again.\n`,
});
- return command(operation, extraEnv, input, sink, true);
+ return command(operation, { ...commandOptions, retried: true });
}
throw new Error(`Native source ${operation} failed (exit ${code}).`);
};
@@ -789,12 +832,10 @@ async function runNativeSource(
const install = async (operation: string) => {
for (const [index, registry] of registries.entries()) {
try {
- await command(
- operation,
- npmRegistryEnvironment(registry),
- undefined,
- packages,
- );
+ await command(operation, {
+ extraEnv: npmRegistryEnvironment(registry),
+ sink: packages,
+ });
registries = registries.slice(index);
if (index > 0)
await recordRegionFallback(home, sourceRegion(registry));
@@ -837,135 +878,311 @@ async function runNativeSource(
"Starting private PostgreSQL and applying migrations…",
);
await reclaimEarlierProcesses(current, home, emit);
+ const storedBefore = await loadInstance({ name: current.name, home });
+ const switchingCheckout = Boolean(
+ storedBefore?.source &&
+ storedBefore.releaseDir !== current.releaseDir,
+ );
+ const hadProvisionedAccount = await localAccountProvisioned(
+ current.root,
+ );
+ const anyServiceRunning = (
+ await Promise.all(
+ (["teamhub", "node-services", "web"] as const).map((name) =>
+ inspectNativeProcess(current.root, name),
+ ),
+ )
+ ).some((state) => state.running);
const postgresWasRunning = (
await inspectNativeProcess(current.root, "postgres")
).running;
// Mark before startup so a failed init/readiness step can stop a process
// it managed to create without touching a previously running cluster.
if (!postgresWasRunning) started.push("postgres");
- const { legacyBackup } = await prepareNativeDatabase({
- instance: current,
- postgresBin: tools.postgresBin,
- env,
- signal,
- onOutput: (chunk) => output.write(chunk),
- });
+ const { legacyBackup } = await timed(
+ "Preparing private PostgreSQL",
+ () =>
+ prepareNativeDatabase({
+ instance: current,
+ postgresBin: tools.postgresBin,
+ env,
+ signal,
+ onOutput: (chunk) => output.write(chunk),
+ }),
+ );
if (legacyBackup)
emit({
kind: "log",
stage,
message: `The data from the earlier Simplex app can't be upgraded to Linger, so Linger starts with a fresh workspace. The earlier data was moved, not deleted, to ${legacyBackup}.\n`,
});
- // The runtime is ready before the checkout's migrations run: when it is
- // not, services still running from an earlier checkout keep the
- // schema they know. Count only the wait beyond the parallel work and
- // keep the progress events that the runtime itself reports.
- if (runtimePending) timer.enter("runtime");
- await runtime;
- timer.enter("services");
- signal.throwIfAborted();
- await command("migrate");
- step("services", "Starting native collaboration services…");
- const ends = await logEnds(current);
+ // Emits the services stage and captures the log ends that
+ // waitHealthy reads, before any service starts.
+ const beginServices = () => {
+ emit({
+ kind: "stage",
+ stage: "services",
+ state: "running",
+ message: "Starting native collaboration services…",
+ });
+ return logEnds(current);
+ };
// Bind LiveKit's saved port before the model controller asks the OS
// for its own port; an unbound port can be assigned to either service.
- const liveKit = voice && (await readLiveKitSettings(current.root));
- if (voice && liveKit) {
- if (!(await inspectNativeProcess(current.root, "livekit")).running)
- started.push("livekit");
- await startNativeLiveKit({
+ const bindLiveKit = async () => {
+ const liveKit = voice && (await readLiveKitSettings(current.root));
+ if (voice && liveKit) {
+ if (!(await inspectNativeProcess(current.root, "livekit")).running)
+ started.push("livekit");
+ await startNativeLiveKit({
+ root: current.root,
+ executable: voice.livekit,
+ settings: liveKit,
+ signal,
+ });
+ } else if (
+ (await inspectNativeProcess(current.root, "livekit")).running
+ )
+ await stopNativeProcess(current.root, "livekit");
+ };
+ const startAndAwaitServices = async (
+ ends: Awaited<ReturnType<typeof logEnds>>,
+ ) => {
+ const serviceOptions = (
+ name: "teamhub" | "node-services" | "web",
+ ) => ({
root: current.root,
- executable: voice.livekit,
- settings: liveKit,
+ name,
+ executable: process.execPath,
+ args: [
+ path.join(current.source!.repo, "scripts/source-native.mjs"),
+ name,
+ ],
+ cwd: current.source!.repo,
+ env:
+ name === "teamhub"
+ ? { ...env, TEAMHUB_LOCAL_IDENTITY_KEY: identityKey }
+ : env,
signal,
+ redactions: secrets,
+ // A changed user.env, port, credential or voice tool restarts it.
+ settings: name === "teamhub" ? teamhubSettings : settings,
+ restartOnConfigurationChange: true,
});
- } else if (
- (await inspectNativeProcess(current.root, "livekit")).running
- )
- await stopNativeProcess(current.root, "livekit");
- await prepareFoundationServices(current, choice, {
- home,
- signal,
- onEvent: emit,
- shareGpu: options.shareGpu,
- });
- // Binds the local stack's gateway for local models; with a runtime's own
- // sign-in, retires one an earlier release started.
- await prepareModelGateway(
- current,
- options.byok && choice !== "local-models"
- ? { runtime: choice, modelSource: "byok" }
- : choice,
- {
- home,
- signal,
- onEvent: emit,
- },
- );
- const serviceOptions = (name: "teamhub" | "node-services" | "web") => ({
- root: current.root,
- name,
- executable: process.execPath,
- args: [
- path.join(current.source!.repo, "scripts/source-native.mjs"),
- name,
- ],
- cwd: current.source!.repo,
- env:
- name === "teamhub"
- ? { ...env, TEAMHUB_LOCAL_IDENTITY_KEY: identityKey }
- : env,
- signal,
- redactions: secrets,
- // A changed user.env, port, credential or voice tool restarts it.
- settings: name === "teamhub" ? teamhubSettings : settings,
- restartOnConfigurationChange: true,
- });
- // Stop the Agent Service only when TeamHub is about to restart for a
- // changed configuration, so its graceful shutdown can requeue
- // in-flight Runs while TeamHub is still up. When TeamHub is not
- // running or not changing, node-services is left alone so it can
- // reconnect. It was running before this run, so it is never recorded
- // as started: if a later step fails, its replacement stays up beside
- // the new TeamHub; if TeamHub's own restart fails, node-services
- // stays stopped until the next resume.
- const preStopped =
- (await nativeConfigurationChanged(serviceOptions("teamhub"))) &&
- (await inspectNativeProcess(current.root, "node-services")).running;
- if (preStopped) await stopNativeProcess(current.root, "node-services");
- for (const name of ["teamhub", "node-services", "web"] as const) {
- const running = (await inspectNativeProcess(current.root, name))
- .running;
- if (!running && !(preStopped && name === "node-services"))
- started.push(name);
- await startNativeProcess(serviceOptions(name));
+ // Stop the Agent Service only when TeamHub is about to restart for a
+ // changed configuration, so its graceful shutdown can requeue
+ // in-flight Runs while TeamHub is still up. When TeamHub is not
+ // running or not changing, node-services is left alone so it can
+ // reconnect. It was running before this run, so it is never recorded
+ // as started: if a later step fails, its replacement stays up beside
+ // the new TeamHub; if TeamHub's own restart fails, node-services
+ // stays stopped until the next resume.
+ const preStopped =
+ (await nativeConfigurationChanged(serviceOptions("teamhub"))) &&
+ (await inspectNativeProcess(current.root, "node-services")).running;
+ if (preStopped)
+ await stopNativeProcess(current.root, "node-services");
+ const serviceNames = ["teamhub", "node-services", "web"] as const;
+ if (preStopped) {
+ for (const name of serviceNames) {
+ const running = (await inspectNativeProcess(current.root, name))
+ .running;
+ if (!running && name !== "node-services") started.push(name);
+ await startNativeProcess(serviceOptions(name));
+ }
+ } else {
+ const states = await Promise.all(
+ serviceNames.map((name) =>
+ inspectNativeProcess(current.root, name),
+ ),
+ );
+ for (const [index, name] of serviceNames.entries()) {
+ if (!states[index]!.running) started.push(name);
+ }
+ // Settle every start before rollback so a supervisor still being
+ // spawned is recorded and can be stopped.
+ const results = await Promise.allSettled(
+ serviceNames.map((name) =>
+ startNativeProcess(serviceOptions(name)),
+ ),
+ );
+ const failed = results.find(
+ (result) => result.status === "rejected",
+ );
+ if (failed) throw failed.reason;
+ }
+ return timed(
+ "Waiting for native collaboration services",
+ () => waitHealthy(current, signal, emit, ends),
+ { stage: "services" },
+ );
+ };
+ const provisionAccount = () =>
+ ensureLocalAccount(current, signal, {
+ email: options.email,
+ password: options.password,
+ provisionOwner: async (email, password) => {
+ secrets.push(password);
+ await command("owner", {
+ extraEnv: { OWNER_EMAIL: email },
+ input: `${password}\n`,
+ stage: "account",
+ });
+ },
+ });
+ const overlapWithRuntime =
+ !switchingCheckout &&
+ !anyServiceRunning &&
+ (Boolean(options.resume) ||
+ (Boolean(options.setupChoice || options.byok) &&
+ (!hadProvisionedAccount || Boolean(legacyBackup))));
+ // Without `stageForLogs`, timings log under the current stage.
+ // `beforeFoundation` runs once the runtime is ready, before the
+ // foundation services.
+ const prepareRuntimeSide = async (
+ stageForLogs?: InstallStage,
+ beforeFoundation?: () => Promise<unknown>,
+ ) => {
+ await timed("Waiting for runtime preparation", () => runtime, {
+ stage: stageForLogs,
+ });
+ signal.throwIfAborted();
+ await beforeFoundation?.();
+ await timed(
+ "Preparing foundation services",
+ () =>
+ prepareFoundationServices(current, choice, {
+ home,
+ signal,
+ onEvent: emit,
+ shareGpu: options.shareGpu,
+ }),
+ { stage: stageForLogs },
+ );
+ // Binds the local stack's gateway for local models; with a runtime's own
+ // sign-in, retires one an earlier release started.
+ await prepareModelGateway(
+ current,
+ options.byok && choice !== "local-models"
+ ? { runtime: choice, modelSource: "byok" }
+ : choice,
+ {
+ home,
+ signal,
+ onEvent: emit,
+ },
+ );
+ };
+ const migrate = (stageForLogs?: InstallStage) =>
+ timed(
+ "Running database migrations",
+ () => command("migrate", { stage: stageForLogs }),
+ { stage: stageForLogs },
+ );
+ const servicesSucceeded = async () => {
+ await saveSourceBinding(current);
+ emit({
+ kind: "stage",
+ stage: "services",
+ state: "succeeded",
+ message: "Native source services are ready.",
+ });
+ };
+ const accountSucceeded = () =>
+ emit({
+ kind: "stage",
+ stage: "account",
+ state: "succeeded",
+ message: "Local account is ready.",
+ });
+ let checks: { service: string; ready: boolean }[];
+ if (overlapWithRuntime) {
+ // LiveKit binds before the fork so the runtime branch's foundation
+ // services can never take its port.
+ const ends = await beginServices();
+ await bindLiveKit();
+ // Each second counts once, toward the critical path: services and
+ // account while branch2 runs, then runtime only for the wait beyond.
+ timer.enter("services");
+ let firstFailure: { error: unknown; stage: InstallStage } | undefined;
+ const failBranch = (
+ error: unknown,
+ failedStage: InstallStage,
+ ): never => {
+ firstFailure ??= { error, stage: failedStage };
+ controller.abort();
+ throw error;
+ };
+ const branch1 = (async () => {
+ try {
+ await prepareRuntimeSide("runtime");
+ } catch (error) {
+ return failBranch(error, "runtime");
+ }
+ })();
+ const branch2 = (async () => {
+ let branchStage: InstallStage = "services";
+ try {
+ await migrate(branchStage);
+ const probed = await startAndAwaitServices(ends);
+ branchStage = "account";
+ timer.enter("account");
+ emit({
+ kind: "stage",
+ stage: branchStage,
+ state: "running",
+ message: "Preparing local account and workspace…",
+ });
+ await provisionAccount();
+ return probed;
+ } catch (error) {
+ return failBranch(error, branchStage);
+ }
+ })();
+ let branch1Pending = true;
+ const settled1 = Promise.allSettled([branch1]).then(([result]) => {
+ branch1Pending = false;
+ return result;
+ });
+ const [result2] = await Promise.allSettled([branch2]);
+ if (branch1Pending) timer.enter("runtime");
+ const result1 = await settled1;
+ if (result1.status === "rejected" || result2.status === "rejected") {
+ stage = runtimeAborted
+ ? "runtime"
+ : (firstFailure?.stage ??
+ (result1.status === "rejected" ? "runtime" : "services"));
+ throw firstFailure
+ ? firstFailure.error
+ : result1.status === "rejected"
+ ? result1.reason
+ : (result2 as PromiseRejectedResult).reason;
+ }
+ checks = result2.value;
+ await servicesSucceeded();
+ stage = "account";
+ accountSucceeded();
+ } else {
+ // The runtime is ready before the checkout's migrations run: when it is
+ // not, services still running from an earlier checkout keep the
+ // schema they know.
+ let ends: Awaited<ReturnType<typeof logEnds>> | undefined;
+ // Count only the runtime wait beyond the parallel work.
+ if (runtimePending) timer.enter("runtime");
+ await prepareRuntimeSide(undefined, async () => {
+ timer.enter("services");
+ await migrate();
+ ends = await beginServices();
+ await bindLiveKit();
+ });
+ checks = await startAndAwaitServices(ends!);
+ await servicesSucceeded();
+ step("account", "Preparing local account and workspace…");
+ await provisionAccount();
+ accountSucceeded();
+ await runtime;
+ signal.throwIfAborted();
}
- const checks = await waitHealthy(current, signal, emit, ends);
- await saveSourceBinding(current);
- emit({
- kind: "stage",
- stage: "services",
- state: "succeeded",
- message: "Native source services are ready.",
- });
- step("account", "Preparing local account and workspace…");
- await ensureLocalAccount(current, signal, {
- email: options.email,
- password: options.password,
- provisionOwner: async (email, password) => {
- secrets.push(password);
- await command("owner", { OWNER_EMAIL: email }, `${password}\n`);
- },
- });
- emit({
- kind: "stage",
- stage,
- state: "succeeded",
- message: "Local account is ready.",
- });
-
- await runtime;
- signal.throwIfAborted();
if (options.externalComputer) {
const authPending =
(runtimeOutcome?.details as { code?: string } | undefined)?.code ===
@@ -1077,9 +1294,8 @@ async function runNativeSource(
}
} catch (error) {
// The side that failed first is the cause; the other one only
- // stopped because of it. Only the Runtime aborts the controller
- // before this point.
- const runtimeFailedFirst = controller.signal.aborted;
+ // stopped because of it.
+ const runtimeFailedFirst = runtimeAborted;
controller.abort();
await runtime;
for (const name of started.reverse()) {
diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.ts
index 2681e84a..60e1e588 100644
--- a/packages/local-installation/src/source-checkout.ts
+++ b/packages/local-installation/src/source-checkout.ts
@@ -25,6 +25,7 @@ import {
import { freePort, portFree } from "./ports.js";
import type { SetupChoice } from "./setup-plan.js";
import type { ByokConfiguration } from "./byok-source.js";
+import type { RuntimeDescriptor } from "./managed-runtimes.js";
import type { InstallerEvent } from "./events.js";
// A Native installation of one Linger source checkout: the desktop client's
@@ -49,6 +50,12 @@ export interface SourceInstallOptions {
// The desktop client is this machine's Computer: source installs skip the
// Go Computer build and enrollment, and the client signs in itself.
externalComputer?: boolean;
+ // Cold-resume restarts of an existing checkout reuse an installed runtime
+ // after one inspection and overlap runtime preparation with service startup.
+ resume?: boolean;
+ // Passes runtime descriptors inspected during startup so callers avoid a
+ // second runtime status probe.
+ onRuntimeDescriptors?: (descriptors: RuntimeDescriptor[]) => void;
}
export interface EnvironmentReport {
platform: string;