Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(limits): a refused turn moves to the bot's backup once its conversation has settled
laijsg1f4a439ca0239
diff --git a/server/automatic-recovery.e2e.test.ts b/server/automatic-recovery.e2e.test.tsindex fee8d63bb4..57e261cfa1 100644--- a/server/automatic-recovery.e2e.test.ts+++ b/server/automatic-recovery.e2e.test.ts@@ -25,7 +25,7 @@ async function withRecoveryFixture(calls: () => Array<{ pid: number; method: string }>;backupPrompts: () => any[];backupReceipt: () => { argv: string[]; prompt: unknown; systemPrompt: string };- dataDir: string; failureFile: string; gateFile: string; evidence: unknown[];+ dataDir: string; failureFile: string; gateFile: string; evidence: unknown[]; serverLog: () => string;}) => Promise<void>,) {const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined,@@ -111,7 +111,7 @@ async function withRecoveryFixture(const { argv, prompt, systemPrompt } = JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8"));return { argv, prompt, systemPrompt };},- dataDir, failureFile, gateFile, evidence,+ dataDir, failureFile, gateFile, evidence, serverLog: () => readFileSync(logPath, "utf8"),});} finally {evidence.push({ calls: jsonLines(rpcFile), backupPrompts: jsonLines(backupFile) });@@ -422,3 +422,65 @@ it.each(["Stop", "new message"])("does not recover a superseded turn after %s",}});}, 90_000);++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 }) => {+ const { bot } = await control("new-bot", "--name", "Researcher");+ const threadId = bot.activeTaskId;+ await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: primary, fallback: [backup] });+ 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;+ const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];++ await send("FIND_REEF_PAPERS_9W");+ await wait();+ await expect.poll(async () => (await messages()).some((message) => message.role === "bot" && message.kind === "text" && message.text === "hello from fake claude"),+ { timeout: 20_000, message: "the backup answers the refused message" }).toBe(true);+ expect((await wait()).status).toBe("settled");+ 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");+ 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);++ await send("try again");+ expect((await wait()).status).toBe("settled");+ expect(prompts(), "the next message goes straight to the backup").toBe(1);+ expect(backupPrompts()).toHaveLength(2);+ const rows = await messages();+ const followUp = rows.findLastIndex((message) => message.role === "user" && message.text === "try again");+ expect(rows.slice(followUp + 1).filter((message) => message.role === "bot" && message.kind === "text"), "the backup answers the follow-up too")+ .toEqual([expect.objectContaining({ text: "hello from fake claude", turnSucceeded: true })]);+ expect(serverLog()).not.toContain("switch-refused");+ evidence.push({ messages: await messages() });+ });+}, 90_000);++it("moves an OpenCode bot whose refused turn had already run a tool to its own backup without sending the message again", async () => {+ await withRecoveryFixture({ enabled: false, method: "session/prompt", afterOutput: true, error: { code: -32603, message: "Free usage limit reached" } },+ async ({ api, control, calls, backupPrompts, 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 send = (text: string) => control("send", "--bot", bot.id, "--task", threadId, "--text", text);+ const wait = () => control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30");+ const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];+ const task = async () => (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).tasks.find((entry: any) => entry.threadId === threadId);++ await send("FILE_THE_TICKET_3K");+ await wait();+ await expect.poll(async () => (await task()).modelSelection, { timeout: 20_000, message: "the conversation moves to the backup" }).toEqual(backup);+ expect((await messages()).filter((message) => message.tool?.nameCode === "chat.notice.backupAlreadyRan")).toHaveLength(1);+ expect(backupPrompts(), "what already ran is not sent again").toHaveLength(0);+ expect((await messages()).filter((message) => message.role === "user" && message.text === "FILE_THE_TICKET_3K")).toHaveLength(1);++ await send("what is left");+ expect((await wait()).status).toBe("settled");+ expect(calls().filter((call) => call.method === "session/prompt")).toHaveLength(1);+ expect(backupPrompts()).toHaveLength(1);+ evidence.push({ messages: await messages() });+ });+}, 90_000);diff --git a/server/chat-notices.ts b/server/chat-notices.tsindex eee7dd0ce4..c3c694b2b6 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -128,6 +128,7 @@ export const CHAT_NOTICE = {"chat.notice.backupConversationBusy": "switched to {name}. This conversation is working, so your message was not sent again.","chat.notice.backupQuestionWaiting": "switched to {name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again. Answer it, then send your message again.","chat.notice.backupMessageMissing": "switched to {name}, but your message could not be found to send again. Send it again.",+ "chat.notice.backupAlreadyRan": "switched to {name}. Part of your request had already run, so it was not sent again. Send what is still to do.","chat.notice.backupContinuingLimit": "continuing on {name} after hitting the usage limit","chat.notice.backupContinuingSignedOut": "continuing on {name} while {engine} is signed out","chat.notice.backupCouldNotContinue": "could not continue on {name}: {error}",diff --git a/server/host/peer-limit-resend.test.ts b/server/host/peer-limit-resend.test.tsindex ad04f78492..ba7ff61760 100644--- a/server/host/peer-limit-resend.test.ts+++ b/server/host/peer-limit-resend.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vitest";import type { Message } from "../store.ts";-import { createPeerLimitResend, nothingRan, type PeerLimitResendDeps, type PeerTurnOpts } from "./peer-limit-resend.ts";+import { nothingRan } from "../turn-outcome.ts";+import { createPeerLimitResend, type PeerLimitResendDeps, type PeerTurnOpts } from "./peer-limit-resend.ts";type Outcome = { ok: boolean; text: string };type Opts = PeerTurnOpts<Outcome> & { origin?: { kind: string } };@@ -17,6 +18,7 @@ describe("nothingRan", () => {expect(nothingRan([ask, failure], 100, "turn-1")).toBe(true);// Some engines send the limit sentence as reply text.expect(nothingRan([{ ...reply, text: LIMIT }], 100, "turn-1", LIMIT)).toBe(true);+ expect(nothingRan([{ ...reply, kind: "compaction", text: undefined }, failure], 100, "turn-1"), "a summary of earlier context").toBe(true);expect(nothingRan([toolCall, failure], 100, "turn-1")).toBe(false);expect(nothingRan([reply, failure], 100, "turn-1")).toBe(false);expect(nothingRan([{ ...reply, kind: "widget" } as Message], 100, "turn-1")).toBe(false);diff --git a/server/host/peer-limit-resend.ts b/server/host/peer-limit-resend.tsindex 62239c348e..14e529661e 100644--- a/server/host/peer-limit-resend.ts+++ b/server/host/peer-limit-resend.ts@@ -6,7 +6,7 @@ import type { hostedModelPolicy } from "../hosted-models.ts";import { limitBackupAllowed } from "../limit-failover.ts";import { turnLimitScope, type QuotaSwitchDeps, type SettledTurn } from "../quota-switch.ts";import type { BotRecord, Message, Store } from "../store.ts";-import type { TurnStops } from "../turn-outcome.ts";+import { nothingRan, type TurnStops } from "../turn-outcome.ts";import type { LimitTakeover, TakeoverScope } from "./limit-takeover.ts";/** The start options a bot-to-bot turn keeps when it is resent: all of them, so it never gains authority. */@@ -80,20 +80,6 @@ export interface PeerLimitResendDeps<Opts, Outcome> {startTurn(botId: string, text: string, opts: Opts): Promise<unknown>;}-/**- * True when the failed turn left nothing behind: no tool call, no reply, no file. Its own failure row, the- * engine's limit sentence (`stopError`, sometimes sent as reply text) and the hand-off's request card, written- * just before the turn (sometimes in the same millisecond), do not count.- */-export function nothingRan(rows: readonly Message[], since: number, turnId: string | undefined, stopError?: string): boolean {- const said = stopError?.trim();- // The turn's digest is written after it ends and only sums it up.- return !rows.some((row) => row.at >= since && row.role === "bot" && row.kind !== "digest" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (- row.kind === "activity" ? Boolean(row.tool?.itemId)- : row.kind === "text" ? Boolean(row.text?.trim()) && row.text!.trim() !== said- : true));-}-/*** Resends a bot-to-bot turn once to the bot's backup AI when its own AI hit a usage limit before anything ran. The* resend keeps the turn's options as they were (sender, provenance, the hand-off it answers), so it never gains authority.diff --git a/server/host/room-limit-takeover.ts b/server/host/room-limit-takeover.tsindex 905b47e19b..06033a080d 100644--- a/server/host/room-limit-takeover.ts+++ b/server/host/room-limit-takeover.ts@@ -2,9 +2,8 @@ import type { ApprovalMode } from "../../shared/approval-mode.ts";import type { ModelSelection, RuntimeEvent } from "../contracts.ts";import { turnLimitScope } from "../quota-switch.ts";import type { Store } from "../store.ts";-import type { TurnStops } from "../turn-outcome.ts";+import { nothingRan, type TurnStops } from "../turn-outcome.ts";import type { LimitTakeover } from "./limit-takeover.ts";-import { nothingRan } from "./peer-limit-resend.ts";/** A room member: only the backups the bot has of its own carry it on, since Automatic recovery leaves channels out. */type Member = { id: string; name: string; modelSelection: ModelSelection; fallback?: ModelSelection[] };diff --git a/server/index.ts b/server/index.tsindex 2785c558d7..c30d6429cb 100644--- a/server/index.ts+++ b/server/index.ts@@ -6677,7 +6677,7 @@ bus.subscribe((event: RuntimeEvent) => {const facts = { ...turnStops.read(event.threadId, event.turnId)?.flags, stopReason: directRequestOwners.get(event.threadId)?.stopped ? "cancelled" : event.stopReason };const held = facts.limit ?? (signedOutStop(facts.stopReason, failureDetail) ? "signed-out" as const : undefined); // a limit or a sign-out: one incident a stretch, the person told by its own noticeconst fileIncident = () => { if (broken && (!held || limitTakeover.firstIncident(broken.id, broken.modelSelection, held, facts.limitResetsAt))) reportIncident({ kind: "failed", bot: broken, threadId: event.threadId, detail: failureDetail, facts, notified: Boolean(held) }); };- if (failed && bot) void quotaSwitch.turnFailed(bot, event, internal);+ let directSettled = () => {}; const settledDirect = new Promise<void>((resolve) => { directSettled = resolve; }); if (failed && bot) void quotaSwitch.turnFailed(bot, event, internal, settledDirect);else if (bot && event.ok) quotaSwitch.turnSucceeded(bot, event.threadId);if (bot && event.ok && !stopped && completedTurnId && !routineRun && !coordinator.assignerOf(event.threadId)) askCards.ownQuestion(bot.id, event.threadId, completedTurnId);const lastReported = turnUsage.get(event.threadId);@@ -6782,9 +6782,9 @@ bus.subscribe((event: RuntimeEvent) => {}).catch(() => {}).finally(() => {clearTimeout(timeout);});- void Promise.all([screenSettled, digestSettled]).finally(() => settleDirectTurn(true)).finally(fileIncident);+ void Promise.all([screenSettled, digestSettled]).finally(() => settleDirectTurn(true)).finally(directSettled).finally(fileIncident);} else {- void digestSettled.finally(() => settleDirectTurn(true)).finally(fileIncident);+ void digestSettled.finally(() => settleDirectTurn(true)).finally(directSettled).finally(fileIncident);}} else if (group && speaker) {const tokens = event.usage ?? lastReported;diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.tsindex f44a57a6dd..23aeb6bb4c 100644--- a/server/quota-switch.test.ts+++ b/server/quota-switch.test.ts@@ -82,9 +82,9 @@ describe("quota switch", () => {return { id, event: { threadId, turnId: `turn-${id}`, ok: false, stopReason: "quota" } };};/** The fold's report of that turn, broken on `why`: the module decides what carries on. */- const ranOut = (turn: ReturnType<typeof begin>, why = QUOTA, internal = false, on = thread()) => {+ const ranOut = (turn: ReturnType<typeof begin>, why = QUOTA, internal = false, on = thread(), settled?: Promise<unknown>) => {cause = why;- return quota.turnFailed(on, turn.event, internal);+ return quota.turnFailed(on, turn.event, internal, settled);};/** The quota card an earlier version left open for that turn: the other engines here, then Not now. */const fails = async (turn: ReturnType<typeof begin>, _why = QUOTA, _internal = false, on = thread()) => {@@ -221,6 +221,99 @@ describe("quota switch", () => {expect(moves, "so it goes back once the limit resets").toEqual([{ threadId: bot.threadId, from: defaultSelection(), to: CODEX }]);});+ it("moves the request only once the turn's conversation has settled, since a working conversation's model cannot change", async () => {+ gate.mockImplementation((_thread, selection) => deps.busy(bot.id, bot.threadId) ? { ok: false, error: "the bot is working — stop it before changing models" } : { ok: true, selection });+ store.setTaskActivity(bot.id, bot.threadId, "working");+ const turn = begin(bot.threadId, { messageId: said("find three papers on reef recovery") });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ cause = QUOTA;+ let settle = () => {};+ const failing = quota.turnFailed(thread(), turn.event, false, new Promise<void>((resolve) => { settle = resolve; }));+ await new Promise((resolve) => setImmediate(resolve));+ expect(gate, "nothing is tried while the conversation still works").not.toHaveBeenCalled();+ store.setTaskActivity(bot.id, bot.threadId, "idle");+ settle();+ expect(await failing).toBeNull();+ expect(thread().modelSelection).toEqual(CODEX);+ expect(resend).toHaveBeenCalledTimes(1);+ expect(passed).toEqual([]);+ });++ it("moves nothing when the person stops the request, or sends another, before its conversation has settled", async () => {+ for (const change of ["stopped", "replaced"] as const) {+ const turn = begin(bot.threadId, { messageId: said(`find papers (${change})`) });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ let settle = () => {};+ const failing = quota.turnFailed(thread(), turn.event, false, new Promise<void>((resolve) => { settle = resolve; }));+ await new Promise((resolve) => setImmediate(resolve));+ if (change === "stopped") requests.get(bot.threadId)!.stopped = true;+ else begin(bot.threadId, { messageId: said("something else") });+ settle();+ expect(await failing).toBeNull();+ expect(thread().modelSelection, change).toEqual(defaultSelection());+ expect(resend, change).not.toHaveBeenCalled();+ }+ });++ it("moves nothing when the request is stopped, its backup taken off the bot's list, or the model switched by hand while the backup is probed", async () => {+ for (const change of ["stopped", "unlisted", "switched", "variant"] as const) {+ let answer = () => {};+ engines[1] = engine("codex", "codex", "Codex", { snapshot: () => new Promise((resolve) => { answer = () => resolve({ state: "available", authenticated: true }); }) });+ backups = [CODEX];+ const turn = begin(bot.threadId, { messageId: said(`find papers (${change})`) });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ passed = [];+ const failing = quota.turnFailed(thread(), turn.event, false, Promise.resolve());+ await new Promise((resolve) => setImmediate(resolve));+ if (change === "stopped") requests.get(bot.threadId)!.stopped = true;+ else if (change === "unlisted") backups = [];+ else store.switchTaskModel(bot.id, bot.threadId, change === "switched" ? CURSOR : { ...defaultSelection(), variant: "high" }, false, false);+ answer();+ expect(await failing).toBeNull();+ expect(thread().modelSelection, change).toEqual(change === "switched" ? CURSOR : change === "variant" ? { ...defaultSelection(), variant: "high" } : defaultSelection());+ expect(resend, change).not.toHaveBeenCalled();+ expect(passed, change).toEqual([{ selection: CODEX, why: change === "unlisted" ? "not-configured" : "conversation-changed" }]);+ if (change === "switched" || change === "variant") store.switchTaskModel(bot.id, bot.threadId, defaultSelection(), false, false);+ }+ });++ it("moves a request whose turn had already run something to the backup without sending it again", async () => {+ for (const ran of ["tool", "reply"] as const) {+ const turn = begin(bot.threadId, { messageId: said(`file the ticket (${ran})`) });+ if (ran === "tool") store.appendMessage(bot.threadId, { role: "bot", kind: "activity", turnId: turn.event.turnId, tool: { name: "create_ticket", itemId: "call-1", ok: true } });+ else store.appendMessage(bot.threadId, { role: "bot", kind: "text", turnId: turn.event.turnId, text: "Filed it as T-42." });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ expect(await ranOut(turn)).toBeNull();+ expect(thread().modelSelection, ran).toEqual(CODEX);+ expect(resend, ran).not.toHaveBeenCalled();+ expect(notices().at(-1), ran).toEqual({ name: "notice: switched to Codex. Part of your request had already run, so it was not sent again. Send what is still to do.", nameCode: "chat.notice.backupAlreadyRan", nameParams: { name: "Codex" }, ok: false });+ store.switchTaskModel(bot.id, bot.threadId, defaultSelection(), false, false);+ }+ });++ it("sends a request again when the only row before the refusal is a summary of the conversation's earlier context", async () => {+ const messageId = said("plan the launch");+ const turn = begin(bot.threadId, { messageId });+ store.appendMessage(bot.threadId, { role: "bot", kind: "compaction", compaction: { summary: "Earlier: the launch is on Friday.", firstKeptId: messageId, foldedThroughId: messageId, tokensBefore: 90_000, by: "harness" } });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ expect(await ranOut(turn)).toBeNull();+ expect(thread().modelSelection).toEqual(CODEX);+ expect(resend).toHaveBeenCalledTimes(1);+ });++ it("sends a request again when a routine's report landed in the conversation while its refused turn settled", async () => {+ const turn = begin(bot.threadId, { messageId: said("plan the launch") });+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });+ let settle = () => {};+ const failing = ranOut(turn, QUOTA, false, thread(), new Promise<void>((resolve) => { settle = resolve; }));+ store.appendMessage(bot.threadId, { role: "bot", kind: "text", text: "Your morning digest is ready.",+ automation: { routineId: "r1", runId: "run-1", name: "Morning digest", trigger: "schedule", executionThreadId: "routine-thread", scheduledFor: 1_800_000_000_000 } });+ settle();+ expect(await failing).toBeNull();+ expect(thread().modelSelection).toEqual(CODEX);+ expect(resend).toHaveBeenCalledTimes(1);+ });+it("never takes a failed tool call for the AI's usage limit, whatever the tool is called", async () => {const turn = begin(bot.threadId, { messageId: said("export the quota report") });coordinator.endTurn(turn.id, { ok: false, text: "tool failed" });@@ -353,13 +446,15 @@ describe("quota switch", () => {it("moves a request the job runtime still holds but sends nothing again: the runtime resumes it", async () => {const turn = begin(bot.threadId, { messageId: said("ask the team for the numbers") });+ store.appendMessage(bot.threadId, { role: "bot", kind: "activity", turnId: turn.event.turnId, tool: { name: "ask_teammate", itemId: "call-1", ok: true } });const mate = store.createBot();coordinator.enqueue({ botId: bot.id, threadId: bot.threadId }, turn.id, undefined, { botId: mate.id, threadId: mate.threadId }, "Pull the quarter's numbers");coordinator.endTurn(turn.id, { ok: false, text: QUOTA });await ranOut(turn);expect(thread().modelSelection).toEqual(CODEX);expect(resend).not.toHaveBeenCalled();- expect(notices()).toEqual([{ name: "notice: switched to Codex. Your request is still under way here and continues on Codex.", nameCode: "chat.notice.backupRequestUnderWay", nameParams: { name: "Codex" }, ok: true }]);+ expect(notices().filter((tool) => tool.name.startsWith("notice:")), "what it already ran is the runtime's to resume, not the person's to send again")+ .toEqual([{ name: "notice: switched to Codex. Your request is still under way here and continues on Codex.", nameCode: "chat.notice.backupRequestUnderWay", nameParams: { name: "Codex" }, ok: true }]);});describe("an AI that is signed out", () => {@@ -391,7 +486,7 @@ describe("quota switch", () => {{ name: `notice: ${NOTICE}`, ok: true, setup: true },{ name: "notice: continuing on Codex while Claude is signed out", nameCode: "chat.notice.backupContinuingSignedOut", nameParams: { name: "Codex", engine: "Claude" }, ok: true },]);- expect(scopes).toEqual(["signed-out"]);+ expect(new Set(scopes), "the backups are weighed for a sign-out, at the refusal and again before the move").toEqual(new Set(["signed-out"]));expect(thread().modelSelection).toEqual(CODEX);expect(resend).toHaveBeenCalledTimes(1);expect(resend.mock.calls[0]![2]).toMatchObject({ id: messageId });diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex b5e807557b..828b77a231 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -3,6 +3,7 @@ import { type ServerText } from "../shared/server-text.ts";// so a bot's own shell with decline-only service trust can never switch the engine or resend the person's message.// A request the job runtime still holds is never sent again: the runtime reruns its root itself.import { approvalModeFor, modelSwitchNeedsAsk } from "../shared/approval-mode.ts";+import { sameModelSelection } from "../shared/thread-model.ts";import type { QuotaSwitchCardData } from "../shared/wire.ts";import { recoveryCapabilityError } from "./automatic-recovery.ts";import type { EngineAccess, ModelCatalog, ModelSelection, ProviderAdapter, ProviderSnapshot } from "./contracts.ts";@@ -13,7 +14,7 @@ import { PROBE_TIMEOUT_MS } from "./engine-install.ts";import { spokenLineFields } from "./live-call-record.ts";import type { WorkOrigin } from "./peer-provenance.ts";import type { BotRecord, Message, Store, TaskRecord } from "./store.ts";-import type { TurnStops } from "./turn-outcome.ts";+import { nothingRan, type TurnStops } from "./turn-outcome.ts";import { signedOutStop, type BackupSkip, type LimitTakeover, type SkippedBackup, type TakeoverScope } from "./host/limit-takeover.ts";export interface QuotaSwitchEngine {@@ -57,8 +58,9 @@ export interface QuotaSwitchDeps {}export interface QuotaSwitch {- /** Never rejects. */- turnFailed(bot: BotRecord, event: SettledTurn, internal: boolean): Promise<Message | null>;+ /** Never rejects. Nothing moves to a backup before `settled` resolves: until the turn's conversation has settled it+ * still reads busy, and a busy conversation's model cannot change. */+ turnFailed(bot: BotRecord, event: SettledTurn, internal: boolean, settled?: Promise<unknown>): Promise<Message | null>;/** Never throws. */turnSucceeded(bot: BotRecord, threadId: string): void;/** Null when `requestId` is not an open quota card of this thread. "unavailable": refused, and the offer stays open. Never rejects. */@@ -154,21 +156,26 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {/** The newest root: a backup engine's retry or a change of computer begins another root for the same request. */const rootOf = (threadId: string, request: QuotaRequest): string | undefined => coordinator.newestRoot(threadId, request.generations)?.id;+ const stillAsked = (threadId: string, request: QuotaRequest): boolean => deps.request(threadId) === request && !request.stopped;+ const sameModel = (a: ModelSelection, b: ModelSelection): boolean => a.instanceId === b.instanceId && a.model === b.model;+/** Moves the thread to `selection` and sends the person's message that hit the limit (or met a signed-out AI) again* there; null once it does, else why that AI cannot take it now. No await from the readiness check to the resend: the* gate, the switch and the resend see one state. */- const continueOn = async (botId: string, threadId: string, selection: ModelSelection, request: QuotaRequest, build: { stale: boolean }, resetsAt?: number,+ const continueOn = async (botId: string, threadId: string, selection: ModelSelection, request: QuotaRequest, build: { stale: boolean; from: ModelSelection; ran: boolean }, resetsAt?: number,scope: TakeoverScope = "engine"): Promise<Omit<SkippedBackup, "selection"> | null> => {const engines = deps.registry.instances();const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);const before = store.projectBotForTask(botId, threadId);const current = before && engines.find((candidate) => candidate.instanceId === before.modelSelection.instanceId);- if (!before) return { why: "conversation-changed" };+ if (!before || !sameModelSelection(before.modelSelection, build.from)) return { why: "conversation-changed" };if (!engine || !current) return { why: "not-configured" };const ready = engine.instanceId === current.instanceId ? selection : await takeover(engine, before, current);if (typeof ready === "string") return { why: ready };const bot = store.projectBotForTask(botId, threadId);- if (!bot || build.stale || !store.taskByThread(botId, threadId)) return { why: "conversation-changed" };+ if (!bot || build.stale || !store.taskByThread(botId, threadId) || !stillAsked(threadId, request) || !sameModelSelection(bot.modelSelection, build.from)) return { why: "conversation-changed" };+ const weighed = deps.takeover?.weighBackups(botId, before.modelSelection, scope, approvalModeFor(before));+ if (weighed && !weighed.backups.some((backup) => sameModel(backup, selection))) return { why: weighed.skipped.find((left) => sameModel(left.selection, selection))?.why ?? "not-configured" };const checked = deps.gate(bot, selection);if (!checked.ok) return { why: "switch-refused", detail: checked.error };try {@@ -179,9 +186,10 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {deps.takeover?.moved(botId, threadId, before.modelSelection, checked.selection, resetsAt, scope);const name = engine.instanceId === current.instanceId ? `${nameOf(engine)} ${checked.selection.model}` : nameOf(engine);const why = scope === "signed-out" ? `while ${nameOf(current)} is signed out` : "after hitting the usage limit";- const held = heldBy(botId, threadId, rootOf(threadId, request));+ const held = heldBy(botId, threadId, rootOf(threadId, request)) ?? (build.ran ? "ran" : null);const original = held ? undefined : resendable(store, threadId, request.messageId);- if (held === "card") notice(threadId, `switched to ${name}. Your request waits on a card above and continues on ${name} once you act on it.`, true, false, { key: "chat.notice.backupCardWaiting", params: { name } });+ if (held === "ran") notice(threadId, `switched to ${name}. Part of your request had already run, so it was not sent again. Send what is still to do.`, false, false, { key: "chat.notice.backupAlreadyRan", params: { name } });+ else if (held === "card") notice(threadId, `switched to ${name}. Your request waits on a card above and continues on ${name} once you act on it.`, true, false, { key: "chat.notice.backupCardWaiting", params: { name } });else if (held === "runtime") notice(threadId, `switched to ${name}. Your request is still under way here and continues on ${name}.`, true, false, { key: "chat.notice.backupRequestUnderWay", params: { name } });else if (held === "busy") notice(threadId, `switched to ${name}. This conversation is working, so your message was not sent again.`, true, false, { key: "chat.notice.backupConversationBusy", params: { name } });else if (held === "question") {@@ -203,13 +211,14 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {* first AI that can take it, the person hears once for this stretch what carries on meanwhile (a sign-out also in this* conversation, where signing in fixes it), and the AI's later turns go there too until the limit resets or it is* signed in again (the turn start's own check). */- const turnFailed = async (bot: BotRecord, event: SettledTurn, internal: boolean): Promise<Message | null> => {+ const turnFailed = async (bot: BotRecord, event: SettledTurn, internal: boolean, settled?: Promise<unknown>): Promise<Message | null> => {const { threadId } = event;try {// Read before any await: the record is this turn's only now.const request = deps.request(threadId);const flags = deps.turnStops.read?.(threadId, event.turnId)?.flags;- const scope = turnLimitScope(event, flags, deps.turnStops.failureCause(event));+ const cause = deps.turnStops.failureCause(event);+ const scope = turnLimitScope(event, flags, cause);if (!scope) return null;const thread = store.projectBotForTask(bot.id, threadId) ?? bot;const from = thread.modelSelection;@@ -232,9 +241,16 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {tell(backups[0]);return null;}- const build = { threadId, stale: false };+ const build = { threadId, stale: false, from, ran: false };building.add(build);try {+ await settled;+ if (!stillAsked(threadId, request)) return null;+ // Rows land until the turn's conversation has settled: a file it made, the last of its reply, and a routine's+ // report held back while the conversation worked, which this turn did not run.+ const path = store.activePath(threadId);+ const asked = path.findIndex((message) => message.id === request.messageId);+ build.ran = asked >= 0 && !nothingRan(path.slice(asked + 1).filter((message) => !message.automation), 0, event.turnId, cause);for (const selection of backups) {const why = await continueOn(bot.id, threadId, selection, request, build, resetsAt, scope);if (!why) {diff --git a/server/turn-outcome.ts b/server/turn-outcome.tsindex de31d1de8f..39a1fae34a 100644--- a/server/turn-outcome.ts+++ b/server/turn-outcome.ts@@ -133,3 +133,17 @@ function sentence(text: string): string {const capital = `${text.charAt(0).toUpperCase()}${text.slice(1)}`;return /[.!?…"]$/.test(capital) ? capital : `${capital}.`;}++/**+ * True when the failed turn left nothing behind: no tool call, no reply, no file. Its own failure row, the+ * engine's limit sentence (`stopError`, sometimes sent as reply text), a summary of the conversation's earlier context+ * and the hand-off's request card, written just before the turn (sometimes in the same millisecond), do not count.+ */+export function nothingRan(rows: readonly Message[], since: number, turnId: string | undefined, stopError?: string): boolean {+ const said = stopError?.trim();+ // The turn's digest is written after it ends and only sums it up.+ return !rows.some((row) => row.at >= since && row.role === "bot" && row.kind !== "digest" && row.kind !== "compaction" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (+ row.kind === "activity" ? Boolean(row.tool?.itemId)+ : row.kind === "text" ? Boolean(row.text?.trim()) && row.text!.trim() !== said+ : true));+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex a172bf1117..5b66867957 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10158,6 +10158,7 @@"chat.notice.backupConversationBusy": "switched to {name}. This conversation is working, so your message was not sent again.","chat.notice.backupQuestionWaiting": "switched to {name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again. Answer it, then send your message again.","chat.notice.backupMessageMissing": "switched to {name}, but your message could not be found to send again. Send it again.",+ "chat.notice.backupAlreadyRan": "switched to {name}. Part of your request had already run, so it was not sent again. Send what is still to do.","chat.notice.backupContinuingLimit": "continuing on {name} after hitting the usage limit","chat.notice.backupContinuingSignedOut": "continuing on {name} while {engine} is signed out","chat.notice.backupCouldNotContinue": "could not continue on {name}: {error}",