Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Usage tab in bot settings for GET /api/kwants/:id/model-usage
Pixel (kwant bot)da26221785d7
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex d8801568..3a726626 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -1,5 +1,5 @@import React, { useEffect, useState } from 'react';-import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2 } from 'lucide-react';+import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2, Gauge } from 'lucide-react';import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';import { playSfx } from '../audio/chiptune';@@ -11,15 +11,17 @@ import { ENGINES, Profile, engineOfModel, profileStatus, profilesForEngine } froimport { MemoryPanel } from './MemoryPanel';import { RoutinesPanel } from './RoutinesPanel';import { SkillsPanel } from './SkillsPanel';+import { UsagePanel } from './UsagePanel';import type { Channel, Kwant } from './Sidebar';import { BotApprovalsSetting } from './ApprovalsSetting';-export type EditTab = 'profile' | 'memory' | 'skills' | 'routines';+export type EditTab = 'profile' | 'memory' | 'skills' | 'routines' | 'usage';const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [{ id: 'profile', label: 'Profile', Icon: UserRound },{ id: 'memory', label: 'Memory', Icon: Brain },{ id: 'skills', label: 'Skills', Icon: ListChecks },{ id: 'routines', label: 'Routines', Icon: CalendarClock },+ { id: 'usage', label: 'Usage', Icon: Gauge },];export interface AgentFormData {@@ -281,6 +283,11 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({<RoutinesPanel kwantId={kwantId} kwants={kwants} channels={channels} /></div>)}+ {isEdit && kwantId && tab === 'usage' && (+ <div role="tabpanel" id="agent-panel-usage" aria-labelledby="agent-tab-usage">+ <UsagePanel kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} />+ </div>+ )}<form onSubmit={handleSubmit} className="space-y-4" hidden={isEdit && !!kwantId && tab !== 'profile'} role={isEdit && kwantId ? 'tabpanel' : undefined} id="agent-panel-profile">{!isEdit && (diff --git a/frontend/src/components/UsagePanel.tsx b/frontend/src/components/UsagePanel.tsxnew file mode 100644index 00000000..5074462b--- /dev/null+++ b/frontend/src/components/UsagePanel.tsx@@ -0,0 +1,130 @@+import React, { useCallback, useEffect, useState } from 'react';+import { Loader2, RefreshCw } from 'lucide-react';+import { formatWhen } from '../continuity';+import { ModelUsage, UsageSums, cacheShare, compactTokens, modelUsageApi, purposeLabel } from '../modelUsage';++const quietBtn =+ 'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700';++const KINDS: Array<{ key: keyof UsageSums; label: string; hint: string }> = [+ { key: 'fresh_input_tokens', label: 'Fresh input', hint: 'Input tokens read at full price' },+ { key: 'cache_read_tokens', label: 'Cache read', hint: 'Input tokens served from the cache' },+ { key: 'cache_write_tokens', label: 'Cache write', hint: 'Input tokens written to the cache' },+ { key: 'output_tokens', label: 'Output', hint: 'Tokens the model wrote' },+];++/** Calls and tokens line, e.g. "fresh 40 · cache read 1.5k · cache write 0 · out 12". */+const tokenLine = (s: Pick<UsageSums, 'fresh_input_tokens' | 'cache_read_tokens' | 'cache_write_tokens' | 'output_tokens'>) =>+ `fresh ${compactTokens(s.fresh_input_tokens)} · cache read ${compactTokens(s.cache_read_tokens)} · cache write ${compactTokens(+ s.cache_write_tokens,+ )} · out ${compactTokens(s.output_tokens)}`;++/** What the Usage tab shows; `usage` null while loading. */+export const UsageView: React.FC<{+ kwantName: string;+ usage: ModelUsage | null;+ error: string | null;+ onReload: () => void;+}> = ({ kwantName, usage, error, onReload }) => {+ if (error)+ return (+ <div className="flex items-center justify-between gap-2 bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs" role="alert">+ <span>{error}</span>+ <button type="button" onClick={onReload} className={quietBtn}>+ <RefreshCw size={12} /> Retry+ </button>+ </div>+ );+ if (!usage)+ return (+ <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading usage…+ </p>+ );+ const t = usage.totals;+ if (t.calls === 0)+ return (+ <p className="text-xs text-zinc-500 border border-dashed border-zinc-800 rounded-lg p-4 text-center" data-usage-empty>+ No model calls recorded for {kwantName} yet. Calls are counted here for bots on an API key or a custom API; Claude, Codex and Grok+ sign-ins report their usage to their own accounts.+ </p>+ );+ const share = cacheShare(t);+ return (+ <div className="space-y-4" data-usage>+ <div className="flex items-center justify-between gap-2">+ <p className="text-xs text-zinc-400">+ {t.calls} {t.calls === 1 ? 'call' : 'calls'}+ {share !== null && `, ${share}% of input from the cache`}+ </p>+ <button type="button" onClick={onReload} className={quietBtn} aria-label="Refresh usage">+ <RefreshCw size={12} /> Refresh+ </button>+ </div>+ <dl className="grid grid-cols-2 sm:grid-cols-4 gap-2">+ {KINDS.map(({ key, label, hint }) => (+ <div key={key} className="bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2" title={hint}>+ <dt className="text-[10px] uppercase tracking-wide text-zinc-500">{label}</dt>+ <dd className="text-base font-semibold text-zinc-100 tabular-nums" data-kind={key}>+ {compactTokens(t[key])}+ </dd>+ </div>+ ))}+ </dl>++ {usage.by_purpose.length > 0 && (+ <section aria-labelledby="usage-by-purpose">+ <h3 id="usage-by-purpose" className="text-[11px] font-medium text-zinc-400 mb-1.5">+ By purpose+ </h3>+ <ul className="space-y-1">+ {usage.by_purpose.map((p) => (+ <li key={p.purpose} className="text-xs text-zinc-300 flex flex-wrap gap-x-2">+ <span className="font-medium text-zinc-200">+ {purposeLabel(p.purpose)} ({p.calls})+ </span>+ <span className="text-zinc-500 tabular-nums">{tokenLine(p)}</span>+ </li>+ ))}+ </ul>+ </section>+ )}++ {usage.recent.length > 0 && (+ <section aria-labelledby="usage-recent">+ <h3 id="usage-recent" className="text-[11px] font-medium text-zinc-400 mb-1.5">+ Recent calls+ </h3>+ <ul className="divide-y divide-zinc-800/70 border border-zinc-800 rounded-lg">+ {usage.recent.map((c) => (+ <li key={c.id} className="px-3 py-1.5 text-xs" data-call={c.purpose}>+ <div className="flex flex-wrap items-baseline gap-x-2">+ <span className="font-medium text-zinc-200">{purposeLabel(c.purpose, true)}</span>+ <span className="text-zinc-500 break-all">{c.model}</span>+ <span className="ml-auto text-[10px] text-zinc-500">{formatWhen(c.created_at)}</span>+ </div>+ <div className="text-zinc-500 tabular-nums">{c.reported ? tokenLine(c) : 'The provider sent no token counts for this call.'}</div>+ </li>+ ))}+ </ul>+ </section>+ )}+ </div>+ );+};++/** Usage tab of the bot settings: loads `/model-usage` for one bot. */+export const UsagePanel: React.FC<{ kwantId: string; kwantName: string }> = ({ kwantId, kwantName }) => {+ const [usage, setUsage] = useState<ModelUsage | null>(null);+ const [error, setError] = useState<string | null>(null);+ const load = useCallback(() => {+ setError(null);+ setUsage(null);+ modelUsageApi+ .get(kwantId)+ .then(setUsage)+ .catch(() => setError("Couldn't load usage."));+ }, [kwantId]);+ useEffect(load, [load]);+ return <UsageView kwantName={kwantName} usage={usage} error={error} onReload={load} />;+};diff --git a/frontend/src/modelUsage.ts b/frontend/src/modelUsage.tsnew file mode 100644index 00000000..4f97c3e3--- /dev/null+++ b/frontend/src/modelUsage.ts@@ -0,0 +1,68 @@+// Per-bot model calls and tokens from `GET /api/kwants/:id/model-usage` (API-key and custom API bots only).+import { request } from './threads';++export type UsagePurpose = 'reply' | 'tool_round' | 'summary' | string;++export interface UsageSums {+ calls: number;+ fresh_input_tokens: number;+ cache_read_tokens: number;+ cache_write_tokens: number;+ output_tokens: number;+ tools_chars: number;+ system_chars: number;+ messages_chars: number;+}++export interface UsageCall {+ id: number;+ context_id: string;+ purpose: UsagePurpose;+ model: string;+ fresh_input_tokens: number;+ cache_read_tokens: number;+ cache_write_tokens: number;+ output_tokens: number;+ /** False when the provider sent no usage numbers for this call. */+ reported: boolean;+ tools_chars: number;+ system_chars: number;+ messages_chars: number;+ created_at: string;+}++export interface ModelUsage {+ kwant_id: string;+ since: string | null;+ totals: UsageSums;+ by_purpose: Array<UsageSums & { purpose: UsagePurpose }>;+ /** Newest first. */+ recent: UsageCall[];+}++const PURPOSE_LABEL: Record<string, [string, string]> = {+ reply: ['Reply', 'Replies'],+ tool_round: ['Tool round', 'Tool rounds'],+ summary: ['Summary', 'Summaries'],+};+/** "Replies" for a group, "Reply" for one call; unknown purposes as they are. */+export const purposeLabel = (p: UsagePurpose, one = false): string => PURPOSE_LABEL[p]?.[one ? 0 : 1] ?? p;++/** 1234 → "1.2k", 2_500_000 → "2.5M"; small numbers as they are. */+export function compactTokens(n: number): string {+ const v = Number.isFinite(n) ? Math.max(0, n) : 0;+ if (v < 1000) return String(Math.round(v));+ if (v < 1_000_000) return `${+(v / 1000).toFixed(v < 100_000 ? 1 : 0)}k`;+ return `${+(v / 1_000_000).toFixed(1)}M`;+}++/** Share of input tokens served from the cache, 0–100, or null with no input. */+export function cacheShare(s: Pick<UsageSums, 'fresh_input_tokens' | 'cache_read_tokens' | 'cache_write_tokens'>): number | null {+ const input = s.fresh_input_tokens + s.cache_read_tokens + s.cache_write_tokens;+ return input > 0 ? Math.round((s.cache_read_tokens / input) * 100) : null;+}++export const modelUsageApi = {+ get: (kwantId: string, limit = 20) =>+ request<ModelUsage>('GET', `/api/kwants/${encodeURIComponent(kwantId)}/model-usage?limit=${limit}`),+};diff --git a/frontend/tests/modelUsage.test.mjs b/frontend/tests/modelUsage.test.mjsnew file mode 100644index 00000000..f4a72da0--- /dev/null+++ b/frontend/tests/modelUsage.test.mjs@@ -0,0 +1,118 @@+// Per-bot usage view for GET /api/kwants/:id/model-usage (the Usage tab in a bot's settings).+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const m = await loadBundled(`+ export { compactTokens, cacheShare, purposeLabel, modelUsageApi } from './src/modelUsage';+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { UsageView } from './src/components/UsagePanel';+ export const view = (props) => renderToStaticMarkup(React.createElement(UsageView, { kwantName: 'Analyst', onReload: () => {}, ...props }));+ export { UsageView };+`);++const sums = (o = {}) => ({+ calls: 0, fresh_input_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, output_tokens: 0,+ tools_chars: 0, system_chars: 0, messages_chars: 0, ...o,+});+// Shaped like the response in grok-harness-ideas/notes.md, Job Y item 6.+const usage = {+ kwant_id: 'k1', since: null,+ totals: sums({ calls: 18, fresh_input_tokens: 720, cache_read_tokens: 24000, cache_write_tokens: 3000, output_tokens: 216 }),+ by_purpose: [+ { purpose: 'reply', ...sums({ calls: 14, fresh_input_tokens: 600, cache_read_tokens: 20000, output_tokens: 180 }) },+ { purpose: 'summary', ...sums({ calls: 1, fresh_input_tokens: 80, cache_write_tokens: 3000, output_tokens: 30 }) },+ { purpose: 'tool_round', ...sums({ calls: 3, fresh_input_tokens: 40, cache_read_tokens: 4000, output_tokens: 6 }) },+ ],+ recent: [+ { id: 18, context_id: 'c', purpose: 'tool_round', model: 'claude-opus-5-5', fresh_input_tokens: 40, cache_read_tokens: 1500,+ cache_write_tokens: 0, output_tokens: 12, reported: true, tools_chars: 1, system_chars: 1, messages_chars: 1, created_at: '2026-10-21T22:01:40Z' },+ { id: 17, context_id: 'c', purpose: 'reply', model: 'gpt-x', fresh_input_tokens: 0, cache_read_tokens: 0,+ cache_write_tokens: 0, output_tokens: 0, reported: false, tools_chars: 1, system_chars: 1, messages_chars: 1, created_at: '2026-10-21T22:01:00Z' },+ ],+};++test('token counts are compact and the cache share counts every input token', () => {+ assert.equal(m.compactTokens(0), '0');+ assert.equal(m.compactTokens(999), '999');+ assert.equal(m.compactTokens(1500), '1.5k');+ assert.equal(m.compactTokens(24000), '24k');+ assert.equal(m.compactTokens(19500), '19.5k');+ assert.equal(m.compactTokens(123456), '123k');+ assert.equal(m.compactTokens(2_500_000), '2.5M');+ assert.equal(m.compactTokens(-3), '0');+ assert.equal(m.compactTokens(NaN), '0');+ // 24000 read of 720 + 24000 + 3000 input.+ assert.equal(m.cacheShare(usage.totals), 87);+ assert.equal(m.cacheShare(sums()), null);+ assert.equal(m.purposeLabel('tool_round'), 'Tool rounds');+ assert.equal(m.purposeLabel('tool_round', true), 'Tool round');+ assert.equal(m.purposeLabel('something_new'), 'something_new');+});++test('the four token kinds, purposes and recent calls render', () => {+ const html = m.view({ usage, error: null });+ assert.match(html, /18 calls, 87% of input from the cache/);+ assert.match(html, /data-kind="fresh_input_tokens">720</);+ assert.match(html, /data-kind="cache_read_tokens">24k</);+ assert.match(html, /data-kind="cache_write_tokens">3k</);+ assert.match(html, /data-kind="output_tokens">216</);+ assert.match(html, /Replies \(14\)/);+ assert.match(html, /Summaries/);+ assert.match(html, /Tool rounds/);+ assert.match(html, /fresh 40 · cache read 1.5k · cache write 0 · out 12/);+ assert.match(html, /data-call="tool_round"><div[^>]*><span[^>]*>Tool round<\/span>/);+ assert.match(html, /claude-opus-5-5/);+ // A call the provider gave no numbers for says so instead of showing zeros.+ assert.match(html, /The provider sent no token counts for this call\./);+ // Newest first, as the server sends it.+ assert.ok(html.indexOf('data-call="tool_round"') < html.indexOf('data-call="reply"'));+});++test('loading, error and empty states', () => {+ assert.match(m.view({ usage: null, error: null }), /role="status".*Loading usage/s);+ const err = m.view({ usage: null, error: "Couldn't load usage." });+ assert.match(err, /role="alert"/);+ assert.match(err, /Retry/);+ const empty = m.view({ usage: { ...usage, totals: sums(), by_purpose: [], recent: [] }, error: null });+ assert.match(empty, /data-usage-empty/);+ assert.match(empty, /No model calls recorded for Analyst yet/);+ assert.doesNotMatch(empty, /data-usage=/);+});++test('Retry and Refresh call onReload', () => {+ let calls = 0;+ const onReload = () => calls++;+ const find = (node, pred) => {+ if (!node || typeof node !== 'object') return null;+ if (Array.isArray(node)) for (const c of node) { const f = find(c, pred); if (f) return f; }+ else {+ if (pred(node)) return node;+ return find(node.props?.children, pred);+ }+ return null;+ };+ const isBtn = (n) => n.type === 'button' && typeof n.props?.onClick === 'function';+ find(m.UsageView({ kwantName: 'A', usage: null, error: 'x', onReload }), isBtn).props.onClick();+ find(m.UsageView({ kwantName: 'A', usage, error: null, onReload }), isBtn).props.onClick();+ assert.equal(calls, 2);+});++test('the API asks for the bot by id with a limit', async () => {+ const seen = [];+ const orig = globalThis.fetch;+ globalThis.fetch = async (url, init) => {+ seen.push([String(url), init?.method]);+ return new Response(JSON.stringify(usage), { status: 200, headers: { 'content-type': 'application/json' } });+ };+ try {+ const got = await m.modelUsageApi.get('k/1');+ assert.equal(got.totals.calls, 18);+ } finally {+ globalThis.fetch = orig;+ }+ assert.match(seen[0][0], /\/api\/kwants\/k%2F1\/model-usage\?limit=20$/);+});