Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
At a usage limit, switch only to a backup the person chose
AdityaUmalebd7ecf5bad6c
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.tsindex 436067568b..b1b32570c5 100644--- a/server/host/limit-takeover.test.ts+++ b/server/host/limit-takeover.test.ts@@ -62,36 +62,45 @@ function takeover(overrides: Partial<LimitTakeoverDeps> = {}, dir = freshDir())}describe("which AI carries on while one is limited", () => {- it("never picks an AI that bills each use by itself, only as a backup the person chose", () => {+ it("carries on only with a backup the person chose, one that bills each use included", () => {const apiClaude = engine("claude-api", "claudeAgent", ["claude-opus-5-5"], { access: "api" });const keyedClaude = engine("claude-key", "claudeAgent", ["claude-opus-5-5"]);const keyed = { "claude-key": { environment: { ANTHROPIC_API_KEY: "sk-ant-fixture" } } } as unknown as InstanceConfigMap;expect(takeover({ engines: () => [CODEX, apiClaude] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);expect(takeover({ engines: () => [CODEX, keyedClaude], configs: () => keyed }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);- expect(takeover({ engines: () => [CODEX, apiClaude, GO] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("opencode", "go-default")]);+ expect(takeover({ engines: () => [CODEX, apiClaude, GO] }).instance.backups("kai", on("codex", "gpt-6")), "nor one on a plan").toEqual([]);expect(takeover({ engines: () => [CODEX, apiClaude], chosen: () => [on("claude-api", "claude-opus-5-5")] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("claude-api", "claude-opus-5-5")]);});- it("takes the backups the person chose first, then the AI a new bot would get, and never the limited AI", () => {- const { instance } = takeover({ chosen: () => [on("opencode", "go-default"), on("codex", "gpt-6-mini")] });+ it("takes the backups the person chose, in their order, and never the limited AI", () => {+ const { instance } = takeover({ chosen: () => [on("opencode", "go-default"), on("codex", "gpt-6-mini"), on("claude", "claude-opus-5-5")] });expect(instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("opencode", "go-default"), on("claude", "claude-opus-5-5")]);- expect(takeover().instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("claude", "claude-opus-5-5")]);+ });++ it("picks no other AI by itself: with no backup chosen the bot waits for the reset", () => {+ const { instance, told } = takeover({ blockedUntil: (id) => (id === "codex" ? NOW + HOUR : null) });+ expect(instance.backups("kai", on("codex", "gpt-6")), "Claude and OpenCode Go are set up, but not chosen").toEqual([]);+ expect(instance.heldAtStart(KAI, on("codex", "gpt-6")), "the AI is tried as usual and the limit tells the person").toBeNull();+ instance.tell(KAI, on("codex", "gpt-6"), { resetsAt: NOW + HOUR });+ expect(told[0]!.text).toMatch(/^Codex reached its limit until .+, so Kai waits until then: no backup you chose can take over\.$/);});it("for one model's own limit tries that AI's default model first, and never the limited model", () => {- const { instance } = takeover();+ const { instance } = takeover({ chosen: () => [on("codex", "gpt-6")] });expect(instance.backups("kai", on("claude", "claude-sonnet-5"), "model")).toEqual([on("claude", "claude-opus-5-5"), on("codex", "gpt-6")]);expect(instance.backups("kai", on("claude", "claude-opus-5-5"), "credits")).toEqual([on("codex", "gpt-6")]);+ expect(takeover().instance.backups("kai", on("claude", "claude-sonnet-5"), "model"), "the same AI's default model, with no backup chosen").toEqual([on("claude", "claude-opus-5-5")]);});it("leaves out an AI that is signed out, held by its own limit, short of this AI's tools, or another sign-in to the same plan", () => {const signedOut = engine("claude", "claudeAgent", ["claude-opus-5-5"], { snapshot: { state: "available", authenticated: false } });- expect(takeover({ engines: () => [signedOut, CODEX] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);- expect(takeover({ blockedUntil: (id) => (id === "claude" ? NOW + HOUR : null) }).instance.backups("kai", on("codex", "gpt-6")))+ const claudeChosen = { chosen: () => [on("claude", "claude-opus-5-5"), on("opencode", "go-default")] };+ expect(takeover({ engines: () => [signedOut, CODEX], ...claudeChosen }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);+ expect(takeover({ blockedUntil: (id) => (id === "claude" ? NOW + HOUR : null), ...claudeChosen }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("opencode", "go-default")]);const fewerTools = engine("claude", "claudeAgent", ["claude-opus-5-5"], { capabilities: { agentsMcp: true } as unknown as TakeoverEngine["capabilities"] });- expect(takeover({ engines: () => [fewerTools, CODEX] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);+ expect(takeover({ engines: () => [fewerTools, CODEX], ...claudeChosen }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);const secondCodex = engine("codex-2", "codex", ["gpt-6"]);expect(takeover({ engines: () => [CODEX, secondCodex], chosen: () => [on("codex-2", "gpt-6")] }).instance.backups("kai", on("codex", "gpt-6")),"never another sign-in to the same plan").toEqual([]);@@ -112,7 +121,7 @@ describe("a model's own limit", () => {}) as RuntimeEvent;it("holds that model alone until the reset it named, at most six hours, an hour when it named none, and not once it works", () => {- const { instance, now } = takeover();+ const { instance, now } = takeover({ chosen: () => [on("claude", "claude-opus-5-5"), on("opencode", "go-default")] });instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), error("model", NOW + 2 * HOUR));expect(instance.modelHeld(on("claude", "claude-opus-5-5"))).toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });expect(instance.modelHeld(on("claude", "claude-sonnet-5")), "the AI's other models still work").toBeNull();@@ -151,7 +160,7 @@ describe("what the person hears", () => {instance.tell({ id: "rosa", name: "Rosa" }, on("codex", "gpt-6"), { resetsAt });expect(told.map((entry) => entry.bot)).toEqual(["Kai", "Rosa"]);expect(told[0]!.text).toMatch(/^Codex reached its limit until .+, so Kai is using Claude meanwhile\.$/);- expect(told[1]!.text).toMatch(/^Codex reached its limit until .+, so Rosa waits until then: no other AI you have set up can take over\.$/);+ expect(told[1]!.text).toMatch(/^Codex reached its limit until .+, so Rosa waits until then: no backup you chose can take over\.$/);instance.worked("kai", on("codex", "gpt-6"));instance.tell(KAI, on("codex", "gpt-6"), { resetsAt, backup: on("claude", "claude-opus-5-5") });expect(told).toHaveLength(3);@@ -200,7 +209,7 @@ describe("a new conversation once an AI is known to be at its limit", () => {const at = { now: NOW };const boot = () => {const clock = new LimitResetClock({ accounts: () => [], now: () => at.now, file: join(dir, "limit-holds.json") });- const { instance, told } = takeover({ blockedUntil: (id) => clock.blockedUntil(id), resetAt: (id) => clock.resetAt(id), now: () => at.now }, dir);+ const { instance, told } = takeover({ blockedUntil: (id) => clock.blockedUntil(id), resetAt: (id) => clock.resetAt(id), now: () => at.now, chosen: () => [on("codex", "gpt-6")] }, dir);return { clock, instance, told };};return { at, boot };@@ -261,10 +270,11 @@ describe("a new conversation once an AI is known to be at its limit", () => {it("keeps one model's own limit through a restart, and a turn that works on another model leaves it held", () => {const dir = freshDir();- const { instance } = takeover({}, dir);+ const codexChosen = { chosen: () => [on("codex", "gpt-6")] };+ const { instance } = takeover(codexChosen, dir);instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), event("t1", "runtime.error", { message: "limit", limit: "model", limitResetsAt: NOW + 2 * HOUR }));instance.noteRuntimeEvent("kai", on("claude", "claude-sonnet-5"), event("t2", "turn.completed", { ok: true }));- const restarted = takeover({}, dir).instance;+ const restarted = takeover(codexChosen, dir).instance;expect(restarted.modelHeld(on("claude", "claude-opus-5-5"))).toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });expect(restarted.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "model", resetsAt: NOW + 2 * HOUR });});@@ -419,7 +429,7 @@ it("sends a signed-out AI's turns only to the backups a turn its AI never starteconst event = (type: string, extra: Record<string, unknown> = {}) =>({ eventId: "e", provider: "claudeAgent", createdAt: new Date(NOW).toISOString(), threadId: "t1", type, ...extra }) as RuntimeEvent;let startup: ModelSelection[] = [];- const { instance } = takeover({ chosen: () => [on("codex", "gpt-6")], signedOutChosen: () => startup });+ const { instance } = takeover({ chosen: () => [on("opencode", "go-default")], signedOutChosen: () => startup });instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), event("turn.completed", { ok: false, stopReason: "auth_required" }));expect(instance.backups("kai", on("claude", "claude-opus-5-5"), "signed-out"), "Automatic recovery off and no list of the bot's own").toEqual([]);expect(instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toBeNull();diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.tsindex d71b120dc7..433383aa4f 100644--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@ -1,6 +1,6 @@import { type ServerToolText } from "../../shared/server-text.ts";-// When the AI a bot runs on reaches its usage limit, or is signed out, the bot carries on with another AI the person has-// set up until that limit resets or the AI is signed in again, without anyone being asked, and the person hears it once+// When the AI a bot runs on reaches its usage limit, or is signed out, the bot carries on with a backup the person chose+// until that limit resets or the AI is signed in again, without anyone being asked, and the person hears it once// for that stretch. What is held (an engine's limit on the reset clock, one model's own limit, a sign-in that expired)// is saved, so every new turn and thread of every bot starts on the AI that carries on, a restart included.import { readFileSync } from "node:fs";@@ -9,10 +9,10 @@ import { approvalModeFor, modelSwitchNeedsAsk, type ApprovalMode } from "../../simport { writeFileAtomic } from "../atomic.ts";import { recoveryCapabilityError } from "../automatic-recovery.ts";import type { InstanceConfigMap, ProviderAdapter, RuntimeEvent } from "../contracts.ts";-import { readyToRun, selectDefaultModelSelection, type DefaultSelectionContext, type SelectableInstance } from "../default-model-selection.ts";+import { readyToRun, type DefaultSelectionContext, type SelectableInstance } from "../default-model-selection.ts";import { engineFailureKind } from "../drivers/engine-errors.ts";import { classifyError } from "../drivers/retry.ts";-import { billsEachUse, failoverLine, limitBackupAllowed, signedOutLine, type LimitFailover } from "../limit-failover.ts";+import { failoverLine, limitBackupAllowed, signedOutLine, type LimitFailover } from "../limit-failover.ts";import { LimitNotices, limitNoticeText, signedOutNoticeText } from "../limit-notices.ts";import { UNNAMED_LIMIT_MS } from "../limit-resets.ts";import type { ModelSelection } from "../../shared/wire.ts";@@ -175,9 +175,8 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {};/** The AIs that may carry on while `from` is limited or signed out, best first: for one model's limit the same AI's own- * default model, then the backups the person chose, then (for a limit) the AI MausBot would pick for a new bot among- * the rest that draw on a plan. One that bills each use spends the person's money, so it carries on only as a backup- * they chose; a signed-out AI's turns go only to a backup they chose. `approval`: the thread's level, when known. */+ * default model, then the backups the person chose. No other AI is picked for them: with none of those usable the bot+ * waits for the reset or a sign-in. `approval`: the thread's level, when known. */function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): ModelSelection[] {const engines = deps.engines();const current = engines.find((engine) => engine.instanceId === from.instanceId);@@ -190,11 +189,6 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {};if (scope === "model" || scope === "credits") add({ instanceId: current.instanceId, model: current.models.default });for (const selection of scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? deps.chosen(botId) : deps.chosen(botId)) add(selection);- if (scope === "signed-out") return out;- const others = engines.filter((engine) => engine.instanceId !== from.instanceId && engine.access !== "api" && !billsEachUse(deps.configs()[engine.instanceId])- && usable(engines, current, { instanceId: engine.instanceId, model: engine.models.default }, scope, approval));- const pick = selectDefaultModelSelection(others, undefined, deps.context);- if (pick.instanceId && pick.model) add(pick);return out;}diff --git a/server/limit-notices.test.ts b/server/limit-notices.test.tsindex f86c0b10b6..c4648893c8 100644--- a/server/limit-notices.test.ts+++ b/server/limit-notices.test.ts@@ -81,8 +81,8 @@ describe("the notice", () => {expect(limitNoticeText({ engine: "Codex", bot: "Kai", backup: "Claude" })).toBe("Codex reached its limit, so Kai is using Claude meanwhile.");expect(limitNoticeText({ engine: "Claude claude-opus-5-5", bot: "Iris", credits: true, backup: "Claude claude-sonnet-5" })).toBe("Claude claude-opus-5-5's extra usage credits are used up, so Iris is using Claude claude-sonnet-5 meanwhile.");- expect(limitNoticeText({ engine: "Codex", bot: "Kai" })).toBe("Codex reached its limit, so Kai waits: no other AI you have set up can take over.");+ expect(limitNoticeText({ engine: "Codex", bot: "Kai" })).toBe("Codex reached its limit, so Kai waits: no backup you chose can take over.");expect(limitNoticeText({ engine: "Claude claude-opus-5-5", bot: "Iris", credits: true, resetsAt: Date.now() + 86_400_000 }))- .toBe("Claude claude-opus-5-5's extra usage credits are used up, so Iris waits: no other AI you have set up can take over.");+ .toBe("Claude claude-opus-5-5's extra usage credits are used up, so Iris waits: no backup you chose can take over.");});});diff --git a/server/limit-notices.ts b/server/limit-notices.tsindex d07865ddbc..6e330ed088 100644--- a/server/limit-notices.ts+++ b/server/limit-notices.ts@@ -31,8 +31,8 @@ export function limitNoticeText(facts: LimitNoticeFacts, timeZone?: string): strconst what = facts.credits ? `${facts.engine}'s extra usage credits are used up` : `${facts.engine} reached its limit${until}`;if (facts.backup) return `${what}, so ${facts.bot} is using ${facts.backup} meanwhile.`;return facts.resetsAt && !facts.credits- ? `${what}, so ${facts.bot} waits until then: no other AI you have set up can take over.`- : `${what}, so ${facts.bot} waits: no other AI you have set up can take over.`;+ ? `${what}, so ${facts.bot} waits until then: no backup you chose can take over.`+ : `${what}, so ${facts.bot} waits: no backup you chose can take over.`;}/** "Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.", and who carries on meanwhilediff --git a/server/limit-reset.e2e.test.ts b/server/limit-reset.e2e.test.tsindex 23a8dc9036..c09fcbcc92 100644--- a/server/limit-reset.e2e.test.ts+++ b/server/limit-reset.e2e.test.ts@@ -259,7 +259,7 @@ it("a turn that works on the engine afterwards ends a refusal's hold long before});}, 120_000);-it("with nothing set up for it, carries the person's request on with another AI they have, says so once, and goes back after the reset", async () => {+it("with another AI set up but no backup chosen, the bot waits for the reset: one notice, nothing sent to that AI, back to work once it resets", async () => {await withLimitFixture({}, async ({ api, control, limit, lift, claudePrompts, evidence }) => {const resetsAt = Math.floor(Date.now() / 1000) + 25;limit(resetsAt);@@ -267,38 +267,30 @@ it("with nothing set up for it, carries the person's request on with another AIconst threadId = bot.activeTaskId;const claudeModel = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).modelSelection;await control("send", "--bot", bot.id, "--task", threadId, "--text", "Draft the launch plan");- const reply = async (id: string) => (await messagesOf(api, id)).findLast((message) => message.role === "bot" && message.kind === "text")?.text;- await expect.poll(() => reply(threadId), { timeout: 40_000 }).toBe("done from fake codex");+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("failed");const first = await messagesOf(api, threadId);- expect(first.map((message) => message.tool?.name)).toContain("notice: continuing on Codex after hitting the usage limit");+ expect(recoveryLines(first)).toEqual([]);+ expect(first.filter((message) => message.role === "user")).toHaveLength(1);const task = async (id: string) => (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).tasks.find((entry: any) => entry.threadId === id);- expect((await task(threadId)).modelSelection).toEqual(codex);+ expect((await task(threadId)).modelSelection ?? claudeModel).toEqual(claudeModel);const notified = async () => (await api("GET", "/api/notifications")).notifications as any[];await expect.poll(async () => (await notified()).filter((entry) => entry.kind === "notice").length, { timeout: 10_000 }).toBe(1);- expect((await notified()).find((entry) => entry.kind === "notice").body).toMatch(/^Verification fixture reached its limit until .+, so Kai is using Codex meanwhile\.$/);- expect((await notified()).filter((entry) => entry.kind === "incident" || entry.kind === "turn-failed"), "one notice, never an incident").toEqual([]);-- // Known to be refusing: another conversation goes to Codex without spending a refused turn on Claude, and no new notice.- const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });- await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");- expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");- expect(recoveryLines(await messagesOf(api, other.threadId))).toEqual([expect.stringMatching(/so Codex took over\.$/)]);- expect(claudePrompts()).toHaveLength(1);- expect((await notified()).filter((entry) => entry.kind === "notice")).toHaveLength(1);+ expect((await notified()).find((entry) => entry.kind === "notice").body).toMatch(/^Verification fixture reached its limit until .+, so Kai waits until then: no backup you chose can take over\.$/);lift();await expect.poll(() => Date.now() > resetsAt * 1000 + 500, { timeout: 40_000, interval: 500 }).toBe(true);await control("send", "--bot", bot.id, "--task", threadId, "--text", "Now polish it");expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");- expect((await task(threadId)).modelSelection).toEqual(claudeModel);- expect(recoveryLines(await messagesOf(api, threadId))).toContain("recovery: Verification fixture's limit has reset, so this conversation is back on Verification fixture.");- expect(await reply(threadId)).toBe("hello from fake claude");+ const reply = (await messagesOf(api, threadId)).findLast((message) => message.role === "bot" && message.kind === "text")?.text;+ expect(reply).toBe("hello from fake claude");+ expect(claudePrompts()).toHaveLength(2);+ expect((await notified()).filter((entry) => entry.kind === "notice"), "the person heard it once").toHaveLength(1);evidence.push({ first, notices: await notified() });});}, 150_000);it("after a restart, a new conversation still starts on the AI that carries on, and the limited Claude is not asked again", async () => {- await withLimitFixture({}, async ({ api, control, limit, claudePrompts, restart, evidence }) => {+ await withLimitFixture({ recovery: { enabled: true, backup: codex } }, async ({ api, control, limit, claudePrompts, restart, evidence }) => {limit(Math.floor(Date.now() / 1000) + 11 * 86_400);const { bot } = await control("new-bot", "--name", "Kai");const threadId = bot.activeTaskId;diff --git a/server/quota-switch.e2e.test.ts b/server/quota-switch.e2e.test.tsindex 4d51a12292..a0a213d55c 100644--- a/server/quota-switch.e2e.test.ts+++ b/server/quota-switch.e2e.test.ts@@ -103,12 +103,16 @@ async function withQuotaFixture(}/** A bot whose conversation runs on the limited engine, and the turn that meets the limit. `carriedOn`: another AI may- * already have taken the request over by the time the wait ends. */-async function meetTheLimit(api: (method: string, path: string, body?: unknown) => Promise<any>, control: (...args: string[]) => Promise<any>, text: string, carriedOn = false) {+ * already have taken the request over by the time the wait ends. `backup`: the AI the person chose as the bot's backup. */+async function meetTheLimit(api: (method: string, path: string, body?: unknown) => Promise<any>, control: (...args: string[]) => Promise<any>, text: string, carriedOn = false, backup?: string) {const { bot } = await control("new-bot", "--name", "Out of quota");const threadId = bot.activeTaskId as string;const limited = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).modelSelection;await api("PATCH", `/api/bots/${bot.id}/tasks/${threadId}`, { modelSelection: { ...limited, instanceId: "claude" }, updateBotDefault: true });+ if (backup) {+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };+ await api("PATCH", `/api/bots/${bot.id}`, { fallback: [{ instanceId: backup, model: instances.find((instance) => instance.instanceId === backup).models.default }] });+ }await control("send", "--bot", bot.id, "--task", threadId, "--text", text);expect(carriedOn ? ["failed", "settled"] : ["failed"]).toContain((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status);const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];@@ -116,34 +120,25 @@ async function meetTheLimit(api: (method: string, path: string, body?: unknown)return { bot, threadId, messages, state };}-it("carries the request on with another AI by itself: the exact message once more there, one notice, the failed root left settled", async () => {- await withQuotaFixture({}, async ({ api, control, backupPrompts, dataDir }) => {+it("carries the request on with the backup the person chose: the exact message there once, the bot's own AI left as it was", async () => {+ await withQuotaFixture({}, async ({ api, control, backupPrompts }) => {const text = "SUMMARISE_THE_QUARTER_4K";- const { bot, threadId, messages, state } = await meetTheLimit(api, control, text, true);+ const { bot, threadId, messages, state } = await meetTheLimit(api, control, text, true, "codex");const { task: sibling } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Sibling keeps its engine" });await expect.poll(async () => (await messages()).findLast((message) => message.role === "bot" && message.kind === "text")?.text, { timeout: 30_000 }).toBe("done from fake codex");const after = await messages();- const failures = after.filter((message) => message.tool?.name?.startsWith("error:"));- expect(failures).toHaveLength(1);- expect(failures[0].tool.name).toMatch(/This Claude account has reached its usage limit/);expect(after.some((message) => message.card?.quotaSwitch), "nothing to answer").toBe(false);- expect(after.filter((message) => message.tool?.name === "notice: continuing on Codex after hitting the usage limit")).toHaveLength(1);- // The message whose turn failed, sent once more: twice in the conversation, once to the AI that works.- expect(after.filter((message) => message.role === "user" && message.text === text)).toHaveLength(2);+ expect(after.filter((message) => message.tool?.name?.startsWith("recovery: Limited Claude hit its limit") && message.tool.name.endsWith("so Codex took over."))).toHaveLength(1);+ expect(after.filter((message) => message.role === "user" && message.text === text)).toHaveLength(1);expect(backupPrompts()).toHaveLength(1);expect(JSON.stringify(backupPrompts()[0])).toContain(text);- // This conversation moved; the bot's own engine and its other conversation did not.+ // The bot's own AI and its other conversation did not move.const bots = await state();- expect(bots.tasks.find((task: any) => task.threadId === threadId)).toMatchObject({ modelSelection: { instanceId: "codex" }, busy: false });expect(bots.modelSelection.instanceId).toBe("claude");expect(bots.tasks.find((task: any) => task.threadId === sibling.threadId).modelSelection?.instanceId ?? bots.modelSelection.instanceId).toBe("claude");- // No job twice: the failed turn's root stayed settled, and the resend is one new root that completed.- expect(readHandoffs(dataDir).filter((node) => node.threadId === threadId).map((node) => [node.status, node.executions])).toEqual([["failed", 1], ["completed", 1]]);- // One notice for this bot; the Chief, told of the incident, hears its own if its own turn meets the limit too.- const notices = (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);- expect(notices.map((entry: any) => entry.body)).toEqual([expect.stringMatching(/^Limited Claude reached its limit.*, so Out of quota is using Codex meanwhile\.$/)]);+ expect(bots.tasks.find((task: any) => task.threadId === threadId)).toMatchObject({ busy: false });});}, 240_000);@@ -153,19 +148,31 @@ it("never moves to another sign-in of the same AI: it says once that the bot waiconst mine = async () => (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);await expect.poll(async () => (await mine()).length, { timeout: 20_000 }).toBe(1);const [notice] = await mine();- expect(notice.body).toMatch(/^Limited Claude reached its limit.*, so Out of quota waits.*: no other AI you have set up can take over\.$/);+ expect(notice.body).toMatch(/^Limited Claude reached its limit.*, so Out of quota waits.*: no backup you chose can take over\.$/);expect((await messages()).filter((entry) => entry.role === "user")).toHaveLength(1);expect((await state()).tasks.find((task: any) => task.threadId === threadId).modelSelection?.instanceId ?? "claude").toBe("claude");expect(backupPrompts()).toHaveLength(0);});}, 240_000);+it("moves nothing when no backup is chosen, though another AI is set up: it says once that the bot waits", async () => {+ await withQuotaFixture({}, async ({ api, control, backupPrompts }) => {+ const { bot, threadId, messages, state } = await meetTheLimit(api, control, "WAIT_FOR_THE_RESET_9Q");+ const mine = async () => (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);+ await expect.poll(async () => (await mine()).length, { timeout: 20_000 }).toBe(1);+ expect((await mine())[0].body).toMatch(/^Limited Claude reached its limit.*, so Out of quota waits.*: no backup you chose can take over\.$/);+ expect((await messages()).filter((message) => message.role === "user")).toHaveLength(1);+ expect((await state()).tasks.find((task: any) => task.threadId === threadId).modelSelection?.instanceId ?? "claude").toBe("claude");+ expect(backupPrompts()).toHaveLength(0);+ });+}, 240_000);+it("moves nothing when OMB_QUOTA_SWITCH=0 switches it off", async () => {await withQuotaFixture({ env: { OMB_QUOTA_SWITCH: "0" } }, async ({ api, control, backupPrompts }) => {const { bot, threadId, messages, state } = await meetTheLimit(api, control, "NO_MOVE_WHEN_OFF_2B");const mine = async () => (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);await expect.poll(async () => (await mine()).length, { timeout: 20_000 }).toBe(1);- expect((await mine())[0].body).toMatch(/, so Out of quota waits.*: no other AI you have set up can take over\.$/);+ expect((await mine())[0].body).toMatch(/, so Out of quota waits.*: no backup you chose can take over\.$/);expect((await messages()).filter((message) => message.role === "user")).toHaveLength(1);expect((await state()).tasks.find((task: any) => task.threadId === threadId).modelSelection?.instanceId ?? "claude").toBe("claude");expect(backupPrompts()).toHaveLength(0);