Skip to content

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

Composer context panel: token counts and the list by category are Advanced only

luishron123629b21571e68
diff --git a/src/components/ComposerContextMenu.test.ts b/src/components/ComposerContextMenu.test.ts
index d841a9d045..2a4f58ea8d 100644
--- a/src/components/ComposerContextMenu.test.ts
+++ b/src/components/ComposerContextMenu.test.ts
@@ -4,6 +4,7 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { contextReading, contextRows, roomContextReadings } from "@/lib/context-usage";
+import { ADVANCED_MODE_KEY } from "@/lib/interface-mode";
import { BotEditorStore, type Bot, type Group, type Message, type TaskUsage, type useStore } from "@/state/store";
import type { ContextBreakdown } from "../../shared/context-breakdown";
import { ComposerContextMenu } from "./ComposerContextMenu";
@@ -32,6 +33,7 @@ const panel = () => host.querySelector<HTMLElement>("[data-context-panel]");
const press = (element: HTMLElement) => act(async () => { element.click(); await new Promise((resolve) => setTimeout(resolve, 0)); });
const words = () => panel()!.textContent!.replace(/\s+/g, " ");
const requests = () => fetched.mock.calls.map(([url, init]) => [String(url).replace(/^.*(?=\/api\/)/, ""), JSON.parse(String((init as RequestInit).body))]);
+const advancedMode = () => localStorage.setItem(ADVANCED_MODE_KEY, "1");
const posted = () => requests().filter(([path]) => !path.endsWith("/context"));
const counted: ContextBreakdown = {
tokens: 136_000, window: 200_000,
@@ -50,7 +52,7 @@ beforeEach(() => {
breakdown = null;
fetched = vi.fn(async (url: unknown) => new Response(String(url).endsWith("/context") ? JSON.stringify({ threadId: "t1", breakdown }) : "{}", { status: 200, headers: { "content-type": "application/json" } }));
vi.stubGlobal("fetch", fetched);
- localStorage.setItem("omb-advanced-mode", "0");
+ localStorage.setItem(ADVANCED_MODE_KEY, "0");
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -64,17 +66,19 @@ afterEach(() => {
});
describe("the composer's context button", () => {
- it("names how full the chat is and opens a panel with the reading and both actions", async () => {
+ it("names how full the chat is and opens a panel with the share used and both actions", async () => {
+ breakdown = counted;
await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });
expect(trigger().getAttribute("aria-label")).toBe("Context 68%");
expect(trigger().getAttribute("aria-expanded")).toBe("false");
expect(panel()).toBeNull();
await press(trigger());
expect(trigger().getAttribute("aria-expanded")).toBe("true");
- expect(words()).toContain("68% used");
- expect(words()).toContain("136k of 200k tokens");
+ expect(words()).toBe("Context68% usedCompact contextStart fresh");
+ expect(panel()!.querySelector("[data-context-meter]")!.getAttribute("data-context-meter")).toBe("68");
expect([...panel()!.querySelectorAll("button")].map((button) => [button.textContent, button.disabled]))
.toEqual([["Compact context", false], ["Start fresh", false]]);
+ expect(requests()).toEqual([]);
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
expect(panel()).toBeNull();
});
@@ -101,12 +105,26 @@ describe("the composer's context button", () => {
expect(panel()!.querySelector<HTMLButtonElement>("[data-context-fresh]")!.disabled).toBe(false);
});
- it("asks the engine what fills the context when the panel opens, and lists it in Simple mode too", async () => {
+ it("keeps token counts out of Simple mode: a reading without a window shows as none, a room bot by name alone", async () => {
+ await render({ bot: chat({ tokens: 170_000 }) });
+ expect(trigger().getAttribute("aria-label")).toBe("Context");
+ await press(trigger());
+ expect(words()).toBe("ContextNo reading yet. It shows after the bot's next reply.Compact contextStart fresh");
+ await press(trigger());
+ await render({ group: { id: "g1", memberContext: { s: { tokens: 170_000 } } } as unknown as Group, members: [{ id: "s", name: "Scout" }] as Bot[] });
+ await press(trigger());
+ expect(words()).toBe("Context of each bot in this roomScoutCompact context");
+ expect(requests()).toEqual([]);
+ });
+
+ it("in Advanced mode adds the tokens and asks the engine what fills the context when the panel opens", async () => {
+ advancedMode();
breakdown = counted;
await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });
expect(requests()).toEqual([]);
await press(trigger());
expect(requests()).toEqual([["/api/bots/b1/context", { threadId: "t1" }]]);
+ expect(words()).toContain("68% used136k of 200k tokens");
expect([...panel()!.querySelectorAll("[data-context-breakdown] > div")].map((row) => [row.querySelector("dt")!.textContent, row.querySelector("dd")!.textContent]))
.toEqual([
["System prompt", "8k · 4%"], ["Memory files", "2k · 1%"], ["Tools", "16k · 8%"], ["Skills and subagents", "4k · 2%"],
@@ -117,6 +135,7 @@ describe("the composer's context button", () => {
});
it("takes the total from the engine's count when it differs from the last turn's reading", async () => {
+ advancedMode();
breakdown = {
tokens: 6_000, window: 200_000,
categories: [
@@ -150,6 +169,7 @@ describe("the composer's context button", () => {
});
it("shows no count after the chat was summarized, even when the engine still answers, until a new turn ends", async () => {
+ advancedMode();
const before: ContextBreakdown = {
tokens: 6_000, window: 200_000,
categories: [{ id: "system_prompt", kind: "used", tokens: 1_900 }, { id: "messages", kind: "used", tokens: 4_100 }, { id: "free_space", kind: "free", tokens: 194_000 }],
@@ -189,6 +209,7 @@ describe("the composer's context button", () => {
});
it("keeps the total alone when the engine has no count, and the last count on screen while a new one loads", async () => {
+ advancedMode();
await render({ bot: chat({ tokens: 136_000, window: 200_000 }, { id: "b2" }) });
await press(trigger());
expect(words()).toContain("68% used");
@@ -213,6 +234,7 @@ describe("the composer's context button", () => {
});
it("keeps the newest count when an older request answers last, also for a panel mounted afterwards", async () => {
+ advancedMode();
const bot = chat({ tokens: 12, window: 200_000 }, { id: "b5" });
const waiting: Array<(response: Response) => void> = [];
fetched.mockImplementation(() => new Promise<Response>((resolve) => waiting.push(resolve)));
diff --git a/src/components/ComposerContextMenu.tsx b/src/components/ComposerContextMenu.tsx
index a6af3be9ec..e056e6ed90 100644
--- a/src/components/ComposerContextMenu.tsx
+++ b/src/components/ComposerContextMenu.tsx
@@ -6,6 +6,7 @@ import { cn } from "@/lib/cn";
import { compactedSinceReading } from "@/lib/context-warning";
import { contextReading, contextRowLabel, contextRows, roomContextReadings, type ContextReading, type ContextRow } from "@/lib/context-usage";
import { t } from "@/lib/i18n";
+import { useAdvancedMode } from "@/lib/interface-mode";
import { formatTokens, type ContextTone } from "@/lib/usage";
import { api } from "@/state/api";
import { visibleMessages, type Bot, type Group, type Message } from "@/state/store";
@@ -35,14 +36,15 @@ function tokensLine(reading: ContextReading): string {
: t("contextMenu.tokens", { tokens: formatTokens(reading.tokens) });
}
-function Meter({ reading, name }: { reading: ContextReading; name?: string }) {
- const used = reading.percent === undefined ? tokensLine(reading) : t("contextMenu.used", { percent: reading.percent });
+function Meter({ reading, name, detailed }: { reading: ContextReading; name?: string; detailed: boolean }) {
+ const tokens = detailed ? tokensLine(reading) : "";
+ const used = reading.percent === undefined ? tokens : t("contextMenu.used", { percent: reading.percent });
return (
<div data-context-meter={reading.percent ?? ""} className="flex flex-col gap-1.5 px-2 py-1">
<div className="flex items-baseline gap-3 text-[13px] leading-[18px]">
<span className={cn("min-w-0 truncate font-medium tabular-nums", TONE_INK[reading.tone] || "text-ink")}>{name ?? used}</span>
<span className="ms-auto shrink-0 text-[12px] leading-4 tabular-nums text-ink-tertiary">
- {name ? used : reading.percent === undefined ? "" : tokensLine(reading)}
+ {name ? used : reading.percent === undefined ? "" : tokens}
</span>
</div>
{reading.percent !== undefined && (
@@ -87,7 +89,7 @@ const lastBreakdown = new Map<string, { moment: string; breakdown: ContextBreakd
const newestRequest = new Map<string, number>();
let requests = 0;
-/** The engine's own count, asked for while the panel is open and again whenever a turn starts or ends. The last answer
+/** The engine's own count, asked for while the panel is open in Advanced mode and again whenever a turn starts or ends. The last answer
* shows until the new one lands; none is asked for or shown between a summary or fresh start and the end of the next turn. */
function useContextBreakdown(bot: Bot | undefined, open: boolean): ContextBreakdown | null {
const id = bot?.id;
@@ -122,7 +124,7 @@ function useContextBreakdown(bot: Bot | undefined, open: boolean): ContextBreakd
return last?.moment === moment ? last.breakdown : null;
}
-function ChatContext({ bot, reading, breakdown, onDone }: { bot: Bot; reading: ContextReading | null; breakdown: ContextBreakdown | null; onDone: () => void }) {
+function ChatContext({ bot, reading, breakdown, detailed, onDone }: { bot: Bot; reading: ContextReading | null; breakdown: ContextBreakdown | null; detailed: boolean; onDone: () => void }) {
const compact = useContextAction();
const fresh = useContextAction();
const messages = visibleMessages(bot);
@@ -132,7 +134,7 @@ function ChatContext({ bot, reading, breakdown, onDone }: { bot: Bot; reading: C
return (
<>
<div className={MENU_LABEL}>{t("contextMenu.title")}</div>
- {reading ? <Meter reading={reading} /> : <p className={MENU_NOTE}>{t("contextMenu.empty")}</p>}
+ {reading && (detailed || reading.percent !== undefined) ? <Meter reading={reading} detailed={detailed} /> : <p className={MENU_NOTE}>{t("contextMenu.empty")}</p>}
{rows && <Breakdown rows={rows} />}
{breakdown?.autoCompact === true && <p className={MENU_NOTE}>{t("contextMenu.providerCompacts")}</p>}
<div className={MENU_SEPARATOR} />
@@ -152,7 +154,7 @@ function ChatContext({ bot, reading, breakdown, onDone }: { bot: Bot; reading: C
);
}
-function RoomContext({ group, members }: { group: Group; members: readonly Bot[] }) {
+function RoomContext({ group, members, detailed }: { group: Group; members: readonly Bot[]; detailed: boolean }) {
const { pending, run } = useContextAction();
const [target, setTarget] = useState<string | null>(null);
const readings = roomContextReadings(group, members);
@@ -162,7 +164,7 @@ function RoomContext({ group, members }: { group: Group; members: readonly Bot[]
{!readings.length && <p className={MENU_NOTE}>{t("contextMenu.roomEmpty")}</p>}
{readings.map(({ bot, reading, requested }) => (
<div key={bot.id} data-context-member={bot.id} className="flex flex-col">
- <Meter reading={reading} name={bot.name} />
+ <Meter reading={reading} name={bot.name} detailed={detailed} />
{requested
? <p className={MENU_NOTE}>{t("contextWarning.roomRequested")}</p>
: <button type="button" data-context-compact className={MENU_ROW} disabled={pending} title={t("contextWarning.roomHint")}
@@ -182,7 +184,8 @@ export function ComposerContextMenu({ bot, group, members, className }: { bot?:
const trigger = useRef<HTMLButtonElement>(null);
const close = () => { setOpen(false); trigger.current?.focus(); };
usePopoverDismiss(open, root, close);
- const breakdown = useContextBreakdown(group ? undefined : bot, open);
+ const advanced = useAdvancedMode();
+ const breakdown = useContextBreakdown(group || !advanced ? undefined : bot, open);
if (!bot && !group) return null;
const context = bot && currentContext(bot, visibleMessages(bot));
const fullest = group
@@ -199,7 +202,7 @@ export function ComposerContextMenu({ bot, group, members, className }: { bot?:
{open && (
<div role="dialog" aria-label={t("contextMenu.title")} data-context-panel
className={cn("animate-pop-in absolute bottom-full end-0 z-50 mb-2 max-h-[min(28rem,calc(100dvh-8rem))] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto overscroll-contain", MENU_SHEET)}>
- {group ? <RoomContext group={group} members={members ?? []} /> : bot && <ChatContext bot={bot} reading={fullest ?? null} breakdown={breakdown} onDone={close} />}
+ {group ? <RoomContext group={group} members={members ?? []} detailed={advanced} /> : bot && <ChatContext bot={bot} reading={fullest ?? null} breakdown={breakdown} detailed={advanced} onDone={close} />}
</div>
)}
</span>