Skip to content

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

Backups: allow another model on the bot's own account

AdityaUmale960a339dbbea
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 11d0499e0e..a05c60e8e5 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -237,8 +237,9 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
return json(res, 400, { error: "fallback must be a list of up to five { instanceId, model } entries" });
}
if (!registry.get(row.instanceId)) return json(res, 400, { error: `fallback engine "${row.instanceId}" is not available` });
- if (chain.some((seen) => seen.instanceId === row.instanceId)) continue;
- chain.push({ instanceId: row.instanceId, model: row.model.trim() });
+ const model = row.model.trim();
+ if (chain.some((seen) => seen.instanceId === row.instanceId && seen.model === model)) continue;
+ chain.push({ instanceId: row.instanceId, model });
}
patch.fallback = chain;
}
diff --git a/server/trust-controls.e2e.test.ts b/server/trust-controls.e2e.test.ts
index 8c448ca033..7d3b84cb0d 100644
--- a/server/trust-controls.e2e.test.ts
+++ b/server/trust-controls.e2e.test.ts
@@ -609,6 +609,15 @@ it("settles only the source task after approval or Stop, leaving the selected si
}
});
+it("keeps two backups on one account with different models, and drops an exact repeat", async () => {
+ const b = await bot("Same-account backups");
+ const sonnet = { instanceId: "claude", model: "claude-sonnet-5" }, opus = { instanceId: "claude", model: "claude-opus-5" };
+ const saved = await api("PATCH", `/api/bots/${b.id}`, { fallback: [sonnet, opus, { ...sonnet, model: " claude-sonnet-5 " }] });
+ expect(saved.status, JSON.stringify(saved.body)).toBe(200);
+ const fleet = await api("GET", "/api/bots");
+ expect(fleet.body.bots.find((row: any) => row.id === b.id).fallback).toEqual([sonnet, opus]);
+});
+
it("preserves accounts referenced by a fallback chain before delete or credential-directory change", async () => {
const account = await api("POST", "/api/instances/claude-accounts", { displayName: "Fallback fixture account" });
expect(account.status, JSON.stringify(account.body)).toBe(201);
diff --git a/src/components/SimpleModelMenu.tsx b/src/components/SimpleModelMenu.tsx
index bdbc499602..1c6242a2dd 100644
--- a/src/components/SimpleModelMenu.tsx
+++ b/src/components/SimpleModelMenu.tsx
@@ -272,6 +272,7 @@ export function SimpleModelMenu(props: SimpleModelMenuProps) {
<Gutter><InstanceProviderMark instance={group.instance} size={14} subtle /></Gutter>
<span className="min-w-0 truncate">{group.label}</span>
</div>
+ {group.note && <p className={cn(MENU_NOTE, "pl-8 pt-0")}>{group.note}</p>}
<GroupBody group={group} props={props} />
</div>
);
diff --git a/src/components/bot-panel/BackupAis.dom.test.ts b/src/components/bot-panel/BackupAis.dom.test.ts
index b27c0c2a48..44ec61b3ed 100644
--- a/src/components/bot-panel/BackupAis.dom.test.ts
+++ b/src/components/bot-panel/BackupAis.dom.test.ts
@@ -124,6 +124,39 @@ describe("a bot's backup AIs in Simple", () => {
expect(host.querySelector("[data-backup]")?.textContent).toContain("Unavailable");
});
+ it("offers the bot's own account too, without its own model, and says it shares the usage limit", async () => {
+ fixture.instances.splice(0, 1, engine("claude", "Claude", "claudeAgent", [["claude-sonnet-5", "Claude Sonnet 5"], ["claude-opus-5", "Claude Opus 5"]]));
+ render();
+ click(host.querySelector("[data-panel-action=backup-add]"));
+ await settle();
+ expect(providers()).toEqual(["claude", "codex", "gemini"]);
+ expect(menu()!.querySelector('[data-simple-provider="claude"]')?.textContent).toContain("Same account as the main AI: it shares the usage limit.");
+ expect(menu()!.querySelector('[data-simple-provider="codex"]')?.textContent).not.toContain("Same account");
+ expect(modelRow("Claude Sonnet 5")).toBeUndefined();
+ click(modelRow("Claude Opus 5"));
+ expect(onChange).toHaveBeenCalledWith([{ instanceId: "claude", model: "claude-opus-5" }]);
+ });
+
+ it("allows a second backup on one account, never the same model twice", async () => {
+ render([{ instanceId: "codex", model: "gpt-5.5" }]);
+ click(host.querySelector("[data-panel-action=backup-add]"));
+ await settle();
+ expect(providers()).toEqual(["codex", "gemini"]);
+ const labels = [...menu()!.querySelectorAll("[data-menu-row]")].map((row) => row.getAttribute("aria-label") ?? "");
+ expect(labels.filter((label) => label.startsWith("GPT-5.5") && !label.startsWith("GPT-5.5 mini"))).toEqual([]);
+ click(modelRow("GPT-5.5 mini"));
+ expect(onChange).toHaveBeenCalledWith([{ instanceId: "codex", model: "gpt-5.5" }, { instanceId: "codex", model: "gpt-5.5-mini" }]);
+ });
+
+ it("lists two backups on one account as separate rows and removes the right one", () => {
+ render([{ instanceId: "codex", model: "gpt-5.5" }, { instanceId: "codex", model: "gpt-5.5-mini" }]);
+ const rows = host.querySelectorAll("[data-backup]");
+ expect([...rows].map((row) => row.querySelector("[data-panel-action=backup-change]")?.getAttribute("aria-label")))
+ .toEqual(["Backup 1: GPT-5.5", "Backup 2: GPT-5.5 mini"]);
+ click(rows[1]!.querySelector("[data-panel-action=backup-remove]"));
+ expect(onChange).toHaveBeenCalledWith([{ instanceId: "codex", model: "gpt-5.5" }]);
+ });
+
it("closes its menu on Escape without letting the key close the panel", async () => {
render();
click(host.querySelector("[data-panel-action=backup-add]"));
diff --git a/src/components/bot-panel/BackupAis.tsx b/src/components/bot-panel/BackupAis.tsx
index f9e939fcce..c763d711da 100644
--- a/src/components/bot-panel/BackupAis.tsx
+++ b/src/components/bot-panel/BackupAis.tsx
@@ -24,6 +24,8 @@ type Backup = NonNullable<Bot["fallback"]>[number];
export const MAX_BACKUPS = 5;
const NO_SELECTION = { instanceId: "", model: "" };
+/** One model of one account: a bot's backups may share an account, never a model. */
+const modelKey = (instanceId: string, model: string) => `${instanceId}\u0000${model}`;
const NOTHING_PROBED: ReadonlySet<string> = new Set();
function BackupChooser({ bot, current, exclude, onPick, label, title, buttonRef, className, children, ...rest }: {
@@ -107,12 +109,18 @@ function BackupChooser({ bot, current, exclude, onPick, label, title, buttonRef,
};
const menuFor = () => {
- const listed = configuredModelInstances(state.instances, current?.instanceId).filter((instance) => !exclude.has(instance.instanceId));
+ const listed = configuredModelInstances(state.instances, current?.instanceId).flatMap((instance) => {
+ const options = instance.models.options.filter((option) => !exclude.has(modelKey(instance.instanceId, option.id)));
+ if (options.length === instance.models.options.length) return [instance];
+ return options.length ? [{ ...instance, models: { ...instance.models, options } }] : [];
+ });
const built = simpleModelMenu({
instances: state.instances, listed, selection: current ?? NO_SELECTION,
bot: { name: bot.name, selection: bot.modelSelection }, query, expanded, probing: NOTHING_PROBED, loading, refreshing,
});
- return current ? built : { ...built, current: null };
+ const groups = built.groups.map((group) => group.instance.instanceId === bot.modelSelection.instanceId
+ ? { ...group, note: t("botPanel.backups.sameAccount") } : group);
+ return { ...built, groups, ...(current ? {} : { current: null }) };
};
const onMenuKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
@@ -208,8 +216,8 @@ export function BackupAis({ bot, onChange }: { bot: Bot; onChange: (fallback: Ba
const { state } = useStore();
const chain = bot.fallback ?? [];
const addRef = useRef<HTMLButtonElement>(null);
- const others = (except: number | null) =>
- new Set([bot.modelSelection.instanceId, ...chain.filter((_, index) => index !== except).map((entry) => entry.instanceId)]);
+ const others = (except: number | null) => new Set([bot.modelSelection, ...chain.filter((_, index) => index !== except)]
+ .map((entry) => modelKey(entry.instanceId, entry.model)));
const describe = (entry: Backup) => {
const instance = state.instances.find((candidate) => candidate.instanceId === entry.instanceId);
const option = instance?.models.options.find((candidate) => candidate.id === entry.model);
@@ -230,7 +238,7 @@ export function BackupAis({ bot, onChange }: { bot: Bot; onChange: (fallback: Ba
{chain.map((entry, index) => {
const { instance, name, short } = describe(entry);
return (
- <li key={entry.instanceId} data-backup={entry.instanceId} className="flex min-w-0 items-center gap-1.5">
+ <li key={modelKey(entry.instanceId, entry.model)} data-backup={entry.instanceId} className="flex min-w-0 items-center gap-1.5">
<span className="w-3 shrink-0 text-[12px] tabular-nums text-ink-tertiary" aria-hidden="true">{index + 1}</span>
<BackupChooser
bot={bot}
diff --git a/src/components/bot-settings/ModelSection.test.ts b/src/components/bot-settings/ModelSection.test.ts
index c60f8b18f2..a233e4c04b 100644
--- a/src/components/bot-settings/ModelSection.test.ts
+++ b/src/components/bot-settings/ModelSection.test.ts
@@ -63,6 +63,47 @@ describe("a bot's backup models", () => {
recovery.enabled = true;
});
+ const control = (node: ReactNode, label: string): { props: { onChange(event: { target: { value: string } }): void } } | undefined => {
+ if (Array.isArray(node)) return node.map((child) => control(child, label)).find(Boolean);
+ if (!isValidElement(node)) return undefined;
+ const props = node.props as { "aria-label"?: string; children?: ReactNode };
+ return props["aria-label"] === label ? node as never : control(props.children, label);
+ };
+
+ it("offers the main AI's own account for another of its models, never the main model itself", () => {
+ instances.splice(0, 1, engine("primary", "Primary", ["p", "q"]));
+ const markup = renderToStaticMarkup(createElement(FallbackChain, { bot: bot([]), onChange: vi.fn() }));
+ expect(markup).toContain('<option value="primary">Primary · Same account as the main AI: it shares the usage limit.</option>');
+ expect(markup).toContain('<option value="codex">Codex</option>');
+ const onChange = vi.fn();
+ control(FallbackChain({ bot: bot([]), onChange }), "Add a backup AI")!.props.onChange({ target: { value: "primary" } });
+ expect(onChange).toHaveBeenCalledWith([{ instanceId: "primary", model: "q" }]);
+ instances.splice(0, 1, engine("primary", "Primary", ["p"]));
+ });
+
+ it("keeps two backups on one account apart, each offering only models no other backup uses", () => {
+ const chain = [{ instanceId: "codex", model: "gpt-a" }, { instanceId: "codex", model: "gpt-b" }];
+ const markup = renderToStaticMarkup(createElement(FallbackChain, { bot: bot(chain), onChange: vi.fn() }));
+ const pickers = [...markup.matchAll(/<select[^>]*aria-label="Model for Codex"[^>]*>(.*?)<\/select>/g)].map((match) => match[1]);
+ expect(pickers).toHaveLength(2);
+ expect(pickers[0]).toContain('value="gpt-a" selected=""');
+ expect(pickers[0]).not.toContain('value="gpt-b"');
+ expect(markup).not.toContain('<option value="codex">');
+ const onChange = vi.fn();
+ const tree = FallbackChain({ bot: bot(chain), onChange });
+ const removes: Array<{ props: { onClick(): void } }> = [];
+ const collect = (node: ReactNode): void => {
+ if (Array.isArray(node)) return node.forEach(collect);
+ if (!isValidElement(node)) return;
+ const props = node.props as { "aria-label"?: string; children?: ReactNode };
+ if (props["aria-label"] === "Remove Codex from the fallback list") removes.push(node as never);
+ collect(props.children);
+ };
+ collect(tree);
+ removes[1]!.props.onClick();
+ expect(onChange).toHaveBeenCalledWith([{ instanceId: "codex", model: "gpt-a" }]);
+ });
+
it("keeps showing a saved model the engine no longer lists", () => {
const markup = renderToStaticMarkup(createElement(FallbackChain, { bot: bot([{ instanceId: "codex", model: "gpt-old" }]), onChange: vi.fn() }));
expect(markup).toMatch(/aria-label="Model for Codex"[^>]*>.*<option value="gpt-old" selected="">gpt-old<\/option>/);
diff --git a/src/components/bot-settings/ModelSection.tsx b/src/components/bot-settings/ModelSection.tsx
index 58735220d6..503d2862cd 100644
--- a/src/components/bot-settings/ModelSection.tsx
+++ b/src/components/bot-settings/ModelSection.tsx
@@ -1,7 +1,7 @@
import { EffortRow, ModelPicker } from "../ModelPicker";
import { X } from "lucide-react";
import { cn } from "@/lib/cn";
-import { useStore, type Bot } from "@/state/store";
+import { useStore, type Bot, type InstanceInfo } from "@/state/store";
import { useBotEditor } from "./BotEditorContext";
import { ProposalStatus } from "./ProposalStatus";
import { ThreadModelsLine } from "../ThreadModelsLine";
@@ -74,24 +74,28 @@ function KeepWarmRow({ bot, workspaceOn, onChange }: { bot: Bot; workspaceOn: bo
export function FallbackChain({ bot, onChange }: { bot: Bot; onChange: (fallback: Bot["fallback"]) => void }) {
const { state } = useStore();
const chain = bot.fallback ?? [];
- const available = state.instances.filter(
- (instance) =>
- instance.snapshot.state === "available" &&
- Boolean(instance.models.default.trim()) &&
- instance.instanceId !== bot.modelSelection.instanceId &&
- !chain.some((entry) => entry.instanceId === instance.instanceId),
- );
+ // Backups may share an account with the main AI or each other, never a model.
+ const taken = (instanceId: string, model: string, except?: number) =>
+ (bot.modelSelection.instanceId === instanceId && bot.modelSelection.model === model)
+ || chain.some((entry, at) => at !== except && entry.instanceId === instanceId && entry.model === model);
+ const offeredBy = (instance: InstanceInfo | undefined) =>
+ instance?.models.options.filter((model) => !model.orgBlocked && (instance.snapshot.authenticated !== false || model.custom)) ?? [];
+ const freeModel = (instance: InstanceInfo) => [instance.models.default, ...offeredBy(instance).map((model) => model.id)]
+ .find((model) => model.trim() && !taken(instance.instanceId, model));
+ const available = state.instances.filter((instance) =>
+ instance.snapshot.state === "available" && Boolean(instance.models.default.trim()) && freeModel(instance) !== undefined);
const nameOf = (instanceId: string) => state.instances.find((instance) => instance.instanceId === instanceId)?.displayName ?? instanceId;
- const modelsOf = (entry: NonNullable<Bot["fallback"]>[number]) => {
- const instance = state.instances.find((candidate) => candidate.instanceId === entry.instanceId);
- const offered = instance?.models.options.filter((model) => !model.orgBlocked && (instance.snapshot.authenticated !== false || model.custom)) ?? [];
+ const modelsOf = (entry: NonNullable<Bot["fallback"]>[number], index: number) => {
+ const offered = offeredBy(state.instances.find((candidate) => candidate.instanceId === entry.instanceId))
+ .filter((model) => !taken(entry.instanceId, model.id, index));
return offered.some((model) => model.id === entry.model) ? offered : [{ id: entry.model, label: entry.model }, ...offered];
};
const add = (instanceId: string) => {
- const instance = state.instances.find((candidate) => candidate.instanceId === instanceId);
- if (!instance || !instance.models.default.trim() || chain.length >= 5 || !available.includes(instance)) return;
- onChange([...chain, { instanceId, model: instance.models.default }]);
+ const instance = available.find((candidate) => candidate.instanceId === instanceId);
+ const model = instance && freeModel(instance);
+ if (!model || chain.length >= 5) return;
+ onChange([...chain, { instanceId, model }]);
};
return (
@@ -103,17 +107,17 @@ export function FallbackChain({ bot, onChange }: { bot: Bot; onChange: (fallback
{chain.length > 0 && (
<ol className="mt-3 flex flex-col gap-1">
{chain.map((entry, index) => (
- <li key={entry.instanceId} className="flex items-center gap-2 rounded-lg bg-inset px-3 py-1.5 text-[13px]">
+ <li key={`${entry.instanceId}\u0000${entry.model}`} className="flex items-center gap-2 rounded-lg bg-inset px-3 py-1.5 text-[13px]">
<span className="w-4 shrink-0 tabular-nums text-ink-secondary">{index + 1}.</span>
<span className="min-w-0 flex-1 truncate text-ink">{nameOf(entry.instanceId)}</span>
<Select size="sm" className="max-w-[45%] shrink-0" value={entry.model}
aria-label={t("model.fallback.model", { name: nameOf(entry.instanceId) })}
- onChange={(event) => onChange(chain.map((candidate) => candidate.instanceId === entry.instanceId ? { ...candidate, model: event.target.value } : candidate))}>
- {modelsOf(entry).map((model) => <option key={model.id} value={model.id}>{model.label}</option>)}
+ onChange={(event) => onChange(chain.map((candidate, at) => at === index ? { ...candidate, model: event.target.value } : candidate))}>
+ {modelsOf(entry, index).map((model) => <option key={model.id} value={model.id}>{model.label}</option>)}
</Select>
<button
type="button"
- onClick={() => onChange(chain.filter((candidate) => candidate.instanceId !== entry.instanceId))}
+ onClick={() => onChange(chain.filter((_, at) => at !== index))}
aria-label={t("model.fallback.remove", { name: nameOf(entry.instanceId) })}
className="shrink-0 rounded p-0.5 text-ink-secondary hover:text-ink"
>
@@ -134,7 +138,8 @@ export function FallbackChain({ bot, onChange }: { bot: Bot; onChange: (fallback
<option value="">{available.length === 0 ? t("model.fallback.none") : t("model.fallback.addOption")}</option>
{available.map((instance) => (
<option key={instance.instanceId} value={instance.instanceId}>
- {instance.displayName}
+ {instance.instanceId === bot.modelSelection.instanceId
+ ? `${instance.displayName} · ${t("botPanel.backups.sameAccount")}` : instance.displayName}
</option>
))}
</Select>
diff --git a/src/lib/simple-model-menu.ts b/src/lib/simple-model-menu.ts
index 666395e991..5548d131c5 100644
--- a/src/lib/simple-model-menu.ts
+++ b/src/lib/simple-model-menu.ts
@@ -42,6 +42,8 @@ export interface MenuGroup {
label: string;
provider: string;
account?: string;
+ /** A short line under the heading, such as why this account is special here. */
+ note?: string;
body: MenuGroupBody;
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 6454005cd9..38855ca7ea 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -4098,6 +4098,7 @@
"botPanel.backups.row": "Backup {position}: {model}",
"botPanel.backups.remove": "Remove {model} from backups",
"botPanel.backups.choose": "Choose a backup AI",
+ "botPanel.backups.sameAccount": "Same account as the main AI: it shares the usage limit.",
"botPanel.appsNoneYet": "None yet",
"botPanel.apps.intro": "Switch on the apps {name} may use. Everything else stays off.",
"botPanel.apps.connectAnother": "Connect another app",