Skip to content

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

Keep each backup model's reasoning setting through recovery

WolveBrowna04eb5224815
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 3f46f1eeef..5ebfecf6d9 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -370,7 +370,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {
/** Which of a paired phone's apps this bot may use; absent: every bot may use what the phone allows (shared/phone-apps.ts). */
phoneApps?: import("./phone-apps.ts").PhoneApps;
/** Ordered backups used only by opt-in, pre-prompt startup recovery. */
- fallback?: Array<{ instanceId: string; model: string }>;
+ fallback?: ModelSelection[];
/** Whether this bot gets the app's built-in browser. */
browser?: boolean;
/** Record a screenshot and a short note of each browser action, kept with
diff --git a/server/automatic-recovery.e2e.test.ts b/server/automatic-recovery.e2e.test.ts
index 57e261cfa1..a9e74d9692 100644
--- a/server/automatic-recovery.e2e.test.ts
+++ b/server/automatic-recovery.e2e.test.ts
@@ -425,10 +425,13 @@ it.each(["Stop", "new message"])("does not recover a superseded turn after %s",
it("carries an OpenCode bot at its usage limit on with the bot's own backup, and its next message stays there", async () => {
await withRecoveryFixture({ enabled: false, method: "session/prompt", error: { code: -32603, message: "Free usage limit reached" } },
- async ({ api, control, calls, backupPrompts, serverLog, evidence }) => {
+ async ({ api, control, calls, backupPrompts, backupReceipt, serverLog, evidence }) => {
const { bot } = await control("new-bot", "--name", "Researcher");
const threadId = bot.activeTaskId;
- await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: primary, fallback: [backup] });
+ const selectedBackup = { ...backup, effort: "medium" };
+ await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: primary, fallback: [selectedBackup] });
+ const saved = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id);
+ expect(saved.fallback).toEqual([selectedBackup]);
const send = (text: string) => control("send", "--bot", bot.id, "--task", threadId, "--text", text);
const wait = () => control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30");
const prompts = () => calls().filter((call) => call.method === "session/prompt").length;
@@ -442,9 +445,11 @@ it("carries an OpenCode bot at its usage limit on with the bot's own backup, and
expect(prompts(), "OpenCode refused it once").toBe(1);
expect(backupPrompts(), "the backup answered the same message").toHaveLength(1);
expect(JSON.stringify(backupPrompts()[0])).toContain("FIND_REEF_PAPERS_9W");
+ const { argv } = backupReceipt();
+ expect(argv.slice(argv.indexOf("--effort"), argv.indexOf("--effort") + 2)).toEqual(["--effort", "medium"]);
expect((await messages()).filter((message) => message.tool?.name?.startsWith("notice: continuing on"))).toHaveLength(1);
const task = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).tasks.find((entry: any) => entry.threadId === threadId);
- expect(task.modelSelection).toEqual(backup);
+ expect(task.modelSelection).toEqual(selectedBackup);
await send("try again");
expect((await wait()).status).toBe("settled");
diff --git a/server/automatic-recovery.ts b/server/automatic-recovery.ts
index 9467f98442..0586676aa9 100644
--- a/server/automatic-recovery.ts
+++ b/server/automatic-recovery.ts
@@ -3,7 +3,7 @@ import { supportsWorkspaceFiles } from "./workspace.ts";
import type { ModelSelection } from "../shared/wire.ts";
type Engine = { driverKind: string; capabilities: ProviderAdapter["capabilities"] };
-type Backup = Pick<ModelSelection, "instanceId" | "model">;
+type Backup = ModelSelection;
/** The backups a bot's turn tries, in order, when its AI provably never started it: the bot's own list, which needs no
* switch, or else the installation's one backup while Automatic recovery is on. */
diff --git a/server/cloud-send-kinds.ts b/server/cloud-send-kinds.ts
index 9ffcca0acc..6c474a51db 100644
--- a/server/cloud-send-kinds.ts
+++ b/server/cloud-send-kinds.ts
@@ -14,7 +14,8 @@ import type { MoveKind } from "../electron/cloud-send-parts.mjs";
import type { AppTrigger } from "../shared/app-triggers.ts";
import { canonicalJson } from "../shared/package-format.ts";
import { isSkillName } from "../shared/skill-md.ts";
-import type { InstalledPlaybook, InstalledPackageMetadata } from "../shared/wire.ts";
+import { EFFORT_LEVELS, type InstalledPlaybook, type InstalledPackageMetadata } from "../shared/wire.ts";
+import { isModelVariant } from "./contracts.ts";
import type { WebhookTrigger } from "../shared/webhooks.ts";
import type { AppTriggerManager } from "./app-triggers.ts";
import type { CalendarCall, CalendarCallManager } from "./calendar-calls.ts";
@@ -246,7 +247,10 @@ const botFieldsSchema = z.object({
pinned: z.boolean().nullable().optional(),
chiefOfStaff: z.boolean().nullable().optional(),
managedSections: z.array(z.string().trim().max(60)).max(100).nullable().optional(),
- fallback: z.array(z.object({ instanceId: z.string().regex(/^[\w.-]{1,128}$/u), model: z.string().min(1).max(500) })).max(5).nullable().optional(),
+ fallback: z.array(z.object({
+ instanceId: z.string().regex(/^[\w.-]{1,128}$/u), model: z.string().min(1).max(500),
+ effort: z.enum(EFFORT_LEVELS).optional(), variant: z.string().refine(isModelVariant).optional(),
+ }).refine((entry) => entry.effort === undefined || entry.variant === undefined)).max(5).nullable().optional(),
projects: z.array(z.object({ id: z.string().regex(/^[\w-]{1,128}$/u), name: z.string().min(1).max(80), emoji: z.string().max(16).optional() }).passthrough()).max(200).nullable().optional(),
playbooks: z.array(playbookSchema).max(50).nullable().optional(),
installedPackage: z.record(z.string(), z.unknown()).nullable().optional(),
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
index aee4382403..3514814da9 100644
--- a/server/host/limit-takeover.test.ts
+++ b/server/host/limit-takeover.test.ts
@@ -65,6 +65,13 @@ function takeover(overrides: Partial<LimitTakeoverDeps> = {}, dir = freshDir())
}
describe("which AI carries on while one is limited", () => {
+ it("keeps the chosen reasoning when the first backup is also the same account's default model", () => {
+ const sameAccount = { ...on("codex", "gpt-6"), effort: "medium" } as const;
+ const other = { ...on("opencode", "go-default"), variant: "thinking" };
+ const { instance } = takeover({ chosen: () => [other, sameAccount] });
+ expect(instance.backups("kai", on("codex", "gpt-6-mini"), "model")).toEqual([sameAccount, other]);
+ });
+
it("keeps a bot on OpenCode Zen's free models while only the Go subscription's meter is full", () => {
const openCode = engine("opencode", "opencode", ["opencode-go/kimi-k2", "opencode/big-pickle"]);
const clock = new LimitResetClock({ accounts: () => [{ id: "opencode", name: "OpenCode", driver: "opencode", environment: {} }], now: () => NOW });
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
index 1fe2f05b2b..f22230c624 100644
--- a/server/host/limit-takeover.ts
+++ b/server/host/limit-takeover.ts
@@ -201,8 +201,7 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
if (!current) return { backups: [], skipped: [] };
const out: ModelSelection[] = [];
const left: SkippedBackup[] = [];
- const add = (selection: ModelSelection) => {
- const pick = { instanceId: selection.instanceId, model: selection.model };
+ const add = (pick: ModelSelection) => {
if (pick.instanceId === from.instanceId && pick.model === from.model) return;
if ([...out, ...left.map((one) => one.selection)].some((known) => known.instanceId === pick.instanceId && known.model === pick.model)) return;
if (pick.instanceId === from.instanceId && (scope === "engine" || scope === "signed-out")) {
@@ -214,7 +213,10 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
else out.push(pick);
};
const picked = chosen ?? deps.chosen(botId);
- if ((scope === "model" || scope === "credits") && picked.length) add({ instanceId: current.instanceId, model: current.models.default });
+ if ((scope === "model" || scope === "credits") && picked.length) {
+ const sameAccountDefault = picked.find((entry) => entry.instanceId === current.instanceId && entry.model === current.models.default);
+ add(sameAccountDefault ?? { instanceId: current.instanceId, model: current.models.default });
+ }
for (const selection of chosen ?? (scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? picked : picked)) add(selection);
return { backups: out, skipped: left };
}
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 86c33ad33a..071c849d90 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -255,16 +255,22 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
if (!Array.isArray(body.fallback) || body.fallback.length > 5) {
return json(res, 400, { error: "fallback must be a list of up to five { instanceId, model } entries" });
}
- const chain: Array<{ instanceId: string; model: string }> = [];
+ const chain: ModelSelection[] = [];
for (const entry of body.fallback as unknown[]) {
- const row = entry && typeof entry === "object" ? (entry as { instanceId?: unknown; model?: unknown }) : null;
+ const row = entry && typeof entry === "object" ? (entry as Partial<Record<keyof ModelSelection, unknown>>) : null;
if (!row || typeof row.instanceId !== "string" || !/^[\w.-]+$/.test(row.instanceId) || typeof row.model !== "string" || !row.model.trim() || row.model.length > 500) {
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` });
const model = row.model.trim();
if (chain.some((seen) => seen.instanceId === row.instanceId && seen.model === model)) continue;
- chain.push({ instanceId: row.instanceId, model });
+ if (row.effort === undefined && row.variant === undefined) {
+ chain.push({ instanceId: row.instanceId, model });
+ } else {
+ const checked = deps.checkedModelSelection(row);
+ if (!checked.ok) return json(res, checked.status, refusalBody(checked));
+ chain.push(checked.selection);
+ }
}
patch.fallback = chain;
}
diff --git a/src/components/BackupReasoning.tsx b/src/components/BackupReasoning.tsx
new file mode 100644
index 0000000000..b369da44fa
--- /dev/null
+++ b/src/components/BackupReasoning.tsx
@@ -0,0 +1,29 @@
+import { offeredEffortLevels } from "../../shared/wire";
+import { t } from "@/lib/i18n";
+import type { InstanceInfo, ModelSelection } from "@/state/store";
+import { variantLabel } from "./model-picker-reasoning";
+import { Select } from "./Select";
+
+export function BackupReasoning({ instance, selection, onChange }: {
+ instance?: InstanceInfo;
+ selection: ModelSelection;
+ onChange: (next: ModelSelection) => void;
+}) {
+ const { instanceId, model, variant, effort } = selection;
+ const options = instance?.capabilities?.modelVariants
+ ? (instance.models.options.find((option) => option.id === model)?.variants ?? [])
+ .map((option) => ({ value: option.id, label: variantLabel(option, instance.driverKind), reasoning: { variant: option.id } }))
+ : offeredEffortLevels(instance, model)
+ .map((level) => ({ value: level, label: t(`model.effort.${level}`), reasoning: { effort: level } }));
+ const value = variant ?? effort ?? "";
+ if (!options.length && !value) return null;
+ return (
+ <Select size="sm" variant="quiet" className="min-w-0 max-w-[42%]" value={value}
+ aria-label={`${t("model.simple.reasoning")} · ${model}`}
+ onChange={(event) => onChange({ instanceId, model, ...options.find((option) => option.value === event.target.value)?.reasoning })}>
+ <option value="">{t("settings.newBotEffort.default")}</option>
+ {value && !options.some((option) => option.value === value) && <option value={value} disabled>{value}</option>}
+ {options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
+ </Select>
+ );
+}
diff --git a/src/components/bot-panel/BackupAis.dom.test.ts b/src/components/bot-panel/BackupAis.dom.test.ts
index 049f382508..c2b045004c 100644
--- a/src/components/bot-panel/BackupAis.dom.test.ts
+++ b/src/components/bot-panel/BackupAis.dom.test.ts
@@ -123,6 +123,38 @@ describe("a bot's backup AIs in Simple", () => {
expect(onChange).toHaveBeenCalledWith([{ instanceId: "gemini", model: "gemini-3-pro" }]);
});
+ it("saves only the selected backup's model-specific reasoning and can restore the provider default", () => {
+ const [model] = codex.models.options;
+ fixture.instances.splice(1, 1, { ...codex, models: { ...codex.models, options: [{ ...model!, effortLevels: ["low", "medium"] }] } });
+ const backup = { instanceId: "codex", model: "gpt-5.5" };
+ const other = { instanceId: "gemini", model: "gemini-3-pro" };
+ render([backup, other]);
+ const picker = host.querySelector<HTMLSelectElement>('select[aria-label="Reasoning · gpt-5.5"]')!;
+ expect([...picker.options].map((option) => option.value)).toEqual(["", "low", "medium"]);
+ expect(picker.selectedOptions[0]?.textContent).toBe("Provider default");
+ picker.value = "medium";
+ flushSync(() => picker.dispatchEvent(new Event("change", { bubbles: true })));
+ expect(onChange).toHaveBeenLastCalledWith([{ ...backup, effort: "medium" }, other]);
+ render([{ ...backup, effort: "medium" }, other]);
+ picker.value = "";
+ flushSync(() => picker.dispatchEvent(new Event("change", { bubbles: true })));
+ expect(onChange).toHaveBeenLastCalledWith([backup, other]);
+ });
+
+ it("saves the provider's variant id when a backup model advertises named reasoning modes", () => {
+ const model = gemini.models.options[0]!;
+ const instance = { ...gemini, capabilities: { ...gemini.capabilities, modelVariants: true },
+ models: { ...gemini.models, options: [{ ...model, variants: [{ id: "thinking-medium", label: "Medium" }] }] } };
+ fixture.instances.splice(2, 1, instance as InstanceInfo);
+ const backup = { instanceId: gemini.instanceId, model: model.id };
+ render([backup]);
+ const picker = host.querySelector<HTMLSelectElement>("select")!;
+ expect([...picker.options].map((option) => option.textContent)).toEqual(["Provider default", "Medium"]);
+ picker.value = "thinking-medium";
+ flushSync(() => picker.dispatchEvent(new Event("change", { bubbles: true })));
+ expect(onChange).toHaveBeenCalledWith([{ ...backup, variant: "thinking-medium" }]);
+ });
+
it("stops offering Add at the most the bot can keep", () => {
const full = Array.from({ length: MAX_BACKUPS }, (_, index) => ({ instanceId: `engine-${index}`, model: "m" }));
render(full);
diff --git a/src/components/bot-panel/BackupAis.tsx b/src/components/bot-panel/BackupAis.tsx
index eb90515363..c55fcc1625 100644
--- a/src/components/bot-panel/BackupAis.tsx
+++ b/src/components/bot-panel/BackupAis.tsx
@@ -16,6 +16,7 @@ import { modelMenuKey, modelMenuPointerMove } from "../model-menu-keys";
import { SIMPLE_POPOVER_WIDTH } from "../ModelPicker";
import { InstanceProviderMark } from "../ProviderIcons";
import { SimpleModelMenu } from "../SimpleModelMenu";
+import { BackupReasoning } from "../BackupReasoning";
import { buttonCls, Card, ColRow, RowIcon, RowText, TrashButton } from "./rows";
import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select";
@@ -193,9 +194,9 @@ function BackupChooser({ bot, current, exclude, onPick, label, title, buttonRef,
botModel={{ label: "", title: "" }}
idPrefix={menuId}
onQuery={setQuery}
- onPick={(instance, model) => {
+ onPick={(instance, model, variant) => {
if (instance.policy) return;
- onPick({ instanceId: instance.instanceId, model });
+ onPick({ instanceId: instance.instanceId, model, ...(variant === undefined ? {} : { variant }) });
close(true);
}}
onPickCurrent={() => close(true)}
@@ -261,6 +262,8 @@ export function BackupAis({ bot, onChange }: { bot: Bot; onChange: (fallback: Ba
{!instance && <span className="shrink-0 text-[12px] text-warning">{t("model.simple.unavailable")}</span>}
<ChevronDown size={12} strokeWidth={2} aria-hidden="true" className="shrink-0 text-ink-tertiary group-hover:text-ink-secondary" />
</BackupChooser>
+ <BackupReasoning instance={instance} selection={entry}
+ onChange={(next) => onChange(chain.map((candidate, at) => at === index ? next : candidate))} />
<TrashButton
data-panel-action="backup-remove"
label={t("botPanel.backups.remove", { model: name })}
diff --git a/src/components/bot-settings/ModelSection.tsx b/src/components/bot-settings/ModelSection.tsx
index 779b1b06d7..ece1a2142d 100644
--- a/src/components/bot-settings/ModelSection.tsx
+++ b/src/components/bot-settings/ModelSection.tsx
@@ -8,6 +8,7 @@ import { CheckWorkSetting } from "./CheckWorkSetting";
import { ThreadModelsLine } from "../ThreadModelsLine";
import { t } from "@/lib/i18n";
import { Select } from "../Select";
+import { BackupReasoning } from "../BackupReasoning";
import { backupNote } from "@/lib/engine-rail";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
@@ -126,9 +127,11 @@ export function FallbackChain({ bot, onChange }: { bot: Bot; onChange: (fallback
<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, at) => at === index ? { ...candidate, model: event.target.value } : candidate))}>
+ onChange={(event) => onChange(chain.map((candidate, at) => at === index ? { instanceId: candidate.instanceId, model: event.target.value } : candidate))}>
{modelsOf(entry, index).map((model) => <option key={model.id} value={model.id}>{model.label}</option>)}
</Select>
+ <BackupReasoning instance={state.instances.find((instance) => instance.instanceId === entry.instanceId)} selection={entry}
+ onChange={(next) => onChange(chain.map((candidate, at) => at === index ? next : candidate))} />
<button
type="button"
onClick={() => onChange(chain.filter((_, at) => at !== index))}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index f12a426fe8..9a2a31d1f6 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -325,7 +325,7 @@ export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" |
connectorTools?: Record<string, ConnectorToolGrant>;
connectorScopes?: { apps: Record<string, "read" | "write"> }; phoneApps?: import("../../shared/phone-apps").PhoneApps;
outbound?: { policy: "ask" | "allow" };
- fallback?: Array<{ instanceId: string; model: string }>;
+ fallback?: ModelSelection[];
browser?: boolean;
recordBrowserSteps?: boolean;
memoryUpkeep?: boolean;