Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Composer: a context button beside the microphone, with compact and start fresh
luishron12307f46461e6ad
diff --git a/src/components/ChatMoreMenu.tsx b/src/components/ChatMoreMenu.tsxindex 72b4a373b0..b180e214e9 100644--- a/src/components/ChatMoreMenu.tsx+++ b/src/components/ChatMoreMenu.tsx@@ -147,7 +147,7 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Silabel: t("chat.usage.menu"),icon: <Gauge size={16} />,separatorBefore: true,- trailing: <span title={usage.detail} data-testid="usage-chip" className={cn("tabular-nums text-[12px]", usage.tone === "danger" ? "text-danger" : usage.tone === "warning" ? "text-warning" : "text-ink-secondary")}>{usage.short}</span>,+ trailing: <span title={usage.detail} data-testid="usage-chip" className="tabular-nums text-[12px] text-ink-secondary">{usage.short}</span>,onSelect: () => advanced ? openBotSettings(dispatch, "usage") : dispatch({ type: "toggleAppSettings", open: true, section: "usage" }),} satisfies SidebarMenuItem] : []),...(remoteClient ? [] : [{diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex cd4c2be2c2..a27ba37d69 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -67,7 +67,7 @@ import {type PasteAttachment,} from "@/lib/composer-attachments";import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRouteForComposer } from "@/lib/group-routing";-import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton";+import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton"; import { ComposerContextMenu } from "./ComposerContextMenu";import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "./PendingApproval";import { CallButton } from "./CallView";import { GroupCallButton } from "./GroupCallView";@@ -957,6 +957,7 @@ export function Composer({<Square size={simpleDock ? 10 : 14} className="fill-current" /></button>)}+ {!locked && <ComposerContextMenu bot={bot} group={group} members={members} className={cn(simpleDock ? "size-7" : "size-8", advanced || singleRow ? "text-ink-secondary hover:bg-raised hover:text-ink" : SIMPLE_CONTROL)} />}{!locked && !busy && micReady && (<buttononClick={toggleMic}diff --git a/src/components/ComposerContextMenu.test.ts b/src/components/ComposerContextMenu.test.tsnew file mode 100644index 0000000000..1cbbb11aa9--- /dev/null+++ b/src/components/ComposerContextMenu.test.ts@@ -0,0 +1,140 @@+// @vitest-environment happy-dom+// The composer's context button: how full the conversation is, with compacting and starting fresh one click away.+import { act, createElement } from "react";+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 { BotEditorStore, type Bot, type Group, type Message, type TaskUsage, type useStore } from "@/state/store";+import { ComposerContextMenu } from "./ComposerContextMenu";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const store = { state: {}, dispatch: vi.fn(), flushBotPatches: vi.fn(async () => null) } as unknown as ReturnType<typeof useStore>;+const line = (id: string, role: Message["role"], kind: Message["kind"] = "text", more: Partial<Message> = {}): Message => ({ id, role, kind, at: 1, text: id, ...more });+const chat = (context: NonNullable<TaskUsage["context"]>, more: Partial<Bot> = {}): Bot => ({+ id: "b1", name: "Pepper", threadId: "t1", busy: false,+ messages: [line("m1", "user"), line("m2", "bot")],+ tasks: [{ threadId: "t1", usage: { input: 0, output: 0, costUsd: null, turns: 1, context } }],+ ...more,+}) as unknown as Bot;++let host: HTMLDivElement;+let root: Root;+let fetched: ReturnType<typeof vi.fn>;++const render = (props: Parameters<typeof ComposerContextMenu>[0]) => act(async () => {+ root.render(createElement(BotEditorStore, { value: store, children: createElement(ComposerContextMenu, props) }));+});+const trigger = () => host.querySelector<HTMLButtonElement>("[data-composer-context] > button")!;+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))]);++beforeEach(() => {+ fetched = vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } }));+ vi.stubGlobal("fetch", fetched);+ localStorage.setItem("omb-advanced-mode", "0");+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});++afterEach(() => {+ act(() => root.unmount());+ host.remove();+ localStorage.clear();+ vi.unstubAllGlobals();+});++describe("the composer's context button", () => {+ it("names how full the chat is and opens a panel with the reading and both actions", async () => {+ 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([...panel()!.querySelectorAll("button")].map((button) => [button.textContent, button.disabled]))+ .toEqual([["Compact context", false], ["Start fresh", false]]);+ await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });+ expect(panel()).toBeNull();+ });++ it("compacts through the chat's own route and stays open; starting fresh closes it", async () => {+ await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });+ await press(trigger());+ await press(panel()!.querySelector<HTMLButtonElement>("[data-context-compact]")!);+ expect(posted()).toEqual([["/api/bots/b1/compact", { threadId: "t1" }]]);+ expect(panel()).not.toBeNull();+ await press(panel()!.querySelector<HTMLButtonElement>("[data-context-fresh]")!);+ expect(posted().at(-1)).toEqual(["/api/bots/b1/start-fresh", { threadId: "t1" }]);+ expect(panel()).toBeNull();+ });++ it("offers neither action while the bot works, and no stale reading once the chat was summarized", async () => {+ await render({ bot: chat({ tokens: 136_000, window: 200_000 }, { busy: true }) });+ await press(trigger());+ expect([...panel()!.querySelectorAll("button")].map((button) => button.disabled)).toEqual([true, true]);+ await render({ bot: chat({ tokens: 136_000, window: 200_000 }, { messages: [line("m1", "user"), line("m2", "bot"), line("m3", "bot", "compaction")] }) });+ expect(trigger().getAttribute("aria-label")).toBe("Context");+ expect(words()).toContain("No reading yet");+ expect(panel()!.querySelector<HTMLButtonElement>("[data-context-compact]")!.disabled).toBe(true);+ 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 }) });+ await press(trigger());+ expect(panel()!.querySelector("[data-context-breakdown]")).toBeNull();+ 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 }) });+ expect(panel()!.querySelector("[data-context-breakdown]")).toBeNull();+ });++ it("shows each measured bot of a room with its own compact, and no start fresh", async () => {+ const members = [{ id: "s", name: "Scout" }, { id: "p", name: "Pixel" }, { id: "q", name: "Quill" }] as Bot[];+ const group = { id: "g1", memberContext: { s: { tokens: 170_000, window: 200_000 }, q: { tokens: 60_000, window: 200_000, compactRequested: true } } } as unknown as Group;+ await render({ group, members });+ expect(trigger().getAttribute("aria-label")).toBe("Context 85%");+ await press(trigger());+ expect([...panel()!.querySelectorAll("[data-context-member]")].map((row) => row.getAttribute("data-context-member"))).toEqual(["s", "q"]);+ expect(words()).toContain("Scout85% used");+ expect(words()).toContain("Compacts before its next turn.");+ expect(panel()!.querySelector("[data-context-fresh]")).toBeNull();+ await press(panel()!.querySelector<HTMLButtonElement>("[data-context-compact]")!);+ expect(posted()).toEqual([["/api/groups/g1/members/s/compact", {}]]);+ await render({ group: { id: "g1", memberContext: null } as unknown as Group, members });+ expect(words()).toContain("No reading yet");+ });+});++describe("context readings", () => {+ it("turns tokens and a window into a share with a tone", () => {+ expect(contextReading(0, 200_000)).toBeNull();+ expect(contextReading(90_000, 200_000)).toEqual({ tokens: 90_000, window: 200_000, percent: 45, tone: "quiet" });+ expect(contextReading(136_000, 200_000)?.tone).toBe("warning");+ expect(contextReading(170_000, 200_000)?.tone).toBe("danger");+ expect(contextReading(170_000, undefined)).toEqual({ tokens: 170_000, window: undefined, percent: undefined, tone: "quiet" });+ 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 }]);+ });+});diff --git a/src/components/ComposerContextMenu.tsx b/src/components/ComposerContextMenu.tsxnew file mode 100644index 0000000000..dc68ac87dd--- /dev/null+++ b/src/components/ComposerContextMenu.tsx@@ -0,0 +1,162 @@+import { useRef, useState } from "react";+import { Gauge, RotateCcw, Shrink } from "lucide-react";++import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";+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 { visibleMessages, type Bot, type Group, type Message } from "@/state/store";+import { useContextAction } from "./ContextWarning";+import { MENU_ICON, MENU_LABEL, MENU_NOTE, MENU_ROW, MENU_SEPARATOR, MENU_SHEET } from "./menu-recipe";++const TONE_INK: Record<ContextTone, string> = { quiet: "", warning: "text-warning", danger: "text-danger" };+const TONE_FILL: Record<ContextTone, string> = { quiet: "bg-ink-tertiary", warning: "bg-warning", danger: "bg-danger" };+const RING = 16;+const RING_RADIUS = 6;+const RING_LENGTH = 2 * Math.PI * RING_RADIUS;++function ContextRing({ percent }: { percent: number }) {+ const filled = RING_LENGTH * Math.min(100, Math.max(4, percent)) / 100;+ return (+ <svg aria-hidden="true" width={RING} height={RING} viewBox={`0 0 ${RING} ${RING}`} fill="none" stroke="currentColor" strokeWidth={1.75} className="-rotate-90">+ <circle cx={RING / 2} cy={RING / 2} r={RING_RADIUS} opacity={0.3} />+ <circle cx={RING / 2} cy={RING / 2} r={RING_RADIUS} strokeLinecap="round" strokeDasharray={`${filled} ${RING_LENGTH}`} />+ </svg>+ );+}++function tokensLine(reading: ContextReading): string {+ return reading.window+ ? t("contextMenu.tokensOfWindow", { tokens: formatTokens(reading.tokens), window: formatTokens(reading.window) })+ : 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 });+ 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)}+ </span>+ </div>+ {reading.percent !== undefined && (+ <div aria-hidden="true" className="h-1 overflow-hidden rounded-full bg-ink/[0.08]">+ <div className={cn("h-full rounded-full", TONE_FILL[reading.tone])} style={{ width: `${Math.min(100, reading.percent)}%` }} />+ </div>+ )}+ </div>+ );+}++function Breakdown({ rows }: { rows: ContextRow[] }) {+ return (+ <dl data-context-breakdown className="flex flex-col gap-1 px-2 py-1 text-[12px] leading-4">+ {rows.map((row) => (+ <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 })}+ </dd>+ </div>+ ))}+ </dl>+ );+}++/** A reading taken before the conversation was summarized says nothing about its size now. */+function currentContext(bot: Bot, messages: readonly Message[]) {+ return compactedSinceReading(messages) ? undefined : bot.tasks?.find((task) => task.threadId === bot.threadId)?.usage?.context;+}++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 atFreshStart = messages.at(-1)?.compaction?.fresh === true;+ const idle = !bot.busy && !compact.pending && !fresh.pending && messages.length > 0 && !atFreshStart;+ return (+ <>+ <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>}+ <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")}+ onClick={() => compact.run(`/api/bots/${bot.id}/compact`, { threadId: bot.threadId })}>+ <Shrink size={16} className={MENU_ICON} />+ <span className="min-w-0 truncate">{compact.pending ? t("contextWarning.compacting") : t("contextMenu.compact")}</span>+ </button>+ <button type="button" data-context-fresh className={MENU_ROW} disabled={!idle}+ title={t(bot.busy ? "contextWarning.busy" : "chat.startFresh.hint")}+ onClick={() => { fresh.run(`/api/bots/${bot.id}/start-fresh`, { threadId: bot.threadId }); onDone(); }}>+ <RotateCcw size={16} className={MENU_ICON} />+ <span className="min-w-0 truncate">{t("chat.startFresh")}</span>+ </button>+ </>+ );+}++function RoomContext({ group, members }: { group: Group; members: readonly Bot[] }) {+ const { pending, run } = useContextAction();+ const [target, setTarget] = useState<string | null>(null);+ const readings = roomContextReadings(group, members);+ return (+ <>+ <div className={MENU_LABEL}>{t("contextMenu.roomTitle")}</div>+ {!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} />+ {requested+ ? <p className={MENU_NOTE}>{t("contextWarning.roomRequested")}</p>+ : <button type="button" data-context-compact className={MENU_ROW} disabled={pending} title={t("contextWarning.roomHint")}+ onClick={() => { setTarget(bot.id); run(`/api/groups/${group.id}/members/${bot.id}/compact`, {}); }}>+ <Shrink size={16} className={MENU_ICON} />+ <span className="min-w-0 truncate">{pending && target === bot.id ? t("contextWarning.compacting") : t("contextMenu.compact")}</span>+ </button>}+ </div>+ ))}+ </>+ );+}++/** How full the conversation's context is, beside the microphone, with the two ways to make it small again. In a room+ * every bot keeps its own context, so each one that has been measured there gets its own line. */+export function ComposerContextMenu({ bot, group, members, className }: { bot?: Bot; group?: Group; members?: readonly Bot[]; className?: string }) {+ const [open, setOpen] = useState(false);+ const root = useRef<HTMLSpanElement>(null);+ const trigger = useRef<HTMLButtonElement>(null);+ const close = () => { setOpen(false); trigger.current?.focus(); };+ usePopoverDismiss(open, root, close);+ if (!bot && !group) return null;+ const context = bot && currentContext(bot, visibleMessages(bot));+ const fullest = group+ ? roomContextReadings(group, members ?? []).map((entry) => entry.reading).sort((a, b) => (b.percent ?? 0) - (a.percent ?? 0))[0]+ : contextReading(context?.tokens, context?.window);+ const name = fullest?.percent === undefined ? t("contextMenu.title") : t("contextWarning.short", { percent: fullest.percent });+ return (+ <span ref={root} data-composer-context className="relative flex shrink-0">+ <button ref={trigger} type="button" aria-label={name} title={name} aria-haspopup="dialog" aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ className={cn("flex shrink-0 items-center justify-center rounded-full", className, fullest && TONE_INK[fullest.tone], open && "bg-ink/[0.09] text-ink")}>+ {fullest?.percent === undefined ? <Gauge size={16} /> : <ContextRing percent={fullest.percent} />}+ </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)}>+ {group ? <RoomContext group={group} members={members ?? []} /> : bot && <ChatContext bot={bot} onDone={close} />}+ </div>+ )}+ </span>+ );+}diff --git a/src/lib/chat-usage-summary.ts b/src/lib/chat-usage-summary.tsindex 24353545f5..25568d8788 100644--- a/src/lib/chat-usage-summary.ts+++ b/src/lib/chat-usage-summary.ts@@ -1,9 +1,9 @@import type { AppState, Bot } from "@/state/store";import { keepWarmLine } from "./cache-keepwarm";import { t } from "./i18n";-import { contextChip, contextDetail, contextShare, costCaption, formatUsd, hasFiniteCost, lastTurnDetail, usageChip, usageDetail } from "./usage";+import { contextDetail, contextShare, costCaption, formatUsd, hasFiniteCost, lastTurnDetail, usageChip, usageDetail } from "./usage";-export function usageSummary(bot: Bot, instances: AppState["instances"]): { short: string; detail: string; tone?: "danger" | "warning" } | null {+export function usageSummary(bot: Bot, instances: AppState["instances"]): { short: string; detail: string } | null {const task = bot.tasks?.find((t) => t.threadId === bot.threadId);const usage = task?.usage;if (!usage || !usageChip(usage)) return null;@@ -20,7 +20,5 @@ export function usageSummary(bot: Bot, instances: AppState["instances"]): { shor].filter(Boolean).join("\n");- const short = usageChip(usage);- const ctx = contextChip(usage);- return { short: ctx ? `${short} · ${ctx}` : short, detail, tone: share?.tone === "danger" ? "danger" : share?.tone === "warning" ? "warning" : undefined };+ return { short: usageChip(usage), detail };}diff --git a/src/lib/context-usage.ts b/src/lib/context-usage.tsnew file mode 100644index 0000000000..4a902018e9--- /dev/null+++ b/src/lib/context-usage.ts@@ -0,0 +1,74 @@+import type { Bot, Group, TaskUsage } 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;+ percent?: number;+ tone: ContextTone;+}++const positive = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value > 0;++export function contextReading(tokens: unknown, window: unknown): ContextReading | null {+ if (!positive(tokens)) return null;+ const size = positive(window) ? window : undefined;+ const percent = size ? Math.min(999, Math.round((tokens / size) * 100)) : undefined;+ return { tokens, window: size, percent, tone: percent === undefined || percent < 50 ? "quiet" : percent < 80 ? "warning" : "danger" };+}++export function roomContextReadings(group: Pick<Group, "memberContext">, members: readonly Bot[]):+ Array<{ bot: Bot; reading: ContextReading; requested: boolean }> {+ return members.flatMap((bot) => {+ const measured = group.memberContext?.[bot.id];+ const reading = measured ? contextReading(measured.tokens, measured.window) : null;+ return reading ? [{ bot, reading, requested: measured?.compactRequested === true }] : [];+ });+}++export type ContextRow = { id: ContextCategory | "free"; tokens: number; percent?: number };++/** 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);+ }+ 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) });+ }+ return rows;+}++export function contextRowLabel(id: ContextRow["id"]): string {+ switch (id) {+ case "systemPrompt": return t("contextMenu.category.systemPrompt");+ case "memoryFiles": return t("contextMenu.category.memoryFiles");+ case "tools": return t("contextMenu.category.tools");+ case "skills": return t("contextMenu.category.skills");+ case "toolCalls": return t("contextMenu.category.toolCalls");+ case "messages": return t("contextMenu.category.messages");+ case "other": return t("contextMenu.category.other");+ case "free": return t("contextMenu.category.free");+ }+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex acee464452..eed24dc519 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2738,6 +2738,25 @@"contextWarning.room": "{name}'s context in this room is {percent}% full.","contextWarning.roomHint": "Its next turn here starts fresh with the room's recent messages. Nothing in the room is deleted.","contextWarning.roomRequested": "Compacts before its next turn.",+ "contextMenu.title": "Context",+ "contextMenu.roomTitle": "Context of each bot in this room",+ "contextMenu.used": "{percent}% used",+ "contextMenu.tokensOfWindow": "{tokens} of {window} tokens",+ "contextMenu.tokens": "{tokens} tokens",+ "contextMenu.rowShare": "{tokens} · {percent}%",+ "contextMenu.empty": "No reading yet. It shows after the bot's next reply.",+ "contextMenu.roomEmpty": "No reading yet. A bot's context shows after its next turn in this room.",+ "contextMenu.providerCompacts": "The provider compacts this conversation automatically.",+ "contextMenu.compact": "Compact context",+ "contextMenu.compactHint": "Summarizes older messages into a short note. The whole conversation stays here.",+ "contextMenu.category.systemPrompt": "System prompt",+ "contextMenu.category.memoryFiles": "Memory files",+ "contextMenu.category.tools": "Tools",+ "contextMenu.category.skills": "Skills and subagents",+ "contextMenu.category.toolCalls": "Tool calls and results",+ "contextMenu.category.messages": "Messages",+ "contextMenu.category.other": "Other",+ "contextMenu.category.free": "Free space","chat.emptyPrompt": "Send a message to start the conversation.","chat.chiefOfStaff": "Chief of Staff","chat.openProfile": "Open agent profile",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 85b68873ef..993fb04f72 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 };+ context?: { tokens: number; window?: number; breakdown?: import("../lib/context-usage").ContextBreakdown };}export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "access" | "yourAccess" | "onlyPeopleAdded"> {