Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: a later start reads engines as before, and a reloaded engine reads its models (#4183)

Milind Soni3a2d56359827
diff --git a/server/drivers/claude-catalog.test.ts b/server/drivers/claude-catalog.test.ts
index 8d0c234701..64f873f0e5 100644
--- a/server/drivers/claude-catalog.test.ts
+++ b/server/drivers/claude-catalog.test.ts
@@ -174,7 +174,7 @@ describe("ClaudeDriver catalog", () => {
writeStartupModelCache(instanceId, {
default: "claude-sonnet-5",
options: [{ id: "claude-haiku-4-5", label: "Claude Haiku 4.5" }],
- });
+ }, { build: "an earlier release" });
}
const instance = await ClaudeDriver.create({
instanceId,
diff --git a/server/harness/engine-status-file.test.ts b/server/harness/engine-status-file.test.ts
index 64c58dd6f8..26616f462c 100644
--- a/server/harness/engine-status-file.test.ts
+++ b/server/harness/engine-status-file.test.ts
@@ -22,7 +22,7 @@ it("writes what the save delay still holds when the process exits cleanly, once"
flushEngineStatusFiles();
expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ v: 1, engines: [row] });
const read = status.read(() => ({ driverKind: "antigravityAgent", cli: "agy" }));
- expect(read.get("work")).toEqual({ snapshot: { state: "available", authenticated: true }, checkedAt: null, settings: null });
+ expect(read.get("work")).toEqual({ state: "available", authenticated: true });
flushEngineStatusFiles();
expect(process.listeners("exit").filter((listener) => listener === flushEngineStatusFiles)).toHaveLength(1);
});
@@ -39,6 +39,6 @@ it("keeps the marks the welcome and the AI tests read: a ChatGPT plan and OpenCo
]);
flushEngineStatusFiles();
const read = status.read((instanceId) => instanceId === "opencode" ? { driverKind: "opencodeGo", cli: "opencode" } : { driverKind: "codex", cli: "codex" });
- expect(read.get("opencode")?.snapshot).toEqual(free);
- expect(read.get("codex")?.snapshot).toEqual(plan);
+ expect(read.get("opencode")).toEqual(free);
+ expect(read.get("codex")).toEqual(plan);
});
diff --git a/server/harness/engine-status-file.ts b/server/harness/engine-status-file.ts
index f4993814a9..e59ff1f69e 100644
--- a/server/harness/engine-status-file.ts
+++ b/server/harness/engine-status-file.ts
@@ -9,15 +9,6 @@ export interface EngineStatusRow {
driverKind: string;
cli: string | null;
snapshot: ProviderSnapshot;
- /** When a probe last gave this status, and a digest of the engine's settings it was probed with. */
- checkedAt?: number;
- settings?: string;
-}
-
-export interface SavedEngineStatus {
- snapshot: ProviderSnapshot;
- checkedAt: number | null;
- settings: string | null;
}
type Target = (instanceId: InstanceId) => { driverKind: string; cli: string | null } | null;
@@ -98,8 +89,8 @@ export function engineStatusFile(file: string) {
};
return {
/** The statuses the last run recorded, for the engines still configured with the same driver and CLI. */
- read(target: Target): Map<InstanceId, SavedEngineStatus> {
- const seeds = new Map<InstanceId, SavedEngineStatus>();
+ read(target: Target): Map<InstanceId, ProviderSnapshot> {
+ const seeds = new Map<InstanceId, ProviderSnapshot>();
let rows: unknown;
try {
rows = (JSON.parse(readFileSync(file, "utf8")) as { engines?: unknown }).engines;
@@ -111,10 +102,7 @@ export function engineStatusFile(file: string) {
if (!row || !text(row.instanceId)) continue;
const now = target(row.instanceId);
const snapshot = snapshotFrom(row.snapshot);
- if (snapshot && now && now.driverKind === row.driverKind && now.cli === (row.cli ?? null)) {
- seeds.set(row.instanceId, { snapshot, checkedAt: typeof row.checkedAt === "number" && Number.isFinite(row.checkedAt) ? row.checkedAt : null,
- settings: text(row.settings) ? row.settings : null });
- }
+ if (snapshot && now && now.driverKind === row.driverKind && now.cli === (row.cli ?? null)) seeds.set(row.instanceId, snapshot);
}
return seeds;
},
diff --git a/server/harness/registry-start-read.test.ts b/server/harness/registry-start-read.test.ts
index 66086e7a6f..9501677057 100644
--- a/server/harness/registry-start-read.test.ts
+++ b/server/harness/registry-start-read.test.ts
@@ -9,7 +9,7 @@ import type { InstanceConfigMap } from "../contracts.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { makeFakeDriver, type FakeDriverOptions } from "../testing/fake-driver.ts";
import { snapshotFrom, STATUS_SAVE_DELAY_MS } from "./engine-status-file.ts";
-import { ENGINE_STATUS_FRESH_MS, enginesByUse, ProviderRegistry, SNAPSHOT_DEADLINE_MS, START_READ_STEP_MS } from "./registry.ts";
+import { enginesByUse, ProviderRegistry, SNAPSHOT_DEADLINE_MS, START_READ_STEP_MS } from "./registry.ts";
const AVAILABLE = { state: "available", version: "0.0.0-fake" } as const;
const GONE = { state: "unavailable", reason: "`fake` CLI not found" } as const;
@@ -24,8 +24,6 @@ const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
/** The recorded status is written a second after the last probe lands. */
const saved = async () => { await vi.advanceTimersByTimeAsync(STATUS_SAVE_DELAY_MS); };
const timersForTheFile = () => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
-/** A start long enough after the last run that its statuses are probed again. */
-const later = () => Date.now() + ENGINE_STATUS_FRESH_MS;
async function engines(options: Record<string, FakeDriverOptions>, registryOptions: ConstructorParameters<typeof ProviderRegistry>[1] = {}, configs?: InstanceConfigMap) {
const fakes = Object.entries(options).map(([kind, opts]) => {
@@ -125,14 +123,13 @@ describe("the start-up read", () => {
await lastRun.registry.describe();
expect(existsSync(file)).toBe(false);
await saved();
- expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ v: 1, engines: [{ instanceId: "fake", driverKind: "fake", cli: "fake-cli", snapshot: AVAILABLE,
- checkedAt: expect.any(Number), settings: expect.stringMatching(/^[0-9a-f]{16}$/) }] });
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ v: 1, engines: [{ instanceId: "fake", driverKind: "fake", cli: "fake-cli", snapshot: AVAILABLE }] });
if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
const probe = gate();
Object.assign(options, { holdSnapshot: probe.promise, answer: GONE });
const { registry, probes } = await engines({ fake: options }, { statusFile: file });
- const read = registry.readAtStart([], () => {}, later());
+ const read = registry.readAtStart();
const [listed] = await registry.describe({ known: true });
expect(listed.snapshot).toEqual(AVAILABLE);
expect(registry.knownSnapshot("fake")).toEqual(AVAILABLE);
@@ -166,7 +163,7 @@ describe("the start-up read", () => {
const probe = gate();
Object.assign(options, { holdSnapshot: probe.promise, answer: GONE });
const { registry, probes } = await engines({ fake: options }, { statusFile: file });
- const read = registry.readAtStart(["fake"], () => {}, later());
+ const read = registry.readAtStart(["fake"]);
expect(probes()).toEqual({ fake: 1 });
const warm = gate();
options.holdSnapshot = warm.promise;
@@ -188,43 +185,7 @@ describe("the start-up read", () => {
await (await engines({ fake: {} }, { statusFile: file })).registry.describe();
await saved();
const { registry } = await engines({ fake: {} }, { statusFile: file });
- expect((await registry.readAtStart([], () => {}, later())).changed).toBe(false);
- });
-
- it("takes an engine the last run found ready within the fresh window as read, and probes one it found unavailable or set up otherwise", async () => {
- const file = statusFile();
- const options: Record<string, FakeDriverOptions> = { ready: {}, gone: { answer: GONE }, rekeyed: {} };
- timersForTheFile();
- await (await engines(options, { statusFile: file })).registry.describe();
- await saved();
- const checkedAt = JSON.parse(readFileSync(file, "utf8")).engines[0].checkedAt as number;
-
- const { registry, probes } = await engines(options, { statusFile: file },
- { ready: { driver: "ready" }, gone: { driver: "gone" }, rekeyed: { driver: "rekeyed", environment: { FAKE_KEY: "other" } } });
- const { changed } = await registry.readAtStart(["ready"], () => {}, checkedAt + ENGINE_STATUS_FRESH_MS - 1);
- expect(probes()).toEqual({ ready: 0, gone: 1, rekeyed: 1 });
- expect(changed).toBe(false);
- expect(registry.lastSnapshot("ready")).toEqual(AVAILABLE);
- expect(registry.provisional()).toBe(false);
- await saved();
- expect(JSON.parse(readFileSync(file, "utf8")).engines[0].checkedAt).toBe(checkedAt);
- // The server's own reads answer from it (a later catalog's new-bot default must not probe every CLI)...
- expect((await registry.describe()).find((engine) => engine.instanceId === "ready")?.snapshot).toEqual(AVAILABLE);
- expect(probes().ready).toBe(0);
- // ...and the list a person asks for probes it.
- await registry.describe({ known: true });
- expect(probes().ready).toBe(1);
-
- const again = await engines(options, { statusFile: file },
- { ready: { driver: "ready" }, gone: { driver: "gone" }, rekeyed: { driver: "rekeyed", environment: { FAKE_KEY: "other" } } });
- await again.registry.readAtStart([], () => {}, checkedAt + ENGINE_STATUS_FRESH_MS - 1);
- again.registry.forgetSnapshots();
- await again.registry.describe();
- expect(again.probes().ready).toBe(1);
-
- const stale = await engines(options, { statusFile: file });
- await stale.registry.readAtStart([], () => {}, checkedAt + ENGINE_STATUS_FRESH_MS);
- expect(stale.probes()).toEqual({ ready: 1, gone: 1, rekeyed: 1 });
+ expect((await registry.readAtStart()).changed).toBe(false);
});
it("keeps no seed for an engine whose driver or CLI changed, or once the engines must be probed again", async () => {
diff --git a/server/harness/registry.ts b/server/harness/registry.ts
index 5fbb8f6eec..ad664f0cc8 100644
--- a/server/harness/registry.ts
+++ b/server/harness/registry.ts
@@ -1,8 +1,5 @@
// Provider instance registry — port of upstream's ProviderInstanceRegistryLive behavior, minus Effect.
-import { createHash } from "node:crypto";
-
import { findCliCandidates } from "../env-path.ts";
-import { buildStamp } from "../environment.ts";
import { installNpmEngine, npmAvailable, serverInstallFor, standaloneLookupPath } from "../engine-install.ts";
import { installStandaloneEngine, isAppStandaloneCopy, type StandaloneInstalled } from "../engine-standalone.ts";
import { withEngineMemory } from "../engine-memory.ts";
@@ -83,11 +80,6 @@ function withinDeadline(read: () => Promise<ProviderSnapshot>): Promise<Provider
]).finally(() => clearTimeout(deadline));
}
-/** An engine the last run found ready this recently is taken as read at start, so a restart or a Cloud's wake probes no
- * CLI; one it found unavailable or signed out is probed, since a restart is how a fix gets picked up. A probe that finds
- * the same status refreshes the recorded time only once it is half this old, so it is not rewritten. */
-export const ENGINE_STATUS_FRESH_MS = 30 * 60_000;
-
/** How long the start-up read waits on one CLI before probing the next, so a stuck CLI holds back no other for long. */
export const START_READ_STEP_MS = 5_000;
@@ -114,12 +106,6 @@ export class ProviderRegistry {
private lastSnapshots = new Map<InstanceId, ProviderSnapshot>();
private seeds = new Map<InstanceId, ProviderSnapshot>();
private seedObjects = new WeakSet<ProviderSnapshot>();
- private checkedAt = new Map<InstanceId, number>();
- /** Engines taken as read at start and not probed since: the server's own reads answer from that status while it is fresh. */
- private takenAsRead = new Set<InstanceId>();
- /** A digest of each engine's settings and this server's build: a status probed under other settings (a key, a sign-out)
- * or another build's CLIs is not fresh. */
- private settings = new Map<InstanceId, string>();
/** Engines the start-up read has not probed yet; null outside that read. */
private unread: Set<InstanceId> | null = null;
private snapshotGeneration = 0;
@@ -186,7 +172,6 @@ export class ProviderRegistry {
// The RAW config: decodeConfig fills in the driver default, which would flag every instance as overridden.
const rawCli = cliOfRaw(entry.config);
if (rawCli) this.cliByInstance.set(instanceId, rawCli);
- this.settings.set(instanceId, createHash("sha256").update(JSON.stringify([entry, buildStamp()])).digest("hex").slice(0, 16));
const live = withUnaskedStops(withEngineHomes(withEngineMemory(await driver.create({
instanceId,
displayName: entry.displayName ?? driver.metadata.displayName,
@@ -234,7 +219,6 @@ export class ProviderRegistry {
forgetSnapshots(): void {
this.snapshotGeneration += 1;
this.seeds.clear();
- this.takenAsRead.clear();
}
/**
@@ -242,24 +226,16 @@ export class ProviderRegistry {
* each CLI is read from a cold disk with no other in the way; `afterFirst` runs once the first has answered; engines
* without a CLI are read at once. An engine the last run saw available that a probe now finds unavailable is probed
* once more, warm, before the read ends. Until the read reaches an engine, a turn on it probes that engine itself
- * (`engineRead`) and `describe({ known: true })` answers it from the last run's status, unless that status is fresh
- * (`ENGINE_STATUS_FRESH_MS`) and counts as read.
+ * (`engineRead`) and `describe({ known: true })` answers it from the last run's status.
*/
- async readAtStart(first: readonly InstanceId[] = [], afterFirst: () => void = () => {}, now = Date.now()) {
+ async readAtStart(first: readonly InstanceId[] = [], afterFirst: () => void = () => {}) {
const live = this.instances().map((instance) => instance.instanceId);
- const fresh = new Set<InstanceId>();
- for (const [instanceId, { snapshot, checkedAt, settings }] of this.status?.read((id) => this.byId.get(id)?.live ? this.cliTarget(id) : null) ?? []) {
+ for (const [instanceId, snapshot] of this.status?.read((id) => this.byId.get(id)?.live ? this.cliTarget(id) : null) ?? []) {
this.seeds.set(instanceId, snapshot);
- if (snapshot.state === "available" && snapshot.authenticated !== false && settings === this.settings.get(instanceId)
- && checkedAt !== null && now - checkedAt >= 0 && now - checkedAt < ENGINE_STATUS_FRESH_MS) {
- fresh.add(instanceId);
- this.takenAsRead.add(instanceId);
- this.lastSnapshots.set(instanceId, snapshot);
- this.checkedAt.set(instanceId, checkedAt);
- } else this.seedObjects.add(snapshot);
+ this.seedObjects.add(snapshot);
}
const seeded = new Map(this.seeds);
- this.unread = new Set(live.filter((id) => !fresh.has(id)));
+ this.unread = new Set(live);
try {
const withCli = new Set(live.filter((id) => this.cliTarget(id)?.cli));
const withoutCli = this.engineRead(...live.filter((id) => !withCli.has(id)));
@@ -423,17 +399,12 @@ export class ProviderRegistry {
return isAppStandaloneCopy(cli, this.enginesBaseDir, standaloneLookupPath(this.enginesBaseDir));
}
- /** `known` is the engine list a person asks for: it probes an engine taken as read at start, and answers one the
- * start-up read has yet to reach from the last run's status. `reuse`: answer from a status read since the last
- * forgetSnapshots(); one older than `ms` is read again in the background and `changed` runs when that read differs. */
+ /** `reuse`: answer from a status read since the last forgetSnapshots(); one older than `ms` is read again in the background
+ * and `changed` runs when that read differs. */
describe(options: { known?: boolean; reuse?: { ms: number; changed(): void } } = {}) {
return this.describeWith((instance) => {
- const { instanceId } = instance;
- const seed = options.known && this.unread?.has(instanceId) ? this.seeds.get(instanceId) : undefined;
- const taken = !options.known && this.takenAsRead.has(instanceId) && Date.now() - (this.checkedAt.get(instanceId) ?? 0) < ENGINE_STATUS_FRESH_MS
- ? this.lastSnapshots.get(instanceId) : undefined;
- const answer = seed ?? taken;
- if (answer) return Promise.resolve(answer);
+ const seed = options.known && this.unread?.has(instance.instanceId) ? this.seeds.get(instance.instanceId) : undefined;
+ if (seed) return Promise.resolve(seed);
const last = options.reuse && this.readsOf.get(instance);
if (!options.reuse || !last || last.generation !== this.snapshotGeneration) return this.read(instance);
if (Date.now() - last.at >= options.reuse.ms) {
@@ -455,11 +426,7 @@ export class ProviderRegistry {
}
// Only while this is still the live instance: a reload may have replaced it during the read.
if (this.byId.get(instance.instanceId)?.live === instance) {
- const before = this.lastSnapshots.get(instance.instanceId), checkedAt = this.checkedAt.get(instance.instanceId);
- if (checkedAt === undefined || Date.now() - checkedAt >= ENGINE_STATUS_FRESH_MS / 2 || !before
- || JSON.stringify(snapshotFrom(before)) !== JSON.stringify(snapshotFrom(snapshot))) this.checkedAt.set(instance.instanceId, Date.now());
this.lastSnapshots.set(instance.instanceId, snapshot);
- this.takenAsRead.delete(instance.instanceId);
this.unread?.delete(instance.instanceId);
this.saveStatus();
}
@@ -469,9 +436,7 @@ export class ProviderRegistry {
private saveStatus(): void {
this.status?.save(this.instances().flatMap(({ instanceId, driverKind }) => {
const snapshot = this.lastSnapshots.get(instanceId) ?? this.seeds.get(instanceId);
- const checkedAt = this.lastSnapshots.has(instanceId) ? this.checkedAt.get(instanceId) : undefined, settings = this.settings.get(instanceId);
- return snapshot ? [{ instanceId, driverKind, cli: this.cliTarget(instanceId)?.cli ?? null, snapshot,
- ...(checkedAt === undefined || settings === undefined ? {} : { checkedAt, settings }) }] : [];
+ return snapshot ? [{ instanceId, driverKind, cli: this.cliTarget(instanceId)?.cli ?? null, snapshot }] : [];
}));
}
@@ -555,9 +520,6 @@ export class ProviderRegistry {
this.byId.clear();
this.cliByInstance.clear();
this.lastSnapshots.clear();
- this.checkedAt.clear();
- this.takenAsRead.clear();
- this.settings.clear();
this.seeds.clear();
}
@@ -566,9 +528,6 @@ export class ProviderRegistry {
this.byId.delete(instanceId);
this.cliByInstance.delete(instanceId);
this.lastSnapshots.delete(instanceId);
- this.checkedAt.delete(instanceId);
- this.takenAsRead.delete(instanceId);
- this.settings.delete(instanceId);
this.seeds.delete(instanceId);
await entry?.live?.dispose();
}
diff --git a/server/startup-model-catalog.test.ts b/server/startup-model-catalog.test.ts
index 5a0b230c93..12f38220cd 100644
--- a/server/startup-model-catalog.test.ts
+++ b/server/startup-model-catalog.test.ts
@@ -164,36 +164,55 @@ describe("startup model catalogs", () => {
seedBots();
let refreshes = 0;
const now = 1_800_000_000_000;
- const open = (age: number) => {
- writeStartupModelCache("timed", CACHED, { checkedAt: now - age });
+ const open = (instanceId: string, age: number, build?: string) => {
+ writeStartupModelCache(instanceId, CACHED, { checkedAt: now - age, ...(build ? { build } : {}) });
let used: ModelCatalog | null = null;
- const opened = openStartupModelCatalog({ instanceId: "timed", use: (catalog) => { used = catalog; }, current: () => CACHED,
+ const opened = openStartupModelCatalog({ instanceId, use: (catalog) => { used = catalog; }, current: () => CACHED,
refresh: async () => { refreshes += 1; }, now });
return { opened, used: () => used };
};
- const fresh = open(STARTUP_MODEL_CACHE_FRESH_MS - 1);
+ const fresh = open("timed-fresh", STARTUP_MODEL_CACHE_FRESH_MS - 1);
expect(fresh.used()).toEqual(CACHED);
expect(await fresh.opened).toBeNull();
expect(refreshes).toBe(0);
- await (open(STARTUP_MODEL_CACHE_FRESH_MS).opened as { pending: Promise<void> }).pending;
+ await (open("timed-old", STARTUP_MODEL_CACHE_FRESH_MS).opened as { pending: Promise<void> }).pending;
expect(refreshes).toBe(1);
// A clock set back is no proof the list is fresh, and another build's CLIs may list other models.
- await (open(-60_000).opened as { pending: Promise<void> }).pending;
+ await (open("timed-ahead", -60_000).opened as { pending: Promise<void> }).pending;
expect(refreshes).toBe(2);
- writeStartupModelCache("timed", CACHED, { checkedAt: now, build: "0.0.1 an older image" });
- await (openStartupModelCatalog({ instanceId: "timed", use: () => {}, current: () => CACHED, refresh: async () => { refreshes += 1; }, now }) as { pending: Promise<void> }).pending;
+ await (open("timed-build", 0, "0.0.1 an older image").opened as { pending: Promise<void> }).pending;
+ expect(refreshes).toBe(3);
+ expect(readStartupModelCacheEntry("timed-fresh")).toMatchObject({ catalog: CACHED, checkedAt: now - STARTUP_MODEL_CACHE_FRESH_MS + 1, build: expect.any(String) });
+ });
+
+ it("reads the list again when an engine opens a second time in one run: its key or settings just changed", async () => {
+ seedBots();
+ let refreshes = 0;
+ const open = () => openStartupModelCatalog({ instanceId: "reopened", use: () => {}, current: () => CACHED, refresh: async () => { refreshes += 1; } });
+ writeStartupModelCache("reopened", CACHED);
+ expect(await open()).toBeNull();
+ expect(refreshes).toBe(0);
+ await (open() as { pending: Promise<void> }).pending;
+ expect(refreshes).toBe(1);
+
+ // A key saved in a server's first run: the bots exist by then, and the engine has opened once already.
+ rmSync(join(DATA_DIR, "bots.json"), { force: true });
+ const firstRun = () => openStartupModelCatalog({ instanceId: "first-run", use: () => {}, current: () => CACHED, refresh: async () => { refreshes += 1; } });
+ await firstRun();
+ expect(refreshes).toBe(2);
+ seedBots();
+ await (firstRun() as { pending: Promise<void> }).pending;
expect(refreshes).toBe(3);
- expect(readStartupModelCacheEntry("timed")).toMatchObject({ catalog: CACHED, checkedAt: expect.any(Number), build: expect.any(String) });
});
it("reads a list the engine did not confirm again at the next start", async () => {
seedBots();
const standIn = { ...CACHED };
unconfirmedModelCatalog(standIn);
- writeStartupModelCache("timed", standIn);
- expect(readStartupModelCacheEntry("timed")?.checkedAt).toBe(0);
+ writeStartupModelCache("unconfirmed", standIn);
+ expect(readStartupModelCacheEntry("unconfirmed")?.checkedAt).toBe(0);
let refreshes = 0;
- const opened = openStartupModelCatalog({ instanceId: "timed", use: () => {}, current: () => standIn, refresh: async () => { refreshes += 1; } }) as { pending: Promise<void> };
+ const opened = openStartupModelCatalog({ instanceId: "unconfirmed", use: () => {}, current: () => standIn, refresh: async () => { refreshes += 1; } }) as { pending: Promise<void> };
await opened.pending;
expect(refreshes).toBe(1);
});
diff --git a/server/startup-model-catalog.ts b/server/startup-model-catalog.ts
index 84575517eb..5eac53e83c 100644
--- a/server/startup-model-catalog.ts
+++ b/server/startup-model-catalog.ts
@@ -11,6 +11,8 @@ const SAFE_INSTANCE_ID = /^[\w.-]+$/;
/** A list this server's build read this recently is used as it is at start; an older one, or one an earlier build read,
* is read again in the background. A sleeping Cloud wakes many times an hour, and each read can start the engine's CLI. */
export const STARTUP_MODEL_CACHE_FRESH_MS = 6 * 60 * 60_000;
+/** Engines opened since this server started: opening one again means its key or settings just changed. */
+const openedThisRun = new Set<string>();
export function startupModelCachePath(instanceId: string): string | null {
if (!SAFE_INSTANCE_ID.test(instanceId)) return null;
@@ -126,6 +128,8 @@ export function openStartupModelCatalog(input: {
refresh: () => Promise<void>;
now?: number;
}): Promise<null> | DeferredStartupModelRefresh {
+ const reopened = openedThisRun.has(input.instanceId);
+ openedThisRun.add(input.instanceId);
const entry = readStartupModelCacheEntry(input.instanceId);
const cached = entry?.catalog ?? null;
if (cached) input.use(cached);
@@ -142,7 +146,7 @@ export function openStartupModelCatalog(input: {
});
}
const age = (input.now ?? Date.now()) - (entry?.checkedAt ?? -Infinity);
- if (cached && entry?.build === buildStamp() && age >= 0 && age < STARTUP_MODEL_CACHE_FRESH_MS) return Promise.resolve(null);
+ if (cached && !reopened && entry?.build === buildStamp() && age >= 0 && age < STARTUP_MODEL_CACHE_FRESH_MS) return Promise.resolve(null);
// A saved list stands in while the refresh waits; with none the engine would offer no model at all until it runs.
const startAfter = cached ? afterFirstEngineRead() : Promise.resolve();
return { pending: startAfter.then(() => input.refresh()).then(persist, () => undefined) };