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
0.9.5: per-bot monthly budgets in the app (#536)
Oleksandr Ivanchenkof80d1a8656e2
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex fdfeb322..ddc4d597 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -153,6 +153,8 @@ import { PromptContext, suggestedPrompts } from './suggestedPrompts';import { isNotificationOpen, placeOfNotification, showDeviceNotification } from './push';import { requestSpendStopFocus } from './spendStop';import { SpendStopNeedsYou } from './components/SpendStop';+import { BudgetNeedsYou } from './components/BotBudget';+import { budgetStore, isBudgetMessage, requestBudgetFocus } from './botBudget';import { EMPTY_PILL, NUDGES_SETTING_EVENT, browserIconDoc, createArrivals, createNudgeIcon, nudgesEnabled, pillAdd, pillPrune, setAppBadgeCount, shouldPill, type Nudge, type PillState } from './attention';import { NeedsYouPill } from './components/NeedsYouPill';import { DevModeError, devApi, devStore, devTeamRefs } from './devMode';@@ -480,6 +482,18 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setSpendStopSeq((n) => n + 1);showPage('inbox', 'new');};+ // 0.9.5 monthly budgets: one shared list, re-read on a space switch and every minute (and on a budget notice, below)+ useEffect(() => {+ budgetStore.reset();+ void budgetStore.refresh();+ const t = window.setInterval(() => {+ if (document.visibilityState !== 'hidden') void budgetStore.refresh();+ }, 60_000);+ return () => window.clearInterval(t);+ }, [space.id]);+ // Raise the limit: the bot's settings at Usage, the budget's first field focused+ const raiseBudgetRef = useRef<(kwantId: string) => void>(() => {});+ const raiseBudget = useCallback((kwantId: string) => raiseBudgetRef.current(kwantId), []);// Home: the chat list on a phone, the open chat elsewhere, with nothing on top.const openHome = () => {if (spaceSettingsTab) closeSpaceSettings();@@ -1235,6 +1249,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({case 'message_added':case 'MessageAdded': {const m: ChatMessage | undefined = event.data?.message;+ if (m && isBudgetMessage(m)) void budgetStore.refresh();const ctx = m ? messageContextId(m) : null;if (!m?.id || !ctx) break;if (m.thread_id) knownThreadsRef.current.add(m.thread_id);@@ -2072,6 +2087,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setEditingKwant(kwant);playSfx('click');};+ raiseBudgetRef.current = (kwantId: string) => {+ const k = kwants.find((x) => x.id === kwantId);+ if (!k) return;+ requestBudgetFocus(kwantId);+ openAgentSettings(k, 'usage');+ };openQuestionRef.current = (kwantId: string) => {const q = latestOpenQuestion(questionsRef.current, kwantId);if (!q) return false;@@ -3964,6 +3985,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({<><PrepushNeedsYou cards={prepush.cards} names={kwantNames} onOpen={openPrepush} /><SpendStopNeedsYou refreshKey={spendStopSeq} onOpenSettings={openUsageSettings} />+ <BudgetNeedsYou onRaise={raiseBudget} /></>}/>@@ -4152,6 +4174,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({welcome={getStartedCard && messages.length === 0 ? getStartedCard : undefined}onOpenAccounts={openSettings}onOpenUsage={openUsageSettings}+ budgetBotId={!isChannel ? currentKwant?.id ?? null : null}+ onRaiseBudget={raiseBudget}onOpenComputerSettings={openComputerSettings}onChangeTeamFolder={(teamId) => {const t = teams.find((x) => x.id === teamId);@@ -4526,6 +4550,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({tokensUsed={tokensUsed}onOpenApiKeys={() => openSpaceSettings('apps', 'accounts')}focusRow={settingsFocusRow}+ onOpenBotBudget={raiseBudget}/></Suspense>}diff --git a/frontend/src/botBudget.ts b/frontend/src/botBudget.tsnew file mode 100644index 00000000..2adb0c3f--- /dev/null+++ b/frontend/src/botBudget.ts@@ -0,0 +1,343 @@+// Per-bot monthly budget (0.9.5, backend G2 since 0.9.0): fresh tokens and/or dollars per calendar+// month in the person's time zone. At 80% the bot warns once; at 100% it finishes its turn and starts+// nothing new until the person raises the limit, continues this month, or the next month starts.+// Every number on screen is the server's (`src/server/bot_budget.rs`); nothing here counts spend.+import { usdText } from './missions';+import { compactTokens } from './modelUsage';+import { stopTokensFrom, stopUsdFrom } from './spendStop';++export type BudgetState = 'off' | 'under' | 'warn' | 'paused' | 'continued';++/** `GET /api/kwants/:id/budget`, one bot's month against its budget. */+export interface BotBudget {+ kwant_id: string;+ kwant_name: string;+ /** `YYYY-MM` in `timezone`. */+ month: string;+ timezone: string;+ used_tokens: number;+ used_usd: number;+ /** 0 when off. */+ budget_tokens: number;+ /** 0 when off. */+ budget_usd: number;+ /** The higher of the set limits' percentages; 0 when off. */+ percent: number;+ over: 'tokens' | 'usd' | null;+ state: BudgetState;+ paused_since: string | null;+ /** Local 00:00 on the 1st of next month. */+ resets_at: string;+ /** Some turn this month reported no usage: the numbers are partly the server's estimate. */+ estimated: boolean;+ /** No turn this month reported a cost: dollars can't be counted for this bot's engine. */+ cost_unreported: boolean;+}++const STATES: readonly BudgetState[] = ['off', 'under', 'warn', 'paused', 'continued'];+const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0);+const str = (v: unknown): string => (typeof v === 'string' ? v : '');++export function parseBudget(x: unknown): BotBudget | null {+ if (!x || typeof x !== 'object') return null;+ const o = x as Record<string, unknown>;+ if (typeof o.kwant_id !== 'string' || !STATES.includes(o.state as BudgetState)) return null;+ return {+ kwant_id: o.kwant_id,+ kwant_name: str(o.kwant_name),+ month: str(o.month),+ timezone: str(o.timezone),+ used_tokens: num(o.used_tokens),+ used_usd: num(o.used_usd),+ budget_tokens: num(o.budget_tokens),+ budget_usd: num(o.budget_usd),+ percent: num(o.percent),+ over: o.over === 'tokens' || o.over === 'usd' ? o.over : null,+ state: o.state as BudgetState,+ paused_since: typeof o.paused_since === 'string' ? o.paused_since : null,+ resets_at: str(o.resets_at),+ estimated: o.estimated === true,+ cost_unreported: o.cost_reported === false,+ };+}++export const hasBudget = (b: Pick<BotBudget, 'state'> | null | undefined): boolean => !!b && b.state !== 'off';+/** The bot is paused at its budget: no new work until the person acts or the month ends. */+export const isPaused = (b: Pick<BotBudget, 'state'> | null | undefined): boolean => b?.state === 'paused';+/** 80% or more and not yet paused (and not continued). */+export const isWarn = (b: Pick<BotBudget, 'state'> | null | undefined): boolean => b?.state === 'warn';++/** The meter's fill, 0–100. */+export const meterPercent = (b: Pick<BotBudget, 'percent'>): number => Math.max(0, Math.min(100, Math.round(b.percent)));++export const PAUSED_LINE = 'Paused: monthly budget reached';+/** The sidebar row's short form; the bar, Inbox and settings keep the full line (#536 Mira F6). */+export const PAUSED_ROW_LINE = 'Paused: budget reached';++function monthName(month: string): string {+ const m = /^(\d{4})-(\d{2})$/.exec(month);+ if (!m) return 'this month';+ return new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, 1)).toLocaleDateString('en-US', { month: 'long', timeZone: 'UTC' });+}++/** "December 1", the day the budget starts over, in the budget's own time zone. */+export function resetDay(b: Pick<BotBudget, 'resets_at' | 'timezone'>): string | null {+ const d = new Date(b.resets_at);+ if (!b.resets_at || Number.isNaN(d.getTime())) return null;+ const opts: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric' };+ try {+ return d.toLocaleDateString('en-US', { ...opts, timeZone: b.timezone || 'UTC' });+ } catch {+ return d.toLocaleDateString('en-US', { ...opts, timeZone: 'UTC' });+ }+}++/** Which limit the line talks about: the one hit, else the one with the higher share. */+function leadIsUsd(b: Pick<BotBudget, 'over' | 'used_tokens' | 'budget_tokens' | 'used_usd' | 'budget_usd'>): boolean {+ if (b.over) return b.over === 'usd';+ const pt = b.budget_tokens > 0 ? b.used_tokens / b.budget_tokens : -1;+ const pu = b.budget_usd > 0 ? b.used_usd / b.budget_usd : -1;+ return pu > pt;+}++/** "1.6M of 2M fresh tokens in November" or "$16.40 of $20.00 in November" (with "about" when estimated). */+export function usedLine(b: Pick<BotBudget, 'over' | 'used_tokens' | 'budget_tokens' | 'used_usd' | 'budget_usd' | 'month' | 'estimated'>): string {+ const about = b.estimated ? 'about ' : '';+ const month = monthName(b.month);+ if (b.budget_tokens <= 0 && b.budget_usd <= 0)+ return `${about}${compactTokens(b.used_tokens)} fresh tokens${b.used_usd > 0 ? ` · ${usdText(b.used_usd)}` : ''} in ${month}`;+ if (leadIsUsd(b)) return `${about}${usdText(b.used_usd) ?? '$0.00'} of ${usdText(b.budget_usd)} in ${month}`;+ return `${about}${compactTokens(b.used_tokens)} of ${compactTokens(b.budget_tokens)} fresh tokens in ${month}`;+}++/** The line under the meter: what the bot does now, in plain words. */+export function stateLine(b: BotBudget): string {+ const day = resetDay(b);+ const on = day ? ` on ${day}` : ' next month';+ const until = day ? ` until ${day}` : ' until next month';+ switch (b.state) {+ case 'off':+ return `No budget: ${b.kwant_name || 'This bot'} can use as much as it needs.`;+ case 'under':+ return `The count starts over${on}.`;+ case 'warn':+ return `${meterPercent(b)}% used. At 100% it finishes what it’s doing and starts nothing new${until}.`;+ case 'paused':+ return `${PAUSED_LINE}. ${b.kwant_name || 'This bot'} starts nothing new until you raise the limit, continue this month, or ${day ?? 'next month'}.`;+ case 'continued':+ return `Continued for ${monthName(b.month)}: the limit is ignored${until}.`;+ }+}++// ---------------------------------------------------------------- the settings fields++export interface BudgetFields {+ tokens: string;+ usd: string;+}++export const fieldsFromBudget = (b: Pick<BotBudget, 'budget_tokens' | 'budget_usd'> | null): BudgetFields => ({+ tokens: b && b.budget_tokens > 0 ? String(b.budget_tokens) : '',+ usd: b && b.budget_usd > 0 ? String(b.budget_usd) : '',+});++export function budgetTokensError(raw: string): string | null {+ if (stopTokensFrom(raw) !== null) return null;+ const s = raw.trim().toLowerCase().replace(/[\s_,]/g, '').replace(/tokens?$/, '');+ if (/^(\d+(?:\.\d+)?)([km]?)$/.test(s)) return 'At most 10 billion tokens a month.';+ return 'Enter a number of tokens, like 500k or 2M, or leave it empty.';+}++export function budgetUsdError(raw: string): string | null {+ if (stopUsdFrom(raw) !== null) return null;+ const s = raw.trim().replace(/^\$/, '').replace(/[\s,]/g, '');+ if (/^\d+(?:\.\d{1,2})?$/.test(s)) return 'At most $100,000 a month.';+ return 'Enter dollars, like 20 or 2.50, or leave it empty.';+}++/** The POST body (0 or null turns a limit off), or null while a field can't be saved. */+export function budgetBody(f: BudgetFields): { budget_tokens: number | null; budget_usd: number | null } | null {+ const t = stopTokensFrom(f.tokens);+ const u = stopUsdFrom(f.usd);+ if (t === null || u === null) return null;+ return { budget_tokens: t > 0 ? t : null, budget_usd: u > 0 ? u : null };+}++/** True when the fields say something other than what is saved. */+export function fieldsChanged(f: BudgetFields, b: Pick<BotBudget, 'budget_tokens' | 'budget_usd'> | null): boolean {+ const body = budgetBody(f);+ if (!body) return true;+ return (body.budget_tokens ?? 0) !== (b?.budget_tokens ?? 0) || (body.budget_usd ?? 0) !== (b?.budget_usd ?? 0);+}++// ---------------------------------------------------------------- the API++export class BudgetError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ }+}++type Fetch = typeof fetch;++async function call<T>(send: Fetch, url: string, read: (b: unknown) => T | null, init: RequestInit | undefined, failed: string): Promise<T> {+ let r: Response;+ try {+ r = await send(url, { cache: 'no-store', ...(init?.body ? { headers: { 'Content-Type': 'application/json' } } : {}), ...init });+ } catch {+ throw new BudgetError('Couldn’t reach the server. Try again.', 0);+ }+ let body: unknown = null;+ try {+ body = await r.json();+ } catch {+ /* not JSON */+ }+ if (!r.ok) {+ const err = body && typeof (body as { error?: unknown }).error === 'string' ? (body as { error: string }).error : '';+ if (r.status === 403) throw new BudgetError('Only you can change a bot’s budget, signed in on this device.', 403);+ throw new BudgetError(err && (r.status === 400 || r.status === 409) ? err : failed, r.status);+ }+ const v = read(body);+ if (v === null) throw new BudgetError('Couldn’t read the budget.', r.status);+ return v;+}++export interface BudgetList {+ month: string;+ resets_at: string;+ bots: BotBudget[];+}++export function parseBudgetList(x: unknown): BudgetList | null {+ if (!x || typeof x !== 'object') return null;+ const o = x as Record<string, unknown>;+ if (!Array.isArray(o.bots)) return null;+ return { month: str(o.month), resets_at: str(o.resets_at), bots: o.bots.map(parseBudget).filter((b): b is BotBudget => !!b) };+}++const enc = encodeURIComponent;++export const botBudgetApi = (send: Fetch = (...a) => fetch(...a)) => ({+ get: (id: string) => call(send, `/api/kwants/${enc(id)}/budget`, parseBudget, undefined, 'Couldn’t load the budget.'),+ set: (id: string, body: { budget_tokens: number | null; budget_usd: number | null }) =>+ call(send, `/api/kwants/${enc(id)}/budget`, parseBudget, { method: 'POST', body: JSON.stringify(body) }, 'Couldn’t save the budget. Try again.'),+ /** Ignores the budget until the month ends (person only). */+ continueMonth: (id: string) => call(send, `/api/kwants/${enc(id)}/budget/continue`, parseBudget, { method: 'POST' }, 'Couldn’t continue. Try again.'),+ /** Undoes Continue: the bot pauses at its budget again. */+ pauseAgain: (id: string) => call(send, `/api/kwants/${enc(id)}/budget/continue`, parseBudget, { method: 'DELETE' }, 'Couldn’t save. Try again.'),+ list: () => call(send, '/api/usage/budgets', parseBudgetList, undefined, 'Couldn’t load the budgets.'),+});++// ---------------------------------------------------------------- the space's budgets, shared++// One list for the sidebar rows, the chat banner, Needs you and Settings › Usage. It is re-read on+// a budget notice (warn, stop, resumed, continued), after any change made here, and every minute.+export interface BudgetSnapshot {+ byBot: Readonly<Record<string, BotBudget>>;+ list: BudgetList | null;+ error: string | null;+ loaded: boolean;+}++const EMPTY: BudgetSnapshot = { byBot: {}, list: null, error: null, loaded: false };+let snapshot: BudgetSnapshot = EMPTY;+const listeners = new Set<() => void>();+let inflight: Promise<void> | null = null;+let fetcher: Fetch = (...a) => fetch(...a);++export const budgetStore = {+ get: (): BudgetSnapshot => snapshot,+ subscribe(fn: () => void): () => void {+ listeners.add(fn);+ return () => listeners.delete(fn);+ },+ /** Puts one bot's fresh record in (the answer to a save, continue or pause-again). */+ put(b: BotBudget) {+ const bots = snapshot.list ? snapshot.list.bots.map((x) => (x.kwant_id === b.kwant_id ? b : x)) : [b];+ if (snapshot.list && !bots.some((x) => x.kwant_id === b.kwant_id)) bots.push(b);+ set({ ...snapshot, byBot: { ...snapshot.byBot, [b.kwant_id]: b }, list: snapshot.list ? { ...snapshot.list, bots } : snapshot.list });+ },+ refresh(): Promise<void> {+ if (inflight) return inflight;+ inflight = botBudgetApi(fetcher)+ .list()+ .then(+ (list) => set({ byBot: Object.fromEntries(list.bots.map((b) => [b.kwant_id, b])), list, error: null, loaded: true }),+ (e: unknown) => set({ ...snapshot, error: e instanceof Error ? e.message : 'Couldn’t load the budgets.', loaded: true }),+ )+ .finally(() => {+ inflight = null;+ });+ return inflight;+ },+ /** Tests and a space switch: forget everything (and use `send` from now on). */+ reset(send?: Fetch) {+ if (send) fetcher = send;+ inflight = null;+ set(EMPTY);+ },+};++function set(next: BudgetSnapshot) {+ snapshot = next;+ for (const fn of [...listeners]) fn();+}++/** Bots that need the person: paused first, then at 80% or more, highest first. */+export function budgetsNeedingYou(list: readonly BotBudget[]): BotBudget[] {+ return list.filter((b) => b.state === 'paused' || b.state === 'warn').sort((a, b) => (a.state === b.state ? b.percent - a.percent : a.state === 'paused' ? -1 : 1));+}++// ---------------------------------------------------------------- chat lines++export const BUDGET_KINDS = ['bot_budget_stopped', 'bot_budget_warn', 'bot_budget_resumed', 'bot_budget_continued'] as const;+export type BudgetKind = (typeof BUDGET_KINDS)[number];++export interface BudgetNoticeMeta {+ kind: BudgetKind;+ kwant_id: string;+ kwant_name: string;+ month: string;+ percent: number;+ detail: string;+}++function metaObject(meta: unknown): Record<string, unknown> | null {+ if (!meta) return null;+ if (typeof meta === 'object') return meta as Record<string, unknown>;+ if (typeof meta !== 'string') return null;+ try {+ const m = JSON.parse(meta);+ return m && typeof m === 'object' ? m : null;+ } catch {+ return null;+ }+}++/** A budget line's meta (a string from the message list, or an object from a live event). */+export function parseBudgetNotice(meta: unknown): BudgetNoticeMeta | null {+ const o = metaObject(meta);+ if (!o || !BUDGET_KINDS.includes(o.kind as BudgetKind) || typeof o.kwant_id !== 'string') return null;+ return { kind: o.kind as BudgetKind, kwant_id: o.kwant_id, kwant_name: str(o.kwant_name), month: str(o.month), percent: num(o.percent), detail: str(o.detail) };+}++/** True for any message that changes a bot's budget state, so the shared list is re-read. */+export const isBudgetMessage = (m: { meta?: unknown } | null | undefined): boolean => !!m && parseBudgetNotice(m.meta) !== null;++// ---------------------------------------------------------------- "Raise the limit" focus++// Set by Raise the limit (a notice, Needs you, the chat banner): the bot's settings open on Usage+// and the budget section puts focus on its first field once. In memory only.+let focusPending: string | null = null;+export const requestBudgetFocus = (kwantId: string): void => {+ focusPending = kwantId;+};+export const takeBudgetFocus = (kwantId: string): boolean => {+ if (focusPending !== kwantId) return false;+ focusPending = null;+ return true;+};diff --git a/frontend/src/components/BotBudget.tsx b/frontend/src/components/BotBudget.tsxnew file mode 100644index 00000000..81a33b21--- /dev/null+++ b/frontend/src/components/BotBudget.tsx@@ -0,0 +1,592 @@+import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react';+import { Check, Gauge, Loader2, PauseCircle, Play, RotateCcw, SlidersHorizontal } from 'lucide-react';+import {+ BotBudget,+ BudgetFields,+ BudgetNoticeMeta,+ PAUSED_LINE,+ botBudgetApi,+ budgetBody,+ budgetStore,+ budgetTokensError,+ budgetUsdError,+ budgetsNeedingYou,+ fieldsChanged,+ fieldsFromBudget,+ hasBudget,+ meterPercent,+ stateLine,+ takeBudgetFocus,+ usedLine,+} from '../botBudget';++const btnAmber =+ 'shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[44px] sm: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 aria-disabled:cursor-default aria-disabled:opacity-70 aria-disabled:hover:bg-amber-500/15 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400';+const btnQuiet =+ 'shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-3 py-1.5 rounded-lg text-xs font-medium border border-zinc-700 text-zinc-300 hover:bg-zinc-800 disabled:opacity-60 disabled:cursor-default focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const btnPrimary =+ 'shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-3 py-1.5 rounded-lg text-xs font-medium border border-sky-500/50 bg-sky-500/15 text-sky-100 hover:bg-sky-500/25 disabled:opacity-50 disabled:cursor-default focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';++/** The space's budgets, shared. The app loads and refreshes the list; this only reads it. */+export function useBudgets() {+ return useSyncExternalStore(budgetStore.subscribe, budgetStore.get, budgetStore.get);+}++// ---------------------------------------------------------------- the meter++/** A small meter: amber from 80%, and full when paused. `size` "row" is 28 px wide, for a sidebar row. */+export const BudgetMeter: React.FC<{ budget: BotBudget; size?: 'row' | 'full'; className?: string }> = ({ budget, size = 'full', className = '' }) => {+ const pct = meterPercent(budget);+ const hot = budget.state === 'warn' || budget.state === 'paused';+ const fill = hot ? 'bg-amber-400' : budget.state === 'continued' ? 'bg-zinc-500' : 'bg-sky-400';+ const label = `${budget.kwant_name || 'This bot'} has used ${pct}% of its monthly budget`;+ return (+ <span+ role="meter"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={pct}+ aria-label={label}+ title={`${pct}% of its monthly budget · ${usedLine(budget)}`}+ data-budget-meter={budget.state}+ className={`relative inline-block shrink-0 overflow-hidden rounded-full ${hot ? 'bg-amber-500/20' : 'bg-zinc-800'} ${size === 'row' ? 'h-1 w-7' : 'h-1.5 w-full'} ${className}`}+ >+ <span className={`absolute inset-y-0 left-0 rounded-full ${fill}`} style={{ width: `${pct}%` }} />+ </span>+ );+};++// ---------------------------------------------------------------- Raise / Continue, once++type Act = 'idle' | 'sending' | 'done' | 'error';++/** Continue this month: one post however fast the clicks; the answer goes into the shared list. */+function useContinueMonth(kwantId: string, send?: typeof fetch, onContinued?: () => void) {+ const api = useRef(botBudgetApi(send)).current;+ const [state, setState] = useState<Act>('idle');+ const [error, setError] = useState<string | null>(null);+ const lock = useRef(false);+ const run = async () => {+ if (lock.current) return;+ lock.current = true;+ setState('sending');+ setError(null);+ try {+ const next = await api.continueMonth(kwantId);+ // Before the shared list changes, so a caller that keeps this row (Inbox) knows in the same render+ onContinued?.();+ budgetStore.put(next);+ setState('done');+ } catch (e) {+ lock.current = false;+ setState('error');+ setError(e instanceof Error && e.message ? e.message : 'Couldn’t continue. Try again.');+ }+ };+ return { state, error, run };+}++/** The pause's two ways on: raise the limit (the bot's settings, at the budget) or continue this month.+ * `onContinued` runs once the continue is saved, so the caller can move focus before this unmounts (#536 Mira F4).+ * The button is aria-disabled, never disabled, while it sends and once done, so focus stays on it. */+export const PausedActions: React.FC<{+ budget: BotBudget;+ onRaise?: (kwantId: string) => void;+ onContinued?: () => void;+ describedBy?: string;+ send?: typeof fetch;+}> = ({ budget, onRaise, onContinued, describedBy, send }) => {+ const { state, error, run } = useContinueMonth(budget.kwant_id, send, onContinued);+ const done = state === 'done' || budget.state === 'continued';+ return (+ <>+ <div className="flex flex-wrap items-center gap-2">+ {onRaise && !done && (+ <button type="button" onClick={() => onRaise(budget.kwant_id)} className={btnQuiet} data-budget-raise aria-describedby={describedBy}>+ <SlidersHorizontal size={13} aria-hidden="true" />+ <span>Raise the limit</span>+ </button>+ )}+ <button+ type="button"+ onClick={() => {+ if (!done) void run();+ }}+ aria-disabled={state === 'sending' || done ? true : undefined}+ className={btnAmber}+ data-budget-continue+ aria-describedby={describedBy}+ >+ {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 this month' : 'Continue this month'}</span>+ </button>+ </div>+ <p className="sr-only" role="status" aria-live="polite">+ {state === 'done' ? `Continued. ${budget.kwant_name} can start new work again.` : ''}+ </p>+ {error && (+ <p role="alert" className="basis-full text-[11px] text-rose-300">+ {error}+ </p>+ )}+ </>+ );+};++// ---------------------------------------------------------------- the chat++/** After Continue in the bar: the bar goes away, so the person can type straight away (#536 Mira F4). */+const focusComposer = () => document.querySelector<HTMLTextAreaElement>('[data-composer-form] textarea')?.focus();++/** Above the composer in a paused bot's chat: why nothing new starts, and the way on. */+export const BudgetPausedBanner: React.FC<{ budget: BotBudget; onRaise?: (kwantId: string) => void; send?: typeof fetch }> = ({ budget, onRaise, send }) => {+ const id = `budget-banner-${budget.kwant_id}`;+ return (+ <section+ aria-labelledby={id}+ data-budget-banner+ className="max-w-4xl mx-auto mb-2 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-amber-500/30 bg-amber-950/30 px-3 py-2"+ >+ <div className="min-w-0 flex-1 basis-56">+ <p id={id} className="flex items-center gap-2 text-xs font-medium text-amber-200">+ <PauseCircle size={14} className="shrink-0 text-amber-400" aria-hidden="true" />+ {PAUSED_LINE}+ </p>+ <p className="mt-0.5 pl-[22px] text-[11px] text-amber-200/70">{usedLine(budget)}. Your message waits and goes through once it can start again.</p>+ </div>+ <PausedActions budget={budget} onRaise={onRaise} onContinued={focusComposer} describedBy={id} send={send} />+ </section>+ );+};++/** The bot's 80% note and its stop notice, in the chat. The buttons follow the bot's state now, not when the line was posted. */+export const BudgetNotice: React.FC<{+ messageId: string;+ text: string;+ meta: BudgetNoticeMeta;+ onRaise?: (kwantId: string) => void;+ canAct?: boolean;+ flash?: boolean;+ send?: typeof fetch;+}> = ({ messageId, text, meta, onRaise, canAct = true, flash, send }) => {+ const { byBot } = useBudgets();+ const live = byBot[meta.kwant_id];+ const headingId = `budget-${messageId}`;+ // Only this month's line still has a way on; an older one stays as a record+ const current = !!live && live.month === meta.month;+ const stopped = meta.kind === 'bot_budget_stopped';+ return (+ <section+ data-message-id={messageId}+ data-budget-notice={meta.kind}+ 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">+ {stopped ? (+ <PauseCircle size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />+ ) : (+ <Gauge size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />+ )}+ <span className="min-w-0">{text}</span>+ </p>+ {(current || meta.detail) && <p className="mt-1 pl-[23px] text-[11px] text-amber-200/60 font-mono">{current ? usedLine(live) : meta.detail}</p>}+ </div>+ {canAct && current && stopped && (live.state === 'paused' || live.state === 'continued') && (+ <PausedActions budget={live} onRaise={onRaise} describedBy={headingId} send={send} />+ )}+ {canAct && current && !stopped && meta.kind === 'bot_budget_warn' && live.state === 'warn' && onRaise && (+ <button type="button" onClick={() => onRaise(meta.kwant_id)} className={btnQuiet} data-budget-raise aria-describedby={headingId}>+ <SlidersHorizontal size={13} aria-hidden="true" />+ <span>Change the budget</span>+ </button>+ )}+ </div>+ </section>+ );+};++// ---------------------------------------------------------------- Needs you++/** Inbox › New, at the top: each bot paused at its budget, then each at 80% or more. Nothing when none. */+export const BudgetNeedsYou: React.FC<{ onRaise?: (kwantId: string) => void; send?: typeof fetch }> = ({ onRaise, send }) => {+ const { list } = useBudgets();+ // Continued during this visit: the row stays, done, so focus and the confirmation stay put (#536 Mira F4).+ // It goes on the next visit to the Inbox. A ref, not state: the shared list's update renders synchronously,+ // and a state update would land one render later, dropping the row (and its focused button) in between.+ const continued = useRef<Set<string>>(new Set()).current;+ const items = list+ ? budgetsNeedingYou(list.bots.map((b) => (continued.has(b.kwant_id) && b.state === 'continued' ? { ...b, state: 'paused' as const } : b)))+ : [];+ if (!items.length) return null;+ // A block whose rows are all done drops data-needs-you, so the all-clear line can come back+ const allDone = items.every((b) => continued.has(b.kwant_id));+ return (+ <section aria-labelledby="needs-budget-h" data-needs-budget data-needs-you={allDone ? undefined : ''}>+ <h3 id="needs-budget-h" className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider">+ <Gauge size={12} aria-hidden="true" />+ Needs you+ </h3>+ <ul className="space-y-2">+ {items.map((b) => {+ const id = `needs-budget-${b.kwant_id}`;+ const paused = b.state === 'paused';+ const done = continued.has(b.kwant_id);+ const live = list?.bots.find((x) => x.kwant_id === b.kwant_id) ?? b;+ return (+ <li key={b.kwant_id} data-needs-budget-item={done ? 'continued' : b.state} className="rounded-xl border border-amber-500/30 bg-amber-950/20 px-3.5 py-2.5 sm:px-4">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <div className="min-w-0 flex-1 basis-56">+ {done ? (+ <p id={id} className="flex items-start gap-2 text-sm text-zinc-300 break-words">+ <Check size={15} className="mt-0.5 shrink-0 text-emerald-400" aria-hidden="true" />+ <span className="min-w-0">{`${b.kwant_name} can start new work again.`}</span>+ </p>+ ) : (+ <p id={id} className="flex items-start gap-2 text-sm text-amber-200 break-words">+ {paused ? (+ <PauseCircle size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />+ ) : (+ <Gauge size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />+ )}+ <span className="min-w-0">+ {paused ? `${b.kwant_name} · ${PAUSED_LINE}` : `${b.kwant_name} has used ${meterPercent(b)}% of its monthly budget.`}+ </span>+ </p>+ )}+ <div className="mt-1.5 pl-[23px] flex flex-wrap items-center gap-x-2 gap-y-1">+ <BudgetMeter budget={b} className="max-w-[160px]" />+ <span className="min-w-0 break-words text-[11px] text-amber-200/60 font-mono">{usedLine(b)}</span>+ </div>+ </div>+ {paused ? (+ <PausedActions+ budget={live}+ onRaise={onRaise}+ onContinued={() => continued.add(b.kwant_id)}+ describedBy={id}+ send={send}+ />+ ) : (+ onRaise && (+ <button type="button" onClick={() => onRaise(b.kwant_id)} className={btnQuiet} data-budget-raise aria-describedby={id}>+ <SlidersHorizontal size={13} aria-hidden="true" />+ <span>Change the budget</span>+ </button>+ )+ )}+ </div>+ </li>+ );+ })}+ </ul>+ </section>+ );+};++// ---------------------------------------------------------------- bot settings › Usage++const field = (err: boolean) =>+ `w-full bg-zinc-950 border rounded-lg px-3 py-2 min-h-[40px] sm:min-h-[36px] text-xs text-zinc-100 focus:outline-none ${err ? 'border-rose-500/60 focus:border-rose-400' : 'border-zinc-800 focus:border-sky-500'}`;++/** "Monthly budget" in a bot's settings: two optional limits (off by default), used / limit, when it starts over, and the way on when paused. */+export const BotBudgetSection: React.FC<{ kwantId: string; kwantName: string; send?: typeof fetch }> = ({ kwantId, kwantName, send }) => {+ const api = useRef(botBudgetApi(send)).current;+ const { byBot } = useBudgets();+ const [loaded, setLoaded] = useState<BotBudget | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [fields, setFields] = useState<BudgetFields>({ tokens: '', usd: '' });+ const [saving, setSaving] = useState(false);+ const [saveError, setSaveError] = useState<string | null>(null);+ const [saved, setSaved] = useState<string | null>(null);+ const [undoing, setUndoing] = useState(false);+ const first = useRef<HTMLInputElement>(null);+ const section = useRef<HTMLElement>(null);++ const load = React.useCallback(() => {+ setLoadError(null);+ setLoaded(null);+ api.get(kwantId).then(+ (b) => {+ setLoaded(b);+ setFields(fieldsFromBudget(b));+ budgetStore.put(b);+ },+ (e: unknown) => setLoadError(e instanceof Error ? e.message : 'Couldn’t load the budget.'),+ );+ }, [api, kwantId]);+ useEffect(load, [load]);+ // Raise the limit: focus the first field once it is on screen+ useEffect(() => {+ if (loaded && takeBudgetFocus(kwantId)) {+ first.current?.scrollIntoView?.({ block: 'center', behavior: 'auto' });+ first.current?.focus({ preventScroll: true });+ }+ }, [loaded, kwantId]);++ // The shared list may be newer (a Continue elsewhere, a turn that crossed 80%)+ const b = byBot[kwantId] ?? loaded;+ const tErr = budgetTokensError(fields.tokens);+ const uErr = budgetUsdError(fields.usd);+ const body = budgetBody(fields);+ const dirty = !!b && fieldsChanged(fields, b);++ const save = async (e?: React.FormEvent) => {+ e?.preventDefault();+ if (!body || saving) return;+ const prev = b?.state;+ setSaving(true);+ setSaveError(null);+ setSaved(null);+ try {+ const next = await api.set(kwantId, body);+ setLoaded(next);+ setFields(fieldsFromBudget(next));+ budgetStore.put(next);+ setSaved(+ next.state === 'off'+ ? 'Budget off.'+ : next.state === 'paused'+ ? 'Saved. It is still over this limit, so it stays paused.'+ : prev === 'paused'+ ? `Saved. ${kwantName} can start new work again.`+ : 'Saved.',+ );+ } catch (err) {+ setSaveError(err instanceof Error ? err.message : 'Couldn’t save the budget. Try again.');+ } finally {+ setSaving(false);+ }+ };++ const pauseAgain = async () => {+ if (undoing) return;+ setUndoing(true);+ setSaveError(null);+ try {+ const next = await api.pauseAgain(kwantId);+ setLoaded(next);+ budgetStore.put(next);+ } catch (err) {+ setSaveError(err instanceof Error ? err.message : 'Couldn’t save. Try again.');+ } finally {+ setUndoing(false);+ }+ };++ return (+ <section ref={section} aria-labelledby="bot-budget-h" data-bot-budget className="space-y-3 rounded-xl border border-zinc-800 bg-zinc-950/60 p-3">+ <div>+ <h3 id="bot-budget-h" className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">+ <Gauge size={13} className="text-sky-300" aria-hidden="true" />+ Monthly budget+ </h3>+ <p className="text-[11px] text-zinc-500">+ When {kwantName} reaches either limit, it finishes what it’s doing and starts nothing new until you raise the limit, continue, or the month+ ends. You get a note at 80%. Leave both empty for no budget.+ </p>+ </div>++ {loadError ? (+ <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300" data-budget-load-error>+ <span className="flex-1">{loadError}</span>+ <button type="button" onClick={load} className="inline-flex items-center gap-1 min-h-[44px] sm:min-h-0 px-2 -mx-2 text-zinc-300 hover:text-zinc-100 underline underline-offset-2">+ <RotateCcw size={11} aria-hidden="true" /> Retry+ </button>+ </p>+ ) : !b ? (+ <p className="flex items-center gap-2 text-[11px] text-zinc-500" role="status" data-budget-loading>+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading the budget…+ </p>+ ) : (+ <>+ <div role="status" aria-live="polite" className="space-y-1.5" data-budget-state={b.state}>+ {hasBudget(b) && <BudgetMeter budget={b} />}+ <p className="font-mono text-[11px] text-zinc-300">{usedLine(b)}</p>+ <p className={`text-[11px] ${b.state === 'paused' || b.state === 'warn' ? 'text-amber-300' : 'text-zinc-400'}`}>{stateLine(b)}</p>+ {b.cost_unreported && b.budget_usd > 0 && (+ <p className="text-[11px] text-zinc-500">This bot’s engine reports no cost, so the dollar limit can’t count its use. Set a token limit too.</p>+ )}+ </div>++ {b.state === 'paused' && (+ <div className="flex flex-wrap items-center gap-2">+ <PausedActions+ budget={b}+ send={send}+ onContinued={() => {+ // The paused row swaps for Pause again once this renders: focus moves there, not to <body> (#536 Mira F4)+ requestAnimationFrame(() => section.current?.querySelector<HTMLButtonElement>('[data-budget-pause-again]')?.focus());+ }}+ />+ <span className="text-[11px] text-zinc-500">or raise a limit below.</span>+ </div>+ )}+ {b.state === 'continued' && (+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" onClick={pauseAgain} disabled={undoing} className={btnQuiet} data-budget-pause-again>+ {undoing ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <PauseCircle size={13} aria-hidden="true" />}+ <span>Pause at the budget again</span>+ </button>+ </div>+ )}++ <form onSubmit={save} className="space-y-2" aria-label={`${kwantName}’s monthly budget`}>+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="space-y-1 min-w-0">+ <label htmlFor="bot-budget-tokens" className="block text-[11px] font-medium text-zinc-300">+ Tokens per month+ </label>+ <input+ ref={first}+ id="bot-budget-tokens"+ type="text"+ inputMode="decimal"+ autoComplete="off"+ placeholder="No limit"+ value={fields.tokens}+ onChange={(e) => setFields((f) => ({ ...f, tokens: e.target.value }))}+ aria-invalid={!!tErr}+ aria-describedby="bot-budget-tokens-hint"+ className={field(!!tErr)}+ />+ <p id="bot-budget-tokens-hint" className={`text-[11px] ${tErr ? 'text-rose-300' : 'text-zinc-500'}`}>+ {tErr ?? 'Like 500k or 2M. Cache reads don’t count.'}+ </p>+ </div>+ <div className="space-y-1 min-w-0">+ <label htmlFor="bot-budget-usd" className="block text-[11px] font-medium text-zinc-300">+ Dollars per month+ </label>+ <input+ id="bot-budget-usd"+ type="text"+ inputMode="decimal"+ autoComplete="off"+ placeholder="No limit"+ value={fields.usd}+ onChange={(e) => setFields((f) => ({ ...f, usd: e.target.value }))}+ aria-invalid={!!uErr}+ aria-describedby="bot-budget-usd-hint"+ className={field(!!uErr)}+ />+ <p id="bot-budget-usd-hint" className={`text-[11px] ${uErr ? 'text-rose-300' : 'text-zinc-500'}`}>+ {uErr ?? 'Like 20 or 2.50. Counts only engines that report a cost.'}+ </p>+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <button type="submit" disabled={!body || !dirty || saving} className={btnPrimary} data-budget-save>+ {saving ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={13} aria-hidden="true" />}+ <span>{saving ? 'Saving…' : 'Save budget'}</span>+ </button>+ {hasBudget(b) && (+ <button+ type="button"+ disabled={saving}+ className={btnQuiet}+ data-budget-off+ onClick={() => {+ setFields({ tokens: '', usd: '' });+ }}+ >+ Clear limits+ </button>+ )}+ <span role="status" aria-live="polite" className="text-[11px] text-emerald-300">+ {saved}+ </span>+ </div>+ {saveError && (+ <p role="alert" className="text-[11px] text-rose-300" data-budget-save-error>+ {saveError}+ </p>+ )}+ </form>+ </>+ )}+ </section>+ );+};++// ---------------------------------------------------------------- Settings › Usage++const STATE_CHIP: Record<BotBudget['state'], { text: string; tone: string }> = {+ off: { text: 'No budget', tone: 'text-zinc-500 border-zinc-800' },+ under: { text: 'On track', tone: 'text-zinc-300 border-zinc-700' },+ warn: { text: '% used', tone: 'text-amber-200 border-amber-500/40 bg-amber-500/10' },+ paused: { text: 'Paused', tone: 'text-amber-100 border-amber-500/60 bg-amber-500/20' },+ continued: { text: 'Continued', tone: 'text-zinc-300 border-zinc-700' },+};++/** Every bot in this space with its budget and this month's use. */+export const BudgetOverview: React.FC<{ open: boolean; onOpenBot?: (kwantId: string) => void }> = ({ open, onOpenBot }) => {+ const { list, error, loaded } = useBudgets();+ useEffect(() => {+ if (open) void budgetStore.refresh();+ }, [open]);+ const withBudget = list?.bots.filter(hasBudget).length ?? 0;+ return (+ <div className="space-y-2" role="group" aria-labelledby="budget-overview-h" data-budget-overview>+ <div>+ <p id="budget-overview-h" className="text-[11px] font-semibold text-zinc-200">+ Monthly budget per bot+ </p>+ <p className="text-[11px] text-zinc-500">The bots in the space you’re in, and their use this month. Set a bot’s budget in its settings, under Usage.</p>+ </div>+ {error && !list ? (+ <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">+ <span className="flex-1">{error}</span>+ <button type="button" onClick={() => void budgetStore.refresh()} className="inline-flex items-center gap-1 min-h-[44px] sm:min-h-0 px-2 -mx-2 text-zinc-300 hover:text-zinc-100 underline underline-offset-2">+ <RotateCcw size={11} aria-hidden="true" /> Retry+ </button>+ </p>+ ) : !list || !loaded ? (+ <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 budgets…+ </p>+ ) : !list.bots.length ? (+ <p className="text-[11px] text-zinc-500">No bots in this space yet.</p>+ ) : (+ <>+ {withBudget === 0 && <p className="text-[11px] text-zinc-400" data-budget-none>No bot has a budget yet, so none of them will pause.</p>}+ <ul className="divide-y divide-zinc-800/80 rounded-lg border border-zinc-800 bg-zinc-950/60" aria-label="Monthly budget per bot">+ {list.bots.map((b) => {+ const chip = STATE_CHIP[b.state];+ return (+ <li key={b.kwant_id} className="flex flex-wrap lg:flex-nowrap items-center gap-x-3 gap-y-1 px-3 py-2" data-budget-row={b.state}>+ <span className="min-w-0 flex-1 basis-32 truncate text-[11px] font-medium text-zinc-200">{b.kwant_name || 'Unnamed bot'}</span>+ <span className={`shrink-0 rounded-full border px-1.5 py-px text-[10px] ${chip.tone}`}>{b.state === 'warn' ? `${meterPercent(b)}% used` : chip.text}</span>+ <span className="basis-full sm:order-last lg:order-none lg:basis-auto lg:w-80 flex items-center gap-2 min-w-0">+ {hasBudget(b) && <BudgetMeter budget={b} className="max-w-[72px]" />}+ <span className="min-w-0 break-words font-mono text-[11px] tabular-nums text-zinc-400">+ {usedLine(b)}+ </span>+ </span>+ {onOpenBot && (+ <button+ type="button"+ onClick={() => onOpenBot(b.kwant_id)}+ className="shrink-0 min-h-[44px] sm:min-h-[32px] px-3 sm:px-2 rounded-md text-[11px] text-sky-300 hover:text-sky-200 hover:bg-sky-500/10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ aria-label={`${hasBudget(b) ? 'Change' : 'Set'} ${b.kwant_name}’s budget`}+ >+ {hasBudget(b) ? 'Change' : 'Set'}+ </button>+ )}+ </li>+ );+ })}+ </ul>+ </>+ )}+ </div>+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 7066018d..a3e82024 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -74,6 +74,8 @@ import { BudgetPausedNotice, HandoffCappedNotice, InterruptedNotice, SystemNoticimport { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainBudget';import { parseSpendStopped } from '../spendStop';import { SpendStoppedNotice } from './SpendStop';+import { parseBudgetNotice } from '../botBudget';+import { BudgetNotice, BudgetPausedBanner, useBudgets } from './BotBudget';import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';import { parseIsolationFailed, parseRequestLimit } from '../isolationNotice';import { IsolationNotice, RequestLimitNotice } from './IsolationNotice';@@ -319,6 +321,10 @@ export interface ChatViewProps {onOpenUsage?: () => void;/** Opens App settings at the Computer card, "Run Claude inside the VM" focused (isolation notices). */onOpenComputerSettings?: () => void;+ /** 0.9.5: the bot this 1:1 chat is with; its monthly-budget pause shows above the box. */+ budgetBotId?: string | null;+ /** 0.9.5: opens a bot's settings at its monthly budget, the first field focused. */+ onRaiseBudget?: (kwantId: string) => void;/** Opens Manage Team with its folder input focused (isolation notices 6 and 7). */onChangeTeamFolder?: (teamId: string) => void;/** Opens the named bot's Edit modal on Profile, where its AI is picked (notice 7). */@@ -534,6 +540,8 @@ export const ChatView: React.FC<ChatViewProps> = ({onOpenAccounts,onOpenUsage,onOpenComputerSettings,+ budgetBotId = null,+ onRaiseBudget,onChangeTeamFolder,onEditBot,canRun = null,@@ -784,6 +792,9 @@ export const ChatView: React.FC<ChatViewProps> = ({setApprovalOffscreen(false);};// The running turn's summary line (WorkingStrip): inside the composer section, right above the box.+ const { byBot: budgetsByBot } = useBudgets();+ const chatBudget = budgetBotId ? budgetsByBot[budgetBotId] : undefined;+ const budgetBanner = chatBudget?.state === 'paused' ? <BudgetPausedBanner budget={chatBudget} onRaise={onRaiseBudget} /> : null;const workingStrip = (<WorkingStripactive={isStreaming}@@ -1340,6 +1351,19 @@ export const ChatView: React.FC<ChatViewProps> = ({/></div>);+ const budgetNote = parseBudgetNotice(msg.meta);+ if (budgetNote && (budgetNote.kind === 'bot_budget_stopped' || budgetNote.kind === 'bot_budget_warn'))+ return (+ <BudgetNotice+ key={msg.id}+ messageId={msg.id}+ text={msg.text}+ meta={budgetNote}+ onRaise={onRaiseBudget}+ canAct={!(budgetBotId === budgetNote.kwant_id && chatBudget?.state === 'paused')}+ flash={flashId === msg.id}+ />+ );const spend = parseSpendStopped(msg.meta);if (spend)return (@@ -2292,6 +2316,7 @@ export const ChatView: React.FC<ChatViewProps> = ({)}{/* Phone and desktop (0.8.1 F4): the quiet line sits inside the composer section, right above the box. */}+ {budgetBanner}{workingStrip}<form@@ -2466,7 +2491,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<AtSign size={phone ? 18 : 17} aria-hidden="true" />{/* Phone (spec A5): "New" anchors to the @ button's own box, never on the field's border or an Ask chip */}{phone && !isStreaming && (- <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''} ${layerPhase ? 'hidden' : ''}`} />+ <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`} />)}</button>{stacked && <span className="flex-1" aria-hidden="true" />}@@ -2479,7 +2504,7 @@ export const ChatView: React.FC<ChatViewProps> = ({{!phone && !isStreaming && (<NewTagid="mention"- className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''} ${layerPhase ? 'hidden' : ''}`}+ className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`}style={{ right: 'calc(11px + var(--kw-cbtn-step))' }}/>)}diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsxindex 479a7f6f..4e183d21 100644--- a/frontend/src/components/InboxNew.tsx+++ b/frontend/src/components/InboxNew.tsx@@ -467,7 +467,7 @@ export const BatchPane: React.FC<{ wide: boolean; onOpenItem: (id: string) => vo};const EmptyQueue: React.FC = () => (- <div className="py-16 flex flex-col items-center text-center gap-2" data-all-clear>+ <div className="py-16 flex flex-col items-center text-center gap-2 [[data-needs-you]~&]:hidden" data-all-clear><CheckCircle2 size={30} className="text-teal-300" aria-hidden="true" /><p className="text-sm font-semibold text-zinc-100">You’re all caught up</p><p className="text-xs text-zinc-400 max-w-xs">Nothing waits on you and nothing is left to review. Questions, approvals and finished work will show up here.</p>diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex ab29eed6..3a76ea0e 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -13,6 +13,7 @@ import { MemoryPanel } from './MemoryPanel';import { RoutinesPanel } from './RoutinesPanel';import { SkillsPanel } from './SkillsPanel';import { UsagePanel } from './UsagePanel';+import { BotBudgetSection } from './BotBudget';import type { Channel, Kwant } from './Sidebar';import { BotApprovalsSetting } from './ApprovalsSetting';import { FlightSchoolPanel } from './FlightSchoolPanel';@@ -382,7 +383,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({</div>)}{isEdit && kwantId && tab === 'usage' && (- <div role="tabpanel" id="agent-panel-usage" aria-labelledby="agent-tab-usage">+ <div role="tabpanel" id="agent-panel-usage" aria-labelledby="agent-tab-usage" className="space-y-4">+ <BotBudgetSection kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} /><UsagePanel kwantId={kwantId} kwantName={initial?.name ?? 'This bot'} /></div>)}diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex 6daac991..12e16615 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -4,6 +4,7 @@ import { AuditorModelSetting } from './AuditorModelSetting';import { Key, X, Settings, Check, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles, KanbanSquare, BellRing } from 'lucide-react';import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';import { DailyUsagePanel } from './DailyUsage';+import { BudgetOverview } from './BotBudget';import { SpendStopFields, StopFields, forgetToday } from './SpendStop';import { stopBody, stopFieldsFromSettings } from '../spendStop';import { CodingAgents } from './CodingAgents';@@ -259,6 +260,8 @@ interface SettingsModalProps {onOpenApiKeys?: () => void;/** A switch to scroll to and focus once loaded, by its row id ("idea-jar" from the jar's Settings button). */focusRow?: string | null;+ /** 0.9.5: opens a bot's settings at its monthly budget (the overview's Set / Change). */+ onOpenBotBudget?: (kwantId: string) => void;}/** App settings: shared by every space (keys, Laya, limits, notifications, sounds). Accounts,@@ -305,7 +308,7 @@ const DiscoverySetting: React.FC<{ value: DiscoverySettings; onChange: (v: Disco);};-export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0, embedded = false, onOpenApiKeys, focusRow = null }) => {+export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0, embedded = false, onOpenApiKeys, focusRow = null, onOpenBotBudget }) => {const { authRequired, deviceLogin, signOut } = useAuth();const computer = useComputerMode(isOpen);const [sfxMuted, setSfxMuted] = useState(isSfxMuted);@@ -808,7 +811,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t</fieldset>)}- <fieldset className="space-y-3 pt-2 border-t border-zinc-800">+ <fieldset className="min-w-0 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>@@ -851,6 +854,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t)}{spendStop !== null && <SpendStopFields value={spendStop} onChange={setSpendStop} open={isOpen} savedKey={spendSaved} />}<DailyUsagePanel open={isOpen} />+ <BudgetOverview open={isOpen} onOpenBot={onOpenBotBudget} /></fieldset>{agentTools !== null && (diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 3031fa88..53ede624 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -27,6 +27,8 @@ import { GlobeSlot, WatchGlobe, useFadeOut, useLingeringIds } from './WatchLive'import type { Browsing } from '../watchLive';import { IdeaJarRow } from './IdeaJarRow';import { ReadyTeamsSidebarBox } from './ReadyTeamsEntry';+import { BudgetMeter, useBudgets } from './BotBudget';+import { PAUSED_ROW_LINE } from '../botBudget';export interface Kwant {id: string;@@ -424,6 +426,7 @@ export const Sidebar: React.FC<SidebarProps> = ({const chatsTab = phone && section === 'chats';const needsRows = chatsTab ? needsYouRows.filter((r) => kwants.some((k) => k.id === r.kwant_id)) : [];const needsIds = new Set(needsRows.map((r) => r.kwant_id));+ const { byBot: budgetsByBot } = useBudgets();const busyNow = chatsTab ? workingIds(kwants, busyKwants, needsIds) : [];// A bot whose turn just ended stays in Working for its globe's fade-out, instead of jumping to Direct// chats (a new row, with no globe) in the same frame (QA F2 on phone)@@ -567,14 +570,19 @@ export const Sidebar: React.FC<SidebarProps> = ({// An open browser step: the status line says so in words while it is open (the name line only has the hand)const needs = needsYou[k.id] ?? 0;const needsTip = `${k.name} needs you in the browser`;- const warn = needs > 0 || status === 'needs_you';+ // 0.9.5: a bot paused at its monthly budget says so where its status goes; at 80% a small amber meter+ const budget = budgetsByBot[k.id];+ const budgetPaused = budget?.state === 'paused';+ const warn = needs > 0 || status === 'needs_you' || budgetPaused;const busyLine = asked? asked.line: attLine? attLine: needs > 0 && !busyKwants[k.id]?.startsWith('Needs you in the browser')? 'Needs you in the browser'- : busyKwants[k.id];+ : budgetPaused && !busyKwants[k.id]+ ? PAUSED_ROW_LINE+ : busyKwants[k.id];// A stuck or finished row opens where that happened (its thread or chat), like its Inbox card// A review row opens its item in the Inboxconst open = asked && onOpenNeedsYou@@ -651,6 +659,7 @@ export const Sidebar: React.FC<SidebarProps> = ({))}{/* W1: this bot's current work is in a browser; the click opens the chat that browser belongs to.Last on the name line and pushed right, so every row's globe lines up in one column */}+ {budget?.state === 'warn' && <BudgetMeter budget={budget!} size="row" className="ml-0.5 self-center" />}{onWatchBrowser && <GlobeSlot browsing={botBrowsing} name={k.name} phone={phone} className="ml-auto mt-1" onWatch={onWatchBrowser} />}{/* Edit and Remove sit at the right end of the one-line status below the name, which makes roomfor them on hover: the name keeps its width and the row its height */}diff --git a/frontend/src/components/SpendStop.tsx b/frontend/src/components/SpendStop.tsxindex 225a68d3..355ac5ea 100644--- a/frontend/src/components/SpendStop.tsx+++ b/frontend/src/components/SpendStop.tsx@@ -189,7 +189,7 @@ export const SpendStopNeedsYou: React.FC<{ send?: typeof fetch; onOpenSettings?:}, [focusSeq]);if (!item) return null;return (- <section ref={box} aria-labelledby="needs-spend-h" data-needs-spend-stop>+ <section ref={box} aria-labelledby="needs-spend-h" data-needs-spend-stop data-needs-you><h3 id="needs-spend-h" className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold text-zinc-500 uppercase tracking-wider"><Gauge size={12} aria-hidden="true" />Needs youdiff --git a/frontend/src/components/dev/PrepushThread.tsx b/frontend/src/components/dev/PrepushThread.tsxindex bd21ddc4..c7adf24b 100644--- a/frontend/src/components/dev/PrepushThread.tsx+++ b/frontend/src/components/dev/PrepushThread.tsx@@ -149,7 +149,7 @@ export const PrepushNeedsYou: React.FC<{ cards: Card[]; names: Record<string, stconst list = needsYou(cards);if (list.length === 0) return null;return (- <section aria-labelledby="needs-prepush-h" data-needs-prepush>+ <section aria-labelledby="needs-prepush-h" data-needs-prepush data-needs-you><h3 id="needs-prepush-h" className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-zinc-500"><ArrowUpFromLine size={12} aria-hidden="true" />Needs youdiff --git a/frontend/tests/botBudget.test.mjs b/frontend/tests/botBudget.test.mjsnew file mode 100644index 00000000..13df883e--- /dev/null+++ b/frontend/tests/botBudget.test.mjs@@ -0,0 +1,465 @@+// Per-bot monthly budgets (0.9.5): the "Monthly budget" section in a bot's settings, the 80% meter and+// Needs-you item, the 100% pause ("Paused: monthly budget reached") with Raise the limit / Continue this+// month in the chat, the sidebar row and Needs you, and the overview in Settings › Usage. Every number+// shown is the server's (src/server/bot_budget.rs).+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://kwant.example/', pretendToBeVisual: true });+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'localStorage', 'sessionStorage']) {+ Object.defineProperty(globalThis, k, { value: k === 'window' ? dom.window : dom.window[k], configurable: true, writable: true });+}+globalThis.requestAnimationFrame = (cb) => setTimeout(cb, 0);+globalThis.cancelAnimationFrame = (id) => clearTimeout(id);+globalThis.IS_REACT_ACT_ENVIRONMENT = false;++const m = await loadBundled(`+ import React from 'react';+ export * from './src/botBudget';+ export { BotBudgetSection, BudgetMeter, BudgetNotice, BudgetPausedBanner, BudgetNeedsYou, BudgetOverview } from './src/components/BotBudget';+ export { React };+ export { createRoot } from 'react-dom/client';+`);++const src = (f) => readFileSync(new URL(`../src/${f}`, import.meta.url), 'utf8');+const flush = () => new Promise((r) => setTimeout(r, 0));+const settle = async () => {+ for (let i = 0; i < 8; i++) await flush();+};+const h = (...a) => m.React.createElement(...a);++/** A fetch that answers by "METHOD url" ([status, body] or a function of the call) and records the calls. */+function fake(routes) {+ const calls = [];+ const send = async (url, init = {}) => {+ const method = init.method ?? 'GET';+ calls.push({ url, method, body: init.body ? JSON.parse(init.body) : undefined });+ const r = routes[`${method} ${url}`];+ if (!r) throw new Error(`unexpected ${method} ${url}`);+ const [status, body] = typeof r === 'function' ? r(init) : r;+ return { ok: status >= 200 && status < 300, status, json: async () => body };+ };+ return { send, calls };+}++const B = (over = {}) => ({+ kwant_id: 'k1',+ kwant_name: 'Juno',+ month: '2026-11',+ timezone: 'UTC',+ used_tokens: 1_600_000,+ used_usd: 0,+ today_tokens: 0,+ budget_tokens: 2_000_000,+ budget_usd: 0,+ percent: 80,+ over: null,+ state: 'warn',+ paused_since: null,+ continued_month: null,+ resets_at: '2026-12-01T00:00:00+00:00',+ usage_reported: true,+ some_unreported: false,+ cost_reported: true,+ estimated: false,+ engine: 'claude',+ ...over,+});+const PAUSED = B({ used_tokens: 2_100_000, percent: 105, over: 'tokens', state: 'paused', paused_since: '2026-11-12T10:00:00Z' });+const OFF = B({ kwant_id: 'k2', kwant_name: 'Lin', budget_tokens: 0, percent: 0, state: 'off', used_tokens: 3000 });+const LIST = (bots) => ({ month: '2026-11', timezone: 'UTC', resets_at: '2026-12-01T00:00:00+00:00', bots });++async function mount(el) {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = m.createRoot(host);+ root.render(el);+ await settle();+ return { host, root, unmount: () => (root.unmount(), host.remove()) };+}+const click = async (el) => {+ el.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));+ await settle();+};+/** Types into a React-controlled input. */+const type = async (input, value) => {+ const set = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value').set;+ set.call(input, value);+ input.dispatchEvent(new dom.window.Event('input', { bubbles: true }));+ await settle();+};++// ---------------------------------------------------------------- the words++test('lines: used / limit and when it starts over, in plain words', () => {+ const b = m.parseBudget(B());+ assert.equal(m.usedLine(b), '1.6M of 2M fresh tokens in November');+ assert.equal(m.resetDay(b), 'December 1');+ assert.equal(m.stateLine(b), '80% used. At 100% it finishes what it’s doing and starts nothing new until December 1.');+ assert.equal(m.stateLine(m.parseBudget(B({ state: 'under', percent: 30 }))), 'The count starts over on December 1.');+ const p = m.parseBudget(PAUSED);+ assert.equal(m.meterPercent(p), 100, 'the meter stops at full');+ assert.match(m.stateLine(p), /^Paused: monthly budget reached\. Juno starts nothing new until you raise the limit, continue this month, or December 1\.$/);+ assert.equal(m.usedLine(m.parseBudget(B({ budget_tokens: 0, budget_usd: 20, used_usd: 16.4, percent: 82 }))), '$16.40 of $20.00 in November');+ assert.equal(m.usedLine(m.parseBudget({ ...OFF })), '3k fresh tokens in November');+ assert.match(m.usedLine(m.parseBudget(B({ estimated: true }))), /^about /);+ assert.equal(m.stateLine(m.parseBudget(OFF)), 'No budget: Lin can use as much as it needs.');+ assert.equal(m.parseBudget(B({ cost_reported: false })).cost_unreported, true);+ assert.equal(m.parseBudget({ kwant_id: 'x', state: 'nope' }), null);+});++test('fields: empty is off, 2M and $2.50 parse, bad input says how', () => {+ assert.deepEqual(m.budgetBody({ tokens: '', usd: '' }), { budget_tokens: null, budget_usd: null });+ assert.deepEqual(m.budgetBody({ tokens: '2M', usd: '2.50' }), { budget_tokens: 2_000_000, budget_usd: 2.5 });+ assert.deepEqual(m.budgetBody({ tokens: '0', usd: '' }), { budget_tokens: null, budget_usd: null });+ assert.equal(m.budgetBody({ tokens: 'lots', usd: '' }), null);+ assert.match(m.budgetTokensError('lots'), /like 500k or 2M/);+ assert.match(m.budgetTokensError('20000000000'), /10 billion/);+ assert.match(m.budgetUsdError('2.505'), /like 20 or 2.50/);+ assert.match(m.budgetUsdError('200000'), /\$100,000/);+ assert.equal(m.fieldsChanged({ tokens: '2000000', usd: '' }, B()), false);+ assert.equal(m.fieldsChanged({ tokens: '1M', usd: '' }, B()), true);+ assert.deepEqual(m.fieldsFromBudget(m.parseBudget(OFF)), { tokens: '', usd: '' });+});++test('chat lines: meta as a string or an object; Needs you puts paused first', () => {+ const meta = { kind: 'bot_budget_stopped', kwant_id: 'k1', kwant_name: 'Juno', month: '2026-11', percent: 105 };+ assert.equal(m.parseBudgetNotice(JSON.stringify(meta)).kind, 'bot_budget_stopped');+ assert.equal(m.parseBudgetNotice(meta).kwant_id, 'k1');+ assert.equal(m.parseBudgetNotice({ kind: 'spend_stopped' }), null);+ assert.equal(m.isBudgetMessage({ meta: { ...meta, kind: 'bot_budget_resumed' } }), true);+ assert.equal(m.isBudgetMessage({ meta: 'not json' }), false);+ const order = m.budgetsNeedingYou([B({ kwant_id: 'a', percent: 85 }), m.parseBudget(OFF), PAUSED, B({ kwant_id: 'b', percent: 95 })]).map((b) => b.kwant_id);+ assert.deepEqual(order, ['k1', 'b', 'a']);+ assert.equal(m.takeBudgetFocus('k1'), false);+ m.requestBudgetFocus('k1');+ assert.equal(m.takeBudgetFocus('k2'), false);+ assert.equal(m.takeBudgetFocus('k1'), true);+ assert.equal(m.takeBudgetFocus('k1'), false, 'focus is taken once');+});++test('api: errors in plain words; the server’s own 400/409 text is shown', async () => {+ const api = m.botBudgetApi(+ fake({+ 'POST /api/kwants/k1/budget': [400, { error: 'At most $100,000 a month.' }],+ 'POST /api/kwants/k1/budget/continue': [403, { error: 'forbidden' }],+ 'GET /api/usage/budgets': [500, {}],+ }).send,+ );+ await assert.rejects(api.set('k1', { budget_tokens: null, budget_usd: 1e9 }), /At most \$100,000 a month\./);+ await assert.rejects(api.continueMonth('k1'), /Only you can change a bot’s budget/);+ await assert.rejects(api.list(), /Couldn’t load the budgets\./);+ const down = m.botBudgetApi(async () => {+ throw new Error('offline');+ });+ await assert.rejects(down.get('k1'), /Couldn’t reach the server/);+});++// ---------------------------------------------------------------- bot settings › Usage++test('Monthly budget: loading, then off by default; set a limit and save', async () => {+ let saved = null;+ const { send, calls } = fake({+ 'GET /api/usage/budgets': [200, LIST([OFF])],+ 'GET /api/kwants/k2/budget': [200, OFF],+ 'POST /api/kwants/k2/budget': (init) => {+ saved = JSON.parse(init.body);+ return [200, { ...OFF, budget_tokens: 1000, percent: 300, over: 'tokens', state: 'paused' }];+ },+ });+ m.budgetStore.reset(send);+ const { host, unmount } = await mount(h(m.BotBudgetSection, { kwantId: 'k2', kwantName: 'Lin', send }));+ assert.equal(host.querySelector('h3').textContent, 'Monthly budget');+ assert.equal(host.querySelector('[data-budget-state]').dataset.budgetState, 'off');+ assert.equal(host.querySelector('[role=meter]'), null, 'no meter with no budget');+ const tokens = host.querySelector('#bot-budget-tokens');+ assert.equal(tokens.value, '');+ assert.equal(tokens.placeholder, 'No limit');+ assert.equal(host.querySelector('label[for=bot-budget-tokens]').textContent, 'Tokens per month');+ const save = host.querySelector('[data-budget-save]');+ assert.equal(save.disabled, true, 'nothing to save yet');++ await type(tokens, 'abc');+ assert.equal(tokens.getAttribute('aria-invalid'), 'true');+ assert.match(host.querySelector('#bot-budget-tokens-hint').textContent, /like 500k or 2M/);+ assert.equal(save.disabled, true);++ await type(tokens, '1k');+ assert.equal(save.disabled, false);+ host.querySelector('form').dispatchEvent(new dom.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle();+ assert.deepEqual(saved, { budget_tokens: 1000, budget_usd: null });+ assert.equal(host.querySelector('[data-budget-state]').dataset.budgetState, 'paused');+ assert.match(host.textContent, /still over this limit, so it stays paused/);+ assert.ok(host.querySelector('[data-budget-continue]'), 'paused: Continue this month is right there');+ assert.equal(m.budgetStore.get().byBot.k2.state, 'paused', 'the shared list has it');+ assert.ok(calls.some((c) => c.method === 'POST'));+ unmount();+});++test('Monthly budget: a load error says so with Retry; Raise the limit focuses the first field', async () => {+ let fail = true;+ const { send } = fake({+ 'GET /api/usage/budgets': [200, LIST([])],+ 'GET /api/kwants/k1/budget': () => (fail ? [500, {}] : [200, PAUSED]),+ });+ m.budgetStore.reset(send);+ m.requestBudgetFocus('k1');+ const { host, unmount } = await mount(h(m.BotBudgetSection, { kwantId: 'k1', kwantName: 'Juno', send }));+ const alert = host.querySelector('[data-budget-load-error]');+ assert.match(alert.textContent, /Couldn’t load the budget\./);+ fail = false;+ await click(alert.querySelector('button'));+ assert.equal(host.querySelector('[data-budget-state]').dataset.budgetState, 'paused');+ assert.equal(document.activeElement, host.querySelector('#bot-budget-tokens'), 'Raise the limit lands on the limit');+ assert.equal(host.querySelector('#bot-budget-tokens').value, '2000000');+ unmount();+});++test('Monthly budget: continued shows Pause at the budget again, which undoes it', async () => {+ const CONT = { ...PAUSED, state: 'continued', continued_month: '2026-11' };+ const { send, calls } = fake({+ 'GET /api/usage/budgets': [200, LIST([CONT])],+ 'GET /api/kwants/k1/budget': [200, CONT],+ 'DELETE /api/kwants/k1/budget/continue': [200, PAUSED],+ });+ m.budgetStore.reset(send);+ const { host, unmount } = await mount(h(m.BotBudgetSection, { kwantId: 'k1', kwantName: 'Juno', send }));+ assert.match(host.textContent, /Continued for November: the limit is ignored until December 1\./);+ await click(host.querySelector('[data-budget-pause-again]'));+ assert.ok(calls.some((c) => c.method === 'DELETE'));+ assert.equal(host.querySelector('[data-budget-state]').dataset.budgetState, 'paused');+ unmount();+});++// ---------------------------------------------------------------- the pause, everywhere++test('paused banner: the line, used / limit, Raise the limit and Continue this month (one post)', async () => {+ let posts = 0;+ const { send } = fake({+ 'POST /api/kwants/k1/budget/continue': () => {+ posts++;+ return [200, { ...PAUSED, state: 'continued' }];+ },+ });+ m.budgetStore.reset(send);+ const raised = [];+ const { host, unmount } = await mount(h(m.BudgetPausedBanner, { budget: m.parseBudget(PAUSED), onRaise: (id) => raised.push(id), send }));+ assert.match(host.textContent, /Paused: monthly budget reached/);+ assert.match(host.textContent, /2\.1M of 2M fresh tokens in November/);+ await click(host.querySelector('[data-budget-raise]'));+ assert.deepEqual(raised, ['k1']);+ const go = host.querySelector('[data-budget-continue]');+ go.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));+ go.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));+ await settle();+ assert.equal(posts, 1, 'a double click posts once');+ assert.match(go.textContent, /Continued this month/);+ assert.equal(go.getAttribute('aria-disabled'), 'true');+ assert.equal(go.disabled, false, 'aria-disabled, never disabled, so focus stays on it (F4)');+ assert.equal(m.budgetStore.get().byBot.k1.state, 'continued');+ unmount();+});++test('chat notice: the stop line’s buttons follow the bot now; an old month’s line is only a record', async () => {+ const { send } = fake({ 'GET /api/usage/budgets': [200, LIST([PAUSED])] });+ m.budgetStore.reset(send);+ await m.budgetStore.refresh();+ const meta = m.parseBudgetNotice({ kind: 'bot_budget_stopped', kwant_id: 'k1', kwant_name: 'Juno', month: '2026-11', percent: 105 });+ const old = { ...meta, month: '2026-10' };+ const { host, unmount } = await mount(+ h('div', null, h(m.BudgetNotice, { messageId: 'a', text: 'Juno reached its monthly budget.', meta, onRaise: () => {} }), h(m.BudgetNotice, { messageId: 'b', text: 'old', meta: old, onRaise: () => {} })),+ );+ const [now, then] = host.querySelectorAll('[data-budget-notice]');+ assert.ok(now.querySelector('[data-budget-continue]'));+ assert.ok(now.querySelector('[data-budget-raise]'));+ assert.equal(then.querySelector('button'), null);+ m.budgetStore.put(m.parseBudget(B()));+ await settle();+ assert.equal(now.querySelector('button'), null, 'raised above the limit: nothing left to do here');+ unmount();+});++test('Needs you: paused first, then 80%; nothing when no bot needs you', async () => {+ const { send } = fake({ 'GET /api/usage/budgets': [200, LIST([PAUSED, B({ kwant_id: 'k3', kwant_name: 'Vega', percent: 86 }), OFF])] });+ m.budgetStore.reset(send);+ await m.budgetStore.refresh();+ const { host, unmount } = await mount(h(m.BudgetNeedsYou, { onRaise: () => {}, send }));+ const items = [...host.querySelectorAll('[data-needs-budget-item]')];+ assert.deepEqual(+ items.map((i) => i.dataset.needsBudgetItem),+ ['paused', 'warn'],+ );+ assert.match(items[0].textContent, /Juno · Paused: monthly budget reached/);+ assert.match(items[1].textContent, /Vega has used 86% of its monthly budget\./);+ assert.equal(items[1].querySelector('[role=meter]').getAttribute('aria-valuenow'), '86');+ m.budgetStore.reset(send);+ await settle();+ assert.equal(host.querySelector('[data-needs-budget]'), null);+ unmount();+});++test('meter: amber from 80%, labelled for screen readers', async () => {+ const { host, unmount } = await mount(h('div', null, h(m.BudgetMeter, { budget: m.parseBudget(B({ percent: 40, state: 'under' })) }), h(m.BudgetMeter, { budget: m.parseBudget(B()), size: 'row' })));+ const [low, hot] = host.querySelectorAll('[role=meter]');+ assert.doesNotMatch(low.innerHTML, /amber/);+ assert.match(hot.innerHTML, /bg-amber-400/);+ assert.equal(hot.getAttribute('aria-label'), 'Juno has used 80% of its monthly budget');+ assert.match(hot.className, /w-7/);+ unmount();+});++// ---------------------------------------------------------------- Settings › Usage++test('overview: loading, error with Retry, empty, and the list with Set / Change', async () => {+ let answer = [500, {}];+ const { send } = fake({ 'GET /api/usage/budgets': () => answer });+ m.budgetStore.reset(send);+ const opened = [];+ const { host, unmount } = await mount(h(m.BudgetOverview, { open: true, onOpenBot: (id) => opened.push(id) }));+ assert.match(host.querySelector('[role=alert]').textContent, /Couldn’t load the budgets\./);+ answer = [200, LIST([])];+ await click(host.querySelector('[role=alert] button'));+ assert.match(host.textContent, /No bots in this space yet\./);+ answer = [200, LIST([OFF])];+ await m.budgetStore.refresh();+ await settle();+ assert.ok(host.querySelector('[data-budget-none]'), 'no bot has a budget yet');+ answer = [200, LIST([PAUSED, OFF])];+ await m.budgetStore.refresh();+ await settle();+ const rows = [...host.querySelectorAll('[data-budget-row]')];+ assert.deepEqual(rows.map((r) => r.dataset.budgetRow), ['paused', 'off']);+ assert.match(rows[0].textContent, /Paused/);+ assert.equal(rows[0].querySelector('button').getAttribute('aria-label'), 'Change Juno’s budget');+ assert.equal(rows[1].querySelector('button').getAttribute('aria-label'), 'Set Lin’s budget');+ await click(rows[1].querySelector('button'));+ assert.deepEqual(opened, ['k2']);+ unmount();+});++// ---------------------------------------------------------------- wiring++test('wiring: bot settings, chat, sidebar, Inbox, Settings › Usage and live refresh', () => {+ const modal = src('components/NewAgentModal.tsx');+ assert.match(modal, /<BotBudgetSection kwantId=\{kwantId\}/);+ const chat = src('components/ChatView.tsx');+ assert.match(chat, /<BudgetNotice/);+ assert.match(chat, /\{budgetBanner\}\s*\{workingStrip\}/);+ const side = src('components/Sidebar.tsx');+ assert.match(side, /budgetPaused && !busyKwants\[k\.id\]\s*\? PAUSED_ROW_LINE/);+ // F7: the row meter shows only at 80%, centred on the name line+ assert.match(side, /\{budget\?\.state === 'warn' && <BudgetMeter budget=\{budget!\} size="row" className="ml-0\.5 self-center" \/>\}/);+ assert.equal(m.PAUSED_ROW_LINE, 'Paused: budget reached');+ // F1: in a paused 1:1 the bar is the one place to act; the stop note is a record+ assert.match(chat, /canAct=\{!\(budgetBotId === budgetNote\.kwant_id && chatBudget\?\.state === 'paused'\)\}/);+ // F2: the composer's "New" sticker hides while the bar shows, at both call sites+ assert.equal(chat.match(/\$\{layerPhase \|\| budgetBanner \? 'hidden' : ''\}/g)?.length, 2);+ assert.doesNotMatch(chat, /\$\{layerPhase \? 'hidden' : ''\}/);+ const app = src('App.tsx');+ assert.match(app, /<BudgetNeedsYou onRaise=\{raiseBudget\} \/>/);+ assert.match(app, /isBudgetMessage\(m\)\) void budgetStore\.refresh\(\)/);+ assert.match(app, /requestBudgetFocus\(kwantId\);\s*openAgentSettings\(k, 'usage'\)/);+ assert.match(app, /onOpenBotBudget=\{raiseBudget\}/);+ assert.match(src('components/SettingsModal.tsx'), /<BudgetOverview open=\{isOpen\} onOpenBot=\{onOpenBotBudget\} \/>/);+});++test('Inbox: the all-clear line hides while a Needs you block sits above it', () => {+ assert.match(src('components/InboxNew.tsx'), /\[\[data-needs-you\]~&\]:hidden[^>]*data-all-clear/);+ for (const f of ['components/BotBudget.tsx', 'components/SpendStop.tsx', 'components/dev/PrepushThread.tsx']) assert.match(src(f), /data-needs-you(>|=\{)/, f);+});++// ---------------------------------------------------------------- Mira's fixes (#536 F3, F4, F6)++test('F4 bar: after Continue this month, focus goes to the composer', async () => {+ const { send } = fake({ 'POST /api/kwants/k1/budget/continue': [200, { ...PAUSED, state: 'continued' }] });+ m.budgetStore.reset(send);+ const form = document.createElement('form');+ form.setAttribute('data-composer-form', '');+ const box = document.createElement('textarea');+ form.appendChild(box);+ document.body.appendChild(form);+ const { host, unmount } = await mount(h(m.BudgetPausedBanner, { budget: m.parseBudget(PAUSED), send }));+ const go = host.querySelector('[data-budget-continue]');+ go.focus();+ await click(go);+ assert.equal(document.activeElement, box, 'the person can type straight away');+ unmount();+ form.remove();+});++test('F4 Inbox: a continued row stays, says so, and keeps focus on an aria-disabled button', async () => {+ const { send } = fake({+ 'GET /api/usage/budgets': [200, LIST([PAUSED])],+ 'POST /api/kwants/k1/budget/continue': [200, { ...PAUSED, state: 'continued', continued_month: '2026-11' }],+ });+ m.budgetStore.reset(send);+ await m.budgetStore.refresh();+ const { host, unmount } = await mount(h(m.BudgetNeedsYou, { onRaise: () => {}, send }));+ const go = host.querySelector('[data-budget-continue]');+ go.focus();+ await click(go);+ const row = host.querySelector('[data-needs-budget-item]');+ assert.equal(row.dataset.needsBudgetItem, 'continued');+ assert.match(row.textContent, /Juno can start new work again\./);+ const done = row.querySelector('[data-budget-continue]');+ assert.equal(done, go, 'the same button, still mounted');+ assert.match(done.textContent, /Continued this month/);+ assert.equal(done.getAttribute('aria-disabled'), 'true');+ assert.equal(done.disabled, false);+ assert.equal(document.activeElement, done, 'focus stays on it');+ assert.equal(row.querySelector('[data-budget-raise]'), null);+ assert.equal(host.querySelector('[data-needs-budget]').hasAttribute('data-needs-you'), false, 'all done: the all-clear can come back');+ assert.match(host.querySelector('[role=status]').textContent, /Continued\. Juno can start new work again\./);+ unmount();+});++test('F4 settings: after Continue, focus lands on Pause at the budget again', async () => {+ const CONT = { ...PAUSED, state: 'continued', continued_month: '2026-11' };+ const { send } = fake({+ 'GET /api/usage/budgets': [200, LIST([PAUSED])],+ 'GET /api/kwants/k1/budget': [200, PAUSED],+ 'POST /api/kwants/k1/budget/continue': [200, CONT],+ });+ m.budgetStore.reset(send);+ const { host, unmount } = await mount(h(m.BotBudgetSection, { kwantId: 'k1', kwantName: 'Juno', send }));+ await click(host.querySelector('[data-budget-continue]'));+ await settle();+ assert.equal(document.activeElement, host.querySelector('[data-budget-pause-again]'));+ unmount();+});++test('F6 settings: a raise that un-pauses says the bot can start again; state lines are zinc-400', async () => {+ const { send } = fake({+ 'GET /api/usage/budgets': [200, LIST([PAUSED])],+ 'GET /api/kwants/k1/budget': [200, PAUSED],+ 'POST /api/kwants/k1/budget': [200, B({ budget_tokens: 5_000_000, used_tokens: 2_100_000, percent: 42, state: 'under' })],+ });+ m.budgetStore.reset(send);+ const { host, unmount } = await mount(h(m.BotBudgetSection, { kwantId: 'k1', kwantName: 'Juno', send }));+ await type(host.querySelector('#bot-budget-tokens'), '5M');+ host.querySelector('form').dispatchEvent(new dom.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle();+ assert.match(host.textContent, /Saved\. Juno can start new work again\./);+ const line = [...host.querySelectorAll('[data-budget-state] p')].find((p) => /starts over/.test(p.textContent));+ assert.match(line.className, /text-zinc-400/);+ unmount();+});++test('F3 and F6 overview: 44 px phone targets, "N% used" chip, readable no-budget note', async () => {+ const { send } = fake({ 'GET /api/usage/budgets': [200, LIST([B({ percent: 80 }), OFF])] });+ m.budgetStore.reset(send);+ const { host, unmount } = await mount(h(m.BudgetOverview, { open: true, onOpenBot: () => {} }));+ const [warn] = host.querySelectorAll('[data-budget-row]');+ assert.match(warn.textContent, /80% used/);+ assert.doesNotMatch(warn.textContent, /Over 80%/);+ assert.match(warn.querySelector('button').className, /min-h-\[44px\] sm:min-h-\[32px\] px-3 sm:px-2/);+ unmount();+ const src2 = src('components/BotBudget.tsx');+ assert.equal(src2.match(/min-h-\[44px\] sm:min-h-\[36px\] px-3/g)?.length, 3, 'all three button styles');+ assert.equal(src2.match(/min-h-\[44px\] sm:min-h-0 px-2 -mx-2/g)?.length, 2, 'both Retry buttons');+ assert.match(src2, /text-\[11px\] text-zinc-400" data-budget-none/);+});diff --git a/src/server/bot_budget.rs b/src/server/bot_budget.rsindex 21e283d9..06b367c3 100644--- a/src/server/bot_budget.rs+++ b/src/server/bot_budget.rs@@ -158,11 +158,16 @@ pub async fn status(state: &AppState, kwant: &Kwant) -> Budget {}}-/// Short token counts: 950, 61k, 2.04M.+/// Short token counts: 950, 1.5k, 61k, 2.04M. One decimal below 100k, like the app's `compactTokens`,+/// so 1,500 of 1,800 reads "1.5k of 1.8k", not "1k of 1k".fn short(n: u64) -> String {match n {0..=999 => n.to_string(),- 1_000..=999_999 => format!("{}k", n / 1_000),+ 1_000..=99_999 => {+ let k = format!("{:.1}", n as f64 / 1_000.0);+ format!("{}k", k.trim_end_matches('0').trim_end_matches('.'))+ }+ 100_000..=999_999 => format!("{}k", (n as f64 / 1_000.0).round() as u64),_ => {let m = format!("{:.2}", n as f64 / 1_000_000.0);format!("{}M", m.trim_end_matches('0').trim_end_matches('.'))@@ -194,7 +199,7 @@ fn next_month_name(b: &Budget) -> String {pub fn stop_text(b: &Budget) -> String {format!(- "{} stopped at its monthly budget. It finished what it was doing and won't start anything new until you raise the budget, continue, or {} starts.",+ "{} stopped at its monthly budget. It finished what it was doing and won't start anything new until you raise the limit, continue, or {} starts.",b.kwant_name,next_month_name(b))@@ -325,7 +330,7 @@ pub async fn book(state: &AppState, kwant_id: &str, fresh_tokens: u64, usd: f64,let key = budget_key(&after.month, after.budget_tokens, after.budget_usd);if state.db.mark_bot_warned(&kwant.id, &key).await.unwrap_or(false) {let text = format!(- "{} has used 80% of its {} budget. At 100% it stops starting new work.",+ "{} has used 80% of its {} budget. At 100% it finishes what it's doing and starts nothing new.",kwant.name,month_name(&after.month));@@ -571,7 +576,7 @@ pub async fn continue_month(State(state): State<AppState>, Path(id): Path<String"Continued for {}. {} can start new work again; the budget applies again on {}.",month_name(&b.month),kwant.name,- b.resets_at.format("%b %-d")+ b.resets_at.format("%B %-d"));release(&state, &kwant, Some((text, "bot_budget_continued"))).await;tracing::info!(kwant = %kwant.id, month = %b.month, "bot budget continued for the month");@@ -678,6 +683,13 @@ mod tests {assert_eq!(short(61_000), "61k");}+ #[test]+ fn short_counts_keep_one_decimal_below_100k() {+ assert_eq!(short(1_500), "1.5k");+ assert_eq!(short(1_800), "1.8k");+ assert_eq!(short(61_000), "61k");+ }+#[test]fn budget_errors_are_stop_errors() {assert!(is_budget_error("bot_budget: Pixel is paused"));diff --git a/tests/bot_budget_test.rs b/tests/bot_budget_test.rsindex 327fd613..23ab6d29 100644--- a/tests/bot_budget_test.rs+++ b/tests/bot_budget_test.rs@@ -269,7 +269,7 @@ async fn warns_once_when_a_turn_crosses_80_percent() {assert_eq!(b["percent"].as_f64(), Some(83.3));let warns = env.direct("bot_budget_warn").await;assert_eq!(warns.len(), 1);- assert_eq!(warns[0].text, "Ann has used 80% of its November budget. At 100% it stops starting new work.");+ assert_eq!(warns[0].text, "Ann has used 80% of its November budget. At 100% it finishes what it's doing and starts nothing new.");// Raised, then set back and lowered: still past 80%, but no second noteenv.set_budget(&env.ann, json!({"budget_tokens": 10 * FRESH})).await;@@ -300,9 +300,9 @@ async fn crossing_turn_finishes_next_is_held_until_continue_or_raise() {assert_eq!(stops.len(), 1, "one notice when the pause starts");assert_eq!(stops[0].text,- "Ann stopped at its monthly budget. It finished what it was doing and won't start anything new until you raise the budget, continue, or December starts."+ "Ann stopped at its monthly budget. It finished what it was doing and won't start anything new until you raise the limit, continue, or December starts.");- assert_eq!(meta(&stops[0])["detail"], "8k of 8k fresh tokens in November");+ assert_eq!(meta(&stops[0])["detail"], "8.7k of 8.7k fresh tokens in November");env.held("second").await;env.held("third").await;@@ -323,7 +323,9 @@ async fn crossing_turn_finishes_next_is_held_until_continue_or_raise() {// Continue this monthlet b = ok(&env.app, "POST", &format!("/api/kwants/{}/budget/continue", env.ann), None).await;assert_eq!((b["state"].as_str(), b["continued_month"].as_str()), (Some("continued"), Some("2026-11")), "{b}");- assert_eq!(env.direct("bot_budget_continued").await.len(), 1);+ let continued = env.direct("bot_budget_continued").await;+ assert_eq!(continued.len(), 1);+ assert_eq!(continued[0].text, "Continued for November. Ann can start new work again; the budget applies again on December 1.");assert!(env.waiting_items().await.is_empty());env.run_parked().await;env.turn("fourth").await;