Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Show fresh tokens and cost per reply, add a chain token budget

Pixel (kwant bot)e7e8b3ce4258
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d44c46c7..394dade9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
or answering the question cancels the reminder. Set the delay with `waiting_follow_up_hours` in
settings (0 turns reminders off). `GET /api/waiting` (you only, never a bot) lists everything bots
are waiting on you for.
+- **See what a reply really cost.** Each reply now shows its fresh tokens (new input, cache writes
+ and output) instead of a total padded with cheap cache reads; hover for the full split and the cost
+ when the engine reports one. Claude sign-in bots now appear in a bot's **Usage** tab too, and
+ **App settings → Usage** lists fresh and cached tokens and cost per day and bot.
+- **Token budget per request.** When bots handing work to each other go over it (200k fresh tokens
+ by default, 0 turns it off) for one of your messages, they pause with one notice in the chat;
+ press **Continue** or say "continue" to let them go on.
### Changed
- A bot reply that ends with a closing line such as "Anything else?", "Should I continue?" or
@@ -35,6 +42,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
("Which city are you in?") still do, unless the next message clearly fits another bot better.
- UK places (London, Belfast, Jersey, Guernsey, Isle of Man) get metric units with road distances
and speeds in miles and mph.
+- A short message with an attachment ("what's the total on this?" plus a PDF) no longer gets the
+ deepest, slowest model tier on its own; asking for depth ("do a deep dive") still does.
### Fixed
- Invisible characters (zero-width, bidi overrides, Unicode tags) are stripped from the city setting.
diff --git a/frontend/src/chainBudget.ts b/frontend/src/chainBudget.ts
new file mode 100644
index 00000000..9a21f4aa
--- /dev/null
+++ b/frontend/src/chainBudget.ts
@@ -0,0 +1,49 @@
+// The chain token budget: when one person message's chain of hand-offs goes over it, kwnt stops
+// handing the turn on and posts one notice (message meta kind "budget_paused") with Continue.
+import { request } from './threads';
+
+export const BUDGET_MAX = 100_000_000;
+
+export interface BudgetPausedMeta {
+ kind: 'budget_paused';
+ /** Fresh tokens the chain had used. */
+ used: number;
+ budget: number;
+ /** Teammates who were about to be handed the turn. */
+ waiting: string[];
+ resumed: boolean;
+}
+
+export function parseBudgetPaused(meta: string | null | undefined): BudgetPausedMeta | null {
+ if (!meta) return null;
+ try {
+ const m = JSON.parse(meta);
+ if (!m || m.kind !== 'budget_paused') return null;
+ const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
+ return {
+ kind: 'budget_paused',
+ used: n(m.used),
+ budget: n(m.budget),
+ waiting: Array.isArray(m.waiting) ? m.waiting.filter((w: unknown): w is string => typeof w === 'string') : [],
+ resumed: m.resumed === true,
+ };
+ } catch {
+ return null;
+ }
+}
+
+/** Error text for the budget field, or null for a whole number from 0 (off) to BUDGET_MAX. */
+export function budgetError(raw: string): string | null {
+ const s = raw.trim().replace(/[ _,]/g, '');
+ if (!/^\d+$/.test(s)) return 'Enter a whole number of tokens, or 0 to turn it off.';
+ if (Number(s) > BUDGET_MAX) return `At most ${BUDGET_MAX.toLocaleString('en-US')}.`;
+ return null;
+}
+
+/** The field's text as a number, once `budgetError` is null. */
+export const budgetValue = (raw: string): number => Number(raw.trim().replace(/[ _,]/g, ''));
+
+export const chainBudgetApi = {
+ /** Hands the turn to the teammates the notice was holding back (person only). */
+ continue: (noticeId: string) => request<{ status: string }>('POST', `/api/chains/${encodeURIComponent(noticeId)}/continue`),
+};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index aa94b37a..a3ac30bd 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -33,10 +33,12 @@ import {
} from '../attachments';
import { FileTiles, UploadChip } from './Attachments';
import { ranOnLabel } from '../engines';
+import { replyTokens } from '../modelUsage';
import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';
import { routeReasonText } from '../routeReason';
-import { InterruptedNotice, SystemNotice } from './SystemNotice';
+import { BudgetPausedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
+import { chainBudgetApi, parseBudgetPaused } from '../chainBudget';
import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';
/** A swipeable chip row whose right fade edge (phones only, see .kw-scroll-row) goes away once
@@ -238,10 +240,6 @@ export const renderFormattedText = (text: string): React.ReactNode => {
});
};
-/** "24.2k" for a token count, so it fits on a phone's line. */
-export const compactTokens = (n: number): string =>
- n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1).replace(/\.0$/, '')}k` : String(n);
-
/** Why Laya picked this bot. Phones show one line and open the rest on a tap. */
const RoutingLine: React.FC<{ text: string; fallback: boolean }> = ({ text, fallback }) => {
const [open, setOpen] = useState(false);
@@ -794,6 +792,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
/>
</div>
);
+ const paused = parseBudgetPaused(msg.meta);
+ if (paused)
+ return (
+ <BudgetPausedNotice
+ key={msg.id}
+ messageId={msg.id}
+ text={msg.text}
+ meta={paused}
+ onContinue={canRun === false ? undefined : chainBudgetApi.continue}
+ flash={flashId === msg.id}
+ />
+ );
if (isSystemNotice(msg) && !parseAttachments(msg.meta).length)
return <SystemNotice key={msg.id} messageId={msg.id} text={msg.text} flash={flashId === msg.id} />;
const isUser = msg.sender_role === 'user';
@@ -804,6 +814,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
const savedActivity = !isUser && msg.meta ? parseActivityMeta(msg.meta) : null;
const ranOn = isUser ? null : ranOnLabel(msg.meta);
const account = isUser ? null : ranOnAccount(msg.meta);
+ const tokens = isUser ? null : replyTokens(msg.tokens_used, msg.meta);
// Any auto-routed channel, not only #general: the server attaches `routing` wherever it picked the bot.
const routed = isUser ? null : parseRoutingMeta(msg.meta);
const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
@@ -840,9 +851,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
</span>
)}
{account && <span className="hidden sm:inline text-zinc-500 text-[10px] truncate max-w-[12rem]">ran on {account}</span>}
- {msg.tokens_used ? (
- <span className="hidden sm:inline text-zinc-500 font-mono text-[10px]">({msg.tokens_used} tokens)</span>
- ) : null}
+ {tokens && (
+ <span className="hidden sm:inline text-zinc-500 font-mono text-[10px] cursor-help" title={tokens.detail}>
+ ({tokens.label})<span className="sr-only">: {tokens.detail}</span>
+ </span>
+ )}
</div>
{routed && <RoutingLine text={routingLine(routed, spaceName ?? 'this space')} fallback={!!routed.fallback} />}
@@ -923,9 +936,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
</>
)}
</button>
- {(account || msg.tokens_used) && (
- <span className="sm:hidden min-w-0 truncate text-[10px]">
- {[account && `ran on ${account}`, msg.tokens_used && `${compactTokens(msg.tokens_used)} tokens`].filter(Boolean).join(' · ')}
+ {(account || tokens) && (
+ <span className="sm:hidden min-w-0 truncate text-[10px]" title={tokens?.detail}>
+ {[account && `ran on ${account}`, tokens?.label].filter(Boolean).join(' · ')}
</span>
)}
</div>
diff --git a/frontend/src/components/DailyUsage.tsx b/frontend/src/components/DailyUsage.tsx
new file mode 100644
index 00000000..3e511f39
--- /dev/null
+++ b/frontend/src/components/DailyUsage.tsx
@@ -0,0 +1,126 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import { Loader2, RotateCcw } from 'lucide-react';
+import { DailyUsage, compactTokens, formatCost, freshOf, modelUsageApi } from '../modelUsage';
+
+interface Day {
+ day: string;
+ fresh: number;
+ cached: number;
+ /** Null when no call that day reported a cost. */
+ cost: number | null;
+ bots: DailyUsage[];
+}
+
+/** Rows (one per bot and day, newest day first) grouped into days with their totals. */
+export function groupDays(rows: DailyUsage[]): Day[] {
+ const days: Day[] = [];
+ for (const r of rows) {
+ let d = days.find((x) => x.day === r.day);
+ if (!d) days.push((d = { day: r.day, fresh: 0, cached: 0, cost: null, bots: [] }));
+ d.fresh += freshOf(r);
+ d.cached += r.cache_read_tokens;
+ if (r.cost_usd != null) d.cost = (d.cost ?? 0) + r.cost_usd;
+ d.bots.push(r);
+ }
+ for (const d of days) d.bots.sort((a, b) => freshOf(b) - freshOf(a));
+ return days;
+}
+
+/** "Today", "Yesterday" or "Mon 20 Oct" for a UTC day. */
+export function dayLabel(day: string, now = new Date()): string {
+ const today = now.toISOString().slice(0, 10);
+ const yesterday = new Date(now.getTime() - 86_400_000).toISOString().slice(0, 10);
+ if (day === today) return 'Today';
+ if (day === yesterday) return 'Yesterday';
+ const d = new Date(`${day}T00:00:00Z`);
+ return Number.isNaN(d.getTime())
+ ? day
+ : d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' });
+}
+
+const Numbers: React.FC<{ fresh: number; cached: number; cost: number | null; strong?: boolean }> = ({ fresh, cached, cost, strong }) => (
+ <span className={`shrink-0 font-mono text-[11px] tabular-nums ${strong ? 'text-zinc-200' : 'text-zinc-400'}`}>
+ <span title={`${fresh.toLocaleString('en-US')} fresh tokens`}>{compactTokens(fresh)}</span>
+ <span className="text-zinc-600"> · </span>
+ <span className="text-zinc-500" title={`${cached.toLocaleString('en-US')} read from cache`}>
+ {compactTokens(cached)}
+ </span>
+ {formatCost(cost) && (
+ <>
+ <span className="text-zinc-600"> · </span>
+ <span>{formatCost(cost)}</span>
+ </>
+ )}
+ </span>
+);
+
+/** Settings → Usage: fresh and cached tokens and cost per day and bot. */
+export const DailyUsageView: React.FC<{ rows: DailyUsage[] | null; error?: string | null; onReload?: () => void; now?: Date }> = ({
+ rows,
+ error,
+ onReload,
+ now,
+}) => {
+ if (error)
+ return (
+ <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">
+ <span className="flex-1">{error}</span>
+ {onReload && (
+ <button type="button" onClick={onReload} className="inline-flex items-center gap-1 text-zinc-300 hover:text-zinc-100 underline underline-offset-2">
+ <RotateCcw size={11} aria-hidden="true" /> Retry
+ </button>
+ )}
+ </p>
+ );
+ if (!rows)
+ return (
+ <p className="flex items-center gap-2 text-[11px] text-zinc-500" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading usage…
+ </p>
+ );
+ if (!rows.length) return <p className="text-[11px] text-zinc-500">No bot replies in the last two weeks.</p>;
+ return (
+ <div className="space-y-2">
+ <p className="text-[11px] text-zinc-500">
+ Fresh tokens · read from cache · cost where the engine reports it. Fresh is new input, cache writes and output: what makes a
+ reply heavy.
+ </p>
+ <ul className="space-y-2" aria-label="Usage per day">
+ {groupDays(rows).map((d) => (
+ <li key={d.day} className="rounded-lg border border-zinc-800 bg-zinc-950/60">
+ <div className="flex items-center gap-2 px-3 py-1.5 border-b border-zinc-800/80">
+ <span className="flex-1 min-w-0 truncate text-[11px] font-medium text-zinc-200">{dayLabel(d.day, now)}</span>
+ <Numbers fresh={d.fresh} cached={d.cached} cost={d.cost} strong />
+ </div>
+ <ul className="px-3 py-1">
+ {d.bots.map((b) => (
+ <li key={b.kwant_id} className="flex items-center gap-2 py-0.5">
+ <span className="flex-1 min-w-0 truncate text-[11px] text-zinc-400">{b.kwant_name ?? 'Deleted bot'}</span>
+ <Numbers fresh={freshOf(b)} cached={b.cache_read_tokens} cost={b.cost_usd ?? null} />
+ </li>
+ ))}
+ </ul>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+};
+
+/** Loads the last two weeks while `open`. */
+export const DailyUsagePanel: React.FC<{ open: boolean }> = ({ open }) => {
+ const [rows, setRows] = useState<DailyUsage[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const load = useCallback(() => {
+ setError(null);
+ setRows(null);
+ modelUsageApi
+ .daily(14)
+ .then((r) => setRows(r.rows))
+ .catch((e) => setError(e instanceof Error ? e.message : 'Could not load usage.'));
+ }, []);
+ useEffect(() => {
+ if (open) load();
+ }, [open, load]);
+ return <DailyUsageView rows={rows} error={error} onReload={load} />;
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 5c023174..26c8d359 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,6 +1,8 @@
import React, { useState, useEffect, useRef } from 'react';
import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff } from 'lucide-react';
import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';
+import { budgetError, budgetValue } from '../chainBudget';
+import { DailyUsagePanel } from './DailyUsage';
import {
BROWSER_NOTIFY_KEY,
MASK,
@@ -48,6 +50,8 @@ interface SettingsData {
timezone?: string;
/** The person's city as they typed it, "" when not set. */
location?: string;
+ /** Fresh tokens per request before hand-offs pause; 0 = off. Missing on older servers. */
+ chain_token_budget?: number;
}
const LIMIT_FIELDS: { key: TurnLimitKey; label: string; hint: string }[] = [
@@ -95,6 +99,9 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const webhookError = webhookUrlError(webhookUrl);
// Kept as typed text so a half-typed value can be shown with its error; null until loaded.
const [limits, setLimits] = useState<Record<TurnLimitKey, string> | null>(null);
+ // Fresh tokens one request's chain may use before hand-offs pause; null on a server without it.
+ const [chainBudget, setChainBudget] = useState<string | null>(null);
+ const chainBudgetError = chainBudget === null ? null : budgetError(chainBudget);
const limitErrors = Object.fromEntries(
LIMIT_FIELDS.map(({ key }) => [key, limits ? limitError(key, limits[key]) : null]),
) as Record<TurnLimitKey, string | null>;
@@ -137,6 +144,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
}
: null,
);
+ setChainBudget(typeof data.chain_token_budget === 'number' ? String(data.chain_token_budget) : null);
setAgentTools(typeof data.agent_tools === 'boolean' ? data.agent_tools : null);
setPlace(
typeof data.timezone === 'string'
@@ -191,7 +199,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
- if (webhookError || limitsInvalid) return;
+ if (webhookError || limitsInvalid || chainBudgetError) return;
setSaveError(null);
setSaving(true);
playSfx('click');
@@ -214,6 +222,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
delegation_follow_up_minutes: Number(limits.delegation_follow_up_minutes),
}
: {}),
+ ...(chainBudget !== null ? { chain_token_budget: budgetValue(chainBudget) } : {}),
...(agentTools !== null ? { agent_tools: agentTools } : {}),
...(place ? { timezone: place.timezone.trim(), location: place.location.trim() } : {}),
}),
@@ -512,6 +521,38 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</fieldset>
)}
+ <fieldset className="space-y-3 pt-2 border-t border-zinc-800">
+ <legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">
+ <Gauge size={14} className="text-sky-300" aria-hidden="true" />
+ <span>Usage</span>
+ </legend>
+ {chainBudget !== null && (
+ <div className="space-y-1">
+ <label htmlFor="chain-token-budget" className="block text-[11px] font-medium text-zinc-300">
+ Token budget per request (fresh tokens)
+ </label>
+ <input
+ id="chain-token-budget"
+ type="text"
+ inputMode="numeric"
+ autoComplete="off"
+ value={chainBudget}
+ onChange={(e) => setChainBudget(e.target.value)}
+ aria-invalid={!!chainBudgetError}
+ aria-describedby="chain-token-budget-hint"
+ className={`w-full sm:w-48 bg-zinc-950 border rounded-lg px-3 py-2 text-xs font-mono text-zinc-100 focus:outline-none transition-colors ${
+ chainBudgetError ? 'border-rose-500/60 focus:border-rose-400' : 'border-zinc-800 focus:border-sky-500'
+ }`}
+ />
+ <p id="chain-token-budget-hint" className={`text-[11px] ${chainBudgetError ? 'text-rose-300' : 'text-zinc-500'}`}>
+ {chainBudgetError ??
+ 'When bots handing work to each other go over this for one of your messages, they pause and ask you before going on. 0 turns it off.'}
+ </p>
+ </div>
+ )}
+ <DailyUsagePanel open={isOpen} />
+ </fieldset>
+
{agentTools !== null && (
<div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">
<div className="flex-1">
diff --git a/frontend/src/components/SystemNotice.tsx b/frontend/src/components/SystemNotice.tsx
index 43d104d0..555492da 100644
--- a/frontend/src/components/SystemNotice.tsx
+++ b/frontend/src/components/SystemNotice.tsx
@@ -1,5 +1,7 @@
import React, { useRef, useState } from 'react';
-import { AlertTriangle, Check, Info, Loader2, RotateCcw } from 'lucide-react';
+import { AlertTriangle, Check, Gauge, Info, Loader2, Play, RotateCcw } from 'lucide-react';
+import { BudgetPausedMeta } from '../chainBudget';
+import { compactTokens } from '../modelUsage';
import { Interruption, RetryState, RetryTarget, interruptionText, runRetryOnce } from '../interruptions';
/** A note kwnt itself wrote (e.g. "Growth wasn't asked: …"): a quiet line, not a bot's reply. */
@@ -78,3 +80,78 @@ export const InterruptedNotice: React.FC<InterruptedNoticeProps> = ({ messageId,
</section>
);
};
+
+export interface BudgetPausedNoticeProps {
+ messageId: string;
+ text: string;
+ meta: BudgetPausedMeta;
+ /** Carries the chain on; without it (a read-only view) there's no button. */
+ onContinue?: (noticeId: string) => Promise<unknown>;
+ flash?: boolean;
+}
+
+/** A chain that went over its token budget: who was waiting, and Continue to let them go on. */
+export const BudgetPausedNotice: React.FC<BudgetPausedNoticeProps> = ({ messageId, text, meta, onContinue, flash }) => {
+ const [state, setState] = useState<'idle' | 'sending' | 'sent' | 'error'>(meta.resumed ? 'sent' : 'idle');
+ const [error, setError] = useState<string | null>(null);
+ const lock = useRef(false);
+ const headingId = `budget-${messageId}`;
+ const run = async () => {
+ if (!onContinue || lock.current) return;
+ lock.current = true;
+ setState('sending');
+ setError(null);
+ try {
+ await onContinue(messageId);
+ setState('sent');
+ } catch (e) {
+ lock.current = false;
+ setState('error');
+ setError(e instanceof Error ? e.message : 'Could not continue.');
+ }
+ };
+ const done = state === 'sent';
+ return (
+ <section
+ data-message-id={messageId}
+ data-budget-paused
+ aria-labelledby={headingId}
+ className={`w-full max-w-5xl rounded-xl border border-amber-500/30 bg-amber-950/20 px-3.5 py-2.5 sm:px-4 ${flash ? 'kw-flash' : ''}`}
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <div className="min-w-0 flex-1 basis-56">
+ <p id={headingId} className="flex items-start gap-2 text-sm text-amber-200 break-words">
+ <Gauge size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />
+ <span className="min-w-0">{text}</span>
+ </p>
+ <p className="mt-1 pl-[23px] text-[11px] text-amber-200/60 font-mono">
+ {compactTokens(meta.used)} of {compactTokens(meta.budget)} fresh tokens
+ </p>
+ </div>
+ {onContinue && (
+ <button
+ type="button"
+ onClick={run}
+ disabled={state === 'sending' || done}
+ aria-describedby={headingId}
+ className="shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer disabled:cursor-default text-amber-100 bg-amber-500/15 border-amber-500/40 hover:bg-amber-500/25 disabled:opacity-70 disabled:hover:bg-amber-500/15 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"
+ >
+ {state === 'sending' ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : done ? (
+ <Check size={13} aria-hidden="true" />
+ ) : (
+ <Play size={13} aria-hidden="true" />
+ )}
+ <span>{state === 'sending' ? 'Continuing…' : done ? 'Continued' : 'Continue'}</span>
+ </button>
+ )}
+ </div>
+ {error && (
+ <p role="alert" className="mt-2 pl-[23px] text-[11px] text-rose-300">
+ {error}
+ </p>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/components/UsagePanel.tsx b/frontend/src/components/UsagePanel.tsx
index 5074462b..cdc093a4 100644
--- a/frontend/src/components/UsagePanel.tsx
+++ b/frontend/src/components/UsagePanel.tsx
@@ -1,12 +1,14 @@
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';
+import { ModelUsage, UsageSums, cacheShare, compactTokens, formatCost, 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 }> = [
+type TokenKey = 'fresh_input_tokens' | 'cache_read_tokens' | 'cache_write_tokens' | 'output_tokens';
+
+const KINDS: Array<{ key: TokenKey; 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' },
@@ -45,8 +47,8 @@ export const UsageView: React.FC<{
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.
+ No model calls recorded for {kwantName} yet. Calls are counted here for bots on an API key, a custom API or a Claude sign-in;
+ Codex and Grok sign-ins report their usage to their own accounts.
</p>
);
const share = cacheShare(t);
@@ -56,6 +58,7 @@ export const UsageView: React.FC<{
<p className="text-xs text-zinc-400">
{t.calls} {t.calls === 1 ? 'call' : 'calls'}
{share !== null && `, ${share}% of input from the cache`}
+ {formatCost(t.cost_usd) && `, ${formatCost(t.cost_usd)}`}
</p>
<button type="button" onClick={onReload} className={quietBtn} aria-label="Refresh usage">
<RefreshCw size={12} /> Refresh
@@ -103,7 +106,7 @@ export const UsageView: React.FC<{
<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>
+ <div className="text-zinc-500 tabular-nums">{c.reported ? tokenLine(c) + (formatCost(c.cost_usd) ? ` · ${formatCost(c.cost_usd)}` : '') : 'The provider sent no token counts for this call.'}</div>
</li>
))}
</ul>
diff --git a/frontend/src/modelUsage.ts b/frontend/src/modelUsage.ts
index 4f97c3e3..75668a7f 100644
--- a/frontend/src/modelUsage.ts
+++ b/frontend/src/modelUsage.ts
@@ -1,4 +1,5 @@
-// Per-bot model calls and tokens from `GET /api/kwants/:id/model-usage` (API-key and custom API bots only).
+// Per-bot model calls and tokens from `GET /api/kwants/:id/model-usage` (API-key, custom API and
+// Claude CLI bots), per-day totals from `GET /api/usage/daily`, and the split on each reply.
import { request } from './threads';
export type UsagePurpose = 'reply' | 'tool_round' | 'summary' | string;
@@ -12,6 +13,8 @@ export interface UsageSums {
tools_chars: number;
system_chars: number;
messages_chars: number;
+ /** USD, summed over the calls that reported a cost (Claude CLI does); null when none did. */
+ cost_usd?: number | null;
}
export interface UsageCall {
@@ -28,6 +31,7 @@ export interface UsageCall {
tools_chars: number;
system_chars: number;
messages_chars: number;
+ cost_usd?: number | null;
created_at: string;
}
@@ -62,7 +66,75 @@ export function cacheShare(s: Pick<UsageSums, 'fresh_input_tokens' | 'cache_read
return input > 0 ? Math.round((s.cache_read_tokens / input) * 100) : null;
}
+/** One bot's totals for one UTC day (`day` is YYYY-MM-DD). */
+export interface DailyUsage extends UsageSums {
+ day: string;
+ kwant_id: string;
+ /** Null once the bot is deleted. */
+ kwant_name?: string | null;
+}
+
+export interface DailyUsageResponse {
+ days: number;
+ /** Newest day first. */
+ rows: DailyUsage[];
+}
+
+/** Tokens the model had to take in or write new: everything but cache reads. */
+export const freshOf = (s: Pick<UsageSums, 'fresh_input_tokens' | 'cache_write_tokens' | 'output_tokens'>): number =>
+ s.fresh_input_tokens + s.cache_write_tokens + s.output_tokens;
+
+/** "$0.42", "$0.003", "<$0.001"; null without a cost. */
+export function formatCost(usd: number | null | undefined): string | null {
+ if (usd == null || !Number.isFinite(usd) || usd < 0) return null;
+ if (usd === 0) return '$0';
+ if (usd < 0.001) return '<$0.001';
+ return `$${usd < 1 ? +usd.toFixed(3) : usd.toFixed(2)}`;
+}
+
+/** A reply's usage split, saved in its meta as `usage`. */
+export interface TurnUsage {
+ fresh_input: number;
+ cache_read: number;
+ cache_write: number;
+ output: number;
+ cost_usd?: number;
+}
+
+export function parseTurnUsage(meta: string | null | undefined): TurnUsage | null {
+ if (!meta) return null;
+ try {
+ const u = JSON.parse(meta)?.usage;
+ if (!u || typeof u !== 'object') return null;
+ const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0);
+ const cost = typeof u.cost_usd === 'number' && Number.isFinite(u.cost_usd) ? u.cost_usd : undefined;
+ return { fresh_input: n(u.fresh_input), cache_read: n(u.cache_read), cache_write: n(u.cache_write), output: n(u.output), cost_usd: cost };
+ } catch {
+ return null;
+ }
+}
+
+/** What a reply shows for its tokens: fresh tokens when the split is known, with the whole split
+ * (and cost) for the tooltip; otherwise the old total, which counts cache reads too. */
+export function replyTokens(tokensUsed: number | null | undefined, meta: string | null | undefined): { count: number; label: string; detail: string } | null {
+ const u = parseTurnUsage(meta);
+ if (u) {
+ const count = u.fresh_input + u.cache_write + u.output;
+ const fmt = (n: number) => n.toLocaleString('en-US');
+ const parts = [
+ `${fmt(count)} fresh tokens: ${fmt(u.fresh_input)} new input, ${fmt(u.cache_write)} written to cache, ${fmt(u.output)} output`,
+ `${fmt(u.cache_read)} more read from cache (cheap, not counted)`,
+ ];
+ const cost = formatCost(u.cost_usd);
+ if (cost) parts.push(`Cost ${cost}`);
+ return { count, label: `${compactTokens(count)} fresh`, detail: parts.join('. ') + '.' };
+ }
+ if (!tokensUsed) return null;
+ return { count: tokensUsed, label: `${compactTokens(tokensUsed)} tokens`, detail: `${tokensUsed.toLocaleString('en-US')} tokens, cache reads included` };
+}
+
export const modelUsageApi = {
get: (kwantId: string, limit = 20) =>
request<ModelUsage>('GET', `/api/kwants/${encodeURIComponent(kwantId)}/model-usage?limit=${limit}`),
+ daily: (days = 14) => request<DailyUsageResponse>('GET', `/api/usage/daily?days=${days}`),
};
diff --git a/frontend/tests/usageVisibility.test.mjs b/frontend/tests/usageVisibility.test.mjs
new file mode 100644
index 00000000..1e3ff4de
--- /dev/null
+++ b/frontend/tests/usageVisibility.test.mjs
@@ -0,0 +1,139 @@
+// F6 usage visibility: replies show fresh tokens (not cache reads) with the split in the tooltip,
+// Settings → Usage shows fresh vs cached and cost per day and bot, and a chain over its token
+// budget shows one notice with Continue.
+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 { replyTokens, parseTurnUsage, formatCost, freshOf, modelUsageApi } from './src/modelUsage';
+ export { parseBudgetPaused, budgetError, budgetValue, chainBudgetApi } from './src/chainBudget';
+ export { groupDays, dayLabel } from './src/components/DailyUsage';
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { DailyUsageView } from './src/components/DailyUsage';
+ import { BudgetPausedNotice } from './src/components/SystemNotice';
+ export const daily = (props) => renderToStaticMarkup(React.createElement(DailyUsageView, props));
+ export const notice = (props) => renderToStaticMarkup(React.createElement(BudgetPausedNotice, props));
+`);
+
+// The usage split a Claude CLI turn saves in its reply's meta (see tests/fixtures/claude).
+const usageMeta = JSON.stringify({
+ engine: 'claude',
+ usage: { fresh_input: 12, cache_read: 83544, cache_write: 8211, output: 487, cost_usd: 0.4189 },
+});
+
+test('a reply shows fresh tokens, not the cache-inclusive total', () => {
+ const t = m.replyTokens(92254, usageMeta);
+ assert.equal(t.count, 12 + 8211 + 487);
+ assert.equal(t.label, '8.7k fresh');
+ assert.match(t.detail, /^8,710 fresh tokens: 12 new input, 8,211 written to cache, 487 output\./);
+ assert.match(t.detail, /83,544 more read from cache/);
+ assert.match(t.detail, /Cost \$0\.419\./);
+});
+
+test('replies without a split keep the old total, labelled as including cache reads', () => {
+ assert.deepEqual(m.replyTokens(26000, JSON.stringify({ engine: 'codex' })), {
+ count: 26000,
+ label: '26k tokens',
+ detail: '26,000 tokens, cache reads included',
+ });
+ assert.equal(m.replyTokens(0, null), null);
+ assert.equal(m.replyTokens(undefined, 'not json'), null);
+ // A split without a cost says nothing about cost
+ assert.doesNotMatch(m.replyTokens(10, JSON.stringify({ usage: { fresh_input: 5, output: 5 } })).detail, /Cost/);
+});
+
+test('costs are short and never negative', () => {
+ assert.equal(m.formatCost(0.4189), '$0.419');
+ assert.equal(m.formatCost(12.5), '$12.50');
+ assert.equal(m.formatCost(0.0004), '<$0.001');
+ assert.equal(m.formatCost(0), '$0');
+ assert.equal(m.formatCost(null), null);
+ assert.equal(m.formatCost(-1), null);
+});
+
+const row = (day, kwant_id, kwant_name, o = {}) => ({
+ day, kwant_id, kwant_name, calls: 1, fresh_input_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, output_tokens: 0,
+ tools_chars: 0, system_chars: 0, messages_chars: 0, cost_usd: null, ...o,
+});
+const rows = [
+ row('2026-10-26', 'a', 'Ann', { fresh_input_tokens: 100, cache_write_tokens: 900, output_tokens: 1000, cache_read_tokens: 50000, cost_usd: 0.5 }),
+ row('2026-10-26', 'b', 'Bob', { fresh_input_tokens: 4000, output_tokens: 1000, cache_read_tokens: 0 }),
+ row('2026-10-24', 'gone', null, { output_tokens: 10, cost_usd: 0.25 }),
+];
+
+test('Settings → Usage groups days with fresh, cached and cost', () => {
+ const days = m.groupDays(rows);
+ assert.deepEqual(days.map((d) => [d.day, d.fresh, d.cached, d.cost]), [
+ ['2026-10-26', 7000, 50000, 0.5],
+ ['2026-10-24', 10, 0, 0.25],
+ ]);
+ assert.deepEqual(days[0].bots.map((b) => b.kwant_name), ['Bob', 'Ann'], 'heaviest bot first');
+
+ const now = new Date('2026-10-26T15:00:00Z');
+ assert.equal(m.dayLabel('2026-10-26', now), 'Today');
+ assert.equal(m.dayLabel('2026-10-25', now), 'Yesterday');
+ assert.equal(m.dayLabel('2026-10-24', now), 'Sat 24 Oct');
+
+ const html = m.daily({ rows, now });
+ assert.match(html, /Today/);
+ assert.match(html, /Ann.*2k.*50k.*\$0\.5/s);
+ assert.match(html, /Deleted bot/);
+ // A day without any reported cost shows none, rather than $0
+ assert.doesNotMatch(m.daily({ rows: [rows[1]], now }), /\$/);
+});
+
+test('Settings → Usage loading, empty and error states', () => {
+ assert.match(m.daily({ rows: null }), /Loading usage/);
+ assert.match(m.daily({ rows: [] }), /No bot replies in the last two weeks/);
+ assert.match(m.daily({ rows: null, error: 'Request failed (HTTP 500).', onReload: () => {} }), /role="alert".*HTTP 500.*Retry/s);
+});
+
+test('the daily endpoint is asked for two weeks', async () => {
+ const seen = [];
+ globalThis.fetch = async (url, init) => {
+ seen.push([init?.method, url]);
+ return new Response(JSON.stringify({ days: 14, rows: [] }), { status: 200 });
+ };
+ await m.modelUsageApi.daily();
+ await m.chainBudgetApi.continue('msg 1');
+ assert.deepEqual(seen, [
+ ['GET', '/api/usage/daily?days=14'],
+ ['POST', '/api/chains/msg%201/continue'],
+ ]);
+});
+
+test('the budget field takes whole numbers up to 100M, 0 for off', () => {
+ assert.equal(m.budgetError('200000'), null);
+ assert.equal(m.budgetError('200,000'), null);
+ assert.equal(m.budgetValue('200,000'), 200000);
+ assert.equal(m.budgetError('0'), null);
+ assert.match(m.budgetError(''), /whole number/);
+ assert.match(m.budgetError('1.5'), /whole number/);
+ assert.match(m.budgetError('-1'), /whole number/);
+ assert.match(m.budgetError('100000001'), /At most 100,000,000/);
+});
+
+const pausedMeta = JSON.stringify({ kind: 'budget_paused', used: 212000, budget: 200000, waiting: ['Bob'], resumed: false });
+
+test('a paused chain shows one notice with Continue', () => {
+ const meta = m.parseBudgetPaused(pausedMeta);
+ assert.deepEqual(meta, { kind: 'budget_paused', used: 212000, budget: 200000, waiting: ['Bob'], resumed: false });
+ assert.equal(m.parseBudgetPaused(JSON.stringify({ kind: 'handoff_refused' })), null);
+ assert.equal(m.parseBudgetPaused(null), null);
+
+ const text = 'Paused before handing on to Bob: this request has used 212k fresh tokens, over the 200k budget.';
+ const html = m.notice({ messageId: 'n1', text, meta, onContinue: async () => {} });
+ assert.match(html, /data-budget-paused/);
+ assert.match(html, /Paused before handing on to Bob/);
+ assert.match(html, /212k of 200k fresh tokens/);
+ assert.match(html, /<button[^>]*type="button"[^>]*>.*Continue<\/span><\/button>/s);
+ // Already continued: the button says so and is disabled
+ const done = m.notice({ messageId: 'n1', text, meta: { ...meta, resumed: true }, onContinue: async () => {} });
+ assert.match(done, /disabled="".*Continued/s);
+ // Nowhere to continue from: no button
+ assert.doesNotMatch(m.notice({ messageId: 'n1', text, meta }), /<button/);
+});
diff --git a/src/db/usage.rs b/src/db/usage.rs
index d73cbb4a..41bf9bd0 100644
--- a/src/db/usage.rs
+++ b/src/db/usage.rs
@@ -14,7 +14,7 @@ pub const PURPOSE_TOOL_ROUND: &str = "tool_round";
pub const PURPOSE_SUMMARY: &str = "summary";
/// A call to record. Token fields are 0 when the provider sent no counts (`reported` false).
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, PartialEq)]
pub struct NewUsage {
pub kwant_id: String,
pub context_id: String,
@@ -30,6 +30,8 @@ pub struct NewUsage {
pub tools_chars: i64,
pub system_chars: i64,
pub messages_chars: i64,
+ /// What the provider said the call cost; `None` when it didn't say.
+ pub cost_usd: Option<f64>,
}
#[derive(Debug, Clone, Serialize, FromRow)]
@@ -46,11 +48,12 @@ pub struct UsageRow {
pub tools_chars: i64,
pub system_chars: i64,
pub messages_chars: i64,
+ pub cost_usd: Option<f64>,
pub created_at: DateTime<Utc>,
}
/// Sums over a set of calls.
-#[derive(Debug, Clone, Default, Serialize, FromRow, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, Serialize, FromRow, PartialEq)]
pub struct UsageTotals {
pub calls: i64,
pub fresh_input_tokens: i64,
@@ -60,6 +63,8 @@ pub struct UsageTotals {
pub tools_chars: i64,
pub system_chars: i64,
pub messages_chars: i64,
+ /// Summed over the calls that reported a cost; `None` when none did.
+ pub cost_usd: Option<f64>,
}
#[derive(Debug, Clone, Serialize, FromRow)]
@@ -73,7 +78,21 @@ pub struct PurposeTotals {
const SUMS: &str = "COUNT(*) AS calls, COALESCE(SUM(fresh_input), 0) AS fresh_input_tokens, \
COALESCE(SUM(cache_read), 0) AS cache_read_tokens, COALESCE(SUM(cache_write), 0) AS cache_write_tokens, \
COALESCE(SUM(output), 0) AS output_tokens, COALESCE(SUM(tools_chars), 0) AS tools_chars, \
- COALESCE(SUM(system_chars), 0) AS system_chars, COALESCE(SUM(messages_chars), 0) AS messages_chars";
+ COALESCE(SUM(system_chars), 0) AS system_chars, COALESCE(SUM(messages_chars), 0) AS messages_chars, \
+ SUM(cost_usd) AS cost_usd";
+
+/// One bot's calls on one day (UTC), for Settings → Usage.
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct DailyUsage {
+ /// `YYYY-MM-DD`, UTC.
+ pub day: String,
+ pub kwant_id: String,
+ /// None once the bot is deleted.
+ pub kwant_name: Option<String>,
+ #[sqlx(flatten)]
+ #[serde(flatten)]
+ pub totals: UsageTotals,
+}
impl Database {
pub(super) async fn migrate_usage(&self) -> Result<(), DbError> {
@@ -98,13 +117,15 @@ impl Database {
] {
sqlx::query(stmt).execute(&self.pool).await?;
}
+ // Added later; fails harmlessly when the column is already there
+ let _ = sqlx::query("ALTER TABLE model_usage ADD COLUMN cost_usd REAL").execute(&self.pool).await;
Ok(())
}
pub async fn record_usage(&self, u: &NewUsage) -> Result<(), DbError> {
sqlx::query(
"INSERT INTO model_usage (kwant_id, context_id, purpose, model, fresh_input, cache_read, cache_write, output, \
- reported, tools_chars, system_chars, messages_chars, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ reported, tools_chars, system_chars, messages_chars, cost_usd, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&u.kwant_id)
.bind(&u.context_id)
@@ -118,6 +139,7 @@ impl Database {
.bind(u.tools_chars)
.bind(u.system_chars)
.bind(u.messages_chars)
+ .bind(u.cost_usd)
.bind(Utc::now())
.execute(&self.pool)
.await?;
@@ -128,7 +150,7 @@ impl Database {
pub async fn recent_usage(&self, kwant_id: &str, limit: i64) -> Result<Vec<UsageRow>, DbError> {
Ok(sqlx::query_as(
"SELECT id, context_id, purpose, model, fresh_input AS fresh_input_tokens, cache_read AS cache_read_tokens, \
- cache_write AS cache_write_tokens, output AS output_tokens, reported, tools_chars, system_chars, messages_chars, created_at \
+ cache_write AS cache_write_tokens, output AS output_tokens, reported, tools_chars, system_chars, messages_chars, cost_usd, created_at \
FROM model_usage WHERE kwant_id = ? ORDER BY id DESC LIMIT ?",
)
.bind(kwant_id)
@@ -158,6 +180,18 @@ impl Database {
.await?;
Ok((all, by_purpose))
}
+
+ /// Every bot's totals per UTC day since `since`, newest day first.
+ pub async fn daily_usage(&self, since: DateTime<Utc>) -> Result<Vec<DailyUsage>, DbError> {
+ Ok(sqlx::query_as(&format!(
+ "SELECT substr(created_at, 1, 10) AS day, kwant_id, \
+ (SELECT name FROM kwants WHERE kwants.id = model_usage.kwant_id) AS kwant_name, {SUMS} \
+ FROM model_usage WHERE created_at >= ? GROUP BY day, kwant_id ORDER BY day DESC, kwant_id"
+ ))
+ .bind(since)
+ .fetch_all(&self.pool)
+ .await?)
+ }
}
#[cfg(test)]
@@ -181,6 +215,7 @@ mod tests {
tools_chars: 100,
system_chars: 200,
messages_chars: 300,
+ cost_usd: None,
};
db.record_usage(&call("k1", PURPOSE_REPLY, 50, 1000)).await.unwrap();
db.record_usage(&call("k1", PURPOSE_TOOL_ROUND, 20, 1200)).await.unwrap();
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index f478bd64..2b970d0c 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -757,6 +757,8 @@ struct ChatRequest<'a> {
stream: bool,
/// Where each call is recorded; `None` records nothing.
record: Option<UsageSink<'a>>,
+ /// The turn's calls added up, for the reply's fresh/cached split; `None` until one reports.
+ turn_usage: std::sync::Mutex<Option<super::TurnUsage>>,
}
/// The bot and conversation a turn's calls are recorded for (see `crate::db::usage`).
@@ -782,6 +784,17 @@ fn prompt_chars(body: &Value) -> (usize, usize, usize) {
/// Records one model call, if the request has somewhere to record it. Never fails the turn.
async fn record_call(request: &ChatRequest<'_>, purpose: &'static str, usage: Option<Usage>, body: &Value) {
+ if let Some(u) = usage {
+ let call = super::TurnUsage {
+ fresh_input: u.input,
+ cache_read: u.cache_read,
+ cache_write: u.cache_creation,
+ output: u.output,
+ cost_usd: None,
+ };
+ let mut sum = request.turn_usage.lock().unwrap_or_else(|e| e.into_inner());
+ sum.get_or_insert_with(Default::default).add(&call);
+ }
let Some(sink) = request.record else {
return;
};
@@ -800,6 +813,7 @@ async fn record_call(request: &ChatRequest<'_>, purpose: &'static str, usage: Op
tools_chars: tools as i64,
system_chars: system as i64,
messages_chars: messages as i64,
+ cost_usd: None,
};
if let Err(e) = sink.db.record_usage(&row).await {
tracing::warn!(error = %e, "could not record model usage");
@@ -1261,6 +1275,7 @@ impl Driver for ApiDriver {
kwant_id: &input.kwant.id,
context_id: &input.thread_id,
}),
+ turn_usage: Default::default(),
};
let caller = Caller {
kwant_id: input.kwant.id.clone(),
@@ -1360,10 +1375,12 @@ impl Driver for ApiDriver {
profile_id: None,
})
.await;
+ let usage = *request.turn_usage.lock().unwrap_or_else(|e| e.into_inner());
return Ok(TurnOutput {
text,
reasoning: Some(format!("Model: {} [Effort: {}]", model, effort)),
tokens_used: tokens,
+ usage,
model: Some(model.clone()),
..Default::default()
});
@@ -1454,6 +1471,7 @@ mod tests {
max_calls: 1,
stream: false,
record: None,
+ turn_usage: Default::default(),
}
}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 8bcdc322..d185c893 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -894,6 +894,11 @@ struct ClaudeResult {
result: String,
#[serde(default)]
usage: Option<serde_json::Value>,
+ #[serde(default)]
+ total_cost_usd: Option<f64>,
+ /// Per model: `{"claude-opus-5-5": {"outputTokens": …, "costUSD": …}, …}`.
+ #[serde(default, rename = "modelUsage")]
+ model_usage: Option<serde_json::Value>,
}
impl ClaudeResult {
@@ -923,6 +928,54 @@ impl ClaudeResult {
.sum::<u64>();
(sum > 0).then_some(sum as usize)
}
+
+ /// The turn's tokens split into fresh input, cache reads, cache writes and output, plus its
+ /// cost when claude reported one. `None` when the result line had no usage.
+ fn split(&self) -> Option<super::TurnUsage> {
+ let u = self.usage.as_ref().filter(|u| u.is_object())?;
+ let n = |k: &str| u[k].as_u64().unwrap_or(0);
+ let split = super::TurnUsage {
+ fresh_input: n("input_tokens"),
+ cache_read: n("cache_read_input_tokens"),
+ cache_write: n("cache_creation_input_tokens"),
+ output: n("output_tokens"),
+ cost_usd: self.total_cost_usd.filter(|c| c.is_finite() && *c >= 0.0),
+ };
+ (split != super::TurnUsage::default()).then_some(split)
+ }
+
+ /// The model that did most of the turn's work (claude also calls a small model for chores).
+ fn main_model(&self) -> Option<String> {
+ let models = self.model_usage.as_ref()?.as_object()?;
+ models
+ .iter()
+ .max_by_key(|(_, m)| m["outputTokens"].as_u64().unwrap_or(0))
+ .map(|(name, _)| name.clone())
+ }
+}
+
+/// Saves a CLI turn's usage as one `model_usage` row, so the bot's Usage tab and the daily
+/// totals see CLI bots too. Never fails the turn.
+async fn record_cli_usage(input: &TurnInput, model: Option<String>, usage: &super::TurnUsage) {
+ let Some(db) = input.store.as_ref().filter(|_| !input.thread_id.is_empty()) else {
+ return;
+ };
+ let row = crate::db::usage::NewUsage {
+ kwant_id: input.kwant.id.clone(),
+ context_id: input.thread_id.clone(),
+ purpose: crate::db::usage::PURPOSE_REPLY,
+ model: model.or_else(|| input.model.clone()).unwrap_or_else(|| "claude".into()),
+ fresh_input: usage.fresh_input as i64,
+ cache_read: usage.cache_read as i64,
+ cache_write: usage.cache_write as i64,
+ output: usage.output as i64,
+ reported: true,
+ cost_usd: usage.cost_usd,
+ ..Default::default()
+ };
+ if let Err(e) = db.record_usage(&row).await {
+ tracing::warn!(error = %e, "could not record CLI usage");
+ }
}
#[async_trait]
@@ -1250,6 +1303,7 @@ impl Driver for CliDriver {
group.disarm();
let mut tokens = None;
+ let mut usage = None;
let output_str = if let Some(ref out_file) = codex_out_file {
let content = tokio::fs::read_to_string(out_file)
.await
@@ -1274,6 +1328,10 @@ impl Driver for CliDriver {
}
}
tokens = result.tokens();
+ usage = result.split();
+ if let Some(u) = &usage {
+ record_cli_usage(&input, result.main_model(), u).await;
+ }
result.result
}
// A failed run with no output is an error, not an empty reply
@@ -1306,6 +1364,7 @@ impl Driver for CliDriver {
text: output_str,
reasoning: Some(self.executed_via(effort)),
tokens_used: tokens,
+ usage,
..Default::default()
})
}
@@ -1341,6 +1400,23 @@ mod tests {
use super::*;
use crate::db::models::{Kwant, Message};
+ #[test]
+ fn claude_result_usage_is_split_into_fresh_and_cached() {
+ let stdout = include_str!("../../tests/fixtures/claude/result_with_usage.jsonl");
+ let result = ClaudeResult::parse(stdout).expect("result line");
+ let split = result.split().expect("usage");
+ assert_eq!(
+ split,
+ super::super::TurnUsage { fresh_input: 12, cache_read: 83_544, cache_write: 8_211, output: 487, cost_usd: Some(0.4189) }
+ );
+ // Cache reads are not fresh: only new input, cache writes and output count.
+ assert_eq!(split.fresh(), 12 + 8_211 + 487);
+ // The model that wrote the answer, not the helper model claude called on the side.
+ assert_eq!(result.main_model().as_deref(), Some("claude-opus-5-5"));
+ // Without usage there is no split, rather than an all-zero one.
+ assert_eq!(ClaudeResult::parse(r#"{"type":"result","result":"hi"}"#).and_then(|r| r.split()), None);
+ }
+
fn kinds(events: &[RuntimeEvent]) -> Vec<String> {
events
.iter()
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 7d05ccc9..aaaabdd2 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -636,11 +636,48 @@ pub async fn detect_available_models(
available
}
+/// What one turn used, split the way providers bill it. `tokens_used` stays the old
+/// cache-inclusive count; this is what the person pays for.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
+pub struct TurnUsage {
+ /// Input tokens neither read from nor written to the cache.
+ pub fresh_input: u64,
+ pub cache_read: u64,
+ pub cache_write: u64,
+ pub output: u64,
+ /// What the provider says the turn cost, when it says (the Claude CLI does).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cost_usd: Option<f64>,
+}
+
+impl TurnUsage {
+ /// Tokens the model really processed this turn: everything but cache reads. Cache writes
+ /// count, because they are new input (billed above plain input).
+ pub fn fresh(&self) -> u64 {
+ self.fresh_input + self.cache_write + self.output
+ }
+
+ pub fn add(&mut self, other: &TurnUsage) {
+ self.fresh_input += other.fresh_input;
+ self.cache_read += other.cache_read;
+ self.cache_write += other.cache_write;
+ self.output += other.output;
+ self.cost_usd = match (self.cost_usd, other.cost_usd) {
+ (Some(a), Some(b)) => Some(a + b),
+ (a, b) => a.or(b),
+ };
+ }
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TurnOutput {
pub text: String,
pub reasoning: Option<String>,
+ /// Every token the turn touched, cache reads included (see [`TurnUsage`] for the split).
pub tokens_used: usize,
+ /// The split, when the engine reported one.
+ #[serde(skip)]
+ pub usage: Option<TurnUsage>,
/// The model id the provider was asked for, when the driver resolved it itself (the API
/// driver with no model picked for the turn).
#[serde(skip)]
diff --git a/src/router/fallback.rs b/src/router/fallback.rs
index 243eebdf..aaaf6ef7 100644
--- a/src/router/fallback.rs
+++ b/src/router/fallback.rs
@@ -121,6 +121,17 @@ fn word_count(prompt: &str) -> usize {
.sum()
}
+/// Words of the person's own message below which an attachment alone doesn't earn the deep tier.
+const SHORT_WITH_ATTACHMENT: usize = 30;
+
+/// A short message whose weight is an attached file ("what's on this?" plus a PDF) gets at most
+/// "medium" effort: reading the file is work for the tools, not a reason for the deepest model.
+/// Asking for depth in so many words ("analyze this thoroughly") still keeps "high".
+pub fn cap_effort_for_attachment(prompt: &str, effort: &str) -> Option<&'static str> {
+ let (own, _files) = prompt.split_once("\n\n[Attached files]")?;
+ (effort.eq_ignore_ascii_case("high") && word_count(own) <= SHORT_WITH_ATTACHMENT && !has_deep_signal(own)).then_some("medium")
+}
+
/// Asks for a one-line answer ("in one line", "just tell me…").
const BRIEF: &[&str] = &["in one line", "one-liner", "in one word", "just tell me", "quick question"];
diff --git a/src/server/auth.rs b/src/server/auth.rs
index fe1b96bc..b2468736 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -336,6 +336,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
// sub-routes such as `/computer` (which machine the bots run on) and `/computer/window`:
// bots change the allowed ones through their `settings_update` action, never these routes
["", "api", "settings", ..] => *method != Method::GET && *method != Method::HEAD,
+ // Carrying on a chain that went over its token budget is the person's call
+ ["", "api", "chains", _, "continue"] => *method == Method::POST,
["", "api", "approvals", _, "resolve"] => *method == Method::POST,
["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,
["", "api", "kwants" | "teams", _] => *method == Method::DELETE,
@@ -850,6 +852,7 @@ mod tests {
assert!(person_only(&put, "/api/kwants/k1/approvals"));
assert!(!person_only(&get, "/api/kwants/k1/approvals"));
assert!(person_only(&post, "/api/settings"));
+ assert!(person_only(&post, "/api/chains/m1/continue"));
assert!(person_only(&put, "/api/settings/"));
assert!(!person_only(&get, "/api/settings"));
assert!(person_only(&put, "/api/settings/computer"));
diff --git a/src/server/budget.rs b/src/server/budget.rs
new file mode 100644
index 00000000..b68f8ef3
--- /dev/null
+++ b/src/server/budget.rs
@@ -0,0 +1,194 @@
+//! The chain token budget: one person message can start a chain of hand-offs, and every turn in it
+//! adds its fresh tokens (see [`crate::drivers::TurnUsage::fresh`]) to the dispatch's job (see
+//! [`super::turns`]). Once a chain is over the budget, no more teammates are handed the turn: the
+//! person gets one notice in the chat, and the chain carries on only when they press Continue on it
+//! or type "continue".
+
+use super::routes::TurnScope;
+use super::AppState;
+use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde_json::json;
+
+/// Setting key: fresh tokens one chain may use before hand-offs pause; 0 turns the guard off.
+pub const SETTING: &str = "chain_token_budget";
+pub const DEFAULT: u64 = 200_000;
+pub const MAX: u64 = 100_000_000;
+/// Message meta kind of the notice.
+pub const KIND: &str = "budget_paused";
+
+/// The budget in fresh tokens; 0 when the guard is off.
+pub async fn limit(state: &AppState) -> u64 {
+ state.db.get_setting(SETTING).await.ok().flatten().and_then(|v| v.parse::<u64>().ok()).unwrap_or(DEFAULT).min(MAX)
+}
+
+/// Whether the person's message asks a paused chain to carry on.
+pub fn is_continue(text: &str) -> bool {
+ let t = text.trim().trim_end_matches(['.', '!']).trim().to_lowercase();
+ matches!(t.as_str(), "continue" | "continue please" | "please continue" | "go on" | "keep going" | "carry on" | "go ahead")
+}
+
+/// Short token counts for the notice: 950, 12k, 1.2M.
+fn short(n: u64) -> String {
+ match n {
+ 0..=999 => n.to_string(),
+ 1_000..=999_999 => format!("{}k", n / 1_000),
+ _ => format!("{:.1}M", n as f64 / 1_000_000.0),
+ }
+}
+
+/// Before handing the turn on: when this chain is over the budget and `replies` would hand it to
+/// someone who hasn't spoken, saves one notice instead and returns true, so the caller stops.
+/// The notice keeps what is needed to carry on: who spoke, and the replies whose @mentions
+/// were waiting.
+pub(super) async fn pause_if_over(scope: &TurnScope, spoken: &[String], replies: &[(String, String)], user_prompt: &str) -> bool {
+ let budget = limit(&scope.state).await;
+ let used = scope.state.turns.job_tokens(&scope.job_id);
+ if budget == 0 || used <= budget || scope.teammates.is_empty() {
+ return false;
+ }
+ let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();
+ let mut waiting: Vec<String> = Vec::new();
+ for (from, text) in replies {
+ for i in crate::router::handoff_mentions(text, &names).targets {
+ let k = &scope.teammates[i];
+ if &k.name != from && !spoken.contains(&k.id) && !waiting.contains(&k.name) {
+ waiting.push(k.name.clone());
+ }
+ }
+ }
+ if waiting.is_empty() {
+ return false;
+ }
+ tracing::info!(job = %scope.job_id, used, budget, waiting = ?waiting, "chain over its token budget: hand-offs paused");
+ let text = format!(
+ "Paused before handing on to {}: this request has used {} fresh tokens, over the {} budget. \
+ Say \"continue\" to let them take their turn, or change the budget in App settings → Usage.",
+ waiting.join(", "),
+ short(used),
+ short(budget),
+ );
+ let meta = json!({
+ "kind": KIND,
+ "used": used,
+ "budget": budget,
+ "waiting": waiting,
+ "spoken": spoken,
+ "replies": replies.iter().map(|(from, text)| json!({"from": from, "text": text})).collect::<Vec<_>>(),
+ "user_prompt": user_prompt,
+ "resumed": false,
+ });
+ let msg = scope.message("system", "kwant", text);
+ scope.save(&msg, Some(meta)).await;
+ true
+}
+
+/// The newest paused-chain notice in a channel that hasn't been carried on, if it's the newest
+/// message from a bot or kwant (a later reply means the chat moved on).
+async fn open_pause(state: &AppState, channel_id: &str) -> Option<crate::db::models::Message> {
+ let recent = state.db.list_messages(channel_id, 10).await.ok()?;
+ let last = recent.into_iter().rev().find(|m| m.sender_role != "user")?;
+ let meta: serde_json::Value = serde_json::from_str(last.meta.as_deref()?).ok()?;
+ (meta["kind"] == KIND && meta["resumed"] != true).then_some(last)
+}
+
+/// Carries a paused chain on from its notice: marks it resumed and hands the turn to the bots
+/// that were waiting, as a new dispatch with its own budget. `Err` says why it can't.
+async fn resume(state: &AppState, notice_id: &str) -> Result<(), (StatusCode, &'static str)> {
+ let notice = state.db.get_message(notice_id).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "no such message"))?;
+ let mut meta: serde_json::Value =
+ notice.meta.as_deref().and_then(|m| serde_json::from_str(m).ok()).ok_or((StatusCode::BAD_REQUEST, "not a paused chain"))?;
+ if meta["kind"] != KIND {
+ return Err((StatusCode::BAD_REQUEST, "not a paused chain"));
+ }
+ if meta["resumed"] == true {
+ return Err((StatusCode::CONFLICT, "this chain was already continued"));
+ }
+ let channel_id = notice.channel_id.clone().ok_or((StatusCode::BAD_REQUEST, "not a channel message"))?;
+ let channel = state.db.get_channel(&channel_id).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "the channel is gone"))?;
+ let space = crate::db::spaces::SpaceId::new(&channel.space_id);
+ let all: Vec<Kwant> = state.db.list_kwants(&space).await.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not load the bots"))?;
+ let replies: Vec<(Kwant, String)> = meta["replies"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|r| {
+ let from = all.iter().find(|k| r["from"].as_str().is_some_and(|f| k.name == f))?;
+ Some((from.clone(), r["text"].as_str()?.to_string()))
+ })
+ .collect();
+ let Some((first, _)) = replies.first().cloned() else {
+ return Err((StatusCode::GONE, "the bots of this chain are gone"));
+ };
+ let spoken: Vec<String> = meta["spoken"].as_array().into_iter().flatten().filter_map(|s| s.as_str().map(str::to_string)).collect();
+ let user_prompt = meta["user_prompt"].as_str().unwrap_or_default().to_string();
+ meta["resumed"] = json!(true);
+ let _ = state.db.set_message_meta(notice_id, &meta).await;
+
+ let job = state.turns.start_job([channel_id.clone(), notice_id.to_string()]);
+ let scope = super::routes::scope_for(state, &first, Some(channel_id), None, &job, 0)
+ .await
+ .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not set up the chat"))?;
+ tokio::spawn(async move {
+ let _job = job;
+ super::routes::run_handoffs_boxed(&scope, &spoken, &replies, &user_prompt).await;
+ });
+ Ok(())
+}
+
+/// For `send_chat`: the person's "continue" right after a paused chain carries it on. Returns the
+/// notice's id when it did. Bots' tokens never get here (`from_person` false).
+pub async fn resume_if_continue(state: &AppState, channel_id: &str, prompt: &str, from_person: bool) -> Option<String> {
+ if !from_person || !is_continue(prompt) {
+ return None;
+ }
+ let notice = open_pause(state, channel_id).await?;
+ resume(state, &notice.id).await.ok()?;
+ Some(notice.id)
+}
+
+/// `POST /api/chains/:message_id/continue` (person only): the Continue button on the notice.
+pub async fn continue_chain(State(state): State<AppState>, Path(message_id): Path<String>) -> Response {
+ match resume(&state, &message_id).await {
+ Ok(()) => {
+ let msg = NewMessage {
+ channel_id: state.db.get_message(&message_id).await.ok().flatten().and_then(|m| m.channel_id),
+ direct_kwant_id: None,
+ sender_role: "user".into(),
+ sender_id: "user".into(),
+ text: "continue".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let _ = state.db.insert_message_with(&msg, &MessageExtra::default()).await;
+ Json(json!({"status": "continued"})).into_response()
+ }
+ Err((status, why)) => (status, Json(json!({"error": why}))).into_response(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn continue_words() {
+ for t in ["continue", "Continue.", " go on ", "Keep going!", "please continue", "go ahead"] {
+ assert!(is_continue(t), "{t}");
+ }
+ for t in ["continue with the plan but shorter", "don't continue", "stop", ""] {
+ assert!(!is_continue(t), "{t}");
+ }
+ }
+
+ #[test]
+ fn short_counts() {
+ assert_eq!((short(950), short(12_400), short(1_250_000)), ("950".into(), "12k".into(), "1.2M".into()));
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index c8ebc707..edfaa4b2 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -13,6 +13,7 @@ pub mod auth;
pub mod signin;
pub mod continuity;
pub mod model_usage;
+pub mod budget;
pub mod scheduler;
pub mod turns;
pub mod delegation;
@@ -315,6 +316,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/search", get(continuity::search))
.route("/api/kwants/:id/memories", get(continuity::list_memories).post(continuity::add_memory))
.route("/api/kwants/:id/model-usage", get(model_usage::get_usage))
+ .route("/api/usage/daily", get(model_usage::get_daily))
+ .route("/api/chains/:id/continue", post(budget::continue_chain))
.route(
"/api/kwants/:id/memories/:mid",
axum::routing::patch(continuity::update_memory).delete(continuity::delete_memory),
diff --git a/src/server/model_usage.rs b/src/server/model_usage.rs
index 570827ef..4a1c902d 100644
--- a/src/server/model_usage.rs
+++ b/src/server/model_usage.rs
@@ -46,3 +46,20 @@ pub async fn get_usage(
_ => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
+
+#[derive(Debug, Deserialize)]
+pub struct DailyQuery {
+ /// How many days back, today included (default 14, at most 90).
+ pub days: Option<i64>,
+}
+
+/// `GET /api/usage/daily`: every bot's tokens and cost per UTC day, newest first, for
+/// Settings → Usage. Covers CLI and API-key bots alike.
+pub async fn get_daily(State(state): State<AppState>, Query(q): Query<DailyQuery>) -> Response {
+ let days = q.days.unwrap_or(14).clamp(1, 90);
+ let since = (Utc::now() - chrono::Duration::days(days - 1)).date_naive().and_hms_opt(0, 0, 0).map(|t| t.and_utc());
+ match state.db.daily_usage(since.unwrap_or(DateTime::<Utc>::MIN_UTC)).await {
+ Ok(rows) => Json(json!({ "days": days, "rows": rows })).into_response(),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index dbe10718..81f8e5de 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -920,6 +920,10 @@ pub(super) fn run_handoffs_boxed<'a>(
}
async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(Kwant, String)], user_prompt: &str) {
+ let named: Vec<(String, String)> = replies.iter().map(|(k, t)| (k.name.clone(), t.clone())).collect();
+ if super::budget::pause_if_over(scope, already_spoken, &named, user_prompt).await {
+ return;
+ }
if let [(from, text)] = replies {
if is_team_channel_lead(scope, from).await {
return delegate_mentions(scope, from, text, user_prompt, already_spoken).await;
@@ -991,6 +995,13 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
queue.push_front((kwant, from, from_text, after));
break;
}
+ // Over the chain's token budget: one notice, and the rest wait for the person's "continue"
+ let waiting: Vec<(String, String)> =
+ std::iter::once((from.clone(), from_text.clone())).chain(queue.iter().map(|(_, f, t, _)| (f.clone(), t.clone()))).collect();
+ if super::budget::pause_if_over(scope, &spoken, &waiting, user_prompt).await {
+ queue.clear();
+ break;
+ }
let waited_for = match after.as_ref().map(|p| (names_of(p), outcomes.get(p))) {
// Waits for a teammate whose turn hasn't run: it was never handed one, so don't wait
Some((_, None)) | None => None,
@@ -1800,6 +1811,13 @@ async fn run_kwant_turn_inner(
reasoning: "Fallback routing".into(),
},
};
+ let mut route = route;
+ if opts.routed.is_none() {
+ if let Some(capped) = crate::router::fallback::cap_effort_for_attachment(&prompt, &route.effort_level) {
+ route.reasoning = format!("{} · effort capped at {capped}: a short message with an attachment", route.reasoning);
+ route.effort_level = capped.into();
+ }
+ }
let route = crate::router::apply_preferred_model(route, &target_kwant.preferred_model);
let target_model = route.selected_model.clone();
@@ -2357,6 +2375,10 @@ async fn run_kwant_turn_inner(
}
}
+ // Counts toward the chain's token budget (see `super::budget`)
+ let fresh = output.usage.map_or(output.tokens_used as u64, |u| u.fresh());
+ state.turns.add_job_tokens(&scope.job_id, fresh);
+
let saved = match &opts.discussion {
None => Some((
output.text.clone(),
@@ -2386,6 +2408,9 @@ async fn run_kwant_turn_inner(
let mut meta = ran_on
.as_ref()
.map(|r| serde_json::json!({ "ran_on": r.to_json(output.model.as_deref(), pick, &effort_level) }));
+ if let Some(usage) = &output.usage {
+ meta.get_or_insert_with(|| serde_json::json!({}))["usage"] = serde_json::json!(usage);
+ }
if let Some(routing) = &opts.routing {
meta.get_or_insert_with(|| serde_json::json!({}))["routing"] = routing.clone();
}
@@ -2436,6 +2461,7 @@ async fn chat_space(state: &AppState, payload: &SendChatPayload) -> Result<Space
pub async fn send_chat(
State(state): State<AppState>,
+ headers: axum::http::HeaderMap,
axum::extract::RawQuery(query): axum::extract::RawQuery,
Json(payload): Json<SendChatPayload>,
) -> axum::response::Response {
@@ -2452,7 +2478,8 @@ pub async fn send_chat(
if let Err(r) = super::spaces::ids_guard(&state, query.as_deref(), &rows).await {
return r;
}
- match send_chat_inner(state, payload).await {
+ let from_person = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "").await.is_ok();
+ match send_chat_inner(state, payload, from_person).await {
Ok(json) => json.into_response(),
Err(status) => status.into_response(),
}
@@ -2461,6 +2488,7 @@ pub async fn send_chat(
async fn send_chat_inner(
state: AppState,
mut payload: SendChatPayload,
+ from_person: bool,
) -> Result<Json<serde_json::Value>, StatusCode> {
let uploads = super::attachments::check_uploads(&state, &payload.attachment_ids).await?;
if let Some(thread_id) = payload.thread_id.clone() {
@@ -2694,6 +2722,13 @@ async fn send_chat_inner(
payload.prompt.push_str(&note);
}
+ // "continue" after a chain paused at its token budget carries that chain on
+ if let Some(cid) = payload.channel_id.as_deref() {
+ if let Some(notice) = super::budget::resume_if_continue(&state, cid, &payload.prompt, from_person).await {
+ return Ok(Json(json!({ "status": "continued", "user_message_id": saved_user_msg.id, "notice_id": notice })));
+ }
+ }
+
// Typed instead of tapped: the answer closes the bot's open question, and a turn still waiting
// on it carries on with it (no second turn)
if let Some((asker, Some(qid))) = &awaiting {
@@ -3122,6 +3157,8 @@ pub struct SettingsResponse {
pub captcha_timeout_minutes: u64,
/// Hours before a bot waiting on the person reminds them once; 0 = never.
pub waiting_follow_up_hours: i64,
+ /// Fresh tokens one chain may use before hand-offs pause (see `super::budget`); 0 = off.
+ pub chain_token_budget: u64,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3150,6 +3187,7 @@ pub struct SaveSettingsPayload {
pub location: Option<String>,
pub captcha_timeout_minutes: Option<u64>,
pub waiting_follow_up_hours: Option<i64>,
+ pub chain_token_budget: Option<u64>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3187,6 +3225,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
.filter(|m| (1..=super::human_steps::MAX_CAPTCHA_TIMEOUT_MINUTES).contains(m))
.unwrap_or(super::human_steps::DEFAULT_CAPTCHA_TIMEOUT_MINUTES),
waiting_follow_up_hours: super::waiting::follow_up_hours(&state).await,
+ chain_token_budget: super::budget::limit(&state).await,
}))
}
@@ -3230,6 +3269,9 @@ pub async fn save_settings(
if payload.waiting_follow_up_hours.is_some_and(|h| !(0..=max_hours).contains(&h)) {
return bad(format!("waiting_follow_up_hours must be 0–{max_hours}"));
}
+ if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {
+ return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));
+ }
let timezone = payload.timezone.as_deref().map(crate::routines::canonical_tz);
if let Some(tz) = timezone.as_deref().filter(|t| !t.is_empty()) {
if let Err(e) = check_tz(tz) {
@@ -3297,6 +3339,9 @@ pub async fn save_settings(
let _ = state.db.set_setting(GLOBAL_SETTING, &global.to_string()).await;
state.turns.limiter.set_limits(per_agent, global);
}
+ if let Some(n) = payload.chain_token_budget {
+ let _ = state.db.set_setting(super::budget::SETTING, &n.to_string()).await;
+ }
if let Some(m) = payload.delegation_follow_up_minutes {
let _ = state.db.set_setting(super::delegation::FOLLOW_UP_SETTING, &m.to_string()).await;
}
diff --git a/src/server/turns.rs b/src/server/turns.rs
index f44a3a09..cef8e849 100644
--- a/src/server/turns.rs
+++ b/src/server/turns.rs
@@ -27,6 +27,8 @@ pub const GLOBAL_SETTING: &str = "max_turns_global";
struct Job {
keys: Vec<String>,
token: CancellationToken,
+ /// Fresh tokens (see [`crate::drivers::TurnUsage::fresh`]) its turns used so far.
+ fresh_tokens: u64,
}
/// A turn the UI can show: running, or waiting for a slot.
@@ -88,7 +90,7 @@ impl TurnRegistry {
let token = CancellationToken::new();
let mut keys: Vec<String> = keys.into_iter().map(Into::into).filter(|k: &String| !k.is_empty()).collect();
keys.push(id.clone());
- self.lock().jobs.insert(id.clone(), Job { keys, token: token.clone() });
+ self.lock().jobs.insert(id.clone(), Job { keys, token: token.clone(), fresh_tokens: 0 });
JobGuard { registry: self.clone(), id, token }
}
@@ -99,6 +101,22 @@ impl TurnRegistry {
}
}
+ /// Adds a finished turn's fresh tokens to its job; returns the job's new total.
+ pub fn add_job_tokens(&self, job_id: &str, fresh: u64) -> u64 {
+ match self.lock().jobs.get_mut(job_id) {
+ Some(job) => {
+ job.fresh_tokens = job.fresh_tokens.saturating_add(fresh);
+ job.fresh_tokens
+ }
+ None => 0,
+ }
+ }
+
+ /// Fresh tokens a job's turns used so far (0 for a finished job).
+ pub fn job_tokens(&self, job_id: &str) -> u64 {
+ self.lock().jobs.get(job_id).map_or(0, |j| j.fresh_tokens)
+ }
+
fn finish_job(&self, id: &str) {
self.lock().jobs.remove(id);
}
diff --git a/tests/chain_budget_test.rs b/tests/chain_budget_test.rs
new file mode 100644
index 00000000..3b97f8c2
--- /dev/null
+++ b/tests/chain_budget_test.rs
@@ -0,0 +1,244 @@
+//! Usage visibility for CLI bots and the chain token budget. A fake claude CLI reports a turn of
+//! heavy usage (mostly cache reads) and @mentions a teammate when asked to, so one person message
+//! can start a chain of hand-offs. Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Message, Database},
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// Replies "answer" plus "@<name>" for a prompt with "MENTION:<name>", but only on the first turn
+/// of a chain (a hand-off turn says "handed this conversation to you"), so a chain is two turns.
+/// Every turn reports 12 new input, 8,211 cache-write, 83,544 cache-read and 487 output tokens,
+/// $0.42: 8,710 fresh tokens.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+mention=$(printf '%s\n' "$last" | sed -n 's/.*MENTION:\([A-Za-z0-9_]*\).*/\1/p' | head -n 1)
+case "$last" in *"handed this conversation to you"*) mention="" ;; esac
+out="answer"
+[ -n "$mention" ] && out="$out @$mention"
+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"$out\",\"total_cost_usd\":0.42,\"usage\":{\"input_tokens\":12,\"cache_creation_input_tokens\":8211,\"cache_read_input_tokens\":83544,\"output_tokens\":487},\"modelUsage\":{\"claude-opus-5-5\":{\"outputTokens\":487}}}"
+"#;
+
+const FRESH_PER_TURN: u64 = 12 + 8_211 + 487;
+
+fn fake_cli() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))
+}
+
+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (s, v) = call(app, method, uri, body).await;
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ channel: String,
+ _tmp: tempfile::TempDir,
+}
+
+/// Ann and Bob on the fake claude in one channel; Bob leads, so Ann's mention of him is a plain
+/// hand-off in the channel.
+async fn setup() -> Env {
+ fake_cli();
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let bot = |name: &str| {
+ json!({"name": name, "title": format!("{name} the tester"), "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"})
+ };
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": bob, "member_kwants": [ann]}))).await;
+ Env { app, state, channel: c["id"].as_str().unwrap().to_string(), _tmp: tmp }
+}
+
+impl Env {
+ async fn say(&self, prompt: &str) -> Value {
+ ok(&self.app, "POST", "/api/chat/send", Some(json!({"channel_id": self.channel, "prompt": prompt, "sender_id": "user"}))).await
+ }
+
+ async fn messages(&self) -> Vec<Message> {
+ self.state.db.list_messages(&self.channel, 100).await.unwrap()
+ }
+
+ async fn replies_from(&self, name: &str) -> usize {
+ self.messages().await.iter().filter(|m| m.sender_role == "kwant" && m.sender_id == name).count()
+ }
+
+ async fn notices(&self) -> Vec<Message> {
+ self.messages().await.into_iter().filter(|m| meta(m)["kind"] == "budget_paused").collect()
+ }
+
+ async fn kwant_id(&self, name: &str) -> String {
+ let kwants = ok(&self.app, "GET", "/api/kwants", None).await;
+ kwants.as_array().unwrap().iter().find(|k| k["name"] == name).unwrap()["id"].as_str().unwrap().to_string()
+ }
+
+ async fn wait_for<F, Fut>(&self, what: &str, mut check: F)
+ where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = bool>,
+ {
+ for _ in 0..200 {
+ if check().await {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("timed out waiting for {what}: {:#?}", self.messages().await.iter().map(|m| (&m.sender_id, &m.text)).collect::<Vec<_>>());
+ }
+
+ /// Lets anything still on its way arrive.
+ async fn settle(&self) {
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ }
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+#[tokio::test]
+async fn a_cli_reply_shows_its_usage_split_and_is_counted_per_bot_and_day() {
+ let env = setup().await;
+ env.say("@Ann hello").await;
+ env.wait_for("Ann's reply", || async { env.replies_from("Ann").await == 1 }).await;
+ env.settle().await;
+
+ let reply = env.messages().await.into_iter().find(|m| m.sender_id == "Ann").unwrap();
+ // tokens_used keeps its old, cache-inclusive meaning; the split is in the meta
+ assert_eq!(reply.tokens_used, 12 + 8_211 + 83_544 + 487);
+ assert_eq!(
+ meta(&reply)["usage"],
+ json!({"fresh_input": 12, "cache_read": 83_544, "cache_write": 8_211, "output": 487, "cost_usd": 0.42})
+ );
+
+ // One model_usage row per CLI turn, on the bot's Usage tab
+ let ann = env.kwant_id("Ann").await;
+ let usage = ok(&env.app, "GET", &format!("/api/kwants/{ann}/model-usage"), None).await;
+ let rows = usage["recent"].as_array().unwrap();
+ assert_eq!(rows.len(), 1, "{usage}");
+ assert_eq!(rows[0]["model"], "claude-opus-5-5");
+ assert_eq!((rows[0]["fresh_input_tokens"].as_i64(), rows[0]["cache_read_tokens"].as_i64()), (Some(12), Some(83_544)));
+ assert_eq!(rows[0]["cost_usd"].as_f64(), Some(0.42));
+
+ // Settings → Usage: per bot and day
+ let daily = ok(&env.app, "GET", "/api/usage/daily?days=7", None).await;
+ let rows = daily["rows"].as_array().unwrap();
+ assert_eq!(rows.len(), 1, "{daily}");
+ assert_eq!((rows[0]["kwant_id"].as_str(), rows[0]["kwant_name"].as_str()), (Some(ann.as_str()), Some("Ann")));
+ assert_eq!(rows[0]["day"].as_str().unwrap(), chrono::Utc::now().format("%Y-%m-%d").to_string());
+ assert_eq!((rows[0]["output_tokens"].as_i64(), rows[0]["cache_write_tokens"].as_i64()), (Some(487), Some(8_211)));
+ assert_eq!(rows[0]["cost_usd"].as_f64(), Some(0.42));
+}
+
+#[tokio::test]
+async fn a_chain_over_its_budget_pauses_hand_offs_until_the_person_says_continue() {
+ let env = setup().await;
+ // One turn fits, a second doesn't
+ ok(&env.app, "POST", "/api/settings", Some(json!({"chain_token_budget": FRESH_PER_TURN - 1}))).await;
+ assert_eq!(ok(&env.app, "GET", "/api/settings", None).await["chain_token_budget"].as_u64(), Some(FRESH_PER_TURN - 1));
+
+ env.say("@Ann look at this MENTION:Bob").await;
+ env.wait_for("the notice", || async { !env.notices().await.is_empty() }).await;
+ env.settle().await;
+ assert_eq!(env.replies_from("Ann").await, 1);
+ assert_eq!(env.replies_from("Bob").await, 0, "no hand-off over the budget");
+ let notices = env.notices().await;
+ assert_eq!(notices.len(), 1, "one notice");
+ assert!(notices[0].text.contains("Bob") && notices[0].text.contains("8k fresh tokens"), "{}", notices[0].text);
+ assert_eq!(meta(&notices[0])["waiting"], json!(["Bob"]));
+
+ // The person says continue: Bob takes the turn he was handed, with a fresh budget
+ let sent = env.say("continue").await;
+ assert_eq!(sent["status"], "continued", "{sent}");
+ env.wait_for("Bob's turn", || async { env.replies_from("Bob").await == 1 }).await;
+ env.settle().await;
+ assert_eq!(env.replies_from("Ann").await, 1, "\"continue\" isn't a new request for Ann");
+ assert_eq!(meta(&env.notices().await[0])["resumed"], true);
+ // Already carried on: the button is refused
+ let (s, _) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notices[0].id), None).await;
+ assert_eq!(s, StatusCode::CONFLICT);
+}
+
+#[tokio::test]
+async fn the_continue_button_carries_a_paused_chain_on() {
+ let env = setup().await;
+ ok(&env.app, "POST", "/api/settings", Some(json!({"chain_token_budget": 1}))).await;
+ env.say("@Ann look at this MENTION:Bob").await;
+ env.wait_for("the notice", || async { !env.notices().await.is_empty() }).await;
+ let notice = env.notices().await.remove(0);
+ ok(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
+ env.wait_for("Bob's turn", || async { env.replies_from("Bob").await == 1 }).await;
+ assert!(env.messages().await.iter().any(|m| m.sender_role == "user" && m.text == "continue"), "the person's continue is in the chat");
+ // Not a notice: refused
+ let first = env.messages().await.remove(0);
+ let (s, _) = call(&env.app, "POST", &format!("/api/chains/{}/continue", first.id), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+}
+
+#[tokio::test]
+async fn a_budget_of_zero_never_pauses() {
+ let env = setup().await;
+ ok(&env.app, "POST", "/api/settings", Some(json!({"chain_token_budget": 0}))).await;
+ env.say("@Ann look at this MENTION:Bob").await;
+ env.wait_for("Bob's turn", || async { env.replies_from("Bob").await == 1 }).await;
+ env.settle().await;
+ assert!(env.notices().await.is_empty());
+}
diff --git a/tests/fixtures/claude/result_with_usage.jsonl b/tests/fixtures/claude/result_with_usage.jsonl
new file mode 100644
index 00000000..6fd49d39
--- /dev/null
+++ b/tests/fixtures/claude/result_with_usage.jsonl
@@ -0,0 +1,3 @@
+{"type":"system","subtype":"init","session_id":"0b5f0d4e-usage-fixture","model":"claude-opus-5-5"}
+{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"The total is 412 EUR."}]},"session_id":"0b5f0d4e-usage-fixture"}
+{"type":"result","subtype":"success","is_error":false,"duration_ms":18234,"num_turns":3,"result":"The total is 412 EUR.","session_id":"0b5f0d4e-usage-fixture","total_cost_usd":0.4189,"usage":{"input_tokens":12,"cache_creation_input_tokens":8211,"cache_read_input_tokens":83544,"output_tokens":487,"service_tier":"standard"},"modelUsage":{"claude-haiku-5-5":{"inputTokens":402,"outputTokens":31,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"costUSD":0.0006},"claude-opus-5-5":{"inputTokens":12,"outputTokens":487,"cacheReadInputTokens":83544,"cacheCreationInputTokens":8211,"costUSD":0.4183}}}
diff --git a/tests/model_usage_test.rs b/tests/model_usage_test.rs
index 03978ad9..4a58526c 100644
--- a/tests/model_usage_test.rs
+++ b/tests/model_usage_test.rs
@@ -20,6 +20,7 @@ fn call_row(kwant: &str, purpose: &'static str, fresh: i64) -> NewUsage {
tools_chars: 900,
system_chars: 5000,
messages_chars: 700,
+ cost_usd: None,
}
}
diff --git a/tests/router_test.rs b/tests/router_test.rs
index 9447970e..975b65c5 100644
--- a/tests/router_test.rs
+++ b/tests/router_test.rs
@@ -856,3 +856,19 @@ fn a_negation_reaches_to_the_end_of_its_clause() {
assert_ne!(heuristic_effort("Don't refactor the module yet, just rename it", "chat"), "high");
assert_eq!(heuristic_effort("Please don't refactor anything, just tell me what time zone Paris is in", "chat"), "low", "a01");
}
+
+#[test]
+fn short_follow_up_with_attachment_does_not_get_the_deep_tier() {
+ use kwnt::router::fallback::cap_effort_for_attachment as cap;
+ let files = "\n\n[Attached files]\nThe user attached these files.\n- report.pdf (2 MB)";
+ // A one-line question about a file: "high" comes down to "medium".
+ assert_eq!(cap(&format!("what's the total on this?{files}"), "high"), Some("medium"));
+ assert_eq!(cap(&format!("Thoughts?{files}"), "High"), Some("medium"));
+ // Lower efforts and messages without files are left alone.
+ assert_eq!(cap(&format!("what's the total on this?{files}"), "medium"), None);
+ assert_eq!(cap("what's the total on this?", "high"), None);
+ // Asking for depth, or a long message, keeps "high".
+ assert_eq!(cap(&format!("do a deep dive on this{files}"), "high"), None);
+ let long = "please go through every line of this and compare it with last month and tell me where we are off ".repeat(2);
+ assert_eq!(cap(&format!("{long}{files}"), "high"), None);
+}