Skip to content

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

Engine status hold: a broken engine is still found broken; postponing is bounded; plain start line keeps the backup AI

milind-sonie446cca7de20
diff --git a/server/cli-program.test.ts b/server/cli-program.test.ts
new file mode 100644
index 0000000000..73d879d9d0
--- /dev/null
+++ b/server/cli-program.test.ts
@@ -0,0 +1,35 @@
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { delimiter, join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "./testing/cleanup.ts";
+import { cliProgramFile, noteProbeUnsettled, probeUnsettled } from "./cli-program.ts";
+
+const scratch: string[] = [];
+afterEach(async () => { for (const dir of scratch.splice(0)) await removeTempDir(dir); });
+
+describe("the program file a CLI runs", () => {
+ it("is found on the PATH given, or as given when it is a path, and only when it is a file", () => {
+ const bin = mkdtempSync(join(tmpdir(), "omb-cli-program-"));
+ scratch.push(bin);
+ const exe = process.platform === "win32" ? ".exe" : "";
+ writeFileSync(join(bin, `opencode${exe}`), "");
+ expect(cliProgramFile("opencode", ["", join(bin, "missing"), bin].join(delimiter))).toBe(join(bin, `opencode${exe}`));
+ expect(cliProgramFile(`"${join(bin, `opencode${exe}`)}" acp`, "")).toBe(join(bin, `opencode${exe}`));
+ expect(cliProgramFile("codex", bin)).toBeNull();
+ expect(cliProgramFile(bin, "")).toBeNull(); // a folder
+ expect(cliProgramFile("", bin)).toBeNull();
+ // A Windows path that is not there is simply not found, on any platform.
+ expect(cliProgramFile("D:\\\\Tools\\\\opencode.cmd", "")).toBeNull();
+ expect(cliProgramFile("d:/tools/opencode.exe", "")).toBeNull();
+ });
+
+ it("remembers which CLIs have a check that could not finish, so a check again runs the program", () => {
+ noteProbeUnsettled("opencode", true);
+ expect(probeUnsettled("opencode")).toBe(true);
+ expect(probeUnsettled("codex")).toBe(false);
+ noteProbeUnsettled("opencode", false);
+ expect(probeUnsettled("opencode")).toBe(false);
+ });
+});
diff --git a/server/cli-program.ts b/server/cli-program.ts
new file mode 100644
index 0000000000..3682aee832
--- /dev/null
+++ b/server/cli-program.ts
@@ -0,0 +1,30 @@
+// The program file an engine's CLI runs, found the way its spawn finds it, without starting anything; and which CLIs have
+// a status check that could not finish, so a check again is a real one. One place for both, for every reader of a
+// program file: the engine status hold (harness/probe-hold.ts) and any cache of probe answers keyed by that file.
+import { statSync } from "node:fs";
+
+import { augmentedPath, findCliCandidates, splitCliString } from "./env-path.ts";
+
+/** The file a CLI string runs: its first word, as given when it is a path, else the first match on `path` (the PATH engines
+ * are started with: the app's own, with the engines' folders registered on it); null when that is not a file. */
+export function cliProgramFile(cli: string, path: string = augmentedPath()): string | null {
+ const program = splitCliString(cli)[0];
+ if (!program) return null;
+ for (const candidate of findCliCandidates(program, path)) {
+ try {
+ if (statSync(candidate).isFile()) return candidate;
+ } catch {}
+ }
+ return null;
+}
+
+const unsettled = new Set<string>();
+
+/** A status check of this CLI could not finish (`true`), or one answered (`false`). */
+export function noteProbeUnsettled(cli: string, open: boolean): void {
+ if (open) unsettled.add(cli); else unsettled.delete(cli);
+}
+
+/** Whether this CLI's last status check could not finish: a check again must run the program, never answer from a kept
+ * copy of an earlier answer. */
+export const probeUnsettled = (cli: string): boolean => unsettled.has(cli);
diff --git a/server/default-model-selection.ts b/server/default-model-selection.ts
index e38c956b00..02b9ea32bf 100644
--- a/server/default-model-selection.ts
+++ b/server/default-model-selection.ts
@@ -38,13 +38,19 @@ export function withInstanceConfig<T extends SelectableInstance>(instances: read
}));
}
+/** Available by a check that answered: an engine only found installed while its checks could not finish (`unverified`,
+ * harness/probe-hold.ts) is never chosen to run a turn, a new bot's default, or a backup; its sign-in is not known yet. */
+export function confirmedAvailable(instance: Pick<SelectableInstance, "snapshot">): boolean {
+ return instance.snapshot.state === "available" && instance.snapshot.unverified !== true;
+}
+
/** A custom endpoint brings its own credential, so its sign-in state does not count. */
export function signedOut(instance: SelectableInstance): boolean {
return instance.snapshot.state === "available" && instance.access !== "custom" && instance.snapshot.authenticated === false;
}
export function readyToRun(instance: SelectableInstance, context: DefaultSelectionContext = {}): boolean {
- return instance.enabled !== false && instance.snapshot.state === "available" && context.refusal?.(instance) === undefined && !signedOut(instance);
+ return instance.enabled !== false && confirmedAvailable(instance) && context.refusal?.(instance) === undefined && !signedOut(instance);
}
const defaultModel = (instance: SelectableInstance) => instance.models.default.trim()
@@ -77,7 +83,7 @@ export function selectDefaultModelSelection(
if (selection.effort && !offeredEffortLevels(instance, selection.model).includes(selection.effort)) delete selection.effort;
return selection;
}
- const available = instances.filter((instance) => instance.enabled !== false && instance.snapshot.state === "available" && context.refusal?.(instance) === undefined && defaultModel(instance));
+ const available = instances.filter((instance) => instance.enabled !== false && confirmedAvailable(instance) && context.refusal?.(instance) === undefined && defaultModel(instance));
const ready = available.filter((instance) => readyToRun(instance, context));
const company = context.company;
const personal = company && instances.some((instance) => company(instance.instanceId))
diff --git a/server/drivers/acp/busy-start.test.ts b/server/drivers/acp/busy-start.test.ts
index 95f899d1b6..5a8deab8ac 100644
--- a/server/drivers/acp/busy-start.test.ts
+++ b/server/drivers/acp/busy-start.test.ts
@@ -1,22 +1,27 @@
import { describe, expect, it, vi } from "vitest";
-import { CHAT_NOTICE } from "../../chat-notices.ts";
import { classifyError } from "../retry.ts";
import { runtimeErrorText } from "../runtime-notice-error.ts";
import { startupFailureRecoverable } from "./startup-recovery.ts";
import { acpRpcError } from "./rpc-error.ts";
-import { BUSY_RETRY_PAUSE_MS, busyStartFailure, sessionNewRetried, type BusyStartDeps } from "./busy-start.ts";
+import { BUSY_RETRY_PAUSE_MS, busyStartFailure, sessionNewRetried, SLOW_FIRST_ANSWER_MS, type BusyStartDeps } from "./busy-start.ts";
import { acpRuntimeFailure } from "./failure-words.ts";
import { classifyOpenCodeError } from "./opencode-go.ts";
/** OpenCode's own refusal on the starved Cloud, as acpRpcError words it. */
const refusal = () => acpRpcError({ code: -32603, message: "Internal error", data: { details: "Internal service failure", errorName: "ServiceUnavailableError" } }, "session/new");
+/** A provider outage: transient, and a backup AI may carry the turn. */
+const outage = () => acpRpcError({ code: -32603, message: "503 upstream overloaded" }, "session/new");
+const MEMORY = "memory stall 10%";
+const recoverable = (error: Error) => startupFailureRecoverable(error, error.message, classifyOpenCodeError(error), { approvalUnconfirmed: false, promptSent: false, promptUnreachedModel: false });
function deps(over: Partial<BusyStartDeps> = {}) {
+ let at = 0;
const paused: number[] = [];
- const made: BusyStartDeps = { pressure: () => null, cloud: () => true, pause: async (ms) => { paused.push(ms); }, ...over };
- return { deps: made, paused };
+ const made: BusyStartDeps = { pressure: () => null, cloud: () => true, pause: async (ms) => { paused.push(ms); }, now: () => at, ...over };
+ return { deps: made, paused, later: (ms: number) => { at += ms; } };
}
+const failOf = (send: () => Promise<unknown>, d: BusyStartDeps) => sessionNewRetried(send, () => true, d).catch((error: Error) => error) as Promise<Error>;
describe("session/new on a busy Cloud", () => {
it("the refusal reads as the customer saw it, and is transient", () => {
@@ -33,48 +38,51 @@ describe("session/new on a busy Cloud", () => {
});
it("waits a bounded pause first while the machine is pressed", async () => {
- const { deps: d, paused } = deps({ pressure: () => "memory stall 10%" });
+ const { deps: d, paused } = deps({ pressure: () => MEMORY });
const send = vi.fn().mockRejectedValueOnce(refusal()).mockResolvedValueOnce({ sessionId: "s1" });
await sessionNewRetried(send, () => true, d);
expect(paused).toEqual([BUSY_RETRY_PAUSE_MS]);
});
- it("still refused on a pressed Cloud: one plain line, keeping what the turn's own handling reads", async () => {
- const { deps: d } = deps({ pressure: () => "memory stall 10%" });
- const failed = await sessionNewRetried(() => Promise.reject(refusal()), () => true, d).catch((error) => error);
- expect(failed.message).toBe(CHAT_NOTICE["chat.notice.cloudBusyStart"]);
+ it("the engine's own refusal on a pressed Cloud: the plain line in the task, handled exactly as before otherwise", async () => {
+ const failed = await failOf(() => Promise.reject(refusal()), deps({ pressure: () => MEMORY }).deps);
expect(runtimeErrorText(failed)).toMatchObject({ key: "chat.notice.cloudBusyStart" });
- expect(failed).toMatchObject({ code: -32603, acpSessionFailure: true });
- // Not a provider outage: no backup AI is started on a machine with no room for one, read as core.ts reads it.
- expect(classifyError({ text: failed.message }).transient).toBe(false);
- const code = classifyOpenCodeError(failed);
- expect(code).toBeUndefined();
- expect(startupFailureRecoverable(failed, failed.message, code, { approvalUnconfirmed: false, promptSent: false, promptUnreachedModel: false })).toBe(false);
- // What the failed task's error row shows.
- expect(acpRuntimeFailure(failed, "OpenCode")).toMatchObject({ message: CHAT_NOTICE["chat.notice.cloudBusyStart"], text: { key: "chat.notice.cloudBusyStart" } });
+ expect(acpRuntimeFailure(failed, "OpenCode")).toMatchObject({ text: { key: "chat.notice.cloudBusyStart" } });
+ // The same message, code and data: retried, classified and handed to a backup AI exactly as the raw refusal is.
+ expect(failed.message).toBe(refusal().message);
+ expect(failed).toMatchObject({ code: -32603, acpSessionFailure: true, data: { errorName: "ServiceUnavailableError" } });
+ expect(recoverable(failed)).toBe(recoverable(refusal()));
+ expect(recoverable(failed)).toBe(true);
});
it("a Cloud pressed for CPU says it ran out of CPU", async () => {
for (const why of ["cpu stall 80%", "cpu throttled 60%", "cpu steal 40%", "event loop delayed 11s"]) {
- const failed = await sessionNewRetried(() => Promise.reject(refusal()), () => true, deps({ pressure: () => why }).deps).catch((error) => error);
- expect(failed.message).toBe(CHAT_NOTICE["chat.notice.cloudOutOfCpu"]);
+ const failed = await failOf(() => Promise.reject(refusal()), deps({ pressure: () => why }).deps);
expect(runtimeErrorText(failed)).toMatchObject({ key: "chat.notice.cloudOutOfCpu" });
}
});
it("a Cloud pressed when the start began counts, though calm when it failed", async () => {
- const readings = ["memory stall 12%", null, null, null];
- const failed = await sessionNewRetried(() => Promise.reject(refusal()), () => true, deps({ pressure: () => readings.shift() ?? null }).deps).catch((error) => error);
- expect(failed.message).toBe(CHAT_NOTICE["chat.notice.cloudBusyStart"]);
+ const readings = [MEMORY, null, null, null];
+ const failed = await failOf(() => Promise.reject(refusal()), deps({ pressure: () => readings.shift() ?? null }).deps);
+ expect(runtimeErrorText(failed)).toMatchObject({ key: "chat.notice.cloudBusyStart" });
+ });
+
+ it("a provider outage keeps its own words and stays recoverable, unless its first answer was slow on a pressed Cloud", async () => {
+ const quick = await failOf(() => Promise.reject(outage()), deps({ pressure: () => MEMORY }).deps);
+ expect(runtimeErrorText(quick)).toBeUndefined();
+ expect(recoverable(quick)).toBe(true);
+ const { deps: d, later } = deps({ pressure: () => MEMORY });
+ const slow = await failOf(() => { later(SLOW_FIRST_ANSWER_MS); return Promise.reject(outage()); }, d);
+ expect(runtimeErrorText(slow)).toMatchObject({ key: "chat.notice.cloudBusyStart" });
+ expect(recoverable(slow)).toBe(true);
});
- it("keeps the engine's words off a Cloud, on a quick refusal, and for a refusal that is not transient", async () => {
- const quick = await sessionNewRetried(() => Promise.reject(refusal()), () => true, deps().deps).catch((error) => error);
- expect(quick.message).toMatch(/ServiceUnavailableError/);
- const desktop = await sessionNewRetried(() => Promise.reject(refusal()), () => true, deps({ pressure: () => "memory stall 10%", cloud: () => false }).deps).catch((error) => error);
- expect(desktop.message).toMatch(/ServiceUnavailableError/);
+ it("keeps the engine's words on a calm Cloud, off a Cloud, and for a refusal that is not transient", async () => {
+ expect(runtimeErrorText(await failOf(() => Promise.reject(refusal()), deps().deps))).toBeUndefined();
+ expect(runtimeErrorText(await failOf(() => Promise.reject(refusal()), deps({ pressure: () => MEMORY, cloud: () => false }).deps))).toBeUndefined();
const key = new Error("Internal error: Invalid API key. (session/new, APIError)");
- expect(busyStartFailure(key, "memory stall 10%", deps().deps)).toBe(key);
+ expect(busyStartFailure(key, MEMORY, true, deps().deps)).toBe(key);
});
it("is not asked again when its process ended, for a timeout, or for a sign-in", async () => {
diff --git a/server/drivers/acp/busy-start.ts b/server/drivers/acp/busy-start.ts
index c9a795c0d0..794f223446 100644
--- a/server/drivers/acp/busy-start.ts
+++ b/server/drivers/acp/busy-start.ts
@@ -1,11 +1,12 @@
// session/new on a starved Cloud: OpenCode 1.19 on a 2 GB shared-CPU Cloud whose memory was held by a bot's commands took
// 26–46 s to answer it and then refused with its own `Internal error: Internal service failure (session/new,
// ServiceUnavailableError)`. A transient refusal on a live process is asked once more (after a pause while the machine is
-// pressed); one that still fails on a Cloud found pressed during the start ends the task with one plain line
-// instead of the engine's words: out of CPU (chat.notice.cloudOutOfCpu) when CPU presses it, else too busy
-// (chat.notice.cloudBusyStart). Our own limits stay as they are (session/new may take
-// NEW_SESSION_TIMEOUT); a timeout is never asked again, which would double the wait.
-import { CHAT_NOTICE } from "../../chat-notices.ts";
+// pressed). One that still fails on a Cloud found pressed during the start, when it is that refusal of the engine's own or
+// its first answer was slow, shows one plain line in the failed task: out of CPU (chat.notice.cloudOutOfCpu) when CPU
+// presses it, else too busy (chat.notice.cloudBusyStart). Its message stays the engine's, so it is handled exactly as
+// before: a provider outage (a 429, "503 overloaded") keeps its own words, and a backup AI still starts where one may.
+// Our own limits stay as they are (session/new may take NEW_SESSION_TIMEOUT); a timeout is never asked again, which would
+// double the wait.
import { engineMemory } from "../../engine-memory.ts";
import { machinePressure } from "../../machine-pressure.ts";
import { classifyError } from "../retry.ts";
@@ -13,18 +14,25 @@ import { RuntimeNoticeError } from "../runtime-notice-error.ts";
/** Before asking again while the machine is pressed: room for what holds it to ease. */
export const BUSY_RETRY_PAUSE_MS = 10_000;
+/** A first answer to session/new this slow came from a starved machine, whatever it said. */
+export const SLOW_FIRST_ANSWER_MS = 20_000;
+/** The engine's own refusal when it could not get its services up in time (OpenCode's `ServiceUnavailableError`). */
+const OWN_BUSY_REFUSAL = /\bServiceUnavailableError\b|\binternal service failure\b/i;
+
export interface BusyStartDeps {
/** Why the machine is pressed now, null when it is not (machine-pressure.ts). */
pressure: () => string | null;
/** This server is a Cloud home, whose plan the plain line names. */
cloud: () => boolean;
pause: (ms: number) => Promise<void>;
+ now: () => number;
}
const defaults: BusyStartDeps = {
pressure: () => machinePressure.reason(),
cloud: () => engineMemory.enabled && !engineMemory.selfHosted(),
pause: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ now: Date.now,
};
const text = (error: unknown) => (error instanceof Error ? error.message : String(error));
@@ -35,36 +43,38 @@ function askAgain(error: unknown): boolean {
return classifyError({ text: text(error) }).transient;
}
-/** The plain line for a start the Cloud was too busy for (`why`: the pressure read during the start, null for none), keeping
- * the fields the turn's own handling reads (the JSON-RPC code, and whether the process is fit for more sessions); any
- * other failure, or one on a calm machine (a provider outage, which a backup AI may carry), as it was. */
-export function busyStartFailure(error: unknown, why: string | null, deps: Pick<BusyStartDeps, "cloud"> = defaults): unknown {
- if (why === null || !deps.cloud() || (error as { acpSignInRequired?: unknown } | null)?.acpSignInRequired === true) return error;
- if (!classifyError({ text: text(error) }).transient) return error;
- const key = why !== null && /^(?:cpu|event loop)\b/.test(why) ? "chat.notice.cloudOutOfCpu" : "chat.notice.cloudBusyStart";
- const fields = error && typeof error === "object" ? error as { code?: unknown; acpSessionFailure?: unknown } : {};
- return Object.assign(new RuntimeNoticeError(CHAT_NOTICE[key], key), {
- ...(fields.code !== undefined ? { code: fields.code } : {}),
- ...(fields.acpSessionFailure !== undefined ? { acpSessionFailure: fields.acpSessionFailure } : {}),
+/** The plain line for a start the Cloud was too busy for (`why`: the pressure read during the start, null for none;
+ * `slow`: its first answer took SLOW_FIRST_ANSWER_MS or more), as the failed task's words; the error is otherwise the same
+ * (its message, code and data), so it is retried, classified and handed to a backup exactly as before. */
+export function busyStartFailure(error: unknown, why: string | null, slow: boolean, deps: Pick<BusyStartDeps, "cloud"> = defaults): unknown {
+ if (why === null || !deps.cloud() || !(error instanceof Error) || (error as { acpSignInRequired?: unknown }).acpSignInRequired === true) return error;
+ if (!classifyError({ text: error.message }).transient || !(OWN_BUSY_REFUSAL.test(error.message) || slow)) return error;
+ const key = /^(?:cpu|event loop)\b/.test(why) ? "chat.notice.cloudOutOfCpu" : "chat.notice.cloudBusyStart";
+ const { code, data, acpSessionFailure } = error as { code?: unknown; data?: unknown; acpSessionFailure?: unknown };
+ return Object.assign(new RuntimeNoticeError(error.message, key), {
+ ...(code !== undefined ? { code } : {}),
+ ...(data !== undefined ? { data } : {}),
+ ...(acpSessionFailure !== undefined ? { acpSessionFailure } : {}),
});
}
/** session/new, asked once more after a transient refusal while its process lives. */
export async function sessionNewRetried<T>(send: () => Promise<T>, alive: () => boolean, deps: BusyStartDeps = defaults): Promise<T> {
- const atStart = deps.pressure();
+ const atStart = deps.pressure(), startedAt = deps.now();
/** The pressure read at the start, else now: a Cloud pressed at any point of the start. */
const during = () => atStart ?? deps.pressure();
try {
return await send();
} catch (first) {
- if (!askAgain(first) || !alive()) throw busyStartFailure(first, during(), deps);
+ const slow = deps.now() - startedAt >= SLOW_FIRST_ANSWER_MS;
+ if (!askAgain(first) || !alive()) throw busyStartFailure(first, during(), slow, deps);
const afterFirst = during();
if (afterFirst !== null) await deps.pause(BUSY_RETRY_PAUSE_MS);
- if (!alive()) throw busyStartFailure(first, afterFirst ?? deps.pressure(), deps);
+ if (!alive()) throw busyStartFailure(first, afterFirst ?? deps.pressure(), slow, deps);
try {
return await send();
} catch (second) {
- throw busyStartFailure(second, afterFirst ?? deps.pressure(), deps);
+ throw busyStartFailure(second, afterFirst ?? deps.pressure(), slow, deps);
}
}
}
diff --git a/server/harness/probe-hold.test.ts b/server/harness/probe-hold.test.ts
index d4aa9af234..dddb5b3ca9 100644
--- a/server/harness/probe-hold.test.ts
+++ b/server/harness/probe-hold.test.ts
@@ -10,7 +10,7 @@ const scratch: string[] = [];
afterEach(async () => { for (const dir of scratch.splice(0)) await removeTempDir(dir); });
describe("a check that could not finish", () => {
- it("is a timeout, a signal or a refused spawn; never a missing file, a permission or an exit status", () => {
+ it("is a timeout, a SIGKILL or a refused spawn; never a crash, a missing file, a permission or an exit status", () => {
// execCli's own cut-off and Node's timeout kill.
expect(inconclusiveFailure(Object.assign(new Error("opencode timed out after 8000 ms"), { killed: true, code: null, signal: null }))).toBe(true);
expect(inconclusiveFailure(Object.assign(new Error("Command failed"), { killed: true, code: null, signal: "SIGTERM" }))).toBe(true);
@@ -19,6 +19,8 @@ describe("a check that could not finish", () => {
for (const code of ["EAGAIN", "ENOMEM", "EMFILE", "ENFILE"]) expect(inconclusiveFailure(Object.assign(new Error(`spawn ${code}`), { code }))).toBe(true);
for (const code of ["ENOENT", "EACCES", "EPERM"]) expect(inconclusiveFailure(Object.assign(new Error(`spawn ${code}`), { code }))).toBe(false);
+ // A program that crashes answers: it is broken.
+ for (const signal of ["SIGSEGV", "SIGABRT", "SIGBUS", "SIGTERM"]) expect(inconclusiveFailure(Object.assign(new Error("Command failed"), { killed: false, code: null, signal }))).toBe(false);
expect(inconclusiveFailure(Object.assign(new Error("Command failed"), { killed: false, code: 1, signal: null }))).toBe(false);
expect(inconclusiveFailure(null)).toBe(false);
expect(inconclusiveMark(Object.assign(new Error("x"), { code: "EAGAIN" }))).toEqual({ busy: true });
@@ -28,7 +30,10 @@ describe("a check that could not finish", () => {
it("keeps the last status that found the engine; else the program file decides", () => {
const busy = { state: "unavailable", reason: "timed out", busy: true } as const;
const known = { state: "available", version: "1.19.3", authenticated: true } as const;
- expect(heldSnapshot(known, busy, () => false)).toBe(known);
+ expect(heldSnapshot(known, busy, () => true)).toBe(known);
+ expect(heldSnapshot(known, busy, () => null)).toBe(known);
+ // The program is gone: the last status no longer stands, after a restart from the saved file either.
+ expect(heldSnapshot(known, busy, () => false)).toEqual({ state: "unavailable", reason: "timed out" });
expect(heldSnapshot(undefined, busy, () => true)).toEqual({ state: "available", unverified: true });
expect(heldSnapshot({ state: "unavailable", reason: "old", version: "1.0.0" }, busy, () => true)).toEqual({ state: "available", unverified: true, version: "1.0.0" });
expect(heldSnapshot(undefined, busy, () => false)).toEqual({ state: "unavailable", reason: "timed out" });
@@ -44,21 +49,21 @@ describe("cliPresent", () => {
const bin = dir(), file = join(bin, "opencode");
writeFileSync(file, "#!/bin/sh\nexit 1\n");
chmodSync(file, 0o755);
- expect(cliPresent("opencode", process.platform, () => [file])).toBe(true);
- expect(cliPresent(`"${file}" acp`, process.platform, (name) => [name])).toBe(true);
+ expect(cliPresent("opencode", process.platform, () => file)).toBe(true);
+ expect(cliPresent(`"${file}" acp`)).toBe(true);
});
it("a missing file, a folder, or (off Windows) a file that cannot run is not there", () => {
const bin = dir(), file = join(bin, "opencode"), folder = join(bin, "folder");
mkdirSync(folder);
- expect(cliPresent("opencode", "linux", () => [])).toBe(false);
- expect(cliPresent("opencode", "linux", () => [join(bin, "gone")])).toBe(false);
- expect(cliPresent("opencode", "linux", () => [folder])).toBe(false);
- expect(cliPresent("", "linux", () => [file])).toBe(false);
+ expect(cliPresent("opencode", "linux", () => null)).toBe(false);
+ expect(cliPresent(join(bin, "gone"), "linux")).toBe(false);
+ expect(cliPresent(folder, "linux")).toBe(false);
+ expect(cliPresent("", "linux")).toBe(false);
writeFileSync(file, "not executable");
chmodSync(file, 0o644);
- if (process.platform !== "win32" && process.getuid?.() !== 0) expect(cliPresent("opencode", "linux", () => [file])).toBe(false);
+ if (process.platform !== "win32" && process.getuid?.() !== 0) expect(cliPresent("opencode", "linux", () => file)).toBe(false);
// Windows has no execute bit: a file that is there is there (a .cmd shim, a D:\ path).
- expect(cliPresent("opencode", "win32", () => [file])).toBe(true);
+ expect(cliPresent("opencode", "win32", () => file)).toBe(true);
});
});
diff --git a/server/harness/probe-hold.ts b/server/harness/probe-hold.ts
index fe377be5aa..bc28348735 100644
--- a/server/harness/probe-hold.ts
+++ b/server/harness/probe-hold.ts
@@ -3,29 +3,40 @@
// throttled while a bot's commands hold its memory) `<cli> --version` can take longer than its limit while the engine works.
// Such a check is never recorded as "unavailable": the registry keeps what it last knew and checks again later, and with
// nothing known it looks for the program file itself (no process started) and takes it as installed but unverified.
-import { accessSync, constants, statSync } from "node:fs";
+import { accessSync, constants } from "node:fs";
+import { cliProgramFile } from "../cli-program.ts";
import type { ProviderSnapshot, RuntimeEvent } from "../contracts.ts";
-import { findCliCandidates, splitCliString } from "../env-path.ts";
import { shortageCode } from "../process-shortage.ts";
/** Before each check again after one that could not finish: then the last of these, until one answers. */
export const PROBE_RETRY_MS = [30_000, 60_000, 120_000, 300_000, 600_000] as const;
+/** This many checks in a row that could not finish while the machine was not pressed are an answer: the engine is broken
+ * (it hangs, or is killed each time), not starved. */
+export const CALM_FAILURES_BELIEVED = 3;
+/** A status this old is checked again even while the machine is pressed or the engine's turn runs. */
+export const STATUS_STALE_MS = 10 * 60_000;
+/** After the person's own change (an install, a sign-in), a check that could not finish is tried again this soon, this many
+ * times, pressed or not; then as any other. */
+export const PROMPT_RETRY_MS = 5_000;
+export const PROMPT_RETRIES = 5;
+/** How long after such a change its checks count as the person's own. */
+export const PERSON_CHECK_MS = 2 * 60_000;
/** An event from one of the engine's turns this recently, with no end since, proves it runs: no check is needed then. */
export const TURN_PROOF_MS = 5 * 60_000;
/** On a small machine a status check waits for the one before it at most this long: longer than a CLI's own version check
* may take (procs.ts CLI_VERSION_TIMEOUT_MS), so two never run at once there unless one is stuck past its own limit. */
export const PROBE_QUEUE_WAIT_MS = 35_000;
-/** A failed `execFile` that says nothing about the program: cut off at its time limit, ended by a signal (the OOM killer's
- * SIGKILL), or never started for want of processes, open files or memory. A missing or non-executable file, or an exit
- * with a status, is an answer. */
+/** A failed `execFile` that says nothing about the program: cut off at its time limit, killed by SIGKILL (the OOM killer),
+ * or never started for want of processes, open files or memory. A missing or non-executable file, an exit with a status,
+ * or any other signal (a crash: SIGSEGV, SIGABRT) is an answer. */
export function inconclusiveFailure(error: unknown): boolean {
if (!error || typeof error !== "object") return false;
const failure = error as { code?: unknown; killed?: unknown; signal?: unknown };
if (shortageCode(failure)) return true;
if (failure.killed === true && typeof failure.code !== "string") return true;
- return typeof failure.signal === "string" && failure.signal !== "" && typeof failure.code !== "number";
+ return failure.signal === "SIGKILL" && typeof failure.code !== "number";
}
/** The `busy` mark a status read sets on an unavailable status whose check could not finish. */
@@ -36,24 +47,23 @@ export const busyOf = (probe: object): { busy?: true } => ("busy" in probe && pr
/** Whether the program this CLI runs is an executable file on the PATH engines are started with: a look at the file, never a
* process. */
-export function cliPresent(cli: string, platform: NodeJS.Platform = process.platform, find: (name: string) => string[] = findCliCandidates): boolean {
- const program = splitCliString(cli)[0];
- if (!program) return false;
- for (const candidate of find(program)) {
- try {
- if (!statSync(candidate).isFile()) continue;
- accessSync(candidate, platform === "win32" ? constants.F_OK : constants.X_OK);
- return true;
- } catch {}
+export function cliPresent(cli: string, platform: NodeJS.Platform = process.platform, find: (cli: string) => string | null = (one) => cliProgramFile(one)): boolean {
+ const file = find(cli);
+ if (!file) return false;
+ try {
+ accessSync(file, platform === "win32" ? constants.F_OK : constants.X_OK);
+ return true;
+ } catch {
+ return false;
}
- return false;
}
-/** What a check that could not finish leaves recorded: the last status that said the engine was there; else, when its
- * program file is there, installed but unverified; else not installed. */
+/** What a check that could not finish leaves recorded: the last status that said the engine was there, while its program
+ * file is still there (a saved status never brings back a deleted engine); else, when the file is there, installed but
+ * unverified; else not installed. */
export function heldSnapshot(before: ProviderSnapshot | undefined, now: ProviderSnapshot, present: () => boolean | null): ProviderSnapshot {
- if (before?.state === "available") return before;
const file = present();
+ if (before?.state === "available" && file !== false) return before;
if (file === true) return { state: "available", unverified: true, ...(before?.version ? { version: before.version } : {}) };
if (file === false) {
const { busy: _busy, ...missing } = now;
diff --git a/server/harness/registry-probe-hold.test.ts b/server/harness/registry-probe-hold.test.ts
index da4bd9fd1f..6675011897 100644
--- a/server/harness/registry-probe-hold.test.ts
+++ b/server/harness/registry-probe-hold.test.ts
@@ -10,7 +10,9 @@ import type { ProviderSnapshot, RuntimeEvent } from "../contracts.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { makeFakeDriver, type FakeDriverHandle, type FakeDriverOptions } from "../testing/fake-driver.ts";
import { STATUS_SAVE_DELAY_MS } from "./engine-status-file.ts";
-import { PROBE_RETRY_MS, TURN_PROOF_MS } from "./probe-hold.ts";
+import { PERSON_CHECK_MS, PROBE_RETRY_MS, PROMPT_RETRY_MS, STATUS_STALE_MS, TURN_PROOF_MS } from "./probe-hold.ts";
+import { readyToRun, selectDefaultModelSelection } from "../default-model-selection.ts";
+import { probeUnsettled } from "../cli-program.ts";
import { ENGINE_LIST_REUSE_MS, ProviderRegistry, SNAPSHOT_DEADLINE_MS } from "./registry.ts";
const SIGNED_IN = { state: "available", version: "1.2.3", authenticated: true } as const satisfies ProviderSnapshot;
@@ -62,6 +64,19 @@ describe("a status check that could not finish", () => {
expect(noEngines(await registry.describe())).toBe(false);
});
+ it("marks the CLI unsettled until a check answers, so no kept answer stands in for the check again", async () => {
+ const { registry, opts, listed } = await engine(SIGNED_IN);
+ await listed();
+ opts.answer = TIMED_OUT;
+ registry.forgetSnapshots();
+ await listed();
+ expect(probeUnsettled("opencode")).toBe(true);
+ opts.answer = SIGNED_IN;
+ registry.forgetSnapshots();
+ await listed();
+ expect(probeUnsettled("opencode")).toBe(false);
+ });
+
it("first ever, with the program file there: installed but unverified, never missing", async () => {
const present = vi.fn(() => true);
const { listed } = await engine(TIMED_OUT, { cliPresent: present });
@@ -97,28 +112,64 @@ describe("a status check that could not finish", () => {
expect(await read).toEqual(SIGNED_IN);
});
- it("is checked again later, backing off, and a check that answers ends the retries", async () => {
+ it("is checked again later, backing off; on a calm machine the third that cannot finish is its answer", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
const { registry, opts, listed, probes } = await engine(SIGNED_IN);
await listed();
opts.answer = TIMED_OUT;
- registry.forgetSnapshots();
- await listed();
+ await vi.advanceTimersByTimeAsync(PERSON_CHECK_MS);
+ expect(await listed()).toEqual(SIGNED_IN);
expect(probes()).toBe(2);
await vi.advanceTimersByTimeAsync(PROBE_RETRY_MS[0]);
expect(probes()).toBe(3);
+ expect(registry.knownSnapshot("opencode")).toEqual(SIGNED_IN);
await vi.advanceTimersByTimeAsync(PROBE_RETRY_MS[0]);
expect(probes()).toBe(3); // the next waits longer
await vi.advanceTimersByTimeAsync(PROBE_RETRY_MS[1] - PROBE_RETRY_MS[0]);
expect(probes()).toBe(4);
-
- opts.answer = NOT_FOUND;
- await vi.advanceTimersByTimeAsync(PROBE_RETRY_MS[2]);
- expect(probes()).toBe(5);
- expect(registry.knownSnapshot("opencode")).toEqual(NOT_FOUND);
+ // A hang or a kill every time on a calm machine is a broken engine, not a starved one.
+ expect(registry.knownSnapshot("opencode")).toEqual({ state: "unavailable", reason: TIMED_OUT.reason });
await vi.advanceTimersByTimeAsync(PROBE_RETRY_MS[4] * 2);
- expect(probes()).toBe(5);
+ expect(probes()).toBe(4);
+ // Once taken as broken, it stays so through the next check that cannot finish, until one answers.
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await listed()).toEqual({ state: "unavailable", reason: TIMED_OUT.reason });
+ opts.answer = SIGNED_IN;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await listed()).toEqual(SIGNED_IN);
+ });
+
+ it("on a pressed machine it is never taken as broken, and is checked anyway at the back-off's last step", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
+ let pressed = false;
+ const { opts, listed, probes, registry } = await engine(SIGNED_IN, { pressed: () => pressed });
+ await listed();
+ opts.answer = TIMED_OUT;
+ pressed = true;
+ await vi.advanceTimersByTimeAsync(PERSON_CHECK_MS);
+ await listed();
+ expect(probes()).toBe(2);
+ const lastStep = PROBE_RETRY_MS.slice(0, PROBE_RETRY_MS.length - 1).reduce((sum, ms) => sum + ms, 0);
+ await vi.advanceTimersByTimeAsync(lastStep - 1);
+ expect(probes()).toBe(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(probes()).toBe(3);
+ expect(registry.knownSnapshot("opencode")).toEqual(SIGNED_IN);
+ });
+
+ it("after the person's own change, a check that cannot finish is tried again promptly, pressed or not", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
+ const SIGNED_OUT = { ...SIGNED_IN, authenticated: false } as const;
+ const { registry, opts, listed, probes } = await engine(SIGNED_OUT, { pressed: () => true });
+ await listed();
+ opts.answer = TIMED_OUT;
+ registry.forgetSnapshots(); // the person signed in
+ expect(await listed()).toEqual(SIGNED_OUT);
+ opts.answer = SIGNED_IN;
+ await vi.advanceTimersByTimeAsync(PROMPT_RETRY_MS);
+ expect(probes()).toBe(3);
+ expect(registry.knownSnapshot("opencode")).toEqual(SIGNED_IN);
});
it("a sign-out read on a pressed machine is checked once more, pressed or not, then believed", async () => {
@@ -149,15 +200,29 @@ describe("a status check that could not finish", () => {
await vi.advanceTimersByTimeAsync(STATUS_SAVE_DELAY_MS);
await first.registry.disposeAll();
- const second = await engine(TIMED_OUT, { statusFile: file, cliPresent: () => false });
+ const second = await engine(TIMED_OUT, { statusFile: file, pressed: () => true });
const { engines } = await second.registry.readAtStart();
expect(engines.find((row) => row.instanceId === "opencode")!.snapshot).toEqual(SIGNED_IN);
expect(await second.listed()).toEqual(SIGNED_IN);
await vi.advanceTimersByTimeAsync(STATUS_SAVE_DELAY_MS);
- const third = await engine(TIMED_OUT, { statusFile: file, cliPresent: () => false });
+ const third = await engine(TIMED_OUT, { statusFile: file, pressed: () => true });
await third.registry.readAtStart();
expect(third.registry.knownSnapshot("opencode")).toEqual(SIGNED_IN);
+ await third.registry.disposeAll();
+
+ // The saved status never brings back an engine whose program was deleted meanwhile.
+ const deleted = await engine(TIMED_OUT, { statusFile: file, pressed: () => true, cliPresent: () => false });
+ await deleted.registry.readAtStart();
+ expect(deleted.registry.knownSnapshot("opencode")).toEqual({ state: "unavailable", reason: TIMED_OUT.reason });
+ });
+
+ it("an engine only found installed is never chosen to run, as a default, or as a backup", async () => {
+ const { registry } = await engine(TIMED_OUT);
+ const rows = await registry.describe();
+ expect(rows[0]!.snapshot).toEqual({ state: "available", unverified: true });
+ expect(readyToRun({ ...rows[0]!, enabled: true })).toBe(false);
+ expect(selectDefaultModelSelection(rows.map((row) => ({ ...row, enabled: true })))).toEqual({ instanceId: "", model: "" });
});
});
@@ -190,7 +255,7 @@ describe("checks that can wait", () => {
expect(probes()).toBe(2);
});
- it("do not run while the machine is pressed", async () => {
+ it("do not run while the machine is pressed, until the last answer is STATUS_STALE_MS old", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
let pressed = false;
const { registry, probes } = await engine(SIGNED_IN, { pressed: () => pressed });
@@ -199,7 +264,7 @@ describe("checks that can wait", () => {
vi.setSystemTime(Date.now() + ENGINE_LIST_REUSE_MS);
await reused(registry);
expect(probes()).toBe(1);
- pressed = false;
+ vi.setSystemTime(Date.now() + STATUS_STALE_MS - ENGINE_LIST_REUSE_MS);
await reused(registry);
expect(probes()).toBe(2);
});
@@ -207,10 +272,10 @@ describe("checks that can wait", () => {
it("a retry that comes due while the machine is pressed waits for another", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
let pressed = false;
- const { registry, opts, listed, probes } = await engine(SIGNED_IN, { pressed: () => pressed });
+ const { opts, listed, probes } = await engine(SIGNED_IN, { pressed: () => pressed });
await listed();
opts.answer = TIMED_OUT;
- registry.forgetSnapshots();
+ await vi.advanceTimersByTimeAsync(5_000);
await listed();
pressed = true;
await vi.advanceTimersByTimeAsync(PROBE_RETRY_MS[0]);
diff --git a/server/harness/registry.ts b/server/harness/registry.ts
index 049e70c74c..a9e107a121 100644
--- a/server/harness/registry.ts
+++ b/server/harness/registry.ts
@@ -8,7 +8,11 @@ import { engineMemory as memoryGate, withEngineMemory } from "../engine-memory.t
import { withEngineHomes } from "../engine-homes/engine-homes.ts";
import { withLocalContext } from "../drivers/local-inject.ts";
import { engineStatusFile, snapshotFrom } from "./engine-status-file.ts";
-import { cliPresent, heldSnapshot, inconclusiveFailure, PROBE_QUEUE_WAIT_MS, PROBE_RETRY_MS, turnActivity } from "./probe-hold.ts";
+import {
+ CALM_FAILURES_BELIEVED, cliPresent, heldSnapshot, inconclusiveFailure, PERSON_CHECK_MS, PROBE_QUEUE_WAIT_MS, PROBE_RETRY_MS, PROMPT_RETRIES, PROMPT_RETRY_MS,
+ STATUS_STALE_MS, turnActivity,
+} from "./probe-hold.ts";
+import { noteProbeUnsettled } from "../cli-program.ts";
import { withUnaskedStops } from "./unasked-stop.ts";
import { withTurnScope } from "../crash-guard.ts";
import { withWslNotice } from "./wsl-launch.ts";
@@ -156,7 +160,14 @@ export class ProviderRegistry {
private readonly small: () => boolean;
private readonly cliPresent: (cli: string) => boolean;
/** Engines whose last check could not finish: how many times in a row, and the check again that is due. */
- private readonly retries = new Map<InstanceId, { attempt: number; timer?: NodeJS.Timeout; signOut?: true }>();
+ /** `calm`: checks in a row that could not finish while the machine was not pressed; `since`: the first of them; `prompt`:
+ * prompt checks again spent after the person's own change. */
+ private readonly retries = new Map<InstanceId, { attempt: number; timer?: NodeJS.Timeout; signOut?: true; calm: number; since: number; prompt: number }>();
+ /** When the last change that may alter an engine's status was made (forgetSnapshots: an install, a sign-in, a key). */
+ private changedAt = -Infinity;
+ /** Engines whose checks failed to finish CALM_FAILURES_BELIEVED times on a calm machine: one more such check is believed
+ * at once, until a check answers. */
+ private readonly calmBroken = new Set<InstanceId>();
private readonly turns = new Map<InstanceId, { activity: ReturnType<typeof turnActivity>; off: () => void }>();
private probeQueue: Promise<void> = Promise.resolve();
/** Whether a turn under way puts off its engine's checks that can wait (where turns wait for room); off unless given. */
@@ -306,18 +317,28 @@ export class ProviderRegistry {
}
/** After a check that could not finish: one more, later, backing off; a turn or a pressed machine puts it off again. */
+ private retryEntry(instanceId: InstanceId) {
+ const entry = this.retries.get(instanceId) ?? { attempt: 0, calm: 0, since: Date.now(), prompt: 0 };
+ this.retries.set(instanceId, entry);
+ return entry;
+ }
+
+ /** Put off by a pressed machine or a turn only up to a point: never past the back-off's last step, nor once the status is
+ * STATUS_STALE_MS old. After the person's own change the check is tried again promptly, pressed or not, a few times. */
private retryLater(instance: ProviderInstance, signOut = false): void {
- const entry = this.retries.get(instance.instanceId) ?? { attempt: 0 };
- this.retries.set(instance.instanceId, entry);
+ const entry = this.retryEntry(instance.instanceId);
if (signOut) entry.signOut = true;
if (entry.timer) return;
+ const prompt = Date.now() - this.changedAt < PERSON_CHECK_MS && entry.prompt < PROMPT_RETRIES;
+ if (prompt) entry.prompt += 1;
entry.timer = setTimeout(() => {
entry.timer = undefined;
if (this.retries.get(instance.instanceId) !== entry || this.byId.get(instance.instanceId)?.live !== instance) return;
entry.attempt += 1;
- if (!entry.signOut && this.probeDeferred(instance.instanceId)) this.retryLater(instance);
+ const due = prompt || entry.signOut === true || entry.attempt >= PROBE_RETRY_MS.length - 1 || Date.now() - entry.since >= STATUS_STALE_MS;
+ if (!due && this.probeDeferred(instance.instanceId)) this.retryLater(instance);
else void this.read(instance);
- }, PROBE_RETRY_MS[Math.min(entry.attempt, PROBE_RETRY_MS.length - 1)]);
+ }, prompt ? PROMPT_RETRY_MS : PROBE_RETRY_MS[Math.min(entry.attempt, PROBE_RETRY_MS.length - 1)]);
entry.timer.unref?.();
}
@@ -330,6 +351,7 @@ export class ProviderRegistry {
/** Every engine's next status read probes its CLI again: an install, update, sign-in or key change may alter what it reports. */
forgetSnapshots(): void {
this.snapshotGeneration += 1;
+ this.changedAt = Date.now();
this.seeds.clear();
}
@@ -552,9 +574,11 @@ export class ProviderRegistry {
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 (options.reuse.maxAgeMs !== undefined && Date.now() - last.at >= options.reuse.maxAgeMs && !this.probeDeferred(instance.instanceId)) return this.read(instance);
- // A check that can wait does not run during a turn of this engine or while the machine is pressed: the last answer stands.
- if (this.probeDeferred(instance.instanceId)) return Promise.resolve(last.snapshot);
+ // A check that can wait does not run during a turn of this engine or while the machine is pressed: the last answer
+ // stands, until it is STATUS_STALE_MS old.
+ const waits = Date.now() - last.at < STATUS_STALE_MS && this.probeDeferred(instance.instanceId);
+ if (options.reuse.maxAgeMs !== undefined && Date.now() - last.at >= options.reuse.maxAgeMs && !waits) return this.read(instance);
+ if (waits) return Promise.resolve(last.snapshot);
if (Date.now() - last.at >= options.reuse.ms) {
const { changed } = options.reuse;
void this.read(instance).then((snapshot) => { if (JSON.stringify(snapshot) !== JSON.stringify(last.snapshot)) changed(); });
@@ -582,7 +606,17 @@ export class ProviderRegistry {
const holdSignOut = !inconclusive && !signOutHeld && before?.authenticated === true && snapshot.state === "available" && snapshot.authenticated === false
&& (lastRead === undefined || lastRead.generation === generation) && this.pressed();
if (holdSignOut) inconclusive = true;
- if (inconclusive) {
+ // A check that keeps failing to finish on a calm machine is an answer: the engine hangs or is killed, it is not starved.
+ const calm = (this.retries.get(instance.instanceId)?.calm ?? 0) + (inconclusive && !holdSignOut && !this.pressed() ? 1 : 0);
+ const believed = inconclusive && !holdSignOut && (calm >= CALM_FAILURES_BELIEVED || (calm > 0 && this.calmBroken.has(instance.instanceId)));
+ if (!inconclusive) this.calmBroken.delete(instance.instanceId);
+ if (believed) {
+ inconclusive = false;
+ this.calmBroken.add(instance.instanceId);
+ const { busy: _busy, ...failed } = snapshot;
+ snapshot = { ...failed, state: "unavailable" };
+ this.log(`engines: ${instance.instanceId}'s status check failed to finish ${calm} times in a row on a calm machine; taken as its answer`);
+ } else if (inconclusive) {
const cli = this.cliTarget(instance.instanceId)?.cli;
snapshot = heldSnapshot(before, snapshot, () => (cli ? this.cliPresent(cli) : null));
this.log(`engines: ${instance.instanceId}'s status check gave no clear answer; ${snapshot === before ? "keeping its last status"
@@ -591,7 +625,12 @@ export class ProviderRegistry {
if (answered || inconclusive) this.readsOf.set(instance, { snapshot, at: Date.now(), generation });
// 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) {
- if (inconclusive) this.retryLater(instance, holdSignOut); else this.stopRetry(instance.instanceId);
+ if (inconclusive) {
+ this.retryEntry(instance.instanceId).calm = calm;
+ this.retryLater(instance, holdSignOut);
+ } else this.stopRetry(instance.instanceId);
+ const cli = this.cliTarget(instance.instanceId)?.cli;
+ if (cli) noteProbeUnsettled(cli, inconclusive && !holdSignOut);
this.lastSnapshots.set(instance.instanceId, snapshot);
this.unread?.delete(instance.instanceId);
this.saveStatus();
diff --git a/server/thread-model.ts b/server/thread-model.ts
index 99b1fd2fc5..4111d46ac7 100644
--- a/server/thread-model.ts
+++ b/server/thread-model.ts
@@ -1,6 +1,6 @@
// A model missing from its engine's catalog is no reason to fall back: engines run IDs their catalog does not list.
import type { ModelSelection } from "./contracts.ts";
-import { readyToRun, signedOut, type DefaultSelectionContext, type SelectableInstance } from "./default-model-selection.ts";
+import { confirmedAvailable, readyToRun, signedOut, type DefaultSelectionContext, type SelectableInstance } from "./default-model-selection.ts";
import { sameModelSelection } from "../shared/thread-model.ts";
export type ThreadEngine = SelectableInstance & { enabled: boolean };
@@ -12,7 +12,7 @@ export interface ThreadModelContext extends DefaultSelectionContext {
}
function canRunOn(engine: ThreadEngine | undefined, selection: ModelSelection, context: ThreadModelContext): engine is ThreadEngine {
- return Boolean(engine?.enabled) && engine!.snapshot.state === "available" && context.refusal?.(engine!) === undefined &&
+ return Boolean(engine?.enabled) && confirmedAvailable(engine!) && context.refusal?.(engine!) === undefined &&
context.allows?.(selection) !== false;
}
diff --git a/src/App.engine-status.test.ts b/src/App.engine-status.test.ts
index 78119b80e0..6656fcfaae 100644
--- a/src/App.engine-status.test.ts
+++ b/src/App.engine-status.test.ts
@@ -62,7 +62,7 @@ it("offers AI setup when there is no conversation and every engine is unavailabl
}
});
-it("keeps the setup page away for an engine that worked earlier on this page, whose status check later fails", () => {
+it("keeps the setup page away for an engine that worked earlier on this page while its checks cannot finish, not after a real loss", () => {
vi.stubGlobal("fetch", () => new Promise(() => {}));
const claude = (snapshot: AppState["instances"][number]["snapshot"]) => ({ instanceId: "claude", driverKind: "claudeAgent", displayName: "Claude", models: { default: "", options: [] }, snapshot });
state = { ...initialState, connected: true, hydrated: true, instances: [claude({ state: "available", authenticated: true })] };
@@ -71,11 +71,13 @@ it("keeps the setup page away for an engine that worked earlier on this page, wh
const root = createRoot(container);
try {
flushSync(() => root.render(createElement(App)));
- for (const snapshot of [{ state: "unavailable", reason: "CLI probe timed out", busy: true }, { state: "unavailable", reason: "CLI probe timed out" }] as const) {
- state = { ...state, instances: [claude(snapshot)] };
- flushSync(() => root.render(createElement(App)));
- expect(container.textContent).not.toContain("Check again");
- }
+ state = { ...state, instances: [claude({ state: "unavailable", reason: "CLI probe timed out", busy: true })] };
+ flushSync(() => root.render(createElement(App)));
+ expect(container.textContent).not.toContain("Check again");
+ // A check that answered "not installed" is a real loss: the setup page shows.
+ state = { ...state, instances: [claude({ state: "unavailable", reason: "`claude` CLI not found" })] };
+ flushSync(() => root.render(createElement(App)));
+ expect(container.textContent).toContain("Check again");
} finally {
root.unmount();
container.remove();
diff --git a/src/components/EngineLibrary.tsx b/src/components/EngineLibrary.tsx
index b3c9571d49..bbb40c3e59 100644
--- a/src/components/EngineLibrary.tsx
+++ b/src/components/EngineLibrary.tsx
@@ -9,6 +9,8 @@ import { InstanceProviderMark } from "./ProviderIcons";
import { useStoreActions } from "@/state/store-select";
export function engineReady(instance: InstanceInfo): boolean {
+ // Only found installed while its checks could not finish: its sign-in is not known yet.
+ if (instance.snapshot.unverified === true) return false;
if (instance.driverKind === "clineAgent") {
return instance.snapshot.state === "available" && instance.snapshot.authenticated === true;
}
diff --git a/src/lib/onboarding.test.ts b/src/lib/onboarding.test.ts
index 320f0eb759..cb0363e1d6 100644
--- a/src/lib/onboarding.test.ts
+++ b/src/lib/onboarding.test.ts
@@ -339,15 +339,21 @@ describe("the no-AI setup page", () => {
expect(noEnginesDue({ connected: true, instances: [row({ state: "available", unverified: true })] }, worked)).toBe(false);
});
- it("never for an engine that worked earlier since the page loaded", () => {
+ it("never for an engine that worked earlier since the page loaded, until a check finds it missing", () => {
const worked = new Set<string>();
expect(noEnginesDue({ connected: true, instances: [row({ state: "available" }, "opencode")] }, worked)).toBe(false);
- expect(noEnginesDue({ connected: true, instances: [row({ state: "unavailable", reason: "gone" } as never, "opencode")] }, worked)).toBe(false);
- expect(workedEarlier(row({ state: "unavailable" }, "opencode"), worked)).toBe(true);
+ expect(workedEarlier(row({ state: "unavailable", busy: true }, "opencode"), worked)).toBe(true);
expect(workedEarlier(row({ state: "unavailable" }, "codex"), worked)).toBe(false);
expect(noEnginesDue({ connected: true, instances: [row({ state: "unavailable" }, "codex")] }, worked)).toBe(true);
+ // A check that answered "not there" is a real loss: the setup page may show again.
+ expect(noEnginesDue({ connected: true, instances: [row({ state: "available" }, "kimi")] }, worked)).toBe(false);
+ expect(noEnginesDue({ connected: true, instances: [row({ state: "unavailable", busy: true }, "kimi")] }, worked)).toBe(false);
+ expect(noEnginesDue({ connected: true, instances: [row({ state: "unavailable" }, "kimi")] }, worked)).toBe(true);
+ // Only found installed is not "worked".
+ expect(workedEarlier(row({ state: "available", unverified: true }, "pi"), worked)).toBe(false);
// Another place, after the connection dropped: its own engines decide.
- expect(noEnginesDue({ connected: false, instances: [row({ state: "unavailable" }, "opencode")] }, worked)).toBe(false);
- expect(noEnginesDue({ connected: true, instances: [row({ state: "unavailable" }, "opencode")] }, worked)).toBe(true);
+ expect(workedEarlier(row({ state: "available" }, "grok"), worked)).toBe(true);
+ expect(noEnginesDue({ connected: false, instances: [row({ state: "unavailable", busy: true }, "grok")] }, worked)).toBe(false);
+ expect(workedEarlier(row({ state: "unavailable", busy: true }, "grok"), worked)).toBe(false);
});
});
diff --git a/src/lib/onboarding.ts b/src/lib/onboarding.ts
index ff9891bbdb..2f145c4e70 100644
--- a/src/lib/onboarding.ts
+++ b/src/lib/onboarding.ts
@@ -249,18 +249,20 @@ export function engineMaybeThere(instance: { snapshot: { state: string; busy?: t
return instance.snapshot.state === "available" || instance.snapshot.busy === true;
}
-type EngineRow = { instanceId: string; snapshot: { state: string; busy?: true; authenticated?: boolean } };
+type EngineRow = { instanceId: string; snapshot: { state: string; busy?: true; unverified?: true; authenticated?: boolean } };
/** Engines seen available since this page loaded. */
const workedThisSession = new Set<string>();
/** A fresh page, as a new load starts (tests). */
export const forgetWorkedEngines = (): void => workedThisSession.clear();
-/** Notes the engines available now; true for one that was available earlier since this page loaded. A setup page never
- * replaces a working engine that reads unavailable later: the app's usual waiting view stays while the server checks it
- * again. */
+/** Notes the engines available now (by a check that answered); true for one that was available earlier since this page
+ * loaded and has not since been found missing. A setup page never replaces a working engine whose later check could not
+ * finish: the app's usual waiting view stays while the server checks it again. */
export function workedEarlier(instance: EngineRow, worked: Set<string> = workedThisSession): boolean {
- if (instance.snapshot.state === "available") worked.add(instance.instanceId);
+ if (instance.snapshot.state === "available" && instance.snapshot.unverified !== true) worked.add(instance.instanceId);
+ // A check that answered "not there" is a real loss: the setup page may show again.
+ else if (instance.snapshot.state !== "available" && instance.snapshot.busy !== true) worked.delete(instance.instanceId);
return worked.has(instance.instanceId);
}