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 limited or signed-out AI stays skipped for every new turn and thread, and is said once (#3907)
Milind Sonie9ab49fbe22c
diff --git a/docs/routine-schedules.md b/docs/routine-schedules.mdindex 2cacfc799a..4b783d124d 100644--- a/docs/routine-schedules.md+++ b/docs/routine-schedules.md@@ -110,9 +110,10 @@ use an appropriate event/webhook workflow instead of a fake weekly schedule.starts again; the same run, never a copy.- Its bot or conversation was busy when it started: it waits there,checking every 30 s, for up to an hour.- - A usage limit with another AI that can carry on: the run starts again on- that AI after a short wait (see "When an engine runs out" in- self-hosting.md), and the owner hears once that the bot is using it.+ - A usage limit with another AI that can carry on, or a signed-out AI with a+ backup AI of the bot's own (or the app-wide one while Automatic recovery is+ on): the run starts again on that AI after a short wait (see "When an engine runs out" and "When an engine is signed+ out" in self-hosting.md), and the owner hears once that the bot is using it.- Signed out, out of credit, payment required, a usage limit nothing can carryon from, or an engine that needs setting up: no retry. The owner gets onenotification per bot and cause saying what to do, and no more until one ofdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 39635bb6b3..fbb07e77de 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -884,25 +884,49 @@ no AI to carry on, it says the bot waits instead. Nobody is asked.then the backups chosen for the bot or in Automatic recovery; then the AI anew bot would get. Only an AI that can run a turn now (installed, signed in,allowed by your organisation, not limited itself) with the tools and the- working folder the current one has. Never another sign-in to the same- subscription, which would rotate accounts around the provider's limit; a- pay-per-use API key on the same AI is fine.+ working folder the current one has, and one the conversation's approval level+ can move to without asking (Auto-accept edits stays on an AI that has it).+ Never another sign-in to the same subscription, which would rotate accounts+ around the provider's limit; a pay-per-use API key on the same AI is fine.- **What moves.** The person's message that met the limit is sent again on thatAI, in that conversation alone; the bot's own model and its other- conversations stay where they are. While the limit lasts, every new turn- (a person's, a routine's, a webhook's) goes straight to that AI without- asking the limited one first, and a routine run the limit stopped starts- again on it.+ conversations stay where they are. While the limit lasts, every new turn and+ conversation of every bot that uses the limited AI (a person's, a routine's,+ a webhook's) goes straight to that AI without asking the limited one first,+ and a routine run the limit stopped starts again on it.- **How long.** The limited AI is held until the reset it named, or for an hour- when it named none. One model's own limit holds that model alone, and for at- most six hours before it is tried again. A conversation that moved goes back- once its AI's limit has reset, with one line saying so.+ when it named none or named one already past; the next turn after that hour+ checks it again. One model's own limit holds that model alone, and for at+ most six hours before it is tried again. The holds are saved+ (`limit-holds.json`, `limit-takeover-holds.json`), so a restart, an update or+ a sleep the Cloud was stopped for keeps them. A conversation that moved goes+ back once its AI's limit has reset, with one line saying so.This is on by default. Start the server with `OMB_QUOTA_SWITCH=0` to switch itoff: then only the backups Automatic recovery names take over, and thenotification says the bot waits. Any other value, or none, leaves it on. Ithas no setting in `config.json` yet.+### When an engine is signed out++When a turn stops because its AI is signed out (its sign-in expired or was+revoked), the person hears it once, in that conversation and as a+notification: "Claude is signed out on the Cloud. Sign in again in Settings →+AI to keep using it.", with a Sign in button that opens those settings. Each+later refused turn still shows that it failed, with no second notice; its+Chief gets one incident, not one a turn. An account out of credit, which some+engines stop the same way, is no sign-out.++The backups a turn its AI never started would get carry on meanwhile (the+bot's own backup AIs, or else the app-wide backup while Automatic recovery is+on), by the same rules as a usage limit (another sign-in to the same AI is fine+here, since nothing is rotated around a limit): the person's message is sent+again there, every new turn and conversation starts there, and a conversation+that moved goes back once the AI is signed in again in the app, or a turn on it+works. No AI is picked for a sign-out by itself, so with no such backup nothing+moves. A new turn tries the signed-out AI again an hour after its last refusal,+unless its status still says signed out.+### Which engine a new bot usesA saved default model (Settings, `openmausbot setup`, or the New Botdiff --git a/server/contracts.ts b/server/contracts.tsindex 033c155236..9ff32f4944 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -46,9 +46,16 @@ export class TurnNotStartedError extends Error {}}-/** The CLI refused sign-in before any model or tool activity, and its process stopped. */+/** The CLI refused sign-in before any model or tool activity, and its process stopped. `known`: refused here because the+ * engine is already known to be signed out, so it is no new refusal. */export class TurnAuthenticationRefusedError extends TurnNotStartedError {override readonly name = "TurnAuthenticationRefusedError";+ readonly known: boolean;++ constructor(turnId: TurnId, message: string, known = false) {+ super(turnId, message);+ this.known = known;+ }}/** The engine's usage limit refused the turn before any model or tool activity (or is known to be refusing untildiff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.tsindex a2673f45a2..d18d60f81a 100644--- a/server/host/limit-takeover.test.ts+++ b/server/host/limit-takeover.test.ts@@ -6,8 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { RuntimeEvent } from "../../shared/runtime-events.ts";import type { ModelSelection } from "../../shared/wire.ts";import type { InstanceConfigMap } from "../contracts.ts";-import { UNNAMED_LIMIT_MS } from "../limit-resets.ts";-import { MODEL_HOLD_MS, createLimitTakeover, type LimitTakeoverDeps, type TakeoverEngine } from "./limit-takeover.ts";+import { LimitResetClock, UNNAMED_LIMIT_MS } from "../limit-resets.ts";+import { MODEL_HOLD_MS, SIGNED_OUT_RECHECK_MS, createLimitTakeover, signedOutStop, type LimitTakeoverDeps, type TakeoverEngine } from "./limit-takeover.ts";const NOW = Date.parse("2026-10-27T10:00:00Z");const HOUR = 3_600_000;@@ -33,14 +33,20 @@ const NAMES: Record<string, string> = { claude: "Claude", codex: "Codex", opencoconst on = (instanceId: string, model: string): ModelSelection => ({ instanceId, model });const KAI = { id: "kai", name: "Kai" };-function takeover(overrides: Partial<LimitTakeoverDeps> = {}) {+const freshDir = () => {const dir = mkdtempSync(join(tmpdir(), "omb-limit-takeover-"));dirs.push(dir);+ return dir;+};++/** `dir`: the data folder, the same one again for a restart. */+function takeover(overrides: Partial<LimitTakeoverDeps> = {}, dir = freshDir()) {const now = { at: NOW };const told: Array<{ bot: string; text: string }> = [];const record = vi.fn();const instance = createLimitTakeover({file: join(dir, "limit-notices.json"),+ holdsFile: join(dir, "limit-takeover-holds.json"),engines: () => [CLAUDE, CODEX, GO],configs: () => ({}),context: {},@@ -107,15 +113,15 @@ describe("a model's own limit", () => {it("holds that model alone until the reset it named, at most six hours, an hour when it named none, and not once it works", () => {const { instance, now } = takeover();- instance.noteRuntimeEvent(on("claude", "claude-opus-5-5"), error("model", NOW + 2 * HOUR));+ instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), error("model", NOW + 2 * HOUR));expect(instance.modelHeld(on("claude", "claude-opus-5-5"))).toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });expect(instance.modelHeld(on("claude", "claude-sonnet-5")), "the AI's other models still work").toBeNull();- instance.noteRuntimeEvent(on("claude", "claude-opus-5-5"), error("model", NOW + 50 * HOUR));+ instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), error("model", NOW + 50 * HOUR));expect(instance.modelHeld(on("claude", "claude-opus-5-5")), "tried again after six hours, the named reset kept").toEqual({ until: NOW + MODEL_HOLD_MS, resetsAt: NOW + 50 * HOUR, scope: "model" });instance.holdModel(on("claude", "claude-sonnet-5"), "credits");expect(instance.modelHeld(on("claude", "claude-sonnet-5"))).toEqual({ until: NOW + UNNAMED_LIMIT_MS, scope: "credits" });- instance.noteRuntimeEvent(on("codex", "gpt-6"), error("engine"));+ instance.noteRuntimeEvent("kai", on("codex", "gpt-6"), error("engine"));expect(instance.modelHeld(on("codex", "gpt-6")), "an engine's own limit is the reset clock's to hold").toBeNull();expect(instance.backups("kai", on("codex", "gpt-6")), "a held model carries on nothing").toEqual([on("opencode", "go-default")]);@@ -174,3 +180,191 @@ describe("what the person hears", () => {]);});});++describe("a new conversation once an AI is known to be at its limit", () => {+ const event = (threadId: string, type: string, extra: Record<string, unknown> = {}) =>+ ({ eventId: "e", provider: "claudeAgent", createdAt: new Date(NOW).toISOString(), threadId, type, ...extra }) as RuntimeEvent;+ /** The reset clock and the takeover as the server wires them, on one data folder: `boot` again is a restart. */+ function server() {+ const dir = freshDir();+ const at = { now: NOW };+ const boot = () => {+ const clock = new LimitResetClock({ accounts: () => [], now: () => at.now, file: join(dir, "limit-holds.json") });+ const { instance, told } = takeover({ blockedUntil: (id) => clock.blockedUntil(id), resetAt: (id) => clock.resetAt(id), now: () => at.now }, dir);+ return { clock, instance, told };+ };+ return { at, boot };+ }+ /** A turn on Claude that its usage limit refused. */+ const refused = (clock: LimitResetClock, threadId: string, limitResetsAt?: number) => {+ clock.noteRuntimeEvent("claude", event(threadId, "turn.started"));+ clock.noteRuntimeEvent(undefined, event(threadId, "runtime.error", { message: "limit", limit: "engine", ...(limitResetsAt ? { limitResetsAt } : {}) }));+ clock.noteRuntimeEvent(undefined, event(threadId, "turn.completed", { ok: false, stopReason: "quota" }));+ };+ const ROSA = { id: "rosa", name: "Rosa" };++ it("starts every bot's next conversation on the AI that carries on, a restart included, until the limit resets", () => {+ const { at, boot } = server();+ const first = boot();+ refused(first.clock, "t1", NOW + 5 * HOUR);+ expect(first.instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "engine", resetsAt: NOW + 5 * HOUR });+ expect(first.instance.heldAtStart(ROSA, on("claude", "claude-sonnet-5")), "every bot that uses it").toEqual({ scope: "engine", resetsAt: NOW + 5 * HOUR });++ at.now = NOW + 20 * 60_000;+ const restarted = boot();+ expect(restarted.clock.blockedUntil("claude"), "a restart, or a sleep the Cloud was stopped for, still knows the limit").toBe(NOW + 5 * HOUR);+ expect(restarted.instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "engine", resetsAt: NOW + 5 * HOUR });+ expect(restarted.instance.backups("kai", on("claude", "claude-opus-5-5"))).toEqual([on("codex", "gpt-6")]);++ at.now = NOW + 5 * HOUR + 1;+ expect(restarted.instance.heldAtStart(KAI, on("claude", "claude-opus-5-5")), "back on its own AI once the limit resets").toBeNull();+ });++ it("with no reset named, or one already past, holds the AI until it is checked again an hour after its last refusal", () => {+ const { at, boot } = server();+ const { clock, instance } = boot();+ refused(clock, "t1", NOW - 60_000);+ expect(instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "engine" });+ at.now = NOW + UNNAMED_LIMIT_MS - 1;+ expect(boot().instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "engine" });+ at.now = NOW + UNNAMED_LIMIT_MS + 1;+ expect(boot().instance.heldAtStart(KAI, on("claude", "claude-opus-5-5")), "the next turn checks it again").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();+ refused(clock, "t1", NOW + 5 * HOUR);+ expect(instance.backups("kai", on("claude", "claude-opus-5-5"), "engine", "edits")).toEqual([]);+ expect(instance.heldAtStart({ ...KAI, approvalMode: "edits" }, on("claude", "claude-opus-5-5"))).toBeNull();+ expect(instance.heldAtStart({ ...KAI, approvalMode: "full" }, on("claude", "claude-opus-5-5"))).toEqual({ scope: "engine", resetsAt: NOW + 5 * HOUR });+ });++ it("is off with the quota switch, unless Automatic recovery has backups of its own for a limit", () => {+ const { boot } = server();+ const { clock } = boot();+ refused(clock, "t1", NOW + 5 * HOUR);+ const off = takeover({ blockedUntil: (id) => clock.blockedUntil(id), enabled: () => false }).instance;+ expect(off.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toBeNull();+ expect(off.heldAtStart(KAI, on("claude", "claude-opus-5-5"), true)).toEqual({ scope: "engine" });+ });++ it("keeps one model's own limit through a restart, and a turn that works on another model leaves it held", () => {+ const dir = freshDir();+ const { instance } = takeover({}, dir);+ instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), event("t1", "runtime.error", { message: "limit", limit: "model", limitResetsAt: NOW + 2 * HOUR }));+ instance.noteRuntimeEvent("kai", on("claude", "claude-sonnet-5"), event("t2", "turn.completed", { ok: true }));+ const restarted = takeover({}, dir).instance;+ expect(restarted.modelHeld(on("claude", "claude-opus-5-5"))).toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });+ expect(restarted.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "model", resetsAt: NOW + 2 * HOUR });+ });++ it("says once per bot what carries on in a conversation that moved at its start, and records it to go back", () => {+ const { instance, told, record } = takeover({ chosen: () => [on("codex", "gpt-6")] });+ expect(instance.carriedOn(KAI, "t1", on("claude", "claude-opus-5-5"), on("codex", "gpt-6"), { scope: "engine", resetsAt: NOW + HOUR }))+ .toEqual([{ name: expect.stringMatching(/^recovery: Claude hit its limit \(resets .+\), so Codex took over\.$/), ok: true }]);+ expect(instance.carriedOn(KAI, "t2", on("claude", "claude-opus-5-5"), on("codex", "gpt-6"), { scope: "engine", resetsAt: NOW + HOUR })).toHaveLength(1);+ expect(told).toHaveLength(1);+ expect(record.mock.calls.map(([failover]) => failover.threadId)).toEqual(["t1", "t2"]);+ });+});++describe("an AI that is signed out", () => {+ const event = (type: string, extra: Record<string, unknown> = {}) =>+ ({ eventId: "e", provider: "claudeAgent", createdAt: new Date(NOW).toISOString(), threadId: "t1", type, ...extra }) as RuntimeEvent;+ const CLAUDE_ON = on("claude", "claude-opus-5-5");+ /** A turn on Claude that stopped because Claude is signed out, as Claude Code says it. */+ const signedOut = (instance: ReturnType<typeof takeover>["instance"], said = "Invalid API key · Please run /login") => {+ instance.noteRuntimeEvent("kai", CLAUDE_ON, event("runtime.error", { message: said, setup: true }));+ instance.noteRuntimeEvent("kai", CLAUDE_ON, event("turn.completed", { ok: false, stopReason: "auth_required" }));+ };++ it("sends new turns to a backup the person chose, says it once with the way to sign in, and goes back once signed in", () => {+ const { instance, told, record } = takeover({ chosen: () => [on("codex", "gpt-6")], where: "on the Cloud" });+ signedOut(instance);+ expect(instance.heldAtStart(KAI, CLAUDE_ON)).toEqual({ scope: "signed-out" });+ expect(instance.backups("kai", CLAUDE_ON, "signed-out")).toEqual([on("codex", "gpt-6")]);+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).toBe("Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.");+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out", backup: on("codex", "gpt-6") }), "once, not once a turn").toBeNull();+ signedOut(instance);+ expect(instance.carriedOn(KAI, "t2", CLAUDE_ON, on("codex", "gpt-6"), { scope: "signed-out" }))+ .toEqual([{ name: "recovery: Claude is signed out, so Codex took over.", ok: true }]);+ expect(told.map((entry) => entry.text)).toEqual(["Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it."]);+ expect(record.mock.calls.at(-1)![0]).toMatchObject({ threadId: "t2", why: "signed-out", resetsAt: null });++ instance.signedIn("claude");+ expect(instance.heldAtStart(KAI, CLAUDE_ON)).toBeNull();+ expect(instance.stillSignedOut("claude")).toBe(false);+ signedOut(instance);+ expect(instance.carriedOn(KAI, "t3", CLAUDE_ON, on("codex", "gpt-6"), { scope: "signed-out" }), "a new sign-out is told again").toEqual([+ { name: "recovery: Claude is signed out, so Codex took over.", ok: true },+ { name: "notice: Claude is signed out on the Cloud, so Kai is using Codex meanwhile. Sign in again in Settings → AI to keep using Claude.", ok: true, setup: true },+ ]);+ });++ it("picks no AI by itself for it, so with no backup chosen the AI is tried as usual", () => {+ const { instance } = takeover();+ signedOut(instance);+ expect(instance.backups("kai", CLAUDE_ON, "signed-out")).toEqual([]);+ expect(instance.heldAtStart(KAI, CLAUDE_ON)).toBeNull();+ });++ it("lets another sign-in to the same AI stand in when the person chose it, never a signed-out one", () => {+ const work = engine("claude-work", "claudeAgent", ["claude-opus-5-5"]);+ const { instance } = takeover({ engines: () => [CLAUDE, work, CODEX], chosen: () => [on("claude-work", "claude-opus-5-5"), on("codex", "gpt-6")] });+ signedOut(instance);+ expect(instance.backups("kai", CLAUDE_ON, "signed-out")).toEqual([on("claude-work", "claude-opus-5-5"), on("codex", "gpt-6")]);+ expect(instance.backups("kai", on("codex", "gpt-6")), "and no limit's backup is an AI known to be signed out").not.toContainEqual(on("claude", "claude-opus-5-5"));+ });++ it("is tried again by a new turn an hour on, unless its status still says signed out; a turn that works ends it", () => {+ let status = false;+ const { instance, now } = takeover({ chosen: () => [on("codex", "gpt-6")], signedOutNow: () => status });+ signedOut(instance);+ now.at = NOW + SIGNED_OUT_RECHECK_MS + 1;+ expect(instance.heldAtStart(KAI, CLAUDE_ON)).toBeNull();+ expect(instance.stillSignedOut("claude"), "a conversation that moved still waits for it").toBe(true);+ status = true;+ expect(instance.heldAtStart(KAI, CLAUDE_ON)).toEqual({ scope: "signed-out" });+ instance.noteRuntimeEvent("rosa", CLAUDE_ON, event("turn.completed", { ok: true }));+ expect(instance.stillSignedOut("claude")).toBe(false);+ });++ it("remembers a sign-out through a restart", () => {+ const dir = freshDir();+ signedOut(takeover({}, dir).instance);+ expect(takeover({ chosen: () => [on("codex", "gpt-6")] }, dir).instance.heldAtStart(KAI, CLAUDE_ON)).toEqual({ scope: "signed-out" });+ });++ it("an account out of credit is no sign-out, even when its AI stops the turn as one", () => {+ const { instance } = takeover({ chosen: () => [on("codex", "gpt-6")] });+ signedOut(instance, "Your Grok account is out of credits. Add credits with Grok, then run it again.");+ expect(instance.stillSignedOut("claude")).toBe(false);+ expect(signedOutStop("auth_required", "Grok is not signed in to your grok.com account")).toBe(true);+ expect(signedOutStop("auth_required", undefined)).toBe(true);+ expect(signedOutStop("auth_required", "Your xAI subscription is inactive")).toBe(false);+ expect(signedOutStop("quota", "Not logged in · Please run /login")).toBe(false);+ });++ it("files one incident a sign-out, and another once it was signed in again", () => {+ const { instance } = takeover();+ signedOut(instance);+ expect(instance.firstIncident("kai", CLAUDE_ON, "signed-out")).toBe(true);+ expect(instance.firstIncident("kai", CLAUDE_ON, "signed-out")).toBe(false);+ instance.signedIn("claude");+ expect(instance.firstIncident("kai", CLAUDE_ON, "signed-out")).toBe(true);+ });+});++it("sends a signed-out AI's turns only to the backups a turn its AI never started would get", () => {+ const event = (type: string, extra: Record<string, unknown> = {}) =>+ ({ eventId: "e", provider: "claudeAgent", createdAt: new Date(NOW).toISOString(), threadId: "t1", type, ...extra }) as RuntimeEvent;+ let startup: ModelSelection[] = [];+ const { instance } = takeover({ chosen: () => [on("codex", "gpt-6")], signedOutChosen: () => startup });+ instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"), event("turn.completed", { ok: false, stopReason: "auth_required" }));+ expect(instance.backups("kai", on("claude", "claude-opus-5-5"), "signed-out"), "Automatic recovery off and no list of the bot's own").toEqual([]);+ expect(instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toBeNull();+ expect(instance.backups("kai", on("codex", "gpt-6")), "a usage limit's backups stay its own").toEqual([on("opencode", "go-default")]);+ startup = [on("codex", "gpt-6")];+ expect(instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "signed-out" });+});diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.tsindex aa806604de..15bd579d60 100644--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@ -1,88 +1,192 @@-// When the AI a bot runs on reaches its usage limit, the bot carries on with another AI the person has set up until that-// limit resets, without anyone being asked, and the person hears it once for that stretch of the limit.+// When the AI a bot runs on reaches its usage limit, or is signed out, the bot carries on with another AI the person has+// set up until that limit resets or the AI is signed in again, without anyone being asked, and the person hears it once+// for that stretch. What is held (an engine's limit on the reset clock, one model's own limit, a sign-in that expired)+// is saved, so every new turn and thread of every bot starts on the AI that carries on, a restart included.+import { readFileSync } from "node:fs";++import { approvalModeFor, modelSwitchNeedsAsk, type ApprovalMode } from "../../shared/approval-mode.ts";+import { writeFileAtomic } from "../atomic.ts";import { recoveryCapabilityError } from "../automatic-recovery.ts";import type { InstanceConfigMap, ProviderAdapter, RuntimeEvent } from "../contracts.ts";import { readyToRun, selectDefaultModelSelection, type DefaultSelectionContext, type SelectableInstance } from "../default-model-selection.ts";-import { billsEachUse, limitBackupAllowed, type LimitFailover } from "../limit-failover.ts";-import { LimitNotices, limitNoticeText } from "../limit-notices.ts";+import { engineFailureKind } from "../drivers/engine-errors.ts";+import { classifyError } from "../drivers/retry.ts";+import { billsEachUse, failoverLine, limitBackupAllowed, signedOutLine, type LimitFailover } from "../limit-failover.ts";+import { LimitNotices, limitNoticeText, signedOutNoticeText } from "../limit-notices.ts";import { UNNAMED_LIMIT_MS } from "../limit-resets.ts";import type { ModelSelection } from "../../shared/wire.ts";/** What a usage limit refused (the runtime error's `limit`): the account on that engine, one model's own window, or* one model's extra usage credits. */export type LimitScope = "engine" | "model" | "credits";+/** Why another AI carries on: one of those limits, or the AI's sign-in expired. */+export type TakeoverScope = LimitScope | "signed-out";/** A model's own limit holds that model at most this long before it is tried again, in case its window ended early. */export const MODEL_HOLD_MS = 6 * 60 * 60_000;+/** A signed-out AI is tried again by a new turn no sooner than this after its last refusal, in case it signed in again+ * some way this server did not see; a finished sign-in in the app, or a turn on it that works, ends the hold at once. */+export const SIGNED_OUT_RECHECK_MS = UNNAMED_LIMIT_MS;+/** A sign-out's one notice stands until the AI is signed in again or works; past this it is said again. */+const SIGNED_OUT_STRETCH_MS = 30 * 24 * 60 * 60_000;/** A model held by its own limit: until when, when the limit said it resets, and which limit it is. */export interface ModelHold { until: number; resetsAt?: number; scope: "model" | "credits" }export type TakeoverEngine = SelectableInstance & { displayName?: string; capabilities: ProviderAdapter["capabilities"] };type Bot = { id: string; name: string };+/** A bot as one of its threads sees it: its approval level decides which AI it may move to by itself. */+type ThreadBot = Bot & Parameters<typeof approvalModeFor>[0];export interface LimitTakeoverDeps {file: string;+ /** Where model holds and sign-outs are kept across restarts. */+ holdsFile?: string;/** Every engine here as last read: no probe, so a turn never waits on one. */engines(): TakeoverEngine[];configs(): InstanceConfigMap;context: DefaultSelectionContext;/** Until when this engine refuses work, or null. */blockedUntil(instanceId: string): number | null;+ /** When this engine's limit resets, when that is known. */+ resetAt?(instanceId: string): number | null;/** The backups the person chose for this bot, or for every bot. */chosen(botId: string): ModelSelection[];+ /** The backups a signed-out AI's turns go to, as for a turn its AI never started: the bot's own list, or the+ * installation's one backup while Automatic recovery is on. `chosen` when not given. */+ signedOutChosen?(botId: string): ModelSelection[];engineName(instanceId: string): string;tell(bot: Bot, text: string): void;- /** A conversation moved off a limited AI: it goes back once that limit resets. */+ /** A conversation moved off a limited or signed-out AI: it goes back once that ends. */record(failover: LimitFailover): void;+ /** OMB_QUOTA_SWITCH: off, nothing carries on by itself. */+ enabled?(): boolean;+ /** Where the AIs run, for the sign-out notice: "on the Cloud", "on this computer". */+ where?: string;+ /** The AI's status, as last read, says it is signed out. */+ signedOutNow?(instanceId: string): boolean;+ /** A sign-out was first noticed: what the app shows of that AI's sign-in is read again. */+ signedOutNoticed?(instanceId: string): void;now?(): number;}+interface SavedHolds { models?: Record<string, ModelHold>; signedOut?: Record<string, number> }++/** A turn its AI stopped for want of a sign-in. ACP engines stop an account out of credit or with no active plan as+ * "auth_required" too; signing in again fixes neither, so those words are no sign-out. */+export function signedOutStop(stopReason: string | null | undefined, said: string | undefined): boolean {+ return stopReason === "auth_required" && !(said && (engineFailureKind(said) === "credits" || classifyError({ text: said }).reason === "quota"));+}+/** A row a conversation shows when its turn carried on elsewhere: `setup` marks the one signing in fixes. */+export interface CarriedOnRow { name: string; ok: boolean; setup?: boolean }+export function createLimitTakeover(deps: LimitTakeoverDeps) {const now = deps.now ?? Date.now;const notices = new LimitNotices(deps.file, now);const heldModels = new Map<string, ModelHold>();+ /** Each signed-out AI and when it last refused a turn for that. */+ const signedOut = new Map<string, number>();+ /** What each thread's turn said in its last setup error, until that turn ends. */+ const setupSaid = new Map<string, string>();const modelKey = (selection: ModelSelection) => `${selection.instanceId}\u0000${selection.model}`;+ const signedOutKey = (instanceId: string) => `signed-out\u0000${instanceId}`;const incidentKey = (botId: string) => `incident\u0000${botId}`;+ /** The notice and incident key of what refused: the account on an engine, a sign-in, or one model. */+ const limitedKey = (from: ModelSelection, scope: TakeoverScope) => scope === "engine" ? from.instanceId+ : scope === "signed-out" ? signedOutKey(from.instanceId) : modelKey(from);++ /** What a restart left held, without what has run out. */+ const load = (file: string): void => {+ let saved: SavedHolds;+ try { saved = JSON.parse(readFileSync(file, "utf8")) as SavedHolds; } catch { return; }+ for (const [key, hold] of Object.entries(saved?.models ?? {})) {+ if (Number.isFinite(hold?.until) && hold.until > now() && (hold.scope === "model" || hold.scope === "credits")) heldModels.set(key, hold);+ }+ for (const [instanceId, at] of Object.entries(saved?.signedOut ?? {})) {+ if (Number.isFinite(at) && at > now() - SIGNED_OUT_STRETCH_MS) signedOut.set(instanceId, at);+ }+ };+ if (deps.holdsFile) load(deps.holdsFile);++ const save = (): void => {+ if (!deps.holdsFile) return;+ const holds: SavedHolds = { models: Object.fromEntries(heldModels), signedOut: Object.fromEntries(signedOut) };+ try {+ writeFileAtomic(deps.holdsFile, JSON.stringify(holds), { mode: 0o600 });+ } catch (error) {+ console.error(`limit takeover: could not save holds: ${error instanceof Error ? error.message : String(error)}`);+ }+ };const modelHeld = (selection: ModelSelection): ModelHold | null => {const held = heldModels.get(modelKey(selection));if (!held) return null;if (held.until > now()) return held;heldModels.delete(modelKey(selection));+ save();return null;};const holdModel = (selection: ModelSelection, scope: "model" | "credits", resetsAt?: number): void => {const at = now(), named = resetsAt !== undefined && resetsAt > at ? resetsAt : undefined;heldModels.set(modelKey(selection), { until: Math.min(named ?? at + UNNAMED_LIMIT_MS, at + MODEL_HOLD_MS), ...(named ? { resetsAt: named } : {}), scope });+ save();};- const usable = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection): boolean => {+ /** A new turn on this AI goes to another one: it refused a sign-in within the re-check interval, or its status says+ * it is still signed out. */+ const signedOutHeld = (instanceId: string): boolean => {+ const at = signedOut.get(instanceId);+ return at !== undefined && (now() - at < SIGNED_OUT_RECHECK_MS || deps.signedOutNow?.(instanceId) === true);+ };++ const noteSignedOut = (instanceId: string): void => {+ const first = !signedOut.has(instanceId);+ signedOut.set(instanceId, now());+ save();+ if (first) deps.signedOutNoticed?.(instanceId);+ };++ /** The AI is signed in again, or a turn on it worked: every bot's next turn may use it, and its next sign-out is told. */+ const signedIn = (instanceId: string): void => {+ if (!signedOut.delete(instanceId)) return;+ save();+ notices.endedEverywhere(signedOutKey(instanceId));+ };++ const usable = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection, scope: TakeoverScope, approval?: ApprovalMode): boolean => {const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);if (!engine || !readyToRun(engine, deps.context) || deps.blockedUntil(engine.instanceId) !== null || modelHeld(selection) !== null) return false;- if (engine.instanceId !== current.instanceId && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return false;+ if (engine.instanceId !== current.instanceId) {+ if (signedOutHeld(engine.instanceId)) return false;+ // Another sign-in to the same plan never carries a limit (that rotates accounts); it may stand in for one signed out.+ if (scope !== "signed-out" && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return false;+ // The same rule as switching by hand: a level the other AI has no such mode for needs the person first.+ if (approval && modelSwitchNeedsAsk(approval, current.driverKind, engine.driverKind)) return false;+ }if (recoveryCapabilityError(current, engine)) return false;return engine.models.default === selection.model || engine.models.options.some((model) => model.id === selection.model);};- /** The AIs that may carry on while `from` is limited, best first: for one model's limit the same AI's own default- * model, then the backups the person chose, then the AI OpenMausBot would pick for a new bot among the rest that draw on- * a plan. One that bills each use spends the person's money, so it carries on only as a backup they chose. */- function backups(botId: string, from: ModelSelection, scope: LimitScope = "engine"): ModelSelection[] {+ /** The AIs that may carry on while `from` is limited or signed out, best first: for one model's limit the same AI's own+ * default model, then the backups the person chose, then (for a limit) the AI MausBot would pick for a new bot among+ * the rest that draw on a plan. One that bills each use spends the person's money, so it carries on only as a backup+ * they chose; a signed-out AI's turns go only to a backup they chose. `approval`: the thread's level, when known. */+ function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): ModelSelection[] {const engines = deps.engines();const current = engines.find((engine) => engine.instanceId === from.instanceId);if (!current) return [];const out: ModelSelection[] = [];const add = (selection: ModelSelection) => {- if (selection.instanceId === from.instanceId && (scope === "engine" || selection.model === from.model)) return;+ if (selection.instanceId === from.instanceId && (scope === "engine" || scope === "signed-out" || selection.model === from.model)) return;if (out.some((known) => known.instanceId === selection.instanceId && known.model === selection.model)) return;- if (usable(engines, current, selection)) out.push({ instanceId: selection.instanceId, model: selection.model });+ if (usable(engines, current, selection, scope, approval)) out.push({ instanceId: selection.instanceId, model: selection.model });};- if (scope !== "engine") add({ instanceId: current.instanceId, model: current.models.default });- for (const selection of deps.chosen(botId)) add(selection);+ if (scope === "model" || scope === "credits") add({ instanceId: current.instanceId, model: current.models.default });+ for (const selection of scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? deps.chosen(botId) : deps.chosen(botId)) add(selection);+ if (scope === "signed-out") return out;const others = engines.filter((engine) => engine.instanceId !== from.instanceId && engine.access !== "api" && !billsEachUse(deps.configs()[engine.instanceId])- && usable(engines, current, { instanceId: engine.instanceId, model: engine.models.default }));+ && usable(engines, current, { instanceId: engine.instanceId, model: engine.models.default }, scope, approval));const pick = selectDefaultModelSelection(others, undefined, deps.context);if (pick.instanceId && pick.model) add(pick);return out;@@ -90,6 +194,38 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {const label = (selection: ModelSelection, from: ModelSelection) => (selection.instanceId === from.instanceId? `${deps.engineName(selection.instanceId)} ${selection.model}` : deps.engineName(selection.instanceId));+ /** What refused, as the person knows it: the AI, or for one model's own limit that AI's model. */+ const refusedName = (from: ModelSelection, scope: TakeoverScope) => (scope === "model" || scope === "credits"+ ? `${deps.engineName(from.instanceId)} ${from.model}` : deps.engineName(from.instanceId));++ /** Once for this stretch of `from`'s limit or sign-out: which AI carries on for `bot` meanwhile, or that it waits.+ * The words told, or null when this stretch was told already. */+ const tell = (bot: Bot, from: ModelSelection, facts: { resetsAt?: number; scope?: TakeoverScope; backup?: ModelSelection }): string | null => {+ const scope = facts.scope ?? "engine";+ const signOut = scope === "signed-out";+ if (!notices.first(bot.id, limitedKey(from, scope), signOut ? now() + SIGNED_OUT_STRETCH_MS : facts.resetsAt)) return null;+ const backup = facts.backup ? { backup: label(facts.backup, from) } : {};+ const text = signOut ? signedOutNoticeText({ engine: refusedName(from, scope), bot: bot.name, where: deps.where ?? "on this computer", ...backup })+ : limitNoticeText({ engine: refusedName(from, scope), bot: bot.name, ...(facts.resetsAt ? { resetsAt: facts.resetsAt } : {}), ...(scope === "credits" ? { credits: true } : {}), ...backup });+ deps.tell(bot, text);+ return text;+ };++ /** A conversation of `botId` moved from `from` to `to` because `from` was limited or signed out; it goes back once+ * that ends. */+ const moved = (botId: string, threadId: string, from: ModelSelection, to: ModelSelection, resetsAt?: number, scope?: TakeoverScope): void => {+ deps.record({ botId, threadId, from, to, resetsAt: resetsAt ?? null, at: now(), ...(scope === "signed-out" ? { why: "signed-out" as const } : {}) });+ };++ /** A turn on `selection` worked for this bot: its engine's next limit is a new stretch, and it is plainly signed in. */+ const worked = (botId: string, selection: ModelSelection): void => {+ for (const who of [botId, incidentKey(botId)]) {+ notices.ended(who, selection.instanceId);+ notices.ended(who, modelKey(selection));+ }+ if (heldModels.delete(modelKey(selection))) save();+ signedIn(selection.instanceId);+ };return {backups,@@ -98,38 +234,54 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {/** This model's own limit refused a turn: it is held until the reset the limit named, an hour when it named none,* and at most MODEL_HOLD_MS. */holdModel,- /** Every runtime event of a bot's thread, with the model it runs on: a model's own limit holds that model. */- noteRuntimeEvent(selection: ModelSelection | undefined, event: RuntimeEvent): void {- if (!selection || event.type !== "runtime.error" || (event.limit !== "model" && event.limit !== "credits")) return;- holdModel(selection, event.limit, event.limitResetsAt);- },- /** Once for this stretch of `from`'s limit: which AI carries on for `bot` meanwhile, or that it waits. */- tell(bot: Bot, from: ModelSelection, facts: { resetsAt?: number; scope?: LimitScope; backup?: ModelSelection }): void {- const scope = facts.scope ?? "engine";- const limited = scope === "engine" ? from.instanceId : modelKey(from);- if (!notices.first(bot.id, limited, facts.resetsAt)) return;- deps.tell(bot, limitNoticeText({- engine: scope === "engine" ? deps.engineName(from.instanceId) : `${deps.engineName(from.instanceId)} ${from.model}`,- bot: bot.name, ...(facts.resetsAt ? { resetsAt: facts.resetsAt } : {}), ...(scope === "credits" ? { credits: true } : {}),- ...(facts.backup ? { backup: label(facts.backup, from) } : {}),- }));+ /** The AI refused a turn because it is signed out. */+ noteSignedOut,+ signedIn,+ /** Whether a conversation moved off this signed-out AI waits before going back: until it is signed in again or a+ * turn on it works. */+ stillSignedOut: (instanceId: string): boolean => signedOut.has(instanceId),+ /** 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);+ 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) ?? undefined : model?.resetsAt;+ return { scope, ...(resetsAt && resetsAt > now() ? { resetsAt } : {}) };},- /** A conversation of `botId` moved from `from` to `to` because of `from`'s limit; it goes back once that resets. */- moved(botId: string, threadId: string, from: ModelSelection, to: ModelSelection, resetsAt?: number): void {- deps.record({ botId, threadId, from, to, resetsAt: resetsAt ?? null, at: now() });+ /** 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 {+ if (event.type === "runtime.error" && event.setup) setupSaid.set(event.threadId, event.message);+ const said = event.type === "turn.completed" || event.type === "session.exited" ? setupSaid.get(event.threadId) : undefined;+ if (said !== undefined) setupSaid.delete(event.threadId);+ if (!selection) return;+ if (event.type === "runtime.error" && (event.limit === "model" || event.limit === "credits")) holdModel(selection, event.limit, event.limitResetsAt);+ else if (event.type === "turn.completed" && event.ok) worked(botId, selection);+ else if (event.type === "turn.completed" && signedOutStop(event.stopReason, said)) noteSignedOut(selection.instanceId);},- /** True once per bot for each stretch of this limit: the one incident its Chief is told about, not one per refused turn. */- firstIncident(botId: string, from: ModelSelection, scope: LimitScope = "engine", resetsAt?: number): boolean {- return notices.first(incidentKey(botId), scope === "engine" ? from.instanceId : modelKey(from), resetsAt);+ tell,+ moved,+ /** A turn refused at its start (a limit, or a sign-out) runs on `to` now: the conversation goes back once that ends,+ * the person hears it once, and these are the rows its conversation shows: one line, and for a sign-out told here,+ * 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 }, ...(told && facts.scope === "signed-out" ? [{ name: `notice: ${told}`, ok: true, setup: true }] : [])];},- /** A turn on `selection` worked for this bot: its engine's next limit is a new stretch, with a notice of its own. */- worked(botId: string, selection: ModelSelection): void {- for (const who of [botId, incidentKey(botId)]) {- notices.ended(who, selection.instanceId);- notices.ended(who, modelKey(selection));- }- heldModels.delete(modelKey(selection));+ /** 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 {+ return notices.first(incidentKey(botId), limitedKey(from, scope), scope === "signed-out" ? now() + SIGNED_OUT_STRETCH_MS : resetsAt);},+ worked,};}diff --git a/server/index.ts b/server/index.tsindex aff5598ae4..c7cef9e2fa 100644--- a/server/index.ts+++ b/server/index.ts@@ -212,7 +212,7 @@ import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts";import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts";import { decodeGeneratedImage } from "./generated-image.ts";-import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createLimitTakeover } from "./host/limit-takeover.ts";+import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";import {isRemoteMcpServer,listMcpServers,@@ -450,7 +450,7 @@ import { createScreenFrameSource, rememberTurnFrame, type ScreenCapture } from "import { screenFrameHash, screenSurfaceForTool, screenTouchingTool, settledFrameIsNews } from "./screen-frame-gate.ts";import { asSchedule, RoutineRequestService } from "./routine-requests.ts"; import { ownerSpokeOnly } from "./cloud-routine-level.ts"; import { routineRunCard, routineRunFallbackText } from "./routine-run-card.ts";import { automationContextText, createAutomationReports, newestAutomationLines } from "./automation-reports.ts"; import { createAutomationDestinations } from "./automation-destinations.ts"; import { createProactive } from "./host/proactive.ts"; import { createFirstHourHooks, startFirstHour, welcomeDonePatch } from "./host/first-hour-host.ts"; import { greetingMessage } from "./host/first-hour.ts"; import { READ_AND_DRAFT_PARTS, READ_AND_DRAFT_REFUSAL, READ_AND_DRAFT_TOOLS, recordsAnswer } from "./read-and-draft.ts"; import { createPresenceRoutes } from "./routes/presence.ts"; import { needsYouNow } from "./today.ts";-import { engineLabel, LimitResetClock, nearLimitNote } from "./limit-resets.ts"; import { planAccountsFromInstances } from "./plan-usage.ts"; import { failoverLine, LimitFailovers, limitBackupAllowed } from "./limit-failover.ts"; import { createLimitResetRoutes } from "./routes/limit-resets.ts";+import { engineLabel, LimitResetClock, nearLimitNote } from "./limit-resets.ts"; import { planAccountsFromInstances } from "./plan-usage.ts"; import { LimitFailovers, limitBackupAllowed } from "./limit-failover.ts"; import { createLimitResetRoutes } from "./routes/limit-resets.ts";import { parseTriggerRequest, triggerTarget } from "./trigger-tools.ts"; import { WebhookRequestError, WebhookRequestService } from "./webhook-requests.ts"; import { createAppTriggerHost } from "./app-trigger-host.ts";import { appliesNow, directApply, UNDO_STALE, type DirectApply } from "./direct-apply.ts";import { createTeamMemoryRequests } from "./team-memory-requests.ts";@@ -1401,7 +1401,7 @@ function bookTurnUsage(row: Omit<UsageRow, "at" | "costSource">, tokensReported}}-const providerAuthSessions = new ProviderAuthSessions(); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled() });+const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => limitTakeover.signedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled() });const mcpOAuth = new McpOAuthManager({file: join(DATA_DIR, "mcp-oauth.json"),isOwnerLive: (owner) => owner === "loopback" || sessions.isLive(owner),@@ -6428,9 +6428,9 @@ bus.subscribe((event: RuntimeEvent) => {broadcast({ kind: "runtime", event: publicEvent });}const routineRun = privateImageEvent ? null : (routines?.handleRuntimeEvent(event) ?? null);- limitClock.noteRuntimeEvent(savedSteps.dispatch.answering(event) ? undefined : runningTurnEngines.get(event.threadId)?.instanceId, event);- const ownerBot = store.botByThread(event.threadId);- const bot = ownerBot ? botForThread(ownerBot.id, event.threadId) ?? undefined : undefined; if (bot) { limitTakeover.noteRuntimeEvent(bot.modelSelection, event); if (event.type === "turn.completed" && event.ok) limitTakeover.worked(bot.id, bot.modelSelection); }+ const replayed = savedSteps.dispatch.answering(event); limitClock.noteRuntimeEvent(replayed ? undefined : runningTurnEngines.get(event.threadId)?.instanceId, event);+ const ownerBot = store.botByThread(event.threadId); // A quick route's model is the one this turn ran on, so its holds and its working turns are that model's.+ const bot = ownerBot ? botForThread(ownerBot.id, event.threadId) ?? undefined : undefined; if (bot && !replayed) limitTakeover.noteRuntimeEvent(bot.id, { ...bot.modelSelection, model: quickFallback.routedModel(event.threadId) ?? bot.modelSelection.model }, event);const group = bot ? undefined : store.groupByThread(event.threadId);if (!bot && !group) return;const speaker = group ? groupSpeakers.get(event.threadId) : undefined;@@ -6834,7 +6834,8 @@ bus.subscribe((event: RuntimeEvent) => {const failureDetail = turnStops.failureCause(event) ?? "the run ended without a result";// Filed once the thread has settled, so the Chief's retry finds it free. A turn the person stopped is cancelled, whatever its engine said.const facts = { ...turnStops.read(event.threadId, event.turnId)?.flags, stopReason: directRequestOwners.get(event.threadId)?.stopped ? "cancelled" : event.stopReason };- const fileIncident = () => { if (broken && (!facts.limit || limitTakeover.firstIncident(broken.id, broken.modelSelection, facts.limit, facts.limitResetsAt))) reportIncident({ kind: "failed", bot: broken, threadId: event.threadId, detail: failureDetail, facts, notified: Boolean(facts.limit) }); };+ 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 notice+ const 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);else if (bot && event.ok) quotaSwitch.turnSucceeded(bot, event.threadId);const question = bot && event.ok && !stopped && completedTurnId && !routineRun && chiefEscalationsEnabled(cfg) ? needsInputQuestion(store.activePath(event.threadId)@@ -8535,9 +8536,8 @@ async function startTurn(const clock = takesTurnClock(userTurnText) ? turnClockLine(Date.now(), hostTimeZone()) + nearLimitNote(limitClock.limit(instanceId), engineName(instanceId), hostTimeZone()) : "";const shareNote = skillsHost.shareNote(bot, threadId, Boolean(privateWorkspace));const startupRecovery = (opts?.automaticRecoveryIndex ?? 0) < startupBackups(liveBot ?? bot, cfg.automaticRecovery).length;- const engineHeld = limitClock.blockedUntil(instanceId), modelHeld = engineHeld ? null : limitTakeover.modelHeld({ instanceId, model }), limitScope = engineHeld ? "engine" as const : modelHeld?.scope ?? "engine", limitResets = engineHeld ? limitClock.resetAt(instanceId) ?? undefined : modelHeld?.resetsAt;- // A limit already known: the turn goes straight to an AI that can carry on, with the reset only when one was named.- if ((engineHeld || modelHeld) && (startupRecovery || (quotaSwitchEnabled() && limitTakeover.backups(bot.id, { instanceId, model }, limitScope).length))) throw new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, limitResets && limitResets > Date.now() ? limitResets : undefined, limitScope, true);+ const held = limitTakeover.heldAtStart(bot, { instanceId, model }, startupRecovery); // a limit or a sign-out already known: straight to an AI that can carry on, with the reset only when one was named+ if (held) throw held.scope === "signed-out" ? new TurnAuthenticationRefusedError(`signed-out-${randomUUID()}`, `${engineName(instanceId)} is signed out.`, true) : new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, held.resetsAt, held.scope, true);const dispatch = await guardTurnDispatch(shareNote.after(savedSteps.dispatch.sendTurn(instance, personLine && !opts?.unattended && !opts?.app?.context && !guestConfined ? { botId: bot.id, message: userMessage, turnText: text, placePicked: wants === "local" && placeSource !== "auto-pin" } : null, {threadId,botId: bot.id,@@ -8615,7 +8615,7 @@ async function startTurn(directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId);if (e instanceof TurnNotStartedError) {retireProviderTurn(e.turnId);- if (e instanceof TurnUsageLimitRefusedError && !e.known) { if (e.scope === "engine") limitClock.noteLimit(instanceId, e.resetsAt); else limitTakeover.holdModel({ instanceId, model }, e.scope, e.resetsAt); }+ if (e instanceof TurnUsageLimitRefusedError && !e.known) { if (e.scope === "engine") limitClock.noteLimit(instanceId, e.resetsAt); else limitTakeover.holdModel({ instanceId, model }, e.scope, e.resetsAt); } else if (e instanceof TurnAuthenticationRefusedError && !e.known) limitTakeover.noteSignedOut(instanceId);if (!mayRecover) e = new DirectTurnSetupCancelled("turn stopped during provider setup");}handoffs.abandon(threadId, dispatchClaimId);@@ -8662,8 +8662,8 @@ async function startTurn(}if (e instanceof PlaceUnavailableError) clearFailedAutoPin(bot.id, threadId, e.place);let message = e instanceof Error ? e.message : String(e);- const current = store.projectBotForTask(bot.id, threadId);- const backups = e instanceof TurnUsageLimitRefusedError && current && quotaSwitchEnabled() ? limitTakeover.backups(bot.id, current.modelSelection, e.scope)+ const current = store.projectBotForTask(bot.id, threadId), takeoverScope = e instanceof TurnUsageLimitRefusedError ? e.scope : e instanceof TurnAuthenticationRefusedError ? "signed-out" as const : undefined;+ const backups = takeoverScope && current && quotaSwitchEnabled() ? limitTakeover.backups(bot.id, current.modelSelection, takeoverScope, approvalModeFor(current)): current ? startupBackups(current, cfg.automaticRecovery) : [];const nextIndex = backups.findIndex((candidate, index) => index >= (opts?.automaticRecoveryIndex ?? 0) &®istry.get(candidate.instanceId)?.enabled && (e instanceof TurnUsageLimitRefusedError ? (candidate.instanceId === instanceId ? e.scope !== "engine" : limitBackupAllowed(instance, registry.get(candidate.instanceId)!, instanceConfigs(cfg)[candidate.instanceId]))@@ -8691,10 +8691,8 @@ async function startTurn(store.switchTaskModel(bot.id, threadId, checked.selection, false, false, {...hostedModels?.resetTask(current.modelSelection, checked.selection), rewound: true,});- if (e instanceof TurnUsageLimitRefusedError) { limitFailovers.record({ botId: bot.id, threadId, from: current.modelSelection, to: checked.selection, resetsAt: e.resetsAt ?? null, at: Date.now() }); limitTakeover.tell(current, current.modelSelection, { ...(e.resetsAt ? { resetsAt: e.resetsAt } : {}), scope: e.scope, backup: checked.selection }); }- store.appendMessage(threadId, { role: "bot", kind: "activity", tool: {- name: e instanceof TurnUsageLimitRefusedError ? `recovery: ${failoverLine(engineName(instanceId), engineName(target.instanceId), e.resetsAt)}` : `recovery: Automatic recovery: ${instance.displayName || instance.driverKind} ${e instanceof TurnAuthenticationRefusedError ? "is signed out" : "could not start"}. Trying ${target.displayName || target.driverKind} · ${checked.selection.model} once in this thread.`, ok: true,- } });+ const rows = takeoverScope ? limitTakeover.carriedOn(current, threadId, current.modelSelection, checked.selection, { scope: takeoverScope, ...(e instanceof TurnUsageLimitRefusedError && e.resetsAt ? { resetsAt: e.resetsAt } : {}) })+ : [{ name: `recovery: Automatic recovery: ${instance.displayName || instance.driverKind} could not start. Trying ${target.displayName || target.driverKind} · ${checked.selection.model} once in this thread.`, ok: true }]; for (const tool of rows) store.appendMessage(threadId, { role: "bot", kind: "activity", tool });if (opts?.coordination || opts?.onSettled) directCoordinationSettlers.delete(dispatchClaimId);else settleDirectCoordination(dispatchClaimId, { ok: false, text: message });await startTurn(bot.id, text, { ...opts, threadId, userMessage, editedMessageId: undefined,@@ -8712,10 +8710,12 @@ async function startTurn(role: "bot",kind: "activity",turnSucceeded: false,- tool: failedTurnTool(message, e instanceof PlaceUnavailableError ? { place: e.row } : e instanceof TurnUsageLimitRefusedError ? { limitResetsAt: e.resetsAt } : {}),+ tool: failedTurnTool(message, e instanceof PlaceUnavailableError ? { place: e.row } : e instanceof TurnUsageLimitRefusedError ? { limitResetsAt: e.resetsAt } : e instanceof TurnAuthenticationRefusedError ? { setup: true } : {}),});- if (opts?.automationSource === undefined && !opts?.commsDepth && !opts?.cardContinuation) {- notify(+ const personTurn = opts?.automationSource === undefined && !opts?.commsDepth && !opts?.cardContinuation, told = personTurn && takeoverScope === "signed-out" ? limitTakeover.tell(bot, bot.modelSelection, { scope: "signed-out" }) : null; // a limit or a sign-out is heard once a stretch, not once a turn+ if (told) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${told}`, ok: true, setup: true } });+ if (personTurn && (!takeoverScope || limitTakeover.firstIncident(bot.id, bot.modelSelection, takeoverScope, e instanceof TurnUsageLimitRefusedError ? e.resetsAt : undefined))) {+ if (!told) notify(buildNotification("turn-failed", bot, threadId, redactSecretsInText(message), { avatarUrl: bot.avatarUrl }),);reportIncident({ kind: "could-not-start", bot, threadId, detail: message });@@ -8868,9 +8868,9 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<void}const engineName = (engine: string) => engineLabel(engine, registry.get(engine) ?? undefined);-const limitClock = new LimitResetClock({ accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),- waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) });-const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), engineName,+const limitClock = new LimitResetClock({ file: join(DATA_DIR, "limit-holds.json"), accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) });+const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,note: (threadId, line) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true } }),switchBack: ({ botId, threadId, from, to }) => {@@ -8881,7 +8881,7 @@ const automationDestinations = createAutomationDestinations({ store, mainThread:cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: routineOpener, reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person) } : null });routines = new RoutineManager({emit: broadcast, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,- limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },+ limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,skipStartupRuns: Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR), // a Cloud home waking from a sleep it was stopped fordiff --git a/server/limit-failover.test.ts b/server/limit-failover.test.tsindex 01eaa49fed..71d12044c5 100644--- a/server/limit-failover.test.ts+++ b/server/limit-failover.test.ts@@ -34,7 +34,7 @@ describe("LimitFailovers", () => {afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });const from = { instanceId: "claude", model: "claude-sonnet-5" };const to = { instanceId: "codex", model: "gpt-fake-default" };- function fixture(options: { blocked?: number | null; current?: typeof from | null; allowed?: boolean } = {}) {+ function fixture(options: { blocked?: number | null; current?: typeof from | null; allowed?: boolean; signedOut?: () => boolean } = {}) {const dir = mkdtempSync(join(tmpdir(), "omb-limit-failovers-"));dirs.push(dir);let now = NOW;@@ -43,7 +43,7 @@ describe("LimitFailovers", () => {const switched: LimitFailover[] = [];const deps = {file: join(dir, "limit-failovers.json"), now: () => now,- blockedUntil: () => state.blocked, threadModel: () => state.current,+ blockedUntil: () => state.blocked, threadModel: () => state.current, signedOut: options.signedOut,switchBack: (failover: LimitFailover) => { if (options.allowed === false) return false; switched.push(failover); state.current = failover.from; return true; },note: (_threadId: string, line: string) => notes.push(line), engineName: (engine: string) => engine === "claude" ? "Claude" : engine,};@@ -84,6 +84,28 @@ describe("LimitFailovers", () => {expect(f.failovers.restore("scout", "t")).toBe(true);});+ it("with a reset that had already passed when the limit refused, waits as for no known reset", () => {+ const f = fixture();+ f.failovers.record({ botId: "scout", threadId: "t", from, to, resetsAt: NOW - 60_000, at: NOW });+ expect(f.failovers.list()).toEqual([expect.objectContaining({ resetsAt: null })]);+ f.at(NOW + 10 * 60_000);+ expect(f.failovers.restore("scout", "t"), "not back at once on a time that told nothing").toBe(false);+ f.at(NOW + HOUR + 1);+ expect(f.failovers.restore("scout", "t")).toBe(true);+ });++ it("goes back to an AI that was signed out once it is signed in again, saying so", () => {+ let out = true;+ const f = fixture({ signedOut: () => out });+ f.failovers.record({ botId: "scout", threadId: "t", from, to, resetsAt: null, at: NOW, why: "signed-out" });+ f.at(NOW + 3 * HOUR);+ expect(f.failovers.restore("scout", "t")).toBe(false);+ out = false;+ expect(f.failovers.restore("scout", "t")).toBe(true);+ expect(f.notes).toEqual(["Claude is signed in again, so this conversation is back on Claude."]);+ expect(new LimitFailovers(f.deps).list()).toEqual([]);+ });+it("forgets a thread someone moved to another model, and remembers across a restart", () => {const moved = fixture({ current: { instanceId: "opencode", model: "x" } });moved.failovers.record({ botId: "scout", threadId: "t", from, to, resetsAt: NOW, at: NOW });diff --git a/server/limit-failover.ts b/server/limit-failover.tsindex cbd47161fb..cdce147f1f 100644--- a/server/limit-failover.ts+++ b/server/limit-failover.ts@@ -1,5 +1,5 @@-// A conversation whose engine hit its usage limit continues on the configured backup, and goes back to its own engine-// once that limit has reset.+// A conversation whose engine hit its usage limit, or was signed out, continues on the configured backup, and goes back to+// its own engine once that limit has reset or it is signed in again.import { readFileSync } from "node:fs";import { sameModelSelection } from "../shared/thread-model.ts";@@ -44,8 +44,14 @@ export function failoverLine(from: string, to: string, resetsAt: number | undefireturn `${from} hit its limit${resetsAt ? ` (resets ${resetClock(resetsAt)})` : ""}, so ${to} took over.`;}-export function backLine(engine: string): string {- return `${engine}'s limit has reset, so this conversation is back on ${engine}.`;+export function backLine(engine: string, why?: LimitFailover["why"]): string {+ return why === "signed-out" ? `${engine} is signed in again, so this conversation is back on ${engine}.`+ : `${engine}'s limit has reset, so this conversation is back on ${engine}.`;+}++/** "Claude is signed out, so Codex took over." */+export function signedOutLine(from: string, to: string): string {+ return `${from} is signed out, so ${to} took over.`;}export interface LimitFailover {@@ -56,6 +62,8 @@ export interface LimitFailover {/** When `from`'s limit resets; unknown means its usage decides, after UNKNOWN_RESET_WAIT_MS. */resetsAt: number | null;at: number;+ /** `from` was signed out, not limited: the conversation goes back once it is signed in again. */+ why?: "signed-out";}/** With no reset time known, a conversation tries its own engine again no sooner than this. */@@ -66,6 +74,8 @@ export interface LimitFailoverDeps {now?: () => number;/** Until when this engine refuses work; null when it should be working. */blockedUntil: (engine: string) => number | null;+ /** This engine refused a turn because it is signed out, and has not been signed in again since. */+ signedOut?: (engine: string) => boolean;/** The thread's model now, or null when the thread is gone. */threadModel: (botId: string, threadId: string) => ModelSelection | null;/** Switches the thread back; false when that is not allowed now (a busy thread, a permission change). */@@ -80,7 +90,7 @@ function load(file: string): LimitFailover[] {const rows = JSON.parse(readFileSync(file, "utf8")) as unknown;return Array.isArray(rows) ? rows.filter((row): row is LimitFailover => typeof row?.botId === "string" && typeof row?.threadId === "string" &&typeof row?.from?.instanceId === "string" && typeof row?.to?.instanceId === "string" && (row.resetsAt === null || Number.isFinite(row.resetsAt)) &&- Number.isFinite(row.at)) : [];+ Number.isFinite(row.at) && (row.why === undefined || row.why === "signed-out")) : [];} catch {return [];}@@ -95,28 +105,31 @@ export class LimitFailovers {this.rows = load(deps.file);}- /** A thread moved to `to` because `from`'s usage limit refused it. */+ /** A thread moved to `to` because `from`'s usage limit refused it, or `from` was signed out. */record(failover: LimitFailover): void {const earlier = this.rows.find((row) => row.threadId === failover.threadId);// A second failover keeps the engine the conversation started on, so it still goes back there.const from = earlier && sameModelSelection(earlier.to, failover.from) ? earlier.from : failover.from;- this.rows = [...this.rows.filter((row) => row.threadId !== failover.threadId), { ...failover, from }].slice(-500);+ // A reset already past when the limit refused names no time: the engine's own hold decides when it goes back.+ const resetsAt = failover.resetsAt !== null && failover.resetsAt > failover.at ? failover.resetsAt : null;+ this.rows = [...this.rows.filter((row) => row.threadId !== failover.threadId), { ...failover, from, resetsAt }].slice(-500);this.save();}- /** Before a turn: a thread on a backup goes back to its own engine once that engine's limit has reset, with one line- * saying so. A thread someone moved to another model since is left alone. */+ /** Before a turn: a thread on a backup goes back to its own engine once that engine's limit has reset, or it is+ * signed in again, with one line saying so. A thread someone moved to another model since is left alone. */restore(botId: string, threadId: string): boolean {const row = this.rows.find((candidate) => candidate.threadId === threadId && candidate.botId === botId);if (!row) return false;const now = this.deps.now?.() ?? Date.now();const current = this.deps.threadModel(botId, threadId);if (!current || !sameModelSelection(current, row.to)) return this.forget(threadId);- const waitUntil = row.resetsAt ?? row.at + UNKNOWN_RESET_WAIT_MS;+ const waitUntil = row.why === "signed-out" ? row.at : row.resetsAt ?? row.at + UNKNOWN_RESET_WAIT_MS;if (waitUntil > now || this.deps.blockedUntil(row.from.instanceId) !== null) return false;+ if (row.why === "signed-out" && this.deps.signedOut?.(row.from.instanceId)) return false;if (!this.deps.switchBack(row)) return false;this.forget(threadId);- this.deps.note(threadId, backLine(this.deps.engineName(row.from.instanceId)));+ this.deps.note(threadId, backLine(this.deps.engineName(row.from.instanceId), row.why));return true;}diff --git a/server/limit-notices.ts b/server/limit-notices.tsindex 8df52dd4b6..61fa1fa0aa 100644--- a/server/limit-notices.ts+++ b/server/limit-notices.ts@@ -35,6 +35,14 @@ export function limitNoticeText(facts: LimitNoticeFacts, timeZone?: string): str: `${what}, so ${facts.bot} waits: no other AI you have set up can take over.`;}+/** "Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.", and who carries on meanwhile+ * when a backup the person chose does. */+export function signedOutNoticeText(facts: { engine: string; bot: string; backup?: string; where: string }): string {+ return facts.backup+ ? `${facts.engine} is signed out ${facts.where}, so ${facts.bot} is using ${facts.backup} meanwhile. Sign in again in Settings → AI to keep using ${facts.engine}.`+ : `${facts.engine} is signed out ${facts.where}. Sign in again in Settings → AI to keep using it.`;+}+export class LimitNotices {private readonly file: string;private readonly now: () => number;@@ -72,6 +80,14 @@ export class LimitNotices {this.save();}+ /** The engine works again for every bot (it is signed in again): each bot's next refusal is a new stretch. */+ endedEverywhere(engine: string): void {+ const kept = Object.fromEntries(Object.entries(this.told).filter(([key]) => !key.endsWith(`\u0000${engine}`)));+ if (Object.keys(kept).length === Object.keys(this.told).length) return;+ this.told = kept;+ this.save();+ }+private save(): void {try { writeFileAtomic(this.file, JSON.stringify(this.told), { mode: 0o600 }); } catch {}}diff --git a/server/limit-reset.e2e.test.ts b/server/limit-reset.e2e.test.tsindex 49cfb33a5b..0813ee7888 100644--- a/server/limit-reset.e2e.test.ts+++ b/server/limit-reset.e2e.test.ts@@ -26,9 +26,11 @@ interface Fixture {claudePrompts: () => unknown[];dataDir: string;evidence: unknown[];+ /** Stops the server and starts it again on the same data, as a Cloud stopped for a sleep or an update does. */+ restart: () => Promise<void>;}-async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolean; codex?: false }, check: (fixture: Fixture) => Promise<void>) {+async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolean; codex?: false; signedOut?: boolean }, check: (fixture: Fixture) => Promise<void>) {const fixture = await launchVerificationServer({});const { dataDir, url, logPath } = fixture.info;const limitedFile = join(dataDir, "claude-limited.json");@@ -56,29 +58,33 @@ async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolawait waitForExit(fixture.child, { signal: "SIGTERM" });const configPath = join(dataDir, "config.json");const config = JSON.parse(readFileSync(configPath, "utf8"));- config.instances.claude.environment = { ...config.instances.claude.environment, FAKE_CLAUDE_LIMITED_FILE: limitedFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_TOOL_CALLS: "[]" };+ config.instances.claude.environment = { ...config.instances.claude.environment, FAKE_CLAUDE_LIMITED_FILE: limitedFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_TOOL_CALLS: "[]",+ ...(setup.signedOut ? { FAKE_CLAUDE_MODE: "not-logged-in" } : {}) };if (setup.codex !== false) config.instances.codex = { driver: "codex", config: { cli: fileURLToPath(new URL("./testing/fake-codex-app-server.ts", import.meta.url)) } };if (setup.secondClaude) config.instances.claudeWork = { ...config.instances.claude, displayName: "Second Claude sign-in" };if (setup.recovery) config.automaticRecovery = setup.recovery;writeFileSync(configPath, JSON.stringify(config));// No engine reports usage here: what the server knows of the limit comes from the refusal itself.writeFileSync(usageFile, JSON.stringify({ providers: [] }));- const log = openSync(logPath, "a", 0o600);- server = spawn(process.execPath, [- "--experimental-strip-types", "--import", new URL("./testing/limit-clock-hooks.mjs", import.meta.url).href, fileURLToPath(new URL("./index.ts", import.meta.url)),- ], {- cwd: fileURLToPath(new URL("..", import.meta.url)),- env: { ...verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), OMB_TEST_LIMIT_CLOCK: "1", OMB_TEST_PLAN_USAGE_FILE: usageFile },- stdio: ["ignore", log, log],- });- closeSync(log);- await expect.poll(async () => {- try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }- }, { timeout: 20_000 }).toBe(true);- if (setup.codex !== false) await expect.poll(async () => {- const { instances } = await api("GET", "/api/instances") as { instances: any[] };- return instances.find((instance) => instance.instanceId === "codex")?.models.options.some((option: any) => option.id === codex.model);- }, { timeout: 20_000 }).toBe(true);+ const start = async () => {+ const log = openSync(logPath, "a", 0o600);+ server = spawn(process.execPath, [+ "--experimental-strip-types", "--import", new URL("./testing/limit-clock-hooks.mjs", import.meta.url).href, fileURLToPath(new URL("./index.ts", import.meta.url)),+ ], {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env: { ...verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), OMB_TEST_LIMIT_CLOCK: "1", OMB_TEST_PLAN_USAGE_FILE: usageFile },+ stdio: ["ignore", log, log],+ });+ closeSync(log);+ await expect.poll(async () => {+ try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }+ }, { timeout: 20_000 }).toBe(true);+ if (setup.codex !== false) await expect.poll(async () => {+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };+ return instances.find((instance) => instance.instanceId === "codex")?.models.options.some((option: any) => option.id === codex.model);+ }, { timeout: 20_000 }).toBe(true);+ };+ await start();// Chief first makes the starter its team's Chief, which answers a teammate's failed run with a Team incidents turn// of its own on Claude, whose prompts these tests count. Stepped down, only the conversations under test run.const { bots } = await api("GET", "/api/bots") as { bots: Array<{ id: string; chiefOfStaff?: boolean }> };@@ -86,6 +92,10 @@ async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolawait api("PATCH", `/api/bots/${starter.id}`, { chiefOfStaff: false });await check({api, control, dataDir, evidence,+ restart: async () => {+ await waitForExit(server, { signal: "SIGTERM" });+ await start();+ },limit: (resetsAt) => writeFileSync(limitedFile, JSON.stringify({ status: "rejected", rateLimitType: "five_hour", resetsAt })),refuse: (info) => writeFileSync(limitedFile, JSON.stringify(info)),lift: () => rmSync(limitedFile, { force: true }),@@ -286,3 +296,89 @@ it("with nothing set up for it, carries the person's request on with another AIevidence.push({ first, notices: await notified() });});}, 150_000);++it("after a restart, a new conversation still starts on the AI that carries on, and the limited Claude is not asked again", async () => {+ await withLimitFixture({}, async ({ api, control, limit, claudePrompts, restart, evidence }) => {+ limit(Math.floor(Date.now() / 1000) + 11 * 86_400);+ const { bot } = await control("new-bot", "--name", "Kai");+ const threadId = bot.activeTaskId;+ const reply = async (id: string) => (await messagesOf(api, id)).findLast((message) => message.role === "bot" && message.kind === "text")?.text;+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Draft the launch plan");+ await expect.poll(() => reply(threadId), { timeout: 40_000 }).toBe("done from fake codex");+ expect(claudePrompts()).toHaveLength(1);++ // A Cloud stopped for a sleep, an update or a crash starts again with the limit still on.+ await restart();+ const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "After the restart" });+ await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");+ expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");+ expect(recoveryLines(await messagesOf(api, other.threadId))).toEqual([expect.stringMatching(/so Codex took over\.$/)]);+ expect(await reply(other.threadId)).toBe("done from fake codex");+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Now the timeline");+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");+ expect(claudePrompts(), "no turn went to the limited Claude after the restart").toHaveLength(1);+ const notices = (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice");+ expect(notices, "the person heard it once").toHaveLength(1);+ evidence.push({ notices });+ });+}, 180_000);++it("a signed-out Claude with Automatic recovery on: its turns go to the chosen backup, and the way to sign in is said once", async () => {+ await withLimitFixture({ signedOut: true, recovery: { enabled: true, backup: codex } }, async ({ api, control, claudePrompts, evidence }) => {+ const { bot } = await control("new-bot", "--name", "Kai");+ const threadId = bot.activeTaskId;+ const reply = async (id: string) => (await messagesOf(api, id)).findLast((message) => message.role === "bot" && message.kind === "text")?.text;+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Draft the launch plan");+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");+ expect(await reply(threadId)).toBe("done from fake codex");+ const first = await messagesOf(api, threadId);+ const told = "Verification fixture is signed out on this computer, so Kai is using Codex meanwhile. Sign in again in Settings → AI to keep using Verification fixture.";+ expect(first.flatMap((message) => message.tool?.name?.match(/^(?:recovery|notice):/) ? [message.tool] : [])).toEqual([+ { name: "recovery: Verification fixture is signed out, so Codex took over.", ok: true },+ { name: `notice: ${told}`, ok: true, setup: true },+ ]);+ expect(first.some((message) => message.tool?.ok === false), "no failed turn").toBe(false);+ expect(claudePrompts()).toHaveLength(1);++ const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });+ await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");+ expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");+ const next = await messagesOf(api, other.threadId);+ expect(recoveryLines(next)).toEqual(["recovery: Verification fixture is signed out, so Codex took over."]);+ expect(next.some((message) => message.tool?.name?.startsWith("notice:")), "said once, not again").toBe(false);+ expect(await reply(other.threadId)).toBe("done from fake codex");+ expect(claudePrompts(), "the signed-out Claude is not asked again").toHaveLength(1);+ const notified = (await api("GET", "/api/notifications")).notifications as any[];+ expect(notified.filter((entry) => entry.kind === "notice").map((entry) => entry.body)).toEqual([told]);+ evidence.push({ first, next, notified });+ });+}, 180_000);++it.each([+ ["as its turns end", false],+ ["as Automatic recovery stops its turns before they start, with no other AI to take them", true],+])("a signed-out Claude with nothing to carry on: every refused turn fails, but the way to sign in is said once (%s)", async (_how, recovering) => {+ await withLimitFixture({ signedOut: true }, async ({ api, control, claudePrompts, evidence }) => {+ const { bot } = await control("new-bot", "--name", "Kai");+ const threadId = bot.activeTaskId;+ if (recovering) await api("PUT", "/api/config", { automaticRecovery: { enabled: true, backup: bot.modelSelection } });+ const told = "Verification fixture is signed out on this computer. Sign in again in Settings → AI to keep using it.";+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Draft the launch plan");+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("failed");+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Are you there?");+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("failed");+ const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });+ await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");+ expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("failed");+ expect(claudePrompts()).toHaveLength(3);+ const messages = [...await messagesOf(api, threadId), ...await messagesOf(api, other.threadId)];+ expect(messages.filter((message) => message.tool?.ok === false), "each refused turn shows it failed, with the sign-in that fixes it")+ .toEqual(Array(3).fill(expect.objectContaining({ tool: { name: "error: Not logged in · Please run /login", ok: false, setup: true } })));+ expect(messages.filter((message) => message.tool?.name?.startsWith("notice:")).map((message) => message.tool))+ .toEqual([{ name: `notice: ${told}`, ok: true, setup: true }]);+ const notified = (await api("GET", "/api/notifications")).notifications as any[];+ expect(notified.filter((entry) => entry.kind === "notice").map((entry) => entry.body)).toEqual([told]);+ expect(notified.filter((entry) => entry.kind !== "notice"), "no notice a turn").toEqual([]);+ evidence.push({ messages, notified });+ });+}, 180_000);diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.tsindex f5fb38e3ab..6ebd48cdd0 100644--- a/server/limit-resets.test.ts+++ b/server/limit-resets.test.ts@@ -10,6 +10,8 @@ import { parseClaudeUsage, parseCodexUsage, type PlanProviderRow, type PlanUsageconst NOW = Date.parse("2026-10-19T10:00:00Z");const HOUR = 3_600_000;+/** Past this after its time, a hold is forgotten. */+const REFUSAL_GRACE_FOR_TEST = 10 * 60_000 + 1;const iso = (at: number) => new Date(at).toISOString();function row(id: string, driver: "claude" | "codex", windows: PlanWindows): PlanProviderRow {@@ -271,6 +273,40 @@ describe("LimitResetClock and the turns that follow a refusal", () => {expect(instance.blockedUntil("claude"), "the guess runs out on its own").toBeNull();});+ it("keeps a refusal's hold through a restart, so a new conversation does not go to the limited engine first", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-holds-"));+ try {+ const file = join(dir, "limit-holds.json");+ let now = NOW;+ const boot = () => new LimitResetClock({ accounts: () => accounts, now: () => now, file });+ const first = boot();+ first.noteRuntimeEvent("claude", started("t1"));+ first.noteRuntimeEvent(undefined, { ...refused("t1", NOW + 50 * HOUR), limit: "engine" } as RuntimeEvent);+ first.noteLimit("codex", undefined);+ now = NOW + 10 * 60_000;+ const restarted = boot();+ expect(restarted.blockedUntil("claude"), "the engine is still held after the restart").toBe(NOW + 50 * HOUR);+ expect(restarted.resetAt("claude")).toBe(NOW + 50 * HOUR);+ expect(restarted.blockedUntil("codex"), "a hold that named no reset keeps its re-check time").toBe(NOW + UNNAMED_LIMIT_MS);+ expect(restarted.resetAt("codex"), "and stays a guess").toBeNull();+ restarted.noteRuntimeEvent("claude", started("t2"));+ restarted.noteRuntimeEvent(undefined, completed("t2", true));+ expect(boot().blockedUntil("claude"), "a turn that worked ends it for good").toBeNull();+ now = NOW + UNNAMED_LIMIT_MS + REFUSAL_GRACE_FOR_TEST;+ expect(boot().blockedUntil("codex")).toBeNull();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("holds the engine until it is checked again when its refusal names a reset that already passed", () => {+ const { instance } = clock();+ instance.noteRuntimeEvent("claude", started("t1"));+ instance.noteRuntimeEvent(undefined, { ...refused("t1", NOW - 5 * 60_000), limit: "engine" } as RuntimeEvent);+ expect(instance.blockedUntil("claude")).toBe(NOW + UNNAMED_LIMIT_MS);+ expect(instance.resetAt("claude"), "a past time is no reset time").toBeNull();+ });+it("never holds the engine for one model's own limit", () => {const { instance } = clock();instance.noteRuntimeEvent("claude", { ...refused("t1", NOW + 50 * HOUR), limit: "model" } as RuntimeEvent);diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex 7110ffc495..bf3ecc1600 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -1,8 +1,10 @@// When each engine's usage limit resets, from its plan usage and from the refusals its turns meet, so a limit-reset-// automation knows when to run and the app can warn before a limit is reached.+// automation knows when to run, the app can warn before a limit is reached, and every new turn of every bot goes+// straight to another AI while one is held. The holds are saved: a restart or a sleep the Cloud was stopped for keeps them.import { readFileSync } from "node:fs";import { NEAR_LIMIT_PERCENT, type EngineLimit, type EngineLimitsReport, type LimitWindowName } from "../shared/limit-reset.ts";+import { writeFileAtomic } from "./atomic.ts";import { loadPlanUsage, type PlanAccount, type PlanProviderRow, type PlanUsageReport, type PlanWindow } from "./plan-usage.ts";import type { RuntimeEvent } from "../shared/runtime-events.ts";@@ -64,6 +66,8 @@ export interface LimitClockOptions {/** The known reset times changed. */onChange?: () => void;now?: () => number;+ /** Where the refusals' holds are kept across restarts; none in tests that need no file. */+ file?: string;}/** A test fixture's plan usage, read fresh each time so a test can move a reset. Never set outside tests. */@@ -95,6 +99,7 @@ export class LimitResetClock {constructor(options: LimitClockOptions) {this.options = options;this.now = options.now ?? Date.now;+ this.loadHolds();}/** The reset a limit-reset automation for this engine waits for: a refusal's own time unless usage shows a later@@ -142,14 +147,15 @@ export class LimitResetClock {else if (event.type === "turn.completed" || event.type === "session.exited") {const ran = this.turnEngines.get(event.threadId) ?? engine;this.turnEngines.delete(event.threadId);- if (event.type === "turn.completed" && event.ok && ran && this.refusals.delete(ran)) { this.guessed.delete(ran); this.options.onChange?.(); }+ if (event.type === "turn.completed" && event.ok && ran && this.refusals.delete(ran)) { this.guessed.delete(ran); this.saveHolds(); this.options.onChange?.(); }}}/** The engine's own usage limit refused a turn: held until the reset it named, or for an hour after this refusal when- * it named none (a guess, never shown as a reset time). */+ * it named none (a guess, never shown as a reset time). A reset already past (a stale window, a skewed clock) names+ * none: the refusal still holds the engine, so the next turn does not go there again at once. */noteLimit(engine: string | undefined, resetsAt: number | undefined): void {- if (resetsAt !== undefined) return this.noteRefusal(engine, resetsAt);+ if (resetsAt !== undefined && resetsAt > this.now()) return this.noteRefusal(engine, resetsAt);// A reset the engine named still stands: a refusal that names none never shortens it.if (!engine || ((this.refusal(engine) ?? 0) > this.now() && !this.guessed.has(engine))) return;this.hold(engine, this.now() + UNNAMED_LIMIT_MS, true);@@ -165,6 +171,7 @@ export class LimitResetClock {if (guessed) this.guessed.add(engine);else this.guessed.delete(engine);this.refusals.set(engine, until);+ this.saveHolds();this.options.onChange?.();if (this.soon) clearTimeout(this.soon);this.soon = setTimeout(() => { this.soon = null; void this.refresh(true); }, SOON_AFTER_REFUSAL_MS);@@ -229,11 +236,36 @@ export class LimitResetClock {if (at < this.now() - REFUSAL_GRACE_MS) {this.refusals.delete(engine);this.guessed.delete(engine);+ this.saveHolds();return null;}return at;}+ /** The holds a restart left, without the ones already past. */+ private loadHolds(): void {+ if (!this.options.file) return;+ let saved: unknown;+ try { saved = JSON.parse(readFileSync(this.options.file, "utf8")); } catch { return; }+ if (!saved || typeof saved !== "object" || Array.isArray(saved)) return;+ for (const [engine, hold] of Object.entries(saved as Record<string, { until?: unknown; guessed?: unknown } | null>)) {+ const until = hold?.until;+ if (typeof until !== "number" || !Number.isFinite(until) || until < this.now() - REFUSAL_GRACE_MS) continue;+ this.refusals.set(engine, until);+ if (hold?.guessed === true) this.guessed.add(engine);+ }+ }++ private saveHolds(): void {+ if (!this.options.file) return;+ const holds = Object.fromEntries([...this.refusals].map(([engine, until]) => [engine, { until, guessed: this.guessed.has(engine) }]));+ try {+ writeFileAtomic(this.options.file, JSON.stringify(holds), { mode: 0o600 });+ } catch (error) {+ console.error(`limit holds: could not save: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+private unnamed(engine: string): EngineLimit {const account = this.options.accounts().find((candidate) => candidate.id === engine);return { engine, name: account?.name ?? engine, driver: account?.driver ?? "claude", window: null, usedPercent: null, resetsAt: null, blocked: false };diff --git a/server/provider-auth-sessions.test.ts b/server/provider-auth-sessions.test.tsindex 6aa256b405..475f52049d 100644--- a/server/provider-auth-sessions.test.ts+++ b/server/provider-auth-sessions.test.ts@@ -17,6 +17,31 @@ function fixture() {return { sessions: new ProviderAuthSessions(), instance, auth };}+describe("a finished sign-in", () => {+ it("is told for the AI it signed in to, whichever way it finished, and never for a flow still waiting or one that failed", async () => {+ const { instance, auth } = fixture();+ const signedIn = vi.fn();+ const sessions = new ProviderAuthSessions({ signedIn });+ await sessions.start(instance, "owner");+ await sessions.status("codex", "owner", "random-flow");+ expect(signedIn).not.toHaveBeenCalled();+ instance.getAuthentication.mockResolvedValueOnce({ ...auth, phase: "failed" } as never);+ await sessions.status("codex", "owner", "random-flow");+ expect(signedIn).not.toHaveBeenCalled();++ await sessions.start(instance, "owner");+ instance.getAuthentication.mockResolvedValueOnce({ ...auth, phase: "succeeded" } as never);+ await sessions.status("codex", "owner", "random-flow");+ expect(signedIn).toHaveBeenLastCalledWith("codex");++ await sessions.start(instance, "owner");+ await sessions.complete("codex", "owner", "random-flow", "https://localhost/callback?code=x");+ instance.startAuthentication.mockResolvedValueOnce({ ...auth, phase: "succeeded" });+ await sessions.start({ ...instance, instanceId: "claude" }, "owner");+ expect(signedIn.mock.calls).toEqual([["codex"], ["codex"], ["claude"]]);+ });+});+describe("provider login ownership", () => {it("forgets only the replaced provider's login reservation", async () => {const { sessions, instance } = fixture();diff --git a/server/provider-auth-sessions.ts b/server/provider-auth-sessions.tsindex 7676018b56..2494035ef8 100644--- a/server/provider-auth-sessions.ts+++ b/server/provider-auth-sessions.ts@@ -16,6 +16,12 @@ const failure = (message: string, status: number) => Object.assign(new Error(mesexport class ProviderAuthSessions {private readonly flows = new Map<string, Flow>();+ /** A sign-in to this AI finished: whatever waited on it being signed out may use it again. */+ private readonly signedIn: (instanceId: string) => void;++ constructor(options: { signedIn?: (instanceId: string) => void } = {}) {+ this.signedIn = options.signedIn ?? (() => {});+ }/** A sign-in under way, until it expires: one whose provider call never returns stops counting then too. */get active(): boolean {@@ -42,7 +48,10 @@ export class ProviderAuthSessions {flow.flowId = result.flowId;const expiry = Date.parse(result.expiresAt ?? "");if (Number.isFinite(expiry)) flow.expiresAt = expiry;- if (result.phase === "succeeded") this.flows.delete(instance.instanceId);+ if (result.phase === "succeeded") {+ this.flows.delete(instance.instanceId);+ this.signedIn(instance.instanceId);+ }return result;} catch (error) {if ((!resuming || flow.revoked) && this.flows.get(instance.instanceId) === flow) this.flows.delete(instance.instanceId);@@ -68,6 +77,7 @@ export class ProviderAuthSessions {const status = await flow.instance.getAuthentication(flowId);if (flow.revoked) throw failure("This sign-in session ended.", 404);if (status.phase !== "waiting") flow.expiresAt = 0;+ if (status.phase === "succeeded") this.signedIn(instanceId);return status;}@@ -78,6 +88,7 @@ export class ProviderAuthSessions {try {await flow.instance.completeAuthentication(flowId, callbackUrl);if (this.flows.get(instanceId) === flow) this.flows.delete(instanceId);+ this.signedIn(instanceId);} finally { flow.busy = false; }}diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.tsindex c7b6802ae2..d0cea49a5e 100644--- a/server/quota-switch.test.ts+++ b/server/quota-switch.test.ts@@ -185,7 +185,7 @@ describe("quota switch", () => {flags = undefined;deps.turnStops = { failureCause: () => cause, read: () => (flags ? { flags } : undefined) };deps.takeover = {- backups: () => backups, tell: (who, from, facts) => { told.push({ botId: who.id, from, facts }); },+ backups: () => backups, tell: (who, from, facts) => { told.push({ botId: who.id, from, facts }); return null; },moved: (_botId, threadId, from, to, resetsAt) => { moves.push({ threadId, from, to, ...(resetsAt ? { resetsAt } : {}) }); },};quota = createQuotaSwitch(deps);@@ -334,6 +334,59 @@ describe("quota switch", () => {expect(resend).not.toHaveBeenCalled();expect(notices()).toEqual([{ name: "notice: switched to Codex. Your request is still under way here and continues on Codex.", ok: true }]);});++ describe("an AI that is signed out", () => {+ const SIGNED_OUT = "Not logged in · Please run /login";+ const NOTICE = "Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.";+ let scopes: unknown[];+ beforeEach(() => {+ scopes = [];+ deps.takeover = {+ backups: (_botId, _from, scope) => { scopes.push(scope); return backups; },+ tell: (who, from, facts) => { told.push({ botId: who.id, from, facts }); return told.length === 1 ? NOTICE : null; },+ moved: (_botId, threadId, from, to, resetsAt, scope) => { moves.push({ threadId, from, to, ...(resetsAt ? { resetsAt } : {}), ...(scope ? { scope } : {}) } as never); },+ };+ quota = createQuotaSwitch(deps);+ });+ /** The person's request that met their AI signed out. */+ const signedOut = (record: Partial<QuotaRequest> = {}, why = SIGNED_OUT) => {+ const turn = begin(bot.threadId, record);+ coordinator.endTurn(turn.id, { ok: false, text: why });+ cause = why;+ return quota.turnFailed(thread(), { ...turn.event, stopReason: "auth_required" }, false);+ };++ it("says once in this conversation how to sign in again, then carries the request on with a backup the person chose", async () => {+ backups = [CODEX];+ const messageId = said("plan the launch");+ await signedOut({ messageId });+ expect(notices()).toEqual([+ { name: `notice: ${NOTICE}`, ok: true, setup: true },+ { name: "notice: continuing on Codex while Claude is signed out", ok: true },+ ]);+ expect(scopes).toEqual(["signed-out"]);+ expect(thread().modelSelection).toEqual(CODEX);+ expect(resend).toHaveBeenCalledTimes(1);+ expect(resend.mock.calls[0]![2]).toMatchObject({ id: messageId });+ expect(told).toEqual([{ botId: bot.id, from: defaultSelection(), facts: { scope: "signed-out" } }]);+ expect(moves, "so it goes back once Claude is signed in again").toEqual([{ threadId: bot.threadId, from: defaultSelection(), to: CODEX, scope: "signed-out" }]);+ });++ it("with no backup chosen moves nothing, and a second refusal adds no notice", async () => {+ backups = [];+ await signedOut({ messageId: said("hi") });+ await signedOut({ messageId: said("hi again") });+ expect(notices()).toEqual([{ name: `notice: ${NOTICE}`, ok: true, setup: true }]);+ expect(thread().modelSelection).toEqual(defaultSelection());+ expect(resend).not.toHaveBeenCalled();+ });++ it("takes an account out of credit that stopped the same way for no sign-out", async () => {+ await signedOut({ messageId: said("hi") }, "Your Grok account is out of credits. Add credits with Grok, then run it again.");+ expect(scopes).not.toContain("signed-out");+ expect(notices().filter((tool) => tool.setup)).toEqual([]);+ });+ });});describe("answering a card an earlier version left open", () => {diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex f6485f8f0f..2efb891deb 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -13,7 +13,7 @@ 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 type { LimitTakeover } from "./host/limit-takeover.ts";+import { signedOutStop, type LimitTakeover, type TakeoverScope } from "./host/limit-takeover.ts";export interface QuotaSwitchEngine {instanceId: string;@@ -40,7 +40,7 @@ export interface QuotaSwitchDeps {coordinator: Pick<Coordinator, "all" | "node">;registry: { instances(): QuotaSwitchEngine[] };turnStops: Pick<TurnStops, "failureCause"> & Partial<Pick<TurnStops, "read">>;- /** Which AIs carry on while one is limited, and the one notice for each stretch of a limit. */+ /** Which AIs carry on while one is limited or signed out, and the one notice for each stretch of either. */takeover?: Pick<LimitTakeover, "backups" | "tell" | "moved">;/** A custom endpoint brings its own credential, so its sign-in state does not count. */access?: (instanceId: string) => EngineAccess | undefined;@@ -100,9 +100,9 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {/** A second press while the engine is read is the same answer, never another. */const answering = new Map<string, Promise<QuotaAnswer>>();- const notice = (threadId: string, text: string, ok: boolean): void => {- // `notice:` makes it a status row every client shows, never a folded tool step.- store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok } });+ const notice = (threadId: string, text: string, ok: boolean, setup = false): void => {+ // `notice:` makes it a status row every client shows, never a folded tool step; `setup`: signing in fixes it.+ store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok, ...(setup ? { setup: true } : {}) } });};const openCard = (threadId: string): Message | undefined => store.messagesFor(threadId)@@ -147,9 +147,11 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {.filter((node) => !node.parentId && node.threadId === threadId && request.generations.has(node.id)).sort((a, b) => a.createdAt - b.createdAt).at(-1)?.id;- /** Moves the thread to `selection` and sends the person's message that hit the limit again there; false when 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): Promise<boolean> => {+ /** Moves the thread to `selection` and sends the person's message that hit the limit (or met a signed-out AI) again+ * there; false when 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,+ scope: TakeoverScope = "engine"): Promise<boolean> => {const engines = deps.registry.instances();const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);const before = store.projectBotForTask(botId, threadId);@@ -165,45 +167,55 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {} catch {return false;}- deps.takeover?.moved(botId, threadId, before.modelSelection, checked.selection, resetsAt);+ 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 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);else if (held === "runtime") notice(threadId, `switched to ${name}. Your request is still under way here and continues on ${name}.`, true);else if (held === "busy") notice(threadId, `switched to ${name}. This conversation is working, so your message was not sent again.`, true);else if (held === "question") {- notice(threadId, `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.`, false);+ notice(threadId, `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.`, false);} else if (!original) {- notice(threadId, `switched to ${name}, but the message that hit the limit could not be found to resend — send it again.`, false);+ notice(threadId, `switched to ${name}, but your message could not be found to send again. Send it again.`, false);} else {- notice(threadId, `continuing on ${name} after hitting the usage limit`, true);+ notice(threadId, `continuing on ${name} ${why}`, true);try {await deps.resend(botId, threadId, original, original.replyToId ? store.messagesFor(threadId).find((message) => message.id === original.replyToId) : undefined, spokenLineFields(original.via, original.callId));} catch (error) {- if (store.taskByThread(botId, threadId)) notice(threadId, `could not continue on ${name} — ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`, false);+ if (store.taskByThread(botId, threadId)) notice(threadId, `could not continue on ${name}: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`, false);}}return true;};- /** A turn its AI's usage limit refused: the person's own message carries on with the first AI that can take it, the- * person hears once for this stretch of the limit what carries on meanwhile, and the AI's later turns go there too until- * the limit resets (the turn start's own check). */+ /** A turn its AI's usage limit refused, or that met its AI signed out: the person's own message carries on with the+ * 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 { 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 = flags?.limit ?? (classifyError({ text: deps.turnStops.failureCause(event) ?? "" }).reason === "quota" ? "engine" : undefined);+ const cause = deps.turnStops.failureCause(event);+ const scope: TakeoverScope | undefined = signedOutStop(event.stopReason, cause) ? "signed-out"+ : flags?.limit ?? (classifyError({ text: cause ?? "" }).reason === "quota" ? "engine" : undefined);if (!scope) return null;const thread = store.projectBotForTask(bot.id, threadId) ?? bot;const from = thread.modelSelection;if (scope === "engine") limited.add(from.instanceId);// OMB_QUOTA_SWITCH=0: nothing carries on by itself; the person still hears once that the bot waits.- const backups = enabled() ? deps.takeover?.backups(bot.id, from, scope) ?? [] : [];- const tell = (backup?: ModelSelection) => deps.takeover?.tell(thread, from, { ...(flags?.limitResetsAt ? { resetsAt: flags.limitResetsAt } : {}), scope, ...(backup ? { backup } : {}) });+ const backups = enabled() ? deps.takeover?.backups(bot.id, from, scope, approvalModeFor(thread)) ?? [] : [];+ const resetsAt = scope === "signed-out" ? undefined : flags?.limitResetsAt;+ // A sign-out is told once, first and without a backup's name: what the person must do is sign in again.+ const told = scope === "signed-out" ? deps.takeover?.tell(thread, from, { scope }) : undefined;+ if (told) notice(threadId, told, true, true);+ const tell = (backup?: ModelSelection) => {+ if (scope !== "signed-out") deps.takeover?.tell(thread, from, { ...(resetsAt ? { resetsAt } : {}), scope, ...(backup ? { backup } : {}) });+ };// Only the person's own request: never a routine's, a webhook's, a relayed or a guest's.const own = !internal && request && !request.stopped && request.origin?.kind === "user"&& (!request.turnId || !event.turnId || request.turnId === event.turnId);@@ -216,7 +228,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {building.add(build);try {for (const selection of backups) {- if (await continueOn(bot.id, threadId, selection, request, build, flags?.limitResetsAt)) {+ if (await continueOn(bot.id, threadId, selection, request, build, resetsAt, scope)) {tell(selection);return null;}diff --git a/server/routine-recovery.e2e.test.ts b/server/routine-recovery.e2e.test.tsindex 236879adc8..304df0fc27 100644--- a/server/routine-recovery.e2e.test.ts+++ b/server/routine-recovery.e2e.test.ts@@ -13,7 +13,7 @@ import { hostTimeout } from "./testing/host-timeout.ts";import { openSse, type SseRecorder } from "./testing/sse.ts";const STALLED = "No activity for 20 minutes — the routine was stopped";-const SIGN_IN = "This bot's AI is signed out. Sign in again in Settings → Model providers.";+const SIGN_IN = "This bot's AI is signed out. Sign in again in Settings → AI.";const ROUTINE_HEADER = '[Routine "Inbox brief" — do this now:]';let fixture: VerificationServer | undefined;diff --git a/server/routine-recovery.test.ts b/server/routine-recovery.test.tsindex 66de703c7d..f2a041d194 100644--- a/server/routine-recovery.test.ts+++ b/server/routine-recovery.test.ts@@ -21,7 +21,7 @@ const MINUTE = 60_000;const ROUTING = "stream error: workspace routing discovery failed: error sending request";const STALL = "No activity for 20 minutes — the routine was stopped";const SIGNED_OUT = "Not logged in · Please run /login";-const SIGN_IN_ACTION = "This bot's AI is signed out. Sign in again in Settings → Model providers.";+const SIGN_IN_ACTION = "This bot's AI is signed out. Sign in again in Settings → AI.";const BUSY = "this thread is already working — interrupt it first";const CRASH = "claude exited 3 before result: fake-claude: simulated crash before result";const CAPPED = "Stopped after 40 tool calls without a final answer";@@ -362,6 +362,22 @@ describe("an unattended run only its owner can fix", () => {expect(h.failed.at(-1)!.alert).toEqual({ detail: SIGN_IN_ACTION });});+ it("starts a signed-out run once more on the backup the person chose, and fails it as before when there is none", async () => {+ const scopes: unknown[] = [];+ const h = harness({ limitBackup: (botId, scope) => { scopes.push(scope); return botId === "maus-1"; } });+ const run = await h.start(h.routine("maus-1").id);+ h.fail(run.threadId!, SIGNED_OUT, { setup: true, stopReason: "auth_required" });+ expect(scopes).toEqual(["signed-out"]);+ expect(h.run(run.id)).toMatchObject({ status: "queued", retried: "failed", attention: "Starting again on the backup AI: this bot's AI is signed out" });+ expect(h.failed).toEqual([]);+ await h.advance(20 * SECOND);+ expect(h.attempts).toEqual([run.threadId, run.threadId]);++ const other = await h.start(h.routine("maus-2").id);+ h.fail(other.threadId!, SIGNED_OUT, { setup: true, stopReason: "auth_required" });+ expect(h.run(other.id)).toMatchObject({ status: "failed", error: `${SIGN_IN_ACTION} The AI said: “${SIGNED_OUT}”` });+ });+it("fails an out-of-credit refusal at once with what to do, and the trial credit says to sign in", async () => {const h = harness();const credits = "Your xAI account is out of credits (xAI says: \"Your team has run out of credits\"). Add credits with xAI, then run it again.";diff --git a/server/routine-recovery.ts b/server/routine-recovery.tsindex 9370409d7a..7971f41391 100644--- a/server/routine-recovery.ts+++ b/server/routine-recovery.ts@@ -25,7 +25,7 @@ export interface RoutineFailureFacts {limitResetsAt?: number;/** A usage limit refused it (the runtime error's `limit`). */limit?: "engine" | "model" | "credits";- /** A backup engine takes over from one whose usage limit refused the run. */+ /** A backup engine takes over from one whose usage limit refused the run, or that is signed out. */backupReady?: boolean;}@@ -61,7 +61,7 @@ const REFUSED_KINDS = new Set(["refused", "tool_schema", "tool_count"]);const OWNER_CAUSES = new Set<RoutineOwnerCause>(["signed_out", "credits", "usage_limit", "setup"]);const OWNER_ACTION: Record<Exclude<RoutineOwnerCause, "setup">, string> = {- signed_out: "This bot's AI is signed out. Sign in again in Settings → Model providers.",+ signed_out: "This bot's AI is signed out. Sign in again in Settings → AI.",credits: "This bot's AI account is out of credit. Add credit with the provider, or choose another AI for this bot.",usage_limit: "This bot's AI reached its usage limit. Its routines work again once it resets, or choose another AI for this bot now.",};@@ -172,6 +172,11 @@ export function recoverRun(run: RoutineRun, failure: string, facts: RoutineFailurun.attention = "Starting again on the backup AI: this bot's AI reached its usage limit";return { queued: true };}+ // A signed-out AI's run starts again on the backup the person chose; its start there says once that it needs signing in.+ if (verdict.cause === "signed_out" && facts.backupReady && requeueOnce(run, "failed", failure, now, now + RETRY_MS)) {+ run.attention = "Starting again on the backup AI: this bot's AI is signed out";+ return { queued: true };+ }const first = firstNotice(notices, run.botId, verdict.cause, now);const reset = verdict.resetsAt;if (reset && reset > now && reset - now <= LIMIT_WAIT_MS && requeueOnce(run, "usage_limit", failure, now, reset + AFTER_RESET_MS)) {diff --git a/server/routines.ts b/server/routines.tsindex 1f6590a72c..ff1a0282e3 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -258,8 +258,8 @@ export interface RoutineManagerOptions {routineTurn?: (threadId: string) => boolean;/** When an engine's usage limit resets (epoch ms), or null while that is not known. */limitResetAt?: (engine: string) => number | null;- /** The bot has a backup engine to continue on when its own engine's usage limit refuses a run. */- limitBackup?: (botId: string, scope?: "engine" | "model" | "credits") => boolean;+ /** The bot has a backup engine to continue on when its own engine's usage limit refuses a run, or it is signed out. */+ limitBackup?: (botId: string, scope?: "engine" | "model" | "credits" | "signed-out") => boolean;/** Work this thread handed to another bot is still open, so its wait is not only on the person. */handedOffWorkLive?: (threadId: string) => boolean;launchId?: string;@@ -1313,7 +1313,7 @@ export class RoutineManager {private settleFailure(run: RoutineRun, failure: string, facts: RoutineFailureFacts) {this.failureFacts.delete(run.id);if (this.closing) return;- const backupReady = (facts.limit !== undefined || facts.limitResetsAt !== undefined) && this.options.limitBackup?.(run.botId, facts.limit) === true;+ const held = facts.limit !== undefined || facts.limitResetsAt !== undefined ? facts.limit ?? "engine" : facts.stopReason === "auth_required" ? "signed-out" : undefined, backupReady = held !== undefined && this.options.limitBackup?.(run.botId, held) === true;const recovery = recoverRun(run, failure, { ...facts, ...(backupReady ? { backupReady } : {}) }, this.now(), this.ownerNotices);if (!recovery.queued) this.failRun(run, recovery.error, "failed", recovery.alert);else {diff --git a/src/components/FirstReplyRescueRow.test.ts b/src/components/FirstReplyRescueRow.test.tsindex 23566870d0..0ee5d6eeb6 100644--- a/src/components/FirstReplyRescueRow.test.ts+++ b/src/components/FirstReplyRescueRow.test.ts@@ -151,3 +151,16 @@ describe("stopped row", () => {expect(host.textContent).toBe("Stopped");});});++describe("a notice that signing in fixes", () => {+ const notice = (name: string, setup?: true): Message => ({ id: "m-2", at: AT, role: "bot", kind: "activity", tool: { name, ok: true, ...(setup ? { setup } : {}) } } as Message);++ it("offers Sign in, which opens the AI settings; other notices offer nothing", () => {+ render(notice("notice: Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.", true));+ expect(host.textContent).toContain("Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.");+ act(() => button("Sign in")!.click());+ expect(dispatch).toHaveBeenCalledWith({ type: "toggleAppSettings", open: true, section: "engines" });+ render(notice("notice: continuing on Codex while Claude is signed out"));+ expect(button("Sign in")).toBeUndefined();+ });+});diff --git a/src/components/StatusActivityRow.tsx b/src/components/StatusActivityRow.tsxindex 28cbcb6ee8..5881528c5a 100644--- a/src/components/StatusActivityRow.tsx+++ b/src/components/StatusActivityRow.tsx@@ -1,15 +1,34 @@import { Info, RefreshCw } from "lucide-react";import { statusActivity } from "@/lib/activity-runs";-import type { Message } from "@/state/store";+import { t } from "@/lib/i18n";+import { useStore, type Message } from "@/state/store";import { CancelledTurnRow } from "./CancelledTurnRow";import { FirstReplyRescueRow } from "./FirstReplyRescueRow";+const pill = "rounded-full border border-hairline/40 px-2.5 py-1 text-[13px] text-ink hover:bg-raised";+export function StatusActivityRow({ message }: { message: Message }) {+ const { dispatch } = useStore();const status = statusActivity(message);if (!status) return null;if (status.kind === "stopped") return <CancelledTurnRow name={message.tool?.name} />;if (message.tool?.rescue) return <FirstReplyRescueRow rescue={message.tool.rescue} text={status.text} at={message.at} />;const Icon = status.kind === "recovery" ? RefreshCw : Info;+ // A notice that signing in fixes (an AI signed out) opens the place to sign in again.+ if (status.kind === "notice" && message.tool?.setup === true) {+ return (+ <div role="status" className="flex w-fit max-w-full flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-hairline/40 bg-panel px-3 py-2 text-[13px] text-ink-secondary">+ <span className="flex min-w-0 items-start gap-2">+ <Icon size={13} aria-hidden="true" className="mt-0.5 shrink-0" />+ <span className="min-w-0 break-words">{status.text}</span>+ </span>+ <button type="button" className={pill} title={t("chat.notice.signInHint")}+ onClick={() => dispatch({ type: "toggleAppSettings", open: true, section: "engines" })}>+ {t("chat.notice.signIn")}+ </button>+ </div>+ );+ }return (<div role="status" className="flex w-fit max-w-full items-start gap-2 rounded-xl border border-hairline/40 bg-panel px-3 py-2 text-[13px] text-ink-secondary"><Icon size={13} aria-hidden="true" className="mt-0.5 shrink-0" />diff --git a/src/locales/en.json b/src/locales/en.jsonindex e95bca25c4..3f1fc14c85 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1964,6 +1964,8 @@"chat.rescue.connect": "Connect your subscription","chat.rescue.connectHint": "Sign in with an AI plan you already pay for","chat.error.signedOut": "{name} isn't signed in yet. Sign in below, then send your message again.",+ "chat.notice.signIn": "Sign in",+ "chat.notice.signInHint": "Open AI settings to sign in again","chat.error.details": "Details","chat.error.requestTooLarge": "This message is too large for {model}. Start a new chat or pick a model that accepts more.","chat.error.dismiss": "Dismiss",