Skip to content

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

Composer context panel: ask the engine for its own count, and list it in Simple mode too

luishron123a87ae05d5c9d
diff --git a/src/components/ComposerContextMenu.test.ts b/src/components/ComposerContextMenu.test.ts
index 1cbbb11aa9..2d5392a8d2 100644
--- a/src/components/ComposerContextMenu.test.ts
+++ b/src/components/ComposerContextMenu.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { contextReading, contextRows, roomContextReadings } from "@/lib/context-usage";
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";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -22,6 +23,7 @@ const chat = (context: NonNullable<TaskUsage["context"]>, more: Partial<Bot> = {
let host: HTMLDivElement;
let root: Root;
let fetched: ReturnType<typeof vi.fn>;
+let breakdown: ContextBreakdown | null;
const render = (props: Parameters<typeof ComposerContextMenu>[0]) => act(async () => {
root.render(createElement(BotEditorStore, { value: store, children: createElement(ComposerContextMenu, props) }));
@@ -30,10 +32,24 @@ const trigger = () => host.querySelector<HTMLButtonElement>("[data-composer-cont
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 posted = () => fetched.mock.calls.map(([url, init]) => [String(url).replace(/^.*(?=\/api\/)/, ""), JSON.parse(String((init as RequestInit).body))]);
+const requests = () => fetched.mock.calls.map(([url, init]) => [String(url).replace(/^.*(?=\/api\/)/, ""), JSON.parse(String((init as RequestInit).body))]);
+const posted = () => requests().filter(([path]) => !path.endsWith("/context"));
+const counted: ContextBreakdown = {
+ tokens: 136_000, window: 200_000,
+ categories: [
+ { id: "system_prompt", kind: "used", tokens: 8_000 }, { id: "system_tools", kind: "used", tokens: 10_000 },
+ { id: "mcp_tools", kind: "used", tokens: 6_000 }, { id: "memory_files", kind: "used", tokens: 2_000 },
+ { id: "skills", kind: "used", tokens: 3_000 }, { id: "custom_agents", kind: "used", tokens: 1_000 },
+ { id: "something_new", kind: "used", tokens: 6_000 }, { id: "messages", kind: "used", tokens: 100_000 },
+ { id: "autocompact_buffer", kind: "buffer", tokens: 24_000 }, { id: "free_space", kind: "free", tokens: 40_000 },
+ ],
+ messages: { toolCalls: 12_000, toolResults: 24_000, attachments: 4_000, assistant: 40_000, user: 20_000 },
+ autoCompact: true, autoCompactAt: 176_000,
+};
beforeEach(() => {
- fetched = vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } }));
+ 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");
host = document.createElement("div");
@@ -86,21 +102,43 @@ describe("the composer's context button", () => {
expect(panel()!.querySelector<HTMLButtonElement>("[data-context-fresh]")!.disabled).toBe(false);
});
- it("lists what fills the context only when the reading carries it, and only in Advanced", async () => {
- const breakdown = { providerCompacts: true, categories: [
- { id: "systemPrompt", tokens: 8_000 }, { id: "messages", tokens: 100_000 }, { id: "toolCalls", tokens: 20_000 }, { id: "somethingNew", tokens: 8_000 },
- ] };
- await render({ bot: chat({ tokens: 136_000, window: 200_000, breakdown }) });
+ it("asks the engine what fills the context when the panel opens, and lists it in Simple mode too", async () => {
+ breakdown = counted;
+ await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });
+ expect(requests()).toEqual([]);
await press(trigger());
- expect(panel()!.querySelector("[data-context-breakdown]")).toBeNull();
+ expect(requests()).toEqual([["/api/bots/b1/context", { threadId: "t1" }]]);
+ 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%"],
+ ["Tool calls and results", "36k · 18%"], ["Messages", "64k · 32%"], ["Other", "6k · 3%"],
+ ["Reserved for compacting", "24k · 12%"], ["Free space", "40k · 20%"],
+ ]);
expect(words()).toContain("The provider compacts this conversation automatically.");
- localStorage.setItem("omb-advanced-mode", "1");
- await act(async () => { window.dispatchEvent(new StorageEvent("storage", { key: "omb-advanced-mode", newValue: "1" })); });
- expect([...panel()!.querySelectorAll("[data-context-breakdown] dt")].map((term) => term.textContent))
- .toEqual(["System prompt", "Tool calls and results", "Messages", "Other", "Free space"]);
- expect(panel()!.querySelector("[data-context-breakdown]")!.textContent).toContain("64k · 32%");
- await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });
+ });
+
+ it("keeps the total alone when the engine has no count, and the last count on screen while a new one loads", async () => {
+ await render({ bot: chat({ tokens: 136_000, window: 200_000 }, { id: "b2" }) });
+ await press(trigger());
+ expect(words()).toContain("68% used");
expect(panel()!.querySelector("[data-context-breakdown]")).toBeNull();
+ expect(words()).not.toContain("The provider compacts");
+ await press(trigger());
+
+ breakdown = counted;
+ await press(trigger());
+ expect(panel()!.querySelector("[data-context-breakdown]")).not.toBeNull();
+ await press(trigger());
+ fetched.mockImplementation(() => new Promise<Response>(() => {}));
+ await press(trigger());
+ expect(panel()!.querySelectorAll("[data-context-breakdown] > div")).toHaveLength(9);
+
+ await press(trigger());
+ fetched.mockImplementation(async () => { throw new Error("offline"); });
+ await press(trigger());
+ expect(panel()!.querySelector("[data-context-breakdown]")).toBeNull();
+ expect(words()).toContain("68% used");
+ expect(store.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: "error" }));
});
it("shows each measured bot of a room with its own compact, and no start fresh", async () => {
@@ -130,11 +168,12 @@ describe("context readings", () => {
expect(roomContextReadings({ memberContext: { a: { tokens: 0, window: 200_000 } } }, [{ id: "a" } as Bot])).toEqual([]);
});
- it("folds unknown kinds into Other and closes with the free space", () => {
- expect(contextRows({ tokens: 100 })).toBeNull();
- expect(contextRows({ tokens: 100, window: 1_000, breakdown: { categories: [] } })).toBeNull();
- expect(contextRows({ tokens: 100, window: 1_000, breakdown: { categories: [{ id: "x", tokens: 30 }, { id: "other", tokens: 20 }, { id: "tools", tokens: 50 }] } }))
- .toEqual([{ id: "tools", tokens: 50, percent: 5 }, { id: "other", tokens: 50, percent: 5 }, { id: "free", tokens: 900, percent: 90 }]);
- expect(contextRows({ tokens: 100, breakdown: { categories: [{ id: "messages", tokens: 100 }] } })).toEqual([{ id: "messages", tokens: 100, percent: undefined }]);
+ it("needs a window and something counted as used; the rest of the messages is what tools did not take", () => {
+ expect(contextRows(null)).toBeNull();
+ expect(contextRows({ tokens: 0, window: 1_000, categories: [{ id: "free_space", kind: "free", tokens: 1_000 }] })).toBeNull();
+ expect(contextRows({ tokens: 100, window: 1_000, categories: [{ id: "messages", kind: "used", tokens: 100 }], messages: { toolCalls: 60, toolResults: 40, attachments: 0, assistant: 0, user: 0 } }))
+ .toEqual([{ id: "toolCalls", tokens: 100, percent: 10 }]);
+ expect(contextRows({ tokens: 100, window: 1_000, categories: [{ id: "messages", kind: "used", tokens: 100 }, { id: "compact_buffer", kind: "buffer", tokens: 50 }] }))
+ .toEqual([{ id: "messages", tokens: 100, percent: 10 }, { id: "reserved", tokens: 50, percent: 5 }]);
});
});
diff --git a/src/components/ComposerContextMenu.tsx b/src/components/ComposerContextMenu.tsx
index dc68ac87dd..e53f4a8d26 100644
--- a/src/components/ComposerContextMenu.tsx
+++ b/src/components/ComposerContextMenu.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { Gauge, RotateCcw, Shrink } from "lucide-react";
import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";
@@ -6,9 +6,10 @@ 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";
+import type { ContextBreakdown } from "../../shared/context-breakdown";
import { useContextAction } from "./ContextWarning";
import { MENU_ICON, MENU_LABEL, MENU_NOTE, MENU_ROW, MENU_SEPARATOR, MENU_SHEET } from "./menu-recipe";
@@ -60,7 +61,7 @@ function Breakdown({ rows }: { rows: ContextRow[] }) {
<div key={row.id} className="flex items-baseline gap-3">
<dt className={cn("min-w-0 truncate", row.id === "free" ? "text-ink-tertiary" : "text-ink-secondary")}>{contextRowLabel(row.id)}</dt>
<dd className="ms-auto shrink-0 tabular-nums text-ink-tertiary">
- {row.percent === undefined ? formatTokens(row.tokens) : t("contextMenu.rowShare", { tokens: formatTokens(row.tokens), percent: row.percent })}
+ {t("contextMenu.rowShare", { tokens: formatTokens(row.tokens), percent: row.percent })}
</dd>
</div>
))}
@@ -73,14 +74,39 @@ function currentContext(bot: Bot, messages: readonly Message[]) {
return compactedSinceReading(messages) ? undefined : bot.tasks?.find((task) => task.threadId === bot.threadId)?.usage?.context;
}
+const lastBreakdown = new Map<string, ContextBreakdown>();
+
+/** The engine's own count, asked for when the panel opens and again whenever a turn starts or ends or the conversation
+ * is summarized. The last answer shows until the new one lands, so the panel is not redrawn; no answer leaves the total alone. */
+function useContextBreakdown(bot: Bot, summarized: boolean): ContextBreakdown | null {
+ const { id, threadId } = bot;
+ const busy = Boolean(bot.busy);
+ const slot = `${id}:${threadId ?? ""}`;
+ const moment = `${slot}:${summarized}`;
+ const [answer, setAnswer] = useState<{ moment: string; breakdown: ContextBreakdown | null } | null>(null);
+ useEffect(() => {
+ if (!threadId) return;
+ let current = true;
+ void api<{ breakdown: ContextBreakdown | null }>(`/api/bots/${id}/context`, { method: "POST", body: JSON.stringify({ threadId }) })
+ .then((reply) => reply?.breakdown ?? null, () => null)
+ .then((breakdown) => {
+ if (breakdown) lastBreakdown.set(slot, breakdown); else lastBreakdown.delete(slot);
+ if (current) setAnswer({ moment, breakdown });
+ });
+ return () => { current = false; };
+ }, [id, threadId, slot, moment, busy]);
+ if (answer?.moment === moment) return answer.breakdown;
+ return summarized ? null : lastBreakdown.get(slot) ?? null;
+}
+
function ChatContext({ bot, onDone }: { bot: Bot; onDone: () => void }) {
- const advanced = useAdvancedMode();
const compact = useContextAction();
const fresh = useContextAction();
const messages = visibleMessages(bot);
const context = currentContext(bot, messages);
- const reading = contextReading(context?.tokens, context?.window);
- const rows = advanced ? contextRows(context) : null;
+ const breakdown = useContextBreakdown(bot, compactedSinceReading(messages));
+ const reading = contextReading(context?.tokens, context?.window) ?? contextReading(breakdown?.tokens, breakdown?.window);
+ const rows = contextRows(breakdown);
const atFreshStart = messages.at(-1)?.compaction?.fresh === true;
const idle = !bot.busy && !compact.pending && !fresh.pending && messages.length > 0 && !atFreshStart;
return (
@@ -88,7 +114,7 @@ function ChatContext({ bot, onDone }: { bot: Bot; onDone: () => void }) {
<div className={MENU_LABEL}>{t("contextMenu.title")}</div>
{reading ? <Meter reading={reading} /> : <p className={MENU_NOTE}>{t("contextMenu.empty")}</p>}
{rows && <Breakdown rows={rows} />}
- {context?.breakdown?.providerCompacts && <p className={MENU_NOTE}>{t("contextMenu.providerCompacts")}</p>}
+ {breakdown?.autoCompact === true && <p className={MENU_NOTE}>{t("contextMenu.providerCompacts")}</p>}
<div className={MENU_SEPARATOR} />
<button type="button" data-context-compact className={MENU_ROW} disabled={!idle || compactedSinceReading(messages)}
title={t(bot.busy ? "contextWarning.busy" : "contextMenu.compactHint")}
@@ -153,7 +179,7 @@ export function ComposerContextMenu({ bot, group, members, className }: { bot?:
</button>
{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(24rem,calc(100dvh-8rem))] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto overscroll-contain", MENU_SHEET)}>
+ 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} onDone={close} />}
</div>
)}
diff --git a/src/lib/context-usage.ts b/src/lib/context-usage.ts
index 4a902018e9..d33193e992 100644
--- a/src/lib/context-usage.ts
+++ b/src/lib/context-usage.ts
@@ -1,17 +1,8 @@
-import type { Bot, Group, TaskUsage } from "@/state/store";
+import type { ContextBreakdown } from "../../shared/context-breakdown";
+import type { Bot, Group } from "@/state/store";
import { t } from "./i18n";
import type { ContextTone } from "./usage";
-export const CONTEXT_CATEGORIES = ["systemPrompt", "memoryFiles", "tools", "skills", "toolCalls", "messages", "other"] as const;
-export type ContextCategory = (typeof CONTEXT_CATEGORIES)[number];
-
-/** What fills the context, by kind, when the engine can tell. `providerCompacts`: the provider folds the conversation
- * on its own as it nears the window. */
-export interface ContextBreakdown {
- categories: ReadonlyArray<{ id: string; tokens: number }>;
- providerCompacts?: boolean;
-}
-
export interface ContextReading {
tokens: number;
window?: number;
@@ -37,27 +28,32 @@ export function roomContextReadings(group: Pick<Group, "memberContext">, members
});
}
-export type ContextRow = { id: ContextCategory | "free"; tokens: number; percent?: number };
+const ROWS = ["systemPrompt", "memoryFiles", "tools", "skills", "toolCalls", "messages", "other", "reserved", "free"] as const;
+export type ContextRow = { id: (typeof ROWS)[number]; tokens: number; percent: number };
+
+const ROW_OF: Record<string, ContextRow["id"]> = {
+ system_prompt: "systemPrompt", memory_files: "memoryFiles",
+ system_tools: "tools", mcp_tools: "tools", mcp_instructions: "tools",
+ skills: "skills", custom_agents: "skills", messages: "messages",
+};
-/** A kind this app has no name for counts as Other; free space closes the list when the window is known. */
-export function contextRows(context: TaskUsage["context"]): ContextRow[] | null {
- const listed = context?.breakdown?.categories;
- if (!context || !Array.isArray(listed)) return null;
- const totals = new Map<ContextCategory, number>();
- for (const entry of listed) {
- if (!positive(entry?.tokens)) continue;
- const id = (CONTEXT_CATEGORIES as readonly string[]).includes(entry.id) ? entry.id as ContextCategory : "other";
- totals.set(id, (totals.get(id) ?? 0) + entry.tokens);
+/** The engine's categories as the rows people read: tool calls and their results come out of the messages, a kind
+ * this app has no name for counts as Other, and what the engine holds back for compacting is not free space. */
+export function contextRows(breakdown: ContextBreakdown | null | undefined): ContextRow[] | null {
+ if (!breakdown || !positive(breakdown.window) || !Array.isArray(breakdown.categories)) return null;
+ const totals = new Map<ContextRow["id"], number>();
+ const add = (id: ContextRow["id"], tokens: number) => { if (positive(tokens)) totals.set(id, (totals.get(id) ?? 0) + tokens); };
+ for (const entry of breakdown.categories) {
+ add(entry.kind === "free" ? "free" : entry.kind === "buffer" ? "reserved" : ROW_OF[entry.id] ?? "other", entry.tokens);
}
- if (!totals.size) return null;
- const window = positive(context.window) ? context.window : undefined;
- const share = (tokens: number) => window ? Math.round((tokens / window) * 1000) / 10 : undefined;
- const rows: ContextRow[] = CONTEXT_CATEGORIES.filter((id) => totals.has(id)).map((id) => ({ id, tokens: totals.get(id)!, percent: share(totals.get(id)!) }));
- if (window) {
- const free = Math.max(0, window - Math.max(context.tokens, rows.reduce((sum, row) => sum + row.tokens, 0)));
- rows.push({ id: "free", tokens: free, percent: share(free) });
+ const tools = Math.min(totals.get("messages") ?? 0, (breakdown.messages?.toolCalls ?? 0) + (breakdown.messages?.toolResults ?? 0));
+ if (tools > 0) {
+ add("toolCalls", tools);
+ if (totals.get("messages") === tools) totals.delete("messages");
+ else totals.set("messages", totals.get("messages")! - tools);
}
- return rows;
+ if (![...totals.keys()].some((id) => id !== "free" && id !== "reserved")) return null;
+ return ROWS.filter((id) => totals.has(id)).map((id) => ({ id, tokens: totals.get(id)!, percent: Math.round((totals.get(id)! / breakdown.window) * 1000) / 10 }));
}
export function contextRowLabel(id: ContextRow["id"]): string {
@@ -69,6 +65,7 @@ export function contextRowLabel(id: ContextRow["id"]): string {
case "toolCalls": return t("contextMenu.category.toolCalls");
case "messages": return t("contextMenu.category.messages");
case "other": return t("contextMenu.category.other");
+ case "reserved": return t("contextMenu.category.reserved");
case "free": return t("contextMenu.category.free");
}
}
diff --git a/src/locales/en.json b/src/locales/en.json
index eed24dc519..e9c818839a 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2756,6 +2756,7 @@
"contextMenu.category.toolCalls": "Tool calls and results",
"contextMenu.category.messages": "Messages",
"contextMenu.category.other": "Other",
+ "contextMenu.category.reserved": "Reserved for compacting",
"contextMenu.category.free": "Free space",
"chat.emptyPrompt": "Send a message to start the conversation.",
"chat.chiefOfStaff": "Chief of Staff",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 993fb04f72..85b68873ef 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -268,7 +268,7 @@ export interface TaskUsage {
costUsd: number | null;
turns: number;
lastTurn?: { input: number; output: number; cachedInput?: number; costUsd: number | null };
- context?: { tokens: number; window?: number; breakdown?: import("../lib/context-usage").ContextBreakdown };
+ context?: { tokens: number; window?: number };
}
export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "access" | "yourAccess" | "onlyPeopleAdded"> {