Skip to content

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

fix(rooms): a room member at its usage limit carries on with its own backup (#4277)

laijsg1dd5c2ad5e7f3
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
index d7ff5cbdb6..556011e4b9 100644
--- a/server/host/limit-takeover.test.ts
+++ b/server/host/limit-takeover.test.ts
@@ -319,6 +319,23 @@ describe("a new conversation once an AI is known to be at its limit", () => {
expect(boot().instance.heldAtStart(KAI, on("claude", "claude-opus-5-5")), "the next turn checks it again").toBeNull();
});
+ it("names the backup a room member's turn starts on, says it once, and records nothing to go back to", () => {
+ const { boot } = server();
+ const { clock, instance, told } = boot();
+ const own = [on("codex", "gpt-6")];
+ expect(instance.takeoverAtStart(KAI, on("claude", "claude-opus-5-5"), own), "nothing holds Claude yet").toBeNull();
+ refused(clock, "t1", NOW + 5 * HOUR);
+ expect(instance.takeoverAtStart(KAI, on("claude", "claude-opus-5-5"), []), "only the backups given, never the installation's").toBeNull();
+ expect(instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"), false, []), "nothing to carry on with").toBeNull();
+ const taken = instance.takeoverAtStart(KAI, on("claude", "claude-opus-5-5"), own);
+ expect(taken).toEqual({ to: on("codex", "gpt-6"), scope: "engine", resetsAt: NOW + 5 * HOUR });
+ const rows = instance.carryOnRows(KAI, on("claude", "claude-opus-5-5"), taken!.to, taken!);
+ expect(rows).toEqual([{ name: expect.stringMatching(/^recovery: Claude hit its limit \(resets .+\), so Codex took over\.$/), ok: true }]);
+ instance.carryOnRows(KAI, on("claude", "claude-opus-5-5"), taken!.to, taken!);
+ expect(told, "the person hears it once for the stretch").toHaveLength(1);
+ expect(instance.takeoverAtStart({ ...KAI, approvalMode: "edits" }, on("claude", "claude-opus-5-5"), own), "a level that must ask first").toBeNull();
+ });
+
it("goes to no AI the thread's approval level can't move to by itself, and then tries its own AI as usual", () => {
const { boot } = server();
const { clock, instance } = boot();
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
index 2b2e723e50..d232433d7a 100644
--- a/server/host/limit-takeover.ts
+++ b/server/host/limit-takeover.ts
@@ -190,8 +190,9 @@ 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. 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. `skipped`: each backup left out, and why. */
- function weighBackups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): { backups: ModelSelection[]; skipped: SkippedBackup[] } {
+ * waits for the reset or a sign-in. `approval`: the thread's level, when known. `chosen`: the backups to weigh instead of
+ * the bot's and the installation's. `skipped`: each backup left out, and why. */
+ function weighBackups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode, chosen?: readonly ModelSelection[]): { backups: ModelSelection[]; skipped: SkippedBackup[] } {
const engines = deps.engines();
const current = engines.find((engine) => engine.instanceId === from.instanceId);
if (!current) return { backups: [], skipped: [] };
@@ -210,12 +211,12 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
else out.push(pick);
};
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);
+ for (const selection of chosen ?? (scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? deps.chosen(botId) : deps.chosen(botId))) add(selection);
return { backups: out, skipped: left };
}
- function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): ModelSelection[] {
- return weighBackups(botId, from, scope, approval).backups;
+ function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode, chosen?: readonly ModelSelection[]): ModelSelection[] {
+ return weighBackups(botId, from, scope, approval, chosen).backups;
}
const passedOver = (bot: Bot, from: ModelSelection, scope: TakeoverScope, left: readonly SkippedBackup[]): void => {
@@ -263,6 +264,24 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
signedIn(selection.instanceId);
};
+ function heldAtStart(bot: ThreadBot, selection: ModelSelection, recovering = false, chosen?: readonly ModelSelection[]): { scope: TakeoverScope; resetsAt?: number } | null {
+ const engineUntil = deps.blockedUntil(selection.instanceId, selection.model);
+ const model = engineUntil === null ? modelHeld(selection) : null;
+ const scope: TakeoverScope | null = engineUntil !== null ? "engine" : model ? model.scope : signedOutHeld(selection.instanceId) ? "signed-out" : null;
+ if (!scope) return null;
+ const carries = (deps.enabled?.() ?? true) && backups(bot.id, selection, scope, approvalModeFor(bot), chosen).length > 0;
+ if (!carries && !(recovering && scope !== "signed-out")) return null;
+ const resetsAt = scope === "engine" ? deps.resetAt?.(selection.instanceId, selection.model) ?? undefined : model?.resetsAt;
+ return { scope, ...(resetsAt && resetsAt > now() ? { resetsAt } : {}) };
+ }
+
+ function carryOnRows(bot: Bot, from: ModelSelection, to: ModelSelection, facts: { scope: TakeoverScope; resetsAt?: number }): CarriedOnRow[] {
+ const told = tell(bot, from, { ...facts, backup: to });
+ const line = facts.scope === "signed-out" ? signedOutLine(refusedName(from, facts.scope), label(to, from))
+ : failoverLine(refusedName(from, facts.scope), label(to, from), facts.resetsAt);
+ return [{ name: `recovery: ${line}`, ok: true, ...(facts.scope === "signed-out" ? { nameCode: "chat.notice.failoverSignedOut", nameParams: { from: refusedName(from, facts.scope), to: label(to, from) } } : {}) }, ...(told && facts.scope === "signed-out" ? [{ name: `notice: ${told}`, ok: true, setup: true }] : [])];
+ }
+
return {
backups,
weighBackups,
@@ -281,16 +300,7 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
/** Before a turn on `selection`: what holds that AI, when another AI can take the turn instead, so it starts there
* with no refused turn first. Null when nothing holds it, or when nothing could carry on and the AI is tried as
* usual. `recovering`: Automatic recovery has backups of its own for a limit. */
- heldAtStart(bot: ThreadBot, selection: ModelSelection, recovering = false): { scope: TakeoverScope; resetsAt?: number } | null {
- const engineUntil = deps.blockedUntil(selection.instanceId, selection.model);
- const model = engineUntil === null ? modelHeld(selection) : null;
- const scope: TakeoverScope | null = engineUntil !== null ? "engine" : model ? model.scope : signedOutHeld(selection.instanceId) ? "signed-out" : null;
- if (!scope) return null;
- const carries = (deps.enabled?.() ?? true) && backups(bot.id, selection, scope, approvalModeFor(bot)).length > 0;
- if (!carries && !(recovering && scope !== "signed-out")) return null;
- const resetsAt = scope === "engine" ? deps.resetAt?.(selection.instanceId, selection.model) ?? undefined : model?.resetsAt;
- return { scope, ...(resetsAt && resetsAt > now() ? { resetsAt } : {}) };
- },
+ heldAtStart,
/** Every runtime event of a bot's thread, with the model its turn ran on: a model's own limit holds that model, a
* refused sign-in holds the AI, and a turn that works ends what held it. */
noteRuntimeEvent(botId: string, selection: ModelSelection | undefined, event: RuntimeEvent): void {
@@ -311,11 +321,20 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
* the notice whose Sign in fixes it. */
carriedOn(bot: Bot, threadId: string, from: ModelSelection, to: ModelSelection, facts: { scope: TakeoverScope; resetsAt?: number }): CarriedOnRow[] {
moved(bot.id, threadId, from, to, facts.resetsAt, facts.scope);
- const told = tell(bot, from, { ...facts, backup: to });
- const line = facts.scope === "signed-out" ? signedOutLine(refusedName(from, facts.scope), label(to, from))
- : failoverLine(refusedName(from, facts.scope), label(to, from), facts.resetsAt);
- return [{ name: `recovery: ${line}`, ok: true, ...(facts.scope === "signed-out" ? { nameCode: "chat.notice.failoverSignedOut", nameParams: { from: refusedName(from, facts.scope), to: label(to, from) } } : {}) }, ...(told && facts.scope === "signed-out" ? [{ name: `notice: ${told}`, ok: true, setup: true }] : [])];
+ return carryOnRows(bot, from, to, facts);
+ },
+ /** Before a turn on `selection`: when what holds that AI is already known and one of `chosen` can take the turn, that
+ * backup and what held it; the backups passed over are logged. Null when the turn goes to `selection` as usual. */
+ takeoverAtStart(bot: ThreadBot, selection: ModelSelection, chosen: readonly ModelSelection[]): { to: ModelSelection; scope: TakeoverScope; resetsAt?: number } | null {
+ const held = heldAtStart(bot, selection, false, chosen);
+ if (!held) return null;
+ const { backups: usable, skipped } = weighBackups(bot.id, selection, held.scope, approvalModeFor(bot), chosen);
+ passedOver(bot, selection, held.scope, skipped);
+ return usable[0] ? { to: usable[0], ...held } : null;
},
+ /** A turn of a room that runs on `to` while `from` is held: the person hears it once, and these are the rows the room
+ * shows. Nothing is recorded to go back, since the member's own AI is tried again on its next turn. */
+ carryOnRows,
/** True once per bot for each stretch of this limit or sign-out: the one incident its Chief is told about, not one per
* refused turn. */
firstIncident(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", resetsAt?: number): boolean {
diff --git a/server/host/room-limit-takeover.test.ts b/server/host/room-limit-takeover.test.ts
new file mode 100644
index 0000000000..5d5ade6c60
--- /dev/null
+++ b/server/host/room-limit-takeover.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { ModelSelection, RuntimeEvent } from "../contracts.ts";
+import type { Message } from "../store.ts";
+import { createRoomLimitTakeover, type RoomLimitTakeoverDeps } from "./room-limit-takeover.ts";
+
+const CLAUDE: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
+const CODEX: ModelSelection = { instanceId: "codex", model: "gpt-6" };
+const ANA = { id: "ana", name: "Ana", modelSelection: CLAUDE, fallback: [CODEX] };
+const LIMIT = "You've hit your weekly limit · resets Oct 12 at 2:30pm (Asia/Calcutta)";
+const ended = (extra: Partial<Extract<RuntimeEvent, { type: "turn.completed" }>> = {}) =>
+ ({ eventId: "e", provider: "claudeAgent", createdAt: new Date(0).toISOString(), threadId: "room", turnId: "turn-1", type: "turn.completed", ok: false, stopReason: "quota", ...extra }) as Extract<RuntimeEvent, { type: "turn.completed" }>;
+
+function room(overrides: { rows?: Message[]; cause?: string; held?: boolean } = {}) {
+ const takeover = {
+ takeoverAtStart: vi.fn(() => ({ to: CODEX, scope: "engine" as const })),
+ heldAtStart: vi.fn(() => (overrides.held === false ? null : { scope: "engine" as const })),
+ noteRuntimeEvent: vi.fn(),
+ };
+ const deps: RoomLimitTakeoverDeps = {
+ store: { activePath: () => overrides.rows ?? [] },
+ turnStops: { read: () => undefined, failureCause: () => overrides.cause ?? LIMIT },
+ takeover: () => takeover,
+ };
+ return { limits: createRoomLimitTakeover(deps), takeover };
+}
+
+describe("a room member at its usage limit", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("starts its turn on a backup of the bot's own, at the member's own approval level", () => {
+ const { limits, takeover } = room();
+ expect(limits.atStart(ANA, "full")).toEqual({ to: CODEX, scope: "engine" });
+ expect(takeover.takeoverAtStart).toHaveBeenCalledWith({ id: "ana", name: "Ana", approvalMode: "full" }, CLAUDE, [CODEX]);
+ limits.atStart({ ...ANA, fallback: undefined }, "full");
+ expect(takeover.takeoverAtStart, "no backup of its own: none, whatever the installation has").toHaveBeenLastCalledWith(expect.anything(), CLAUDE, []);
+ });
+
+ it("notes the room's events as the speaker's, on the model its turn ran on", () => {
+ const { limits, takeover } = room();
+ limits.dispatched("room", CODEX);
+ const event = ended({ ok: true });
+ limits.noteEvent("ana", event);
+ expect(takeover.noteRuntimeEvent).toHaveBeenCalledWith("ana", CODEX, event);
+ });
+
+ it("sends a turn refused before anything ran once more, and never again from within that resend", async () => {
+ const { limits } = room();
+ const inner = vi.fn(async () => true);
+ const again = vi.fn(async () => (await limits.resendOnce("room", ANA, "full", ended(), 0, inner)) ?? "not again");
+ expect(await limits.resendOnce("room", ANA, "full", ended(), 0, again)).toBe("not again");
+ expect(again).toHaveBeenCalledTimes(1);
+ expect(inner).not.toHaveBeenCalled();
+ expect(await limits.resendOnce("room", ANA, "full", ended(), 0, inner), "a later turn may be resent again").toBe(true);
+ });
+
+ it.each<[string, Parameters<typeof room>[0], ReturnType<typeof ended> | undefined]>([
+ ["a turn that worked", {}, ended({ ok: true })],
+ ["a turn with no end seen", {}, undefined],
+ ["a failure that is no limit", { cause: "The model crashed" }, ended({ stopReason: "error" })],
+ ["a turn that already said something", { rows: [{ id: "m", at: 5, role: "bot", kind: "text", text: "Half an answer" } as Message] }, ended()],
+ ["a turn that already ran a tool", { rows: [{ id: "m", at: 5, role: "bot", kind: "activity", tool: { name: "ls", ok: true, itemId: "i1" } } as Message] }, ended()],
+ ["a member with no backup to take it", { held: false }, ended()],
+ ])("sends nothing again for %s", async (_name, overrides, end) => {
+ const { limits } = room(overrides);
+ const again = vi.fn(async () => true);
+ expect(await limits.resendOnce("room", ANA, "full", end, 0, again)).toBeUndefined();
+ expect(again).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/host/room-limit-takeover.ts b/server/host/room-limit-takeover.ts
new file mode 100644
index 0000000000..905b47e19b
--- /dev/null
+++ b/server/host/room-limit-takeover.ts
@@ -0,0 +1,53 @@
+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 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[] };
+type TurnEnded = Extract<RuntimeEvent, { type: "turn.completed" }>;
+
+export interface RoomLimitTakeoverDeps {
+ store: Pick<Store, "activePath">;
+ turnStops: Pick<TurnStops, "read" | "failureCause">;
+ takeover(): Pick<LimitTakeover, "takeoverAtStart" | "heldAtStart" | "noteRuntimeEvent">;
+}
+
+export function createRoomLimitTakeover(deps: RoomLimitTakeoverDeps) {
+ const selections = new Map<string, ModelSelection>();
+ const resending = new Set<string>();
+
+ return {
+ atStart: (member: Member, approvalMode: ApprovalMode) =>
+ deps.takeover().takeoverAtStart({ id: member.id, name: member.name, approvalMode }, member.modelSelection, member.fallback ?? []),
+ dispatched(threadId: string, selection: ModelSelection): void {
+ selections.set(threadId, selection);
+ },
+ selectionOf: (threadId: string): ModelSelection | undefined => selections.get(threadId),
+ noteEvent(speakerId: string, event: RuntimeEvent): void {
+ deps.takeover().noteRuntimeEvent(speakerId, selections.get(event.threadId), event);
+ },
+ /** Runs `again` once when this member's turn ended refused at a usage limit or a sign-out before it said or did
+ * anything, and a backup now takes its next turn: a turn that ran anything would run it twice. */
+ async resendOnce<T>(threadId: string, member: Member, approvalMode: ApprovalMode, ended: TurnEnded | undefined, since: number,
+ again: () => Promise<T>): Promise<T | undefined> {
+ const key = `${threadId}\u0000${member.id}`;
+ if (!ended || ended.ok || resending.has(key)) return undefined;
+ const said = deps.turnStops.failureCause(ended);
+ if (!turnLimitScope(ended, deps.turnStops.read(threadId, ended.turnId)?.flags, said)) return undefined;
+ if (!nothingRan(deps.store.activePath(threadId), since, ended.turnId, said)) return undefined;
+ if (!deps.takeover().heldAtStart({ id: member.id, name: member.name, approvalMode }, member.modelSelection, false, member.fallback ?? [])) return undefined;
+ resending.add(key);
+ try {
+ return await again();
+ } finally {
+ resending.delete(key);
+ }
+ },
+ };
+}
+
+export type RoomLimitTakeover = ReturnType<typeof createRoomLimitTakeover>;
diff --git a/server/index.ts b/server/index.ts
index f22d1752c5..ad1bca055b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -211,7 +211,7 @@ import {
} from "./contracts.ts";
import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";
import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts"; import { outOfProcesses } from "./process-shortage.ts";
-import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts";
+import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts"; import { createRoomLimitTakeover } from "./host/room-limit-takeover.ts";
import { decodeGeneratedImage } from "./generated-image.ts";
import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";
import {
@@ -4940,7 +4940,7 @@ const TURN_STALL_MS = Math.max(60_000, stallLimitMs(process.env.OMB_TURN_STALL_M
const TOOL_STALL_MS = Math.max(TURN_STALL_MS, stallLimitMs(process.env.OMB_TOOL_STALL_MS, 2 * 60 * 60_000));
const COMPUTER_WAIT_MAX_MS = Math.max(1_000, Number(process.env.OMB_COMPUTER_WAIT_MAX_MS) || 30 * 60_000);
const roomStallCompletions = new RoomTurnStallRegistry();
-const turnStops = new TurnStops();
+const turnStops = new TurnStops(); const roomLimits = createRoomLimitTakeover({ store, turnStops, takeover: () => limitTakeover });
function stoppedTurnText(threadId: string, turnId: string | undefined, cause?: string, stopReason?: string | null): string {
const stop = turnStops.read(threadId, turnId);
const reason = cause ?? stop?.cause ?? stop?.error ?? `The turn did not complete (${stopReason?.trim() || "no reason given"})`;
@@ -6328,6 +6328,7 @@ bus.subscribe((event: RuntimeEvent) => {
const group = bot ? undefined : store.groupByThread(event.threadId);
if (!bot && !group) return;
const speaker = group ? groupSpeakers.get(event.threadId) : undefined;
+ if (speaker && !replayed) roomLimits.noteEvent(speaker.botId, event);
const pushMessage = (m: Omit<Message, "id" | "at">) => {
const owner = bot ? directRequestOwners.get(event.threadId) : undefined;
@@ -6795,7 +6796,7 @@ bus.subscribe((event: RuntimeEvent) => {
} else if (group && speaker) {
const tokens = event.usage ?? lastReported;
const speakingBot = store.bot(speaker.botId);
- const selection = speakingBot?.modelSelection;
+ const selection = roomLimits.selectionOf(event.threadId) ?? speakingBot?.modelSelection;
roomMemberContexts.record(event.threadId, speaker.botId, compactionReading(registry.get(event.providerInstanceId ?? selection?.instanceId ?? "")?.adapter.capabilities, lastContext), selection?.model, selection && registry.get(selection.instanceId)?.models);
const promptBytes = turnPromptBytes.get(event.threadId);
turnPromptBytes.delete(event.threadId);
@@ -9558,9 +9559,12 @@ async function runClaimedGroupMemberTurn(
const preparedApprovalMode = roomTurnApprovalMode(bot, threadId, orchestration);
const preparedSelection = { ...bot.modelSelection };
const preparedComposio = bot.composio;
- const instance = registry.get(bot.modelSelection.instanceId);
+ const ownInstance = registry.get(bot.modelSelection.instanceId);
+ const roomTakeover = roomLimits.atStart(bot, preparedApprovalMode);
+ const turnSelection: ModelSelection = roomTakeover?.to ?? preparedSelection;
+ const instance = registry.get(turnSelection.instanceId);
const userName = userNameFor(threadId);
- if (providerInstancesChanging.has(bot.modelSelection.instanceId)) {
+ if (providerInstancesChanging.has(bot.modelSelection.instanceId) || providerInstancesChanging.has(turnSelection.instanceId)) {
onDispatchError?.(`${bot.name}'s provider account is being updated — try again shortly`);
return true;
}
@@ -9634,7 +9638,7 @@ async function runClaimedGroupMemberTurn(
const reportDispatchError = (message: string) => { roomFailure = message; onDispatchError?.(message); };
try {
assertWithinBudget(cfg, DATA_DIR); if (!operation?.continuesRun) usageCapGate.assertTurn(bot.id, personWaitingInRoom(operation, routineTriggerOf(threadId)), threadLanguage(threadId));
- assertModelVariantSupported(preparedSelection, instance.adapter.capabilities);
+ assertModelVariantSupported(turnSelection, instance.adapter.capabilities);
const integrations: NonNullable<Parameters<typeof instance.adapter.sendTurn>[0]["integrations"]> = {};
const skillAuthoring =
skillAuthoringEnabled(cfg) &&
@@ -9726,7 +9730,8 @@ async function runClaimedGroupMemberTurn(
: Boolean(readyGroup && store.groupTaskByThread(readyGroup.id, threadId));
if (!readyGroup || !stillOwnsThread || !readyGroup.memberIds.includes(readyBot.id)) return false;
const setupChanged =
- registry.get(readyBot.modelSelection.instanceId) !== instance ||
+ registry.get(readyBot.modelSelection.instanceId) !== ownInstance ||
+ registry.get(turnSelection.instanceId) !== instance ||
roomTurnApprovalMode(readyBot, threadId, orchestration) !== preparedApprovalMode ||
readyBot.modelSelection.instanceId !== preparedSelection.instanceId ||
readyBot.modelSelection.model !== preparedSelection.model ||
@@ -9850,7 +9855,7 @@ async function runClaimedGroupMemberTurn(
const roomPlaceRefusal = roomKind && computerPlaceRefusal(roomKind);
if (roomPlaceRefusal) throw Object.assign(new Error(roomPlaceRefusal.message), { code: roomPlaceRefusal.code });
if (!roomTeamComputer && roomPlan.computer === "cloud") {
- const unsupported = cloudPlaceRefusal(cloudEngine(instance, readyBot.modelSelection.model), "room", readyBot.name)
+ const unsupported = cloudPlaceRefusal(cloudEngine(instance, turnSelection.model), "room", readyBot.name)
?? computerToolsRefusal(readyBot.toolScope, "room", readyBot.name);
if (unsupported) throw unsupported;
}
@@ -9930,7 +9935,7 @@ async function runClaimedGroupMemberTurn(
// The speaker's desktop, never the coordinator's; claim the lease before asynchronous VM setup.
if (readyBot.computer === "vm") {
if (instance.adapter.capabilities.computerMcp !== true) {
- throw placeUnavailable("vm", { state: "vm-cannot", params: { bot: readyBot.name, model: cloudEngine(instance, readyBot.modelSelection.model).name }, source: "room" }, Boolean(CLOUD_HOME));
+ throw placeUnavailable("vm", { state: "vm-cannot", params: { bot: readyBot.name, model: cloudEngine(instance, turnSelection.model).name }, source: "room" }, Boolean(CLOUD_HOME));
}
const target = { ...localVmTargetForThread(readyBot.id, threadId) };
await waitForLocalVmUpdate(target, threadId, roomSetupIsCurrent, { botId: readyBot.id, name: readyBot.name, color: readyBot.color });
@@ -10114,6 +10119,8 @@ async function runClaimedGroupMemberTurn(
}
const turnTexts: string[] = [];
let turnCompletedOk = false;
+ let turnCompleted: Extract<RuntimeEvent, { type: "turn.completed" }> | undefined;
+ let oneTimeInputTaken = false;
let providerTurnId: string | undefined;
let abandoned = false;
const retirementOwner = `room-abandoned:${randomUUID()}`;
@@ -10165,6 +10172,7 @@ async function runClaimedGroupMemberTurn(
if (e.type === "item.completed" && e.itemType === "assistant_text") turnTexts.push(e.text);
else if (e.type === "turn.completed") {
turnCompletedOk = e.ok;
+ turnCompleted = e;
const end = roomTurnEnd(e, Boolean(orchestration), roomClaimFailure);
if (orchestration && end.stopReason !== undefined) {
orchestration.result.stopReason = roomClaimFailure ? end.stopReason : stoppedTurnText(threadId, e.turnId, undefined, end.stopReason);
@@ -10190,11 +10198,15 @@ async function runClaimedGroupMemberTurn(
clearHeldReplay(group.id, bot.id, heldReplay.messageIds);
turnPromptBytes.set(threadId, { stable: Buffer.byteLength(roomSystem.stable), volatile: Buffer.byteLength(roomSystem.volatile) });
runningTurnEngines.set(threadId, instance);
+ const roomSelection = roomTakeover ? turnSelection : readyBot.modelSelection; roomLimits.dispatched(threadId, roomSelection);
// A private chat reaches a room only through the explicit, disclosed session_search, never automatically.
const roomRecalled = cardContinuation ? "" : autoRecallPrompt(bot, threadId, resolvedLatestImages.text, { conversations: false, userName });
const turnApprovalMode = roomTurnApprovalMode(readyBot, threadId, orchestration);
if (!done) releaseTurnLevel = roomTurnLevels.dispatched(threadId, readyBot.id, turnApprovalMode);
const { reset: roomReset, displaced } = roomMemberContexts.dispatch(threadId, readyBot.id, instance.instanceId, cfg.context);
+ for (const tool of roomTakeover ? limitTakeover.carryOnRows(readyBot, preparedSelection, roomTakeover.to, roomTakeover) : []) {
+ store.appendMessage(threadId, { role: "bot", kind: "activity", from: { botId: readyBot.id, name: readyBot.name, color: readyBot.color }, tool });
+ }
if (roomReset) {
store.appendMessage(threadId, {
role: "bot", kind: "activity", from: { botId: readyBot.id, name: readyBot.name, color: readyBot.color },
@@ -10203,12 +10215,12 @@ async function runClaimedGroupMemberTurn(
}
if (roomReset || displaced) broadcast({ kind: "group", group: publicGroupState(store.group(groupId) ?? group) });
const roomShareNote = skillsHost.shareNote(bot, threadId, Boolean(workspace));
- const clock = turnClockLine(Date.now(), hostTimeZone()), roomPick = cardContinuation ? "" : takeRoomPick(operation, readyBot.id);
+ const clock = turnClockLine(Date.now(), hostTimeZone()), roomPick = cardContinuation ? "" : takeRoomPick(operation, readyBot.id); oneTimeInputTaken = Boolean(roomPick) || heldReplay.messageIds.length > 0;
const roomToolScope = toolScopeForTurn(readyBot.id), roomUserMcp = claudeUserMcpEnabled(cfg) && !managedPolicy.restrictsMcp();
const roomSession = roomSessions.dispatch({
threadId, botId: readyBot.id, claimId: internalGeneration, instance, guestConfined: roomGuestConfined, reset: Boolean(roomReset), hooks: Boolean(integrations.hooks),
context: () => ({ ...roomMemberContexts.forThread(threadId)?.[readyBot.id], compactAt: nativeCompactTokens(instance) }),
- config: [roomSystem.stable, cwd, readyBot.modelSelection, turnApprovalMode, roomToolScope, roomUserMcp, integrations],
+ config: [roomSystem.stable, cwd, roomSelection, turnApprovalMode, roomToolScope, roomUserMcp, integrations],
window: roomWindow, tail: roomTail, wrap: (body) => withTurnClock(clock, withRecalled(roomRecalled, roomPick + attachmentsForBox(body, cwd) + roomShareNote.text + devsReports.note(threadId, Boolean(integrations.agents)))),
});
guardTurnDispatch(roomShareNote.after(instance.adapter.sendTurn({
@@ -10229,8 +10241,8 @@ async function runClaimedGroupMemberTurn(
...(integrations.browser && browserIsThePlace(roomPlan) ? { preloadBrowserTools: true } : {}),
...skillsHost.turnSettings(readyBot, threadId, instance, managedPolicy.restrictsMcp()),
botSettingsFile: botSettingsFile(readyBot),
- ...(instance.instanceId === readyBot.modelSelection.instanceId
- ? memberTurnSelection(readyBot.modelSelection)
+ ...(instance.instanceId === roomSelection.instanceId
+ ? memberTurnSelection(roomSelection)
: { model: instance.models.default }),
})), () => abandoned || Boolean(isCancelled?.()), async () => {
// Stop may have landed before the adapter had a process to interrupt: interrupt again now.
@@ -10346,6 +10358,9 @@ async function runClaimedGroupMemberTurn(
if (skillAuthoring) skillAuthoringClaim.claimed = false;
return false;
}
+ const resent = orchestration || cardContinuation || oneTimeInputTaken || outcome !== "settled" || isCancelled?.() ? undefined : await roomLimits.resendOnce(threadId, bot, preparedApprovalMode, turnCompleted, roomSpeaker?.since ?? 0,
+ () => runGroupMemberTurn(groupId, threadId, bot.id, hop, spoken, undefined, onDispatchError, isCancelled, onProviderHandshakeStarted, onProviderHandshakeSettled, skillAuthoringClaim, undefined, operation));
+ if (resent !== undefined) return resent;
if (
!orchestration &&
diff --git a/server/room-limit-takeover.e2e.test.ts b/server/room-limit-takeover.e2e.test.ts
new file mode 100644
index 0000000000..72d2e50365
--- /dev/null
+++ b/server/room-limit-takeover.e2e.test.ts
@@ -0,0 +1,106 @@
+// A room member whose AI is at its usage limit carries on with a backup, as a bot in its own chat does.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { handleToolCall, request } from "../scripts/mcp-server.ts";
+import { readUsage } from "./usage-ledger.ts";
+
+const LIMIT = "You've hit your weekly limit · resets Oct 12 at 2:30pm (Asia/Calcutta)";
+const BACKUP_REPLY = "done from fake codex";
+
+const jsonLines = (path: string): any[] => existsSync(path)
+ ? readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+
+type Room = { api: (method: string, path: string, body?: unknown) => Promise<any>; send: (text: string, settles?: string) => Promise<void>; messages: () => Promise<any[]>; claudeTurns: () => any[]; usage: () => any[]; bot: any };
+
+/** One room with one member on fake Claude, whose every turn its usage limit refuses, and fake Codex beside it. */
+async function withLimitedRoom(choose: (f: { api: (method: string, path: string, body?: unknown) => Promise<any>; bot: any; codex: { instanceId: string; model: string } }) => Promise<void>,
+ check: (f: Room) => Promise<void>) {
+ const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true }, ["codex"]);
+ const { url, dataDir, logPath } = fixture.info;
+ const evidence: unknown[] = [{ url }];
+ const cli = (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;
+ const tool = (name: string, args: Record<string, unknown>) => handleToolCall(name, args, (path, options) => request(path, options, url)) as Promise<any>;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(url + path, {
+ method, headers: { "content-type": "application/json", origin: url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),
+ });
+ const result: any = await response.json();
+ expect(response.ok, `${method} ${path}: ${JSON.stringify(result)}`).toBe(true);
+ return result;
+ };
+ const planPath = join(dataDir, "room-plan.json");
+ try {
+ await expect.poll(async () => {
+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };
+ return instances.find((instance) => instance.instanceId === "codex")?.models.options.length > 0;
+ }, { timeout: 30_000 }).toBe(true);
+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };
+ const codex = { instanceId: "codex", model: instances.find((instance) => instance.instanceId === "codex").models.default as string };
+ // A Chief's turn on the same fake Claude would work and end the limit, which a real limit would refuse as well.
+ const { bots } = await api("GET", "/api/bots") as { bots: Array<{ id: string; chiefOfStaff?: boolean }> };
+ for (const chief of bots.filter((entry) => entry.chiefOfStaff)) await api("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: false });
+ const { bot } = await cli("new-bot", "--name", "Analyst");
+ expect(bot.modelSelection?.instanceId ?? (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).modelSelection.instanceId).toBe("claude");
+ const { channel } = await tool("create_channel", { name: "Numbers", member_ids: [bot.id] });
+ writeFileSync(planPath, JSON.stringify({ [bot.id]: { failWith: LIMIT } }));
+ await choose({ api, bot, codex });
+ const send = async (text: string, settles = "settled") => {
+ await cli("send-channel", "--channel", channel.id, "--text", `@Analyst ${text}`);
+ expect((await cli("wait", "--channel", channel.id, "--timeout", "60")).status).toBe(settles);
+ };
+ const messages = async () => (await api("GET", `/api/threads/${channel.activeTaskId}/messages?limit=200`)).messages as any[];
+ try {
+ const usage = () => readUsage(dataDir, { from: new Date(Date.now() - 3_600_000), to: new Date(Date.now() + 3_600_000) }).filter((row) => row.threadId === channel.activeTaskId && row.botId === bot.id);
+ await check({ api, send, messages, claudeTurns: () => jsonLines(`${planPath}.evidence.jsonl`).filter((turn) => turn.botId === bot.id), usage, bot });
+ } finally {
+ evidence.push({ messages: await messages() });
+ }
+ } finally {
+ evidence.push({ claudeTurns: jsonLines(`${planPath}.evidence.jsonl`) });
+ writeFileSync(`${logPath}.room-limit-takeover.json`, JSON.stringify(evidence, null, 2));
+ await fixture.close();
+ console.info(JSON.stringify({ logPath, fixtureRemoved: !existsSync(dataDir) }));
+ }
+}
+
+/** The refused turn is answered once by the backup, the room says which AI took over, and the member's next turn starts
+ * on the backup with no refused turn first. The member's own model stays as it was. */
+async function carriesOn({ api, send, messages, claudeTurns, usage, bot }: Room) {
+ await send("How did October close?");
+ expect(claudeTurns()).toHaveLength(1);
+ let rows = await messages();
+ expect(rows.filter((row) => row.role === "bot" && row.kind === "text" && row.text === BACKUP_REPLY)).toHaveLength(1);
+ expect(rows.find((row) => row.role === "bot" && row.kind === "text" && row.text === BACKUP_REPLY)?.from?.botId).toBe(bot.id);
+ expect(rows.filter((row) => row.kind === "activity" && /^recovery: .*took over\.$/.test(row.tool?.name ?? ""))).toHaveLength(1);
+ expect(rows.filter((row) => row.role === "user")).toHaveLength(1);
+
+ await send("And November so far?");
+ expect(claudeTurns(), "the limit is known, so the next turn starts on the backup").toHaveLength(1);
+ rows = await messages();
+ expect(rows.filter((row) => row.role === "bot" && row.kind === "text" && row.text === BACKUP_REPLY)).toHaveLength(2);
+ expect((await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).modelSelection.instanceId).toBe("claude");
+ await expect.poll(() => usage().filter((row) => row.instanceId === "codex").length, { timeout: 15_000, message: "each backup turn is booked to the backup" }).toBe(2);
+}
+
+it("carries a room member at its usage limit on with that bot's own backup", async () => {
+ await withLimitedRoom(async ({ api, bot, codex }) => {
+ await api("PATCH", `/api/bots/${bot.id}`, { fallback: [codex] });
+ }, carriesOn);
+}, 180_000);
+
+it("never sends a room member's turn to the installation's backup, which leaves channels out", async () => {
+ await withLimitedRoom(async ({ api, codex }) => {
+ await api("PUT", "/api/config", { automaticRecovery: { enabled: true, backup: codex } });
+ }, async ({ send, messages, claudeTurns, usage }) => {
+ await send("How did October close?", "failed");
+ await send("And November so far?", "failed");
+ expect(claudeTurns(), "each turn is tried on its own AI, as before").toHaveLength(2);
+ const rows = await messages();
+ expect(rows.some((row) => row.kind === "text" && row.text === BACKUP_REPLY)).toBe(false);
+ expect(rows.some((row) => row.kind === "activity" && /took over/.test(row.tool?.name ?? ""))).toBe(false);
+ expect(usage().some((row) => row.instanceId === "codex")).toBe(false);
+ });
+}, 180_000);