Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(limits): end an AI's limit hold once usage shows room, and add Try again now
AdityaUmale02785592148b
diff --git a/server/limit-reset-requests.test.ts b/server/limit-reset-requests.test.tsindex 963cf15776..a9468b5bcb 100644--- a/server/limit-reset-requests.test.ts+++ b/server/limit-reset-requests.test.ts@@ -153,6 +153,16 @@ describe("the limit-reset routes", () => {return { ...h, call, created };}+ it("Try again now ends the engine's hold and answers with the limits as they are now (emails 1a1c2500, 1a1c136d)", async () => {+ const { call, clock } = routes();+ clock.noteRefusal("claude", NOW + 5 * HOUR);+ expect(clock.blockedUntil("claude")).not.toBeNull();+ const response = await call("POST", "/api/limit-resets/release", { engine: "claude" });+ expect(response).toMatchObject({ status: 200, body: { engines: expect.any(Array) } });+ expect(clock.blockedUntil("claude")).toBeNull();+ expect(await call("POST", "/api/limit-resets/release", {})).toMatchObject({ status: 400 });+ });+it("Continue creates a one-time limit-reset automation in that same conversation, told the turn hit the limit", async () => {const { call, routines, store, created } = routes();const response = await call("POST", "/api/limit-resets/continue", { botId: "scout", threadId: "thread-1" });diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.tsindex 19efc4d125..699c8d886c 100644--- a/server/limit-resets.test.ts+++ b/server/limit-resets.test.ts@@ -430,11 +430,52 @@ describe("LimitResetClock and the turns that follow a refusal", () => {expect(instance.blockedUntil("codex"), "a read from after it").toBeNull();});- it("keeps a Claude hold whatever its usage shows, since Claude refuses on limits those windows do not show", () => {+ it("ends a Claude hold too once fresh usage shows room, but not while a window is still at its limit (emails 1a1c2500, 1a1c136d)", () => {const { instance } = clock();instance.noteRefusal("claude", NOW + 23 * HOUR);+ instance.noteUsage(report(claude([100, NOW + 2 * HOUR], [8, NOW + 5 * 24 * HOUR])));+ expect(instance.blockedUntil("claude"), "a window still full keeps it held").not.toBeNull();instance.noteUsage(report(claude([3, NOW + 4 * HOUR], [8, NOW + 5 * 24 * HOUR])));- expect(instance.blockedUntil("claude")).toBe(NOW + 23 * HOUR);+ expect(instance.blockedUntil("claude")).toBeNull();+ });++ it("re-reads usage every few minutes while an engine is held, with nothing else waiting, and so ends a hold that reset early", async () => {+ vi.useFakeTimers({ now: NOW });+ let usage = report(claude([100, NOW + 23 * HOUR], [8, NOW + 5 * 24 * HOUR]));+ const loadUsage = vi.fn(async () => ({ ...usage, fetchedAt: iso(Date.now()) }));+ const instance = new LimitResetClock({ accounts: () => accounts, loadUsage, waiting: () => false });+ instance.start();+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(loadUsage, "nothing held, nothing waiting: no reads").not.toHaveBeenCalled();+ instance.noteRefusal("claude", Date.now() + 23 * HOUR);+ await vi.advanceTimersByTimeAsync(6_000);+ expect(instance.blockedUntil("claude"), "the read soon after the refusal still shows the full window").not.toBeNull();+ usage = report(claude([2, NOW + 5 * HOUR], [8, NOW + 5 * 24 * HOUR]));+ await vi.advanceTimersByTimeAsync(6 * 60_000);+ expect(instance.blockedUntil("claude")).toBeNull();+ instance.stop();+ });++ it("ends a hold at once on Try again now, saved across a restart, and a new refusal holds it again", () => {+ const dir = mkdtempSync(join(tmpdir(), "limit-release-"));+ try {+ const file = join(dir, "holds.json");+ const changed = vi.fn();+ const boot = () => new LimitResetClock({ accounts: () => accounts, now: () => NOW, file, onChange: changed });+ const instance = boot();+ expect(instance.release("claude"), "nothing held").toBe(false);+ instance.noteRefusal("claude", NOW + 23 * HOUR);+ changed.mockClear();+ expect(instance.release("claude")).toBe(true);+ expect(changed).toHaveBeenCalled();+ expect(instance.blockedUntil("claude")).toBeNull();+ expect(boot().blockedUntil("claude"), "still released after a restart").toBeNull();+ instance.noteRefusal("claude", NOW + 23 * HOUR);+ expect(instance.blockedUntil("claude")).toBe(NOW + 23 * HOUR);+ instance.stop();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }});it("never holds the engine for one model's own limit", () => {diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex 56b0214283..e5f212d139 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -46,11 +46,12 @@ export function engineLimitFromUsage(row: PlanProviderRow): EngineLimit | null {/** How far apart a refusal's reset and its window's own reset can be: a refusal names its minute, usage the second. */const SAME_RESET_MS = 5 * 60_000;-/** A Codex refusal's hold that fresh usage shows is over: no window at its limit and none resetting at the hold's time,- * so the window that refused is gone (a plan upgrade, a reset Codex moved). Every new turn goes to another AI while the- * engine is held, so no turn could end the hold. Claude keeps its holds: it also refuses on limits these windows do not show. */-function codexHoldGone(row: PlanProviderRow, limit: EngineLimit, held: number | undefined, guessed: boolean): boolean {- if (held === undefined || guessed || limit.driver !== "codex" || limit.blocked || limit.usedPercent === null) return false;+/** A refusal's hold that fresh usage shows is over: no window at its limit and none resetting at the hold's time, so the+ * window that refused is gone (a plan upgrade, a reset moved early or done outside the app). Every new turn goes to another+ * AI while the engine is held, so no turn could end the hold. Claude too: if it still refuses on a limit these windows do+ * not show, that refusal holds it again. A guessed hold (no reset named) has no time to compare and runs out in an hour. */+function holdGone(row: PlanProviderRow, limit: EngineLimit, held: number | undefined, guessed: boolean): boolean {+ if (held === undefined || guessed || limit.blocked || limit.usedPercent === null || limit.usedPercent >= 100) return false;const windows = [windowLine("5-hour", row.fiveHour), windowLine("weekly", row.weekly)];return windows.every((line) => line === null || (line.resetsAt !== null && Math.abs(line.resetsAt - held) > SAME_RESET_MS));}@@ -208,7 +209,7 @@ export class LimitResetClock {const limit = engineLimitFromUsage(row);if (!limit) continue;next.set(limit.engine, limit);- if (fetchedAt >= (this.heldAt.get(limit.engine) ?? 0) && codexHoldGone(row, limit, this.refusals.get(limit.engine), this.guessed.has(limit.engine))) {+ if (fetchedAt >= (this.heldAt.get(limit.engine) ?? 0) && holdGone(row, limit, this.refusals.get(limit.engine), this.guessed.has(limit.engine))) {this.refusals.delete(limit.engine);this.heldAt.delete(limit.engine);released = true;@@ -220,6 +221,16 @@ export class LimitResetClock {this.options.onChange?.();}+ /** The person's "Try again now": the engine's hold ends at once, so the next turn goes to it. A refusal holds it again. */+ release(engine: string): boolean {+ if (!this.refusals.delete(engine)) return false;+ this.guessed.delete(engine);+ this.heldAt.delete(engine);+ this.saveHolds();+ this.options.onChange?.();+ return true;+ }+/** Reads usage again when what is known is older than `maxAgeMs`; one read at a time. */async ensureFresh(maxAgeMs = LIMIT_POLL_MS): Promise<void> {if (this.now() - this.checkedAt < maxAgeMs) return;@@ -244,7 +255,8 @@ export class LimitResetClock {start(): void {if (this.timer) return;- this.timer = setInterval(() => { if (this.options.waiting?.()) void this.ensureFresh(LIMIT_POLL_MS - 1_000); }, 60_000);+ // While an engine is held its usage is read every few minutes too, so a limit that reset early ends the hold.+ this.timer = setInterval(() => { if (this.refusals.size || this.options.waiting?.()) void this.ensureFresh(LIMIT_POLL_MS - 1_000); }, 60_000);this.timer.unref?.();}diff --git a/server/routes/limit-resets.ts b/server/routes/limit-resets.tsindex 952bd64419..d7bc11a465 100644--- a/server/routes/limit-resets.ts+++ b/server/routes/limit-resets.ts@@ -1,8 +1,9 @@-// The engines' usage limits and the automations that wait for them to reset. All three need admin scope+// The engines' usage limits and the automations that wait for them to reset. All four need admin scope// (request-auth's default):// GET /api/limit-resets each engine's limit: how full, when it resets, whether it refuses work// POST /api/limit-resets/continue {botId, threadId}: the stopped turn's "Continue when your limit resets"// POST /api/limit-resets/after-reset {routineId, engine}: move only that automation's next run past the reset+// POST /api/limit-resets/release {engine}: "Try again now", end the engine's limit hold at onceimport { AFTER_RESET_MS, type LimitResetSchedule } from "../../shared/limit-reset.ts";import type { RequestAuth } from "../request-auth.ts";import type { LimitResetClock } from "../limit-resets.ts";@@ -51,6 +52,13 @@ export function createLimitResetRoutes(deps: LimitResetRouteDeps): RouteHandlerif (url.searchParams.get("refresh") === "1" || deps.clock.report().checkedAt === 0) await fresh;return json(res, 200, deps.clock.report());}+ if (path === "/api/limit-resets/release" && method === "POST") {+ const body = await readBody(req, 4096) as Record<string, unknown> | null;+ const engine = exactId(body?.engine);+ if (!engine) return json(res, 400, { error: "engine is required" });+ deps.clock.release(engine);+ return json(res, 200, deps.clock.report());+ }if (path === "/api/limit-resets/continue" && method === "POST") {const body = await readBody(req, 4096) as Record<string, unknown> | null;const botId = exactId(body?.botId), threadId = exactId(body?.threadId);diff --git a/src/components/EngineUsage.tsx b/src/components/EngineUsage.tsxindex 94bb0277a4..88f3d55522 100644--- a/src/components/EngineUsage.tsx+++ b/src/components/EngineUsage.tsx@@ -4,7 +4,7 @@ import { createPortal } from "react-dom";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import {- limitLine, limitsCheckedAt, loadLimits, reportsUsage, resetTime, usageBars, usageRows, usageTone, useEngineLimits, USAGE_BARS, windowLabel,+ limitLine, limitsCheckedAt, loadLimits, releaseLimit, reportsUsage, resetTime, usageBars, usageRows, usageTone, useEngineLimits, USAGE_BARS, windowLabel,type EngineLimit, type UsageTone,} from "@/lib/limit-resets";import type { Routine } from "@/lib/routines";@@ -103,6 +103,7 @@ export function UsageGlyph({ limit, className }: { limit: EngineLimit; className* clears and a fresh check. */export function UsageRows({ limit }: { limit: EngineLimit }) {const [checking, setChecking] = useState(false);+ const { dispatch } = useStore();const now = Date.now();const checkedAt = limitsCheckedAt();return (@@ -128,11 +129,23 @@ export function UsageRows({ limit }: { limit: EngineLimit }) {{limit.blocked && (<div className="flex items-start justify-between gap-3 border-t-[0.5px] border-ink/10 pt-2.5 text-[12px] leading-4"><p className="min-w-0 text-ink-tertiary">{t("limits.clearsOnReply", { engine: limit.name })}</p>- <button type="button" data-usage-check disabled={checking} aria-busy={checking}- onClick={() => { setChecking(true); void loadLimits(true).finally(() => setChecking(false)); }}- className="shrink-0 font-medium text-ink underline underline-offset-2 hover:text-ink-secondary disabled:cursor-wait disabled:opacity-60">- {t("common.checkAgain")}- </button>+ <span className="flex shrink-0 flex-col items-end gap-1.5">+ <button type="button" data-usage-check disabled={checking} aria-busy={checking}+ onClick={() => { setChecking(true); void loadLimits(true).finally(() => setChecking(false)); }}+ className="font-medium text-ink underline underline-offset-2 hover:text-ink-secondary disabled:cursor-wait disabled:opacity-60">+ {t("common.checkAgain")}+ </button>+ <button type="button" data-usage-release disabled={checking} aria-busy={checking}+ onClick={() => {+ setChecking(true);+ void releaseLimit(limit.engine)+ .catch((cause) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }))+ .finally(() => setChecking(false));+ }}+ className="font-medium text-ink underline underline-offset-2 hover:text-ink-secondary disabled:cursor-wait disabled:opacity-60">+ {t("limits.tryAgainNow")}+ </button>+ </span></div>)}</div>diff --git a/src/components/limit-resets.test.ts b/src/components/limit-resets.test.tsindex fd25e28ac8..244a92b8bc 100644--- a/src/components/limit-resets.test.ts+++ b/src/components/limit-resets.test.ts@@ -228,6 +228,13 @@ describe("the bars", () => {flushSync(() => blocked.querySelector<HTMLButtonElement>("[data-usage-check]")!.click());await settle();expect(fixture.api).toHaveBeenCalledWith("/api/limit-resets?refresh=1");+ fixture.api.mockClear();+ fixture.api.mockImplementation(async () => ({ checkedAt: NOW, engines: [windows(100, 80)] }));+ // the check above keeps both buttons busy until its read settles+ await vi.waitFor(() => expect(blocked.querySelector<HTMLButtonElement>("[data-usage-release]")!.disabled).toBe(false));+ flushSync(() => blocked.querySelector<HTMLButtonElement>("[data-usage-release]")!.click());+ await settle();+ expect(fixture.api, "Try again now ends the hold (emails 1a1c2500, 1a1c136d)").toHaveBeenCalledWith("/api/limit-resets/release", { method: "POST", body: JSON.stringify({ engine: "claude" }) });expect(opened).not.toHaveBeenCalled();});diff --git a/src/lib/limit-resets.ts b/src/lib/limit-resets.tsindex 8f78751ed0..af67eb383e 100644--- a/src/lib/limit-resets.ts+++ b/src/lib/limit-resets.ts@@ -41,6 +41,11 @@ export function loadLimits(refresh = false): Promise<void> {return loading;}+/** "Try again now": the server ends the engine's limit hold, so the next turn goes to it; a refusal holds it again. */+export async function releaseLimit(engine: string): Promise<void> {+ rememberLimits(await api<EngineLimitsReport>("/api/limit-resets/release", { method: "POST", body: JSON.stringify({ engine }) }));+}+/** When the server last read the engines' usage; 0 before any read. */export const limitsCheckedAt = () => report?.checkedAt ?? 0;diff --git a/src/locales/en.json b/src/locales/en.jsonindex df0e4cfd02..ded467dd59 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -5198,6 +5198,7 @@"limits.resets": "resets {time}","limits.windowAtLimit": "At its limit","limits.clearsOnReply": "Clears by itself once {engine} replies again.",+ "limits.tryAgainNow": "Try again now","limits.cardTitle": "{engine} usage","limits.checked": "checked {when}","limits.dueOne": "1 automation runs before then",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex eaae453b01..31ae821201 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7708,6 +7708,7 @@"settings.recovery.ownBackups": "Bots com modelos de reserva próprios (Modelo → Modelos de reserva deste bot) usam essas opções, esteja esta configuração ligada ou não.","limits.windowAtLimit": "No limite","limits.clearsOnReply": "O bloqueio termina automaticamente quando {engine} voltar a responder.",+ "limits.tryAgainNow": "Tentar agora","limits.cardTitle": "Uso do {engine}","limits.checked": "verificado {when}","botAccess.share": "Compartilhar",