Skip to content

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

Usage bars: a failed usage read no longer takes them away (#6851)

Milind Sonid23570390175
diff --git a/packages/phone-protocol/src/limit-reset.ts b/packages/phone-protocol/src/limit-reset.ts
index fb89d219ef..f6138ec555 100644
--- a/packages/phone-protocol/src/limit-reset.ts
+++ b/packages/phone-protocol/src/limit-reset.ts
@@ -57,6 +57,9 @@ export interface EngineLimit {
meter?: string;
/** Every window the engine reported, in the engine's order. A server that predates it sends only the deciding window above. */
windows?: LimitWindowUsage[];
+ /** When these windows were read, when that is before the report's checkedAt: the latest read failed and this is the
+ * reading before it. Absent when the windows are from the latest read. */
+ checkedAt?: number;
}
export interface EngineLimitsReport {
diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.ts
index 07bfbb0db4..16f5089b92 100644
--- a/server/limit-resets.test.ts
+++ b/server/limit-resets.test.ts
@@ -263,6 +263,58 @@ describe("LimitResetClock", () => {
expect(fixture.limit("claude")).toMatchObject({ usedPercent: 91, resetsAt: NOW + 5 * HOUR });
});
+ it("keeps the last reading through a failed read, for an hour at most and only until one of its windows resets", async () => {
+ const failed: PlanProviderRow = { ...claude([0, null], [0, null]), ok: false, error: "Claude's usage could not be reached",
+ fiveHour: { available: false, remainingPercent: null, usedPercent: null, resetsAt: null }, weekly: { available: false, remainingPercent: null, usedPercent: null, resetsAt: null } };
+ let next = report(claude([38, NOW + 3 * HOUR], [12, NOW + 90 * HOUR]));
+ const { instance, at } = clock({ loadUsage: async () => next });
+ await instance.refresh(true);
+ expect(instance.limit("claude")).toMatchObject({ usedPercent: 38 });
+ expect(instance.limit("claude")?.checkedAt).toBeUndefined();
+
+ next = report(failed);
+ at(NOW + 10 * 60_000);
+ await instance.refresh(true);
+ expect(instance.report().checkedAt).toBe(NOW + 10 * 60_000);
+ expect(instance.limit("claude")).toMatchObject({ usedPercent: 38, window: "5-hour", checkedAt: NOW, windows: [
+ { window: "5-hour", usedPercent: 38, resetsAt: NOW + 3 * HOUR }, { window: "weekly", usedPercent: 12, resetsAt: NOW + 90 * HOUR },
+ ] });
+ at(NOW + HOUR);
+ await instance.refresh(true);
+ expect(instance.limit("claude")).toMatchObject({ usedPercent: 38, checkedAt: NOW });
+ at(NOW + HOUR + 60_000);
+ await instance.refresh(true);
+ expect(instance.report().engines).toEqual([]);
+
+ next = report(claude([100, NOW + 2 * HOUR], [12, NOW + 90 * HOUR]));
+ await instance.refresh(true);
+ expect(instance.limit("claude")).toMatchObject({ usedPercent: 100, blocked: true });
+ expect(instance.blockedUntil("claude")).toBe(NOW + 2 * HOUR);
+ next = report(failed);
+ await instance.refresh(true);
+ expect(instance.limit("claude")).toMatchObject({ usedPercent: 100, blocked: false, checkedAt: NOW + HOUR + 60_000 });
+ // Shown only: a kept reading never holds the engine, as before.
+ expect(instance.blockedUntil("claude")).toBeNull();
+ next = report(failed);
+ at(NOW + 2 * HOUR);
+ await instance.refresh(true);
+ expect(instance.report().engines).toEqual([]);
+ });
+
+ it("drops an engine whose account is no longer read, failed read or not", async () => {
+ let current: Array<(typeof accounts)[number] & { noUsage?: true }> = accounts;
+ let next = report(claude([38, NOW + 3 * HOUR], [12, NOW + 90 * HOUR]));
+ const instance = new LimitResetClock({ accounts: () => current, now: () => NOW, loadUsage: async () => next });
+ await instance.refresh(true);
+ next = report();
+ await instance.refresh(true);
+ expect(instance.report().engines).toEqual([]);
+ next = report(claude([38, NOW + 3 * HOUR], [12, NOW + 90 * HOUR]));
+ await instance.refresh(true);
+ current = [{ ...accounts[0]!, noUsage: true }];
+ expect(instance.report().engines).toEqual([]);
+ });
+
it("reads usage once an account is added after a refresh that had none", async () => {
const load = vi.fn(async () => report(claude([50, NOW + HOUR], [5, NOW + 90 * HOUR])));
let current: typeof accounts = [];
diff --git a/server/limit-resets.ts b/server/limit-resets.ts
index 8406d821ce..0d5dac0b36 100644
--- a/server/limit-resets.ts
+++ b/server/limit-resets.ts
@@ -5,7 +5,7 @@ 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 { LIMIT_POLL_MS, limitReadDue } from "./limit-poll.ts";
+import { LIMIT_IDLE_POLL_MS, LIMIT_POLL_MS, limitReadDue } from "./limit-poll.ts";
import { codexHasCreditRoom } from "./codex-credits.ts";
import { claudeHasExtraUsageRoom, loadPlanUsage, type PlanAccount, type PlanProviderRow, type PlanUsageReport, type PlanWindow } from "./plan-usage.ts";
import type { RuntimeEvent } from "../shared/runtime-events.ts";
@@ -113,6 +113,8 @@ export class LimitResetClock {
private readonly options: LimitClockOptions;
private readonly now: () => number;
private usage = new Map<string, EngineLimit>();
+ /** When each engine's usage was last read successfully. */
+ private readonly readAt = new Map<string, number>();
private readonly refusals = new Map<string, number>();
/** Engines held by a refusal that named no reset time: the hold is a guess, never shown as a reset. */
private readonly guessed = new Set<string>();
@@ -162,7 +164,8 @@ export class LimitResetClock {
* the Go subscription's and never covers Zen's free models. */
private meterFor(engine: string, model?: string): EngineLimit | undefined {
const usage = this.reading(engine);
- if (!usage || !meterHoldsEngine(usage.driver)) return undefined;
+ // A reading kept through a failed read (lastReading) is shown only: whether the engine is held is left to fresh ones.
+ if (!usage || !meterHoldsEngine(usage.driver) || usage.checkedAt !== undefined) return undefined;
return usage.driver !== "opencode" || !model || (typedOpenCodeModel(model) ?? model).startsWith(OPENCODE_GO_MODEL_PREFIX) ? usage : undefined;
}
@@ -245,8 +248,13 @@ export class LimitResetClock {
let released = false;
for (const row of report.providers) {
const limit = engineLimitFromUsage(row);
- if (!limit) continue;
+ if (!limit) {
+ const kept = row.ok ? undefined : this.lastReading(row.id);
+ if (kept) next.set(row.id, kept);
+ continue;
+ }
next.set(limit.engine, limit);
+ this.readAt.set(limit.engine, this.now());
if (meterHoldsEngine(row.driver) && 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);
@@ -259,6 +267,16 @@ export class LimitResetClock {
this.options.onChange?.();
}
+ /** A failed read (a refused or timed-out request, a laptop just woken) leaves the engine's last reading in place, so
+ * the usage shown does not vanish until the next read: for an hour at most, and only while none of its windows has
+ * reset since. It carries when it was read, and is shown only: it never says the engine refuses work. */
+ private lastReading(engine: string): EngineLimit | undefined {
+ const usage = this.usage.get(engine), at = this.readAt.get(engine), now = this.now();
+ if (!usage || at === undefined || now - at > LIMIT_IDLE_POLL_MS) return undefined;
+ if ((usage.windows ?? []).some((window) => window.resetsAt !== null && window.resetsAt <= now)) return undefined;
+ return { ...usage, blocked: false, checkedAt: at };
+ }
+
/** 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;
diff --git a/src/components/EngineUsage.tsx b/src/components/EngineUsage.tsx
index 96187648b4..e139b6e1e9 100644
--- a/src/components/EngineUsage.tsx
+++ b/src/components/EngineUsage.tsx
@@ -127,7 +127,7 @@ export function UsageRows({ limit }: { limit: EngineLimit }) {
const [checking, setChecking] = useState(false);
const { dispatch } = useStore();
const now = Date.now();
- const checkedAt = limitsCheckedAt();
+ const checkedAt = limit.checkedAt ?? limitsCheckedAt();
return (
<div data-usage-rows className="flex flex-col gap-2.5">
<div className="flex items-baseline justify-between gap-3">
diff --git a/src/components/ModelPicker.usage.test.ts b/src/components/ModelPicker.usage.test.ts
index e880059559..eaac96eaad 100644
--- a/src/components/ModelPicker.usage.test.ts
+++ b/src/components/ModelPicker.usage.test.ts
@@ -102,6 +102,16 @@ describe("the model button's usage bars", () => {
});
}
+ it("show in Advanced's composer footer, where the model now sits, outside the narrow header's hiding", () => {
+ fixture.advanced = true;
+ flushSync(() => root.render(createElement(ModelPicker, { bot: scout, threadId: scout.threadId, quiet: true })));
+ const bars = chip().querySelector("[data-usage-bars]");
+ expect(bars?.getAttribute("data-usage-bars")).toBe("fine");
+ expect(bars?.querySelector("[data-usage-glyph]")?.getAttribute("data-usage-glyph")).toBe("3");
+ expect(chip().closest("[class*='@container/chathead']")).toBeNull();
+ expect(chip().textContent).toContain("Claude: 38% used, resets 3:40 PM");
+ });
+
it("draw nothing for an engine that reports no usage", () => {
remember([{ ...usage(0), usedPercent: null, window: null, resetsAt: null, windows: [] }]);
render();
diff --git a/src/components/limit-resets.test.ts b/src/components/limit-resets.test.ts
index 64913a17ec..c00ae51a2d 100644
--- a/src/components/limit-resets.test.ts
+++ b/src/components/limit-resets.test.ts
@@ -277,6 +277,11 @@ describe("the bars", () => {
expect(mount(createElement(UsageRows, { limit: windows(38, 80) })).querySelector("[data-usage-checked]")?.textContent).toBe("checked 3 min ago");
});
+ it("say when the usage shown was read, when the latest read failed and kept the one before", () => {
+ limits.rememberLimits({ checkedAt: NOW, engines: [{ ...windows(38, 80), checkedAt: NOW - 12 * 60_000 }] });
+ expect(mount(createElement(UsageRows, { limit: { ...windows(38, 80), checkedAt: NOW - 12 * 60_000 } })).querySelector("[data-usage-checked]")?.textContent).toBe("checked 12 min ago");
+ });
+
it("read limits on their own as a background poll, so a sleeping Cloud home stays asleep", async () => {
fixture.api.mockClear();
mount(createElement(UsageBars, { engine: "claude" }));