Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Show a usage ring for every connected AI in the model menu
enixmomo-gitc9861b686174
diff --git a/src/components/EngineUsage.tsx b/src/components/EngineUsage.tsxindex 03c71d2db9..49d36b6db0 100644--- a/src/components/EngineUsage.tsx+++ b/src/components/EngineUsage.tsx@@ -99,6 +99,27 @@ export function UsageGlyph({ limit, className }: { limit: EngineLimit; className);}+const RING = 14;+const RING_STROKE = 2;+const RING_RADIUS = (RING - RING_STROKE) / 2;+const RING_LENGTH = 2 * Math.PI * RING_RADIUS;+const RING_INK: Record<UsageTone, string> = { fine: "text-success", near: "text-warning", out: "text-danger" };++/** A ring drawn clockwise from the top for the usage left; at the limit it is empty and struck through. */+export function UsageRing({ limit, className }: { limit: EngineLimit; className?: string }) {+ const tone = usageTone(limit);+ const left = tone === "out" ? 0 : Math.max(0, 100 - (limit.usedPercent ?? 0));+ const middle = RING / 2;+ return (+ <svg aria-hidden="true" data-usage-ring={tone} width={RING} height={RING} viewBox={`0 0 ${RING} ${RING}`} className={cn("shrink-0", RING_INK[tone], className)}>+ <circle cx={middle} cy={middle} r={RING_RADIUS} fill="none" stroke="currentColor" strokeWidth={RING_STROKE} opacity={0.3} />+ {left > 0 && <circle cx={middle} cy={middle} r={RING_RADIUS} fill="none" stroke="currentColor" strokeWidth={RING_STROKE} strokeLinecap="round"+ strokeDasharray={`${(RING_LENGTH * left) / 100} ${RING_LENGTH}`} transform={`rotate(-90 ${middle} ${middle})`} />}+ {tone === "out" && <path d={`M3 ${RING - 3}L${RING - 3} 3`} stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" />}+ </svg>+ );+}+/** When the usage was last read, each window's share left with its reset and a track filled by use; at the limit, how it* clears and a fresh check. */export function UsageRows({ limit }: { limit: EngineLimit }) {@@ -152,6 +173,33 @@ export function UsageRows({ limit }: { limit: EngineLimit }) {);}+/** One AI's rows, the bot's own to begin with. When another connected AI reports usage too, a ring for each sits above+ * the rows, and pressing a ring shows that AI's rows. */+function UsageOverview({ engine }: { engine: string | undefined }) {+ const limits = useEngineLimits().filter(reportsUsage);+ const [picked, setPicked] = useState<string>();+ const shown = limits.find((limit) => limit.engine === (picked ?? engine));+ const now = Date.now();+ return (+ <div className="flex flex-col gap-2.5">+ {limits.some((limit) => limit.engine !== engine) && (+ <div data-usage-rings role="group" aria-label={t("limits.title")} className="-mx-1.5 flex flex-wrap gap-1">+ {limits.map((limit) => (+ <button key={limit.engine} type="button" data-usage-engine={limit.engine} aria-pressed={limit === shown} aria-label={limitLine(limit, now, ", ")}+ title={limitLine(limit, now)} onClick={() => setPicked(limit.engine)}+ className={cn("flex h-6 min-w-0 items-center gap-1.5 rounded-full px-1.5 text-[12px] leading-4",+ limit === shown ? "bg-ink/[0.08] font-medium text-ink" : "text-ink-secondary hover:bg-ink/[0.06] hover:text-ink")}>+ <UsageRing limit={limit} />+ <span className="max-w-28 truncate">{limit.name}</span>+ </button>+ ))}+ </div>+ )}+ {shown && <UsageRows limit={shown} />}+ </div>+ );+}+const HOVER_OPEN_MS = 250;const HOVER_CLOSE_MS = 150;const CARD_WIDTH = 272;@@ -169,7 +217,7 @@ function UsageCard({ limit, anchor, onEnter, onLeave }: { limit: EngineLimit; anreturn (<div data-usage-card role="group" aria-label={limit.name} style={style} className="menu-surface z-[90] px-3 py-2.5"onPointerEnter={onEnter} onPointerLeave={onLeave} onPointerDown={keep} onMouseDown={keep} onClick={keep} onKeyDown={keep}>- <UsageRows limit={limit} />+ <UsageOverview engine={limit.engine} /></div>);}@@ -208,11 +256,10 @@ export function UsageBars({ engine, compact = false, hover = true, className }:/** Widens the narrow header's square model button to fit the bars while they warn. */export const USAGE_WARN_WIDENS = "@max-4xl/chathead:has-[[data-usage-warn]]:w-auto @max-4xl/chathead:has-[[data-usage-warn]]:gap-1.5 @max-4xl/chathead:has-[[data-usage-warn]]:px-2";-/** The rows at the top of the open model menu. */+/** The rows at the top of the open model menu, with a ring for every connected AI that reports usage. */export function UsageMenuRows({ engine }: { engine: string | undefined }) {- const limit = useEngineUsage(engine);- if (!limit) return null;- return <div data-usage-menu className="shrink-0 border-b-[0.5px] border-ink/10 px-3.5 py-2.5"><UsageRows limit={limit} /></div>;+ if (!useEngineLimits().some(reportsUsage)) return null;+ return <div data-usage-menu className="shrink-0 border-b-[0.5px] border-ink/10 px-3.5 py-2.5"><UsageOverview engine={engine} /></div>;}/** A phone's header has no model button: near or at the limit, the bars stand alone and open the bot's model. */diff --git a/src/components/ModelPicker.usage.test.ts b/src/components/ModelPicker.usage.test.tsindex dc12165c8b..075d420be0 100644--- a/src/components/ModelPicker.usage.test.ts+++ b/src/components/ModelPicker.usage.test.ts@@ -1,6 +1,6 @@// @vitest-environment happy-dom// The usage bars inside the model button, in both modes, in the narrow header and in the bot panel, and the same rows-// at the top of the open model menu.+// at the top of the open model menu, under a ring for every connected AI that reports usage.import { createElement } from "react";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";@@ -149,3 +149,66 @@ describe("the model button's usage bars", () => {expect(document.querySelector("[data-usage-menu]")).toBeNull();});});++describe("the model menu's usage rings", () => {+ const other = (engine: string, name: string, used: number, blocked = false): EngineLimit =>+ ({ ...usage(used, blocked), engine, name, driver: "codex", window: "weekly", windows: [{ window: "weekly", usedPercent: used, resetsAt: RESET }] });+ const openMenu = async () => {+ render();+ flushSync(() => chip().click());+ await settle();+ return document.querySelector<HTMLElement>("[data-model-picker-content]")!;+ };+ const rings = (menu: HTMLElement) => [...menu.querySelectorAll<HTMLButtonElement>("[data-usage-engine]")];+ const shownRows = (menu: HTMLElement) => [...menu.querySelectorAll("[data-usage-row]")].map((row) => row.getAttribute("data-usage-row"));++ for (const advanced of [false, true]) {+ it(`show one ring for every AI that reports usage, coloured by how much is left (${advanced ? "Advanced" : "Simple"})`, async () => {+ fixture.advanced = advanced;+ remember([usage(38), other("codex", "Codex", 91), other("gemini", "Gemini", 100, true), { ...other("local", "Local", 0), usedPercent: null, windows: [] }]);+ const menu = await openMenu();+ expect(menu.firstElementChild?.hasAttribute("data-usage-menu")).toBe(true);+ expect(rings(menu).map((ring) => [ring.dataset.usageEngine, ring.textContent, ring.querySelector("[data-usage-ring]")?.getAttribute("data-usage-ring")]))+ .toEqual([["claude", "Claude", "fine"], ["codex", "Codex", "near"], ["gemini", "Gemini", "out"]]);+ expect(rings(menu).map((ring) => ring.querySelector("[data-usage-ring]")?.getAttribute("class")?.match(/text-\w+/)?.[0])).toEqual(["text-success", "text-warning", "text-danger"]);+ expect(rings(menu).map((ring) => ring.getAttribute("aria-label"))).toEqual(["Claude: 38% used, resets 3:40 PM", "Codex: 91% used, resets 3:40 PM", "Gemini: at its limit, resets 3:40 PM"]);+ });+ }++ it("start on the bot's own AI, and show another AI's rows when its ring is pressed", async () => {+ remember([usage(38), other("codex", "Codex", 91)]);+ const menu = await openMenu();+ expect(rings(menu).map((ring) => ring.getAttribute("aria-pressed"))).toEqual(["true", "false"]);+ expect(shownRows(menu)).toEqual(["5-hour", "weekly"]);+ flushSync(() => rings(menu)[1]!.click());+ expect(rings(menu).map((ring) => ring.getAttribute("aria-pressed"))).toEqual(["false", "true"]);+ expect(shownRows(menu)).toEqual(["weekly"]);+ expect(menu.querySelector("[data-usage-rows]")?.textContent).toContain("Codex usage");+ expect(document.querySelector("[data-model-picker-content]")).not.toBeNull();+ });++ it("draw less of the ring as the usage runs down, and none at the limit", async () => {+ remember([usage(25), other("codex", "Codex", 75), other("gemini", "Gemini", 100, true)]);+ const menu = await openMenu();+ const arcs = rings(menu).map((ring) => ring.querySelector("circle[stroke-dasharray]")?.getAttribute("stroke-dasharray")?.split(" ").map(Number));+ expect(arcs[0]![0]! / arcs[0]![1]!).toBeCloseTo(0.75);+ expect(arcs[1]![0]! / arcs[1]![1]!).toBeCloseTo(0.25);+ expect(arcs[2]).toBeUndefined();+ expect(rings(menu)[2]!.querySelector("path")).not.toBeNull();+ });++ it("stay away while the bot's own AI is the only one that reports usage", async () => {+ const menu = await openMenu();+ expect(menu.querySelector("[data-usage-rings]")).toBeNull();+ expect(shownRows(menu)).toEqual(["5-hour", "weekly"]);+ });++ it("show another AI's ring, with no rows until it is pressed, when the bot's own AI reports no usage", async () => {+ remember([other("codex", "Codex", 91)]);+ const menu = await openMenu();+ expect(rings(menu).map((ring) => ring.getAttribute("aria-pressed"))).toEqual(["false"]);+ expect(shownRows(menu)).toEqual([]);+ flushSync(() => rings(menu)[0]!.click());+ expect(shownRows(menu)).toEqual(["weekly"]);+ });+});