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.

Token limits on screen: no limit by default, set or remove one in one place

Pixel (kwant bot)8e75530f9bf5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e32866b..74359219 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
(`mission_default_task_budget_tokens`, `mission_default_budget_tokens`). Existing tasks and missions
still on the old automatic limit have it removed; limits you set yourself stay. A task already
blocked for its budget stays in Needs you until you remove its limit and unblock it.
+- **Token limits on screen.** With no limit, a task or mission shows plain usage ("64.9k tokens used")
+ and no bar. **Set a limit** next to Cost on a task, and under the mission's cost, offers 50k, 200k,
+ 1M or a custom amount; **Change** and **Remove limit** take it from there. A task stopped by its
+ limit gets **Remove limit and continue**, on its board card and in its panel, plus **Raise limit**.
+ Settings → Usage has a **Token limits** group for the default on new tasks and missions, "No limit"
+ unless you pick one.
## [Mac 0.2.0] - 2026-10-28
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 97b52b4b..f40e0b93 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -87,8 +87,15 @@ import {
openFlags,
resolveOptions,
resolvedText,
+ LIMIT_PICKS,
+ LIMIT_RANGE,
+ LimitScope,
+ NO_LIMIT,
costRatio,
costText,
+ limitError,
+ outOfBudget,
+ parseLimit,
durationText,
eventText,
formatBytes,
@@ -159,6 +166,146 @@ const SpendBar: React.FC<{ spent: number; budget: number; label: string }> = ({
);
};
+/**
+ * A token limit, set in place: quick picks, a custom amount, or none. Closed, it's a "Set a limit"
+ * link (no limit) or "Change" / "Remove limit". `spent` hides picks a new limit would already be under.
+ */
+export const LimitEditor: React.FC<{
+ budget: number;
+ spent: number;
+ scope: LimitScope;
+ disabled?: boolean;
+ /** Opened from the start, e.g. by "Raise limit". */
+ startOpen?: boolean;
+ /** Text on the custom field's save button. */
+ saveLabel?: string;
+ /** Hide "No limit" (it has its own button nearby). */
+ hideNone?: boolean;
+ onSet: (budget: number) => void;
+ onClose?: () => void;
+}> = ({ budget, spent, scope, disabled = false, startOpen = false, saveLabel = 'Save', hideNone = false, onSet, onClose }) => {
+ const [open, setOpen] = useState(startOpen);
+ const [custom, setCustom] = useState<string | null>(null);
+ const fieldId = useId();
+ const hintId = useId();
+ const above = budget > 0 || startOpen ? spent : 0;
+ const err = custom === null ? null : limitError(custom, scope, above);
+ const picks = LIMIT_PICKS.filter((n) => n > above && n >= LIMIT_RANGE[scope][0]);
+ const close = () => {
+ setOpen(false);
+ setCustom(null);
+ onClose?.();
+ };
+ const set = (n: number) => {
+ onSet(n);
+ close();
+ };
+ const link = `inline-flex items-center min-h-[32px] rounded text-[11px] text-sky-300 hover:text-sky-200 hover:underline underline-offset-2 disabled:opacity-50 ${focusRing}`;
+ if (!open) {
+ return (
+ <span className="flex flex-wrap items-center gap-x-3" data-limit-editor="closed">
+ {budget > 0 ? (
+ <>
+ <button type="button" disabled={disabled} onClick={() => setOpen(true)} className={link} data-limit-change>
+ Change
+ </button>
+ <button type="button" disabled={disabled} onClick={() => onSet(NO_LIMIT)} className={link} data-limit-remove>
+ Remove limit
+ </button>
+ </>
+ ) : (
+ <button type="button" disabled={disabled} onClick={() => setOpen(true)} className={link} data-limit-set>
+ Set a limit
+ </button>
+ )}
+ </span>
+ );
+ }
+ const chip = (on: boolean) =>
+ `min-h-[40px] sm:min-h-[32px] px-2.5 rounded-lg border text-xs tabular-nums disabled:opacity-50 ${focusRing} ${
+ on ? 'border-sky-500 bg-sky-500/15 text-sky-100' : 'border-zinc-700 bg-zinc-900 text-zinc-200 hover:bg-zinc-800'
+ }`;
+ return (
+ <div role="group" aria-label={`${scope === 'mission' ? 'Mission' : 'Task'} token limit`} className="mt-1.5 space-y-2" data-limit-editor="open">
+ <div className="flex flex-wrap gap-1.5">
+ {!hideNone && (
+ <button type="button" disabled={disabled} aria-pressed={budget === NO_LIMIT} onClick={() => set(NO_LIMIT)} className={chip(budget === NO_LIMIT)} data-limit-pick={0}>
+ No limit
+ </button>
+ )}
+ {picks.map((n) => (
+ <button key={n} type="button" disabled={disabled} aria-pressed={budget === n} onClick={() => set(n)} className={chip(budget === n)} data-limit-pick={n}>
+ {formatTokens(n)}
+ </button>
+ ))}
+ <button type="button" disabled={disabled} aria-pressed={custom !== null} onClick={() => setCustom((c) => (c === null ? '' : c))} className={chip(custom !== null)} data-limit-custom>
+ Custom
+ </button>
+ </div>
+ {custom !== null && (
+ <form
+ className="flex flex-wrap items-start gap-1.5"
+ onSubmit={(e) => {
+ e.preventDefault();
+ const n = parseLimit(custom);
+ if (!err && n !== null) set(n);
+ }}
+ >
+ <label htmlFor={fieldId} className="sr-only">
+ Token limit
+ </label>
+ <input
+ id={fieldId}
+ autoFocus
+ inputMode="decimal"
+ autoComplete="off"
+ placeholder="e.g. 300k"
+ value={custom}
+ onChange={(e) => setCustom(e.target.value)}
+ aria-invalid={!!(custom.trim() && err)}
+ aria-describedby={hintId}
+ className={`${field} w-32 flex-none`}
+ />
+ <button type="submit" disabled={disabled || !!err} className={quietBtn}>
+ {saveLabel}
+ </button>
+ <p id={hintId} className={`basis-full text-[11px] ${custom.trim() && err ? 'text-rose-300' : 'text-zinc-500'}`}>
+ {custom.trim() && err ? err : 'Tokens, like 300k or 2M.'}
+ </p>
+ </form>
+ )}
+ <button type="button" onClick={close} className={link}>
+ Cancel
+ </button>
+ </div>
+ );
+};
+
+/** A task stopped by its token limit: the way on is to remove the limit, or raise it past what it used. */
+const LimitReachedBox: React.FC<{ task: Task; busy: boolean; onContinue?: (budget: number) => void }> = ({ task: t, busy, onContinue }) => {
+ const [raising, setRaising] = useState(false);
+ return (
+ <div className="px-3 py-2.5 rounded-lg border border-rose-500/30 bg-rose-500/10 space-y-2" data-limit-reached>
+ <p className="text-xs text-rose-200">
+ It stopped at its {formatTokens(t.budget_tokens)} token limit after using {formatTokens(t.spent_tokens)}. Remove the limit to let it finish, or raise it.
+ </p>
+ {onContinue && !raising && (
+ <div className="flex flex-wrap gap-2">
+ <button type="button" disabled={busy} onClick={() => onContinue(NO_LIMIT)} className={mainBtn} data-remove-limit-continue>
+ Remove limit and continue
+ </button>
+ <button type="button" disabled={busy} onClick={() => setRaising(true)} className={quietBtn} data-raise-limit>
+ Raise limit
+ </button>
+ </div>
+ )}
+ {onContinue && raising && (
+ <LimitEditor budget={t.budget_tokens} spent={t.spent_tokens} scope="task" disabled={busy} startOpen hideNone saveLabel="Raise and continue" onSet={onContinue} onClose={() => setRaising(false)} />
+ )}
+ </div>
+ );
+};
+
/** Two-letter initials for the owner chip. */
const initials = (name: string) =>
name
@@ -239,7 +386,9 @@ export const MissionSummary: React.FC<{
busy: boolean;
onApprove: () => void;
onCancel: () => void;
-}> = ({ mission: m, busy, onApprove, onCancel }) => {
+ /** Set or remove the mission's token limit (0 = none). */
+ onSetBudget?: (budget: number) => void;
+}> = ({ mission: m, busy, onApprove, onCancel, onSetBudget }) => {
const st = missionStatusLabel(m.status);
const total = Object.entries(m.counts)
.filter(([k]) => k !== 'cancelled')
@@ -253,7 +402,7 @@ export const MissionSummary: React.FC<{
{m.goal && <p className="mt-0.5 text-xs text-zinc-400 break-words">{m.goal}</p>}
</div>
<Badge tone={st.tone}>{st.label}</Badge>
- {m.over_budget && <Badge tone="rose">Over budget</Badge>}
+ {m.over_budget && <Badge tone="rose">Over its limit</Badge>}
</div>
<div className="space-y-1">
<div className="flex flex-wrap justify-between gap-x-3 text-[11px] text-zinc-400">
@@ -261,11 +410,18 @@ export const MissionSummary: React.FC<{
{m.counts.verified} of {total} task{total === 1 ? '' : 's'} verified
{m.lead_name ? ` · Led by ${m.lead_name}` : ''}
</span>
- <span className="tabular-nums">{costText(m.spent_tokens, m.budget_tokens)}</span>
+ <span className="tabular-nums" data-mission-cost>
+ {costText(m.spent_tokens, m.budget_tokens)}
+ </span>
</div>
- <SpendBar spent={m.spent_tokens} budget={m.budget_tokens} label="Mission budget used" />
+ {m.budget_tokens > 0 && <SpendBar spent={m.spent_tokens} budget={m.budget_tokens} label="Mission token limit used" />}
+ {onSetBudget && m.status !== 'done' && m.status !== 'cancelled' && (
+ <div className="flex justify-end">
+ <LimitEditor budget={m.budget_tokens} spent={m.spent_tokens} scope="mission" disabled={busy} onSet={onSetBudget} />
+ </div>
+ )}
</div>
- {m.over_budget && <p className="text-[11px] text-rose-300">No new task starts until you raise the budget.</p>}
+ {m.over_budget && <p className="text-[11px] text-rose-300">No new task starts until you raise or remove the mission’s token limit.</p>}
{m.status === 'draft' && (
<div className="flex flex-wrap items-center gap-2 pt-1">
<p className="text-xs text-amber-200 flex-1 min-w-[12rem]">{m.lead_name ?? 'A bot'} planned this. Nothing runs until you approve it.</p>
@@ -289,7 +445,10 @@ export const TaskCard: React.FC<{
now?: number;
showMission?: boolean;
onOpen: (t: Task) => void;
-}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen }) => {
+ /** Out of budget: remove its limit and put it back in Ready, from the card. */
+ onRemoveLimit?: (t: Task) => void;
+ busy?: boolean;
+}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen, onRemoveLimit, busy = false }) => {
const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
const checks = checksText(t.checks_summary);
const optionalNote = optionalChecksNote(t.checks_summary);
@@ -374,6 +533,11 @@ export const TaskCard: React.FC<{
)}
</span>
</button>
+ {onRemoveLimit && outOfBudget(t) && (
+ <button type="button" disabled={busy} onClick={() => onRemoveLimit(t)} className={`${mainBtn} mt-1.5 w-full`} data-card-remove-limit>
+ Remove limit and continue
+ </button>
+ )}
</li>
);
};
@@ -388,7 +552,9 @@ export const Board: React.FC<{
showMission?: boolean;
onColumn: (c: Column) => void;
onOpen: (t: Task) => void;
-}> = ({ tasks, names, column, now, showMission, onColumn, onOpen }) => {
+ onRemoveLimit?: (t: Task) => void;
+ busy?: boolean;
+}> = ({ tasks, names, column, now, showMission, onColumn, onOpen, onRemoveLimit, busy }) => {
const grouped = useMemo(() => groupByColumn(tasks), [tasks]);
const tabsId = useId();
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
@@ -406,7 +572,7 @@ export const Board: React.FC<{
return items.length ? (
<ul className="space-y-2">
{items.map((t) => (
- <TaskCard key={t.id} task={t} names={names} now={now} showMission={showMission} onOpen={onOpen} />
+ <TaskCard key={t.id} task={t} names={names} now={now} showMission={showMission} onOpen={onOpen} onRemoveLimit={onRemoveLimit} busy={busy} />
))}
</ul>
) : (
@@ -1241,6 +1407,10 @@ export const TaskDetailBody: React.FC<{
onRestoreError?: (e: unknown) => void;
/** Flight School: the person sets the task's kind of work. */
onSetClass?: (taskClass: string) => void;
+ /** Set or remove the task's token limit (0 = none). */
+ onSetBudget?: (budget: number) => void;
+ /** Out of budget: set the new limit (0 = none) and put it back in Ready. */
+ onContinueWithLimit?: (budget: number) => void;
}> = ({
detail,
names,
@@ -1264,8 +1434,11 @@ export const TaskDetailBody: React.FC<{
onRestored,
onRestoreError,
onSetClass,
+ onSetBudget,
+ onContinueWithLimit,
}) => {
const t = detail.task;
+ const limitHit = outOfBudget(t);
const flags = openFlags(t);
const others = t.needs_you.filter((n) => !OWN_SECTION.has(n.kind));
const changeItems = t.needs_you.filter((n) => n.kind === 'workflow_change');
@@ -1282,7 +1455,8 @@ export const TaskDetailBody: React.FC<{
const reasonId = useId();
const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
const st = stateLabel(t.state);
- const actions = actionsFor(t);
+ // Unblocking without a new limit would stop it again at once.
+ const actions = actionsFor(t).filter((a) => !(limitHit && a === 'unblock'));
const chat = sourceChat(t);
const [showAll, setShowAll] = useState(false);
const events = showAll ? detail.events : detail.events.slice(-12);
@@ -1310,7 +1484,8 @@ export const TaskDetailBody: React.FC<{
{t.priority >= 2 && <Badge tone={t.priority >= 3 ? 'rose' : 'amber'}>{priorityLabel(t.priority)}</Badge>}
{t.mission_title && <span className="text-[11px] text-zinc-500 break-words">{t.mission_title}</span>}
</div>
- {(t.state === 'blocked' || t.state === 'failed') && (
+ {limitHit && <LimitReachedBox task={t} busy={busy} onContinue={onContinueWithLimit} />}
+ {((t.state === 'blocked' && !limitHit) || t.state === 'failed') && (
<p className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200">{cardStatus(t, names, now)}</p>
)}
{notice && <Notice text={notice.text} error={notice.error} />}
@@ -1472,12 +1647,17 @@ export const TaskDetailBody: React.FC<{
<Fact label="Owner">{owner ?? <span className="text-zinc-500">No owner yet</span>}</Fact>
<Fact label="From">{sourceLabel(t.source_kind)}</Fact>
<Fact label="Cost">
- <span className="tabular-nums">{costText(t.spent_tokens, t.budget_tokens)}</span>
+ <span className="tabular-nums" data-task-cost>
+ {costText(t.spent_tokens, t.budget_tokens)}
+ </span>
{t.budget_tokens > 0 && (
<span className="block mt-1">
- <SpendBar spent={t.spent_tokens} budget={t.budget_tokens} label="Task budget used" />
+ <SpendBar spent={t.spent_tokens} budget={t.budget_tokens} label="Task token limit used" />
</span>
)}
+ {onSetBudget && !limitHit && t.state !== 'verified' && t.state !== 'cancelled' && (
+ <LimitEditor budget={t.budget_tokens} spent={t.spent_tokens} scope="task" disabled={busy} onSet={onSetBudget} />
+ )}
</Fact>
<Fact label="Tries">
{t.attempts} of {t.max_attempts}
@@ -1783,6 +1963,12 @@ export interface MissionBoardViewProps {
onOpenTask: (t: Task) => void;
onApproveMission: (m: Mission) => void;
onCancelMission: (m: Mission) => void;
+ /** Set or remove a mission's token limit (0 = none). */
+ onSetMissionBudget?: (m: Mission, budget: number) => void;
+ /** An out-of-budget card's one-click way on: remove its limit and put it back in Ready. */
+ onRemoveLimit?: (t: Task) => void;
+ /** A card action is running. */
+ busyCard?: boolean;
onRefresh: () => void;
onBack?: () => void;
/** With a mission picked: the board, or how its tasks connect. */
@@ -1814,6 +2000,9 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
onOpenTask,
onApproveMission,
onCancelMission,
+ onSetMissionBudget,
+ onRemoveLimit,
+ busyCard = false,
onRefresh,
onBack,
view = 'board',
@@ -1914,7 +2103,15 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
</div>
)}
- {mission && <MissionSummary mission={mission} busy={busyMission} onApprove={() => onApproveMission(mission)} onCancel={() => onCancelMission(mission)} />}
+ {mission && (
+ <MissionSummary
+ mission={mission}
+ busy={busyMission}
+ onApprove={() => onApproveMission(mission)}
+ onCancel={() => onCancelMission(mission)}
+ onSetBudget={onSetMissionBudget ? (n) => onSetMissionBudget(mission, n) : undefined}
+ />
+ )}
{mission && onView && (
<div role="group" aria-label="Show as" className="inline-flex rounded-lg border border-zinc-800 p-0.5" data-view-toggle>
{(['board', 'graph'] as const).map((v) => (
@@ -1931,7 +2128,14 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
</div>
)}
{drafts.map((m) => (
- <MissionSummary key={m.id} mission={m} busy={busyMission} onApprove={() => onApproveMission(m)} onCancel={() => onCancelMission(m)} />
+ <MissionSummary
+ key={m.id}
+ mission={m}
+ busy={busyMission}
+ onApprove={() => onApproveMission(m)}
+ onCancel={() => onCancelMission(m)}
+ onSetBudget={onSetMissionBudget ? (n) => onSetMissionBudget(m, n) : undefined}
+ />
))}
{showGraph ? (
@@ -1958,7 +2162,17 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
</p>
</div>
) : (
- <Board tasks={shown} names={names} column={column} now={now} showMission={!missionId} onColumn={onColumn} onOpen={onOpenTask} />
+ <Board
+ tasks={shown}
+ names={names}
+ column={column}
+ now={now}
+ showMission={!missionId}
+ onColumn={onColumn}
+ onOpen={onOpenTask}
+ onRemoveLimit={onRemoveLimit}
+ busy={busyCard}
+ />
)}
</>
)}
@@ -1985,6 +2199,7 @@ export const MissionBoardPage: React.FC<{
const [needsToken, setNeedsToken] = useState(false);
const [notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
const [busyMission, setBusyMission] = useState(false);
+ const [busyCard, setBusyCard] = useState(false);
const [openId, setOpenId] = useState<string | null>(null);
const [detail, setDetail] = useState<TaskDetail | null>(null);
const [detailError, setDetailError] = useState<string | null>(null);
@@ -2168,6 +2383,74 @@ export const MissionBoardPage: React.FC<{
}
};
+ const limitDone = (n: number) => (n > 0 ? `Its limit is now ${formatTokens(n)} tokens.` : 'No limit now. It can use as many tokens as it needs.');
+
+ const setTaskBudget = async (budget: number) => {
+ if (!openId) return;
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ const t = await missionsApi.setTaskBudget(openId, budget);
+ if (!alive.current) return;
+ setTasks((list) => (list ? upsertTask(list, t) : list));
+ setDetailNotice({ text: limitDone(budget), error: false });
+ await loadDetail(openId);
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ setDetailNotice({ text: failMsg(e), error: true });
+ } finally {
+ if (alive.current) setBusy(false);
+ }
+ };
+
+ /** Out of budget: the new limit (0 = none), then Unblock. From the open task, or a card on the board. */
+ const continueWithLimit = async (taskId: string, budget: number, fromCard: boolean) => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ if (fromCard) setBusyCard(true);
+ else setBusy(true);
+ if (!fromCard) setDetailNotice(null);
+ try {
+ const t = await missionsApi.continueWithLimit(taskId, budget);
+ if (!alive.current) return;
+ setTasks((list) => (list ? upsertTask(list, t) : list));
+ const text = `${budget > 0 ? `Its limit is now ${formatTokens(budget)} tokens` : 'Limit removed'}. “${t.title}” is back in Ready.`;
+ if (fromCard) setNotice({ text, error: false });
+ else setDetailNotice({ text, error: false });
+ playSfx('click');
+ if (openIdRef.current === taskId) await loadDetail(taskId);
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ if (fromCard) setNotice({ text: failMsg(e), error: true });
+ else setDetailNotice({ text: failMsg(e), error: true });
+ } finally {
+ inFlight.current = false;
+ if (alive.current) {
+ setBusy(false);
+ setBusyCard(false);
+ }
+ }
+ };
+
+ const setMissionBudget = async (m: Mission, budget: number) => {
+ setBusyMission(true);
+ setNotice(null);
+ try {
+ const next = await missionsApi.setBudget(m.id, budget);
+ if (!alive.current) return;
+ setMissions((list) => upsertMission(list, next));
+ setNotice({ text: budget > 0 ? `“${m.title}” can use up to ${formatTokens(budget)} tokens.` : `“${m.title}” has no token limit now.`, error: false });
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ else setNotice({ text: failMsg(e), error: true });
+ } finally {
+ if (alive.current) setBusyMission(false);
+ }
+ };
+
const approveCheck = async (c: Check) => {
setBusy(true);
setDetailNotice(null);
@@ -2382,6 +2665,9 @@ export const MissionBoardPage: React.FC<{
onOpenTask={(t) => openTask(t.id)}
onApproveMission={(m) => missionAction(m, true)}
onCancelMission={(m) => missionAction(m, false)}
+ onSetMissionBudget={setMissionBudget}
+ onRemoveLimit={(t) => continueWithLimit(t.id, NO_LIMIT, true)}
+ busyCard={busyCard}
onRefresh={() => {
load();
if (view === 'graph' && missionId) loadGraph(missionId);
@@ -2413,6 +2699,8 @@ export const MissionBoardPage: React.FC<{
changes={changes}
onRunHeld={runHeld}
onSetClass={setClass}
+ onSetBudget={setTaskBudget}
+ onContinueWithLimit={(n) => continueWithLimit(detail.task.id, n, false)}
onRetryAutofix={retryAutofix}
onSkipAutofix={skipAutofix}
onDecideChange={decideChange}
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 5846e027..2e05b729 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -30,7 +30,22 @@ import { useEngines } from '../useEngines';
import { LayaStatusRow } from './LayaStatus';
import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';
import { ProactiveSettings, WORK_AHEAD_CAP_MAX, WORK_AHEAD_CAP_MIN, parseProactiveSettings } from '../decideFirst';
-import { AUTOFIX_MODES, AutofixSettings, MISSION_BOARD_SETTING_EVENT, parseAutofixSettings, parseMissionBoardSetting } from '../missions';
+import {
+ AUTOFIX_MODES,
+ AutofixSettings,
+ DefaultLimits,
+ LIMIT_PICKS,
+ LimitScope,
+ MISSION_BOARD_SETTING_EVENT,
+ NO_LIMIT,
+ defaultLimitsBody,
+ formatTokens,
+ limitError as tokenLimitError,
+ parseAutofixSettings,
+ parseDefaultLimits,
+ parseLimit,
+ parseMissionBoardSetting,
+} from '../missions';
import { FlightSchoolSettings, TIERS, TIER_HINTS, TIER_LABELS, Tier, parseFlightSchoolSettings } from '../flightSchool';
const RECOVERY_PCTS = [0, 10, 25, 50, 100];
@@ -131,12 +146,86 @@ interface SettingsData {
location?: string;
/** Fresh tokens per request before hand-offs pause; 0 = off. Missing on older servers. */
chain_token_budget?: number;
+ /** Default token limits for new tasks and missions; 0 = no limit. Missing on older servers. */
+ mission_default_task_budget_tokens?: number;
+ mission_default_budget_tokens?: number;
/** Proactive bots; missing on older servers. */
decide_first?: boolean;
work_ahead?: boolean;
work_ahead_daily_cap?: number;
}
+/**
+ * A default token limit: "No limit" or a quick pick, or Custom with a typed amount. `value` is the
+ * typed text while it's custom, so a half-typed amount shows its error; `onChange` gets the text.
+ */
+const DefaultLimitField: React.FC<{ id: string; label: string; scope: LimitScope; value: string; onChange: (v: string) => void }> = ({ id, label, scope, value, onChange }) => {
+ const n = parseLimit(value);
+ const [custom, setCustom] = useState(() => n === null || (n !== NO_LIMIT && !(LIMIT_PICKS as readonly number[]).includes(n)));
+ const err = custom ? tokenLimitError(value, scope) : null;
+ const choice = custom ? 'custom' : String(n ?? NO_LIMIT);
+ return (
+ <div className="space-y-1">
+ <label htmlFor={id} className="block text-[11px] font-medium text-zinc-300">
+ {label}
+ </label>
+ <div className="flex flex-wrap gap-2">
+ <select
+ id={id}
+ value={choice}
+ onChange={(e) => {
+ if (e.target.value === 'custom') {
+ setCustom(true);
+ onChange('');
+ } else {
+ setCustom(false);
+ onChange(e.target.value);
+ }
+ }}
+ className="bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 min-h-[40px] sm:min-h-[36px] text-xs text-zinc-100 focus:outline-none focus:border-sky-500"
+ >
+ <option value={String(NO_LIMIT)}>No limit</option>
+ {LIMIT_PICKS.map((p) => (
+ <option key={p} value={String(p)}>
+ {formatTokens(p)} tokens
+ </option>
+ ))}
+ <option value="custom">Custom…</option>
+ </select>
+ {custom && (
+ <input
+ aria-label={`${label}, custom amount`}
+ type="text"
+ inputMode="decimal"
+ autoComplete="off"
+ placeholder="e.g. 300k"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ aria-invalid={!!err}
+ aria-describedby={`${id}-err`}
+ className={`w-32 bg-zinc-950 border rounded-lg px-3 py-2 text-xs text-zinc-100 focus:outline-none ${err ? 'border-rose-500/60 focus:border-rose-400' : 'border-zinc-800 focus:border-sky-500'}`}
+ />
+ )}
+ </div>
+ {custom && (
+ <p id={`${id}-err`} className={`text-[11px] ${err ? 'text-rose-300' : 'text-zinc-500'}`}>
+ {err ?? 'Tokens, like 300k or 2M.'}
+ </p>
+ )}
+ </div>
+ );
+};
+
+/** Typed default-limit text → numbers, or null while one can't be saved. */
+const defaultLimitsFrom = (t: { task: string; mission: string }): DefaultLimits | null => {
+ const task = parseLimit(t.task);
+ const mission = parseLimit(t.mission);
+ if (task === null || mission === null) return null;
+ if (task !== NO_LIMIT && tokenLimitError(t.task, 'task')) return null;
+ if (mission !== NO_LIMIT && tokenLimitError(t.mission, 'mission')) return null;
+ return { task, mission };
+};
+
const LIMIT_FIELDS: { key: TurnLimitKey; label: string; hint: string }[] = [
{ key: 'max_turns_per_agent', label: 'Replies at once per bot', hint: 'More than this and a bot’s next request waits in line.' },
{ key: 'max_turns_global', label: 'Replies at once in total', hint: 'Across all bots in every space; keeps the server responsive.' },
@@ -194,6 +283,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
// 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);
+ // Default token limits for new tasks and missions, as typed; null on a server without them.
+ const [tokenLimits, setTokenLimits] = useState<{ task: string; mission: string } | null>(null);
+ const tokenLimitsValue = tokenLimits ? defaultLimitsFrom(tokenLimits) : null;
+ const tokenLimitsInvalid = !!tokenLimits && !tokenLimitsValue;
const limitErrors = Object.fromEntries(
LIMIT_FIELDS.map(({ key }) => [key, limits ? limitError(key, limits[key]) : null]),
) as Record<TurnLimitKey, string | null>;
@@ -237,6 +330,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
: null,
);
setChainBudget(typeof data.chain_token_budget === 'number' ? String(data.chain_token_budget) : null);
+ const dl = parseDefaultLimits(data);
+ setTokenLimits(dl ? { task: String(dl.task), mission: String(dl.mission) } : null);
setAgentTools(typeof data.agent_tools === 'boolean' ? data.agent_tools : null);
setProactive(parseProactiveSettings(data));
setMissionBoard(parseMissionBoardSetting(data));
@@ -295,7 +390,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
- if (webhookError || limitsInvalid || chainBudgetError) return;
+ if (webhookError || limitsInvalid || chainBudgetError || tokenLimitsInvalid) return;
setSaveError(null);
setSaving(true);
playSfx('click');
@@ -319,6 +414,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
}
: {}),
...(chainBudget !== null ? { chain_token_budget: budgetValue(chainBudget) } : {}),
+ ...(tokenLimitsValue ? defaultLimitsBody(tokenLimitsValue) : {}),
...(agentTools !== null ? { agent_tools: agentTools } : {}),
...(proactive ?? {}),
...(missionBoard !== null ? { mission_board: missionBoard } : {}),
@@ -629,6 +725,33 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<Gauge size={14} className="text-sky-300" aria-hidden="true" />
<span>Usage</span>
</legend>
+ {tokenLimits !== null && (
+ <div className="space-y-2" role="group" aria-labelledby="token-limits-h" data-token-limits>
+ <div>
+ <p id="token-limits-h" className="text-[11px] font-semibold text-zinc-200">
+ Token limits
+ </p>
+ <p className="text-[11px] text-zinc-500">Bots can use as many tokens as they need. Set a limit to cap spending per task.</p>
+ </div>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <DefaultLimitField
+ id="default-task-limit"
+ label="New tasks"
+ scope="task"
+ value={tokenLimits.task}
+ onChange={(v) => setTokenLimits((p) => (p ? { ...p, task: v } : p))}
+ />
+ <DefaultLimitField
+ id="default-mission-limit"
+ label="New missions"
+ scope="mission"
+ value={tokenLimits.mission}
+ onChange={(v) => setTokenLimits((p) => (p ? { ...p, mission: v } : p))}
+ />
+ </div>
+ <p className="text-[11px] text-zinc-500">You can still set or remove a limit on any task or mission from the board.</p>
+ </div>
+ )}
{chainBudget !== null && (
<div className="space-y-1">
<label htmlFor="chain-token-budget" className="block text-[11px] font-medium text-zinc-300">
@@ -936,7 +1059,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</button>
<button
type="submit"
- disabled={saving || !!webhookError || limitsInvalid}
+ disabled={saving || !!webhookError || limitsInvalid || tokenLimitsInvalid}
className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50"
>
{saving ? 'Saving…' : 'Save'}
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 0d26f7fb..c41c44e4 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -536,11 +536,60 @@ export function formatTokens(n: number): string {
}
const trim = (x: number) => (Math.abs(x) >= 100 ? String(Math.round(x)) : x.toFixed(1).replace(/\.0$/, ''));
-/** "12.4k of 50k tokens"; just the spend when there's no budget. */
+/** "12.4k of 50k tokens"; "64.9k tokens used" when there's no limit (budget 0). */
export function costText(spent: number, budget: number): string {
- return budget > 0 ? `${formatTokens(spent)} of ${formatTokens(budget)} tokens` : `${formatTokens(spent)} tokens`;
+ return budget > 0 ? `${formatTokens(spent)} of ${formatTokens(budget)} tokens` : `${formatTokens(spent)} tokens used`;
}
+// ---------------------------------------------------------------------------
+// Token limits (docs/mission-control.md §15): budget_tokens 0 is "no limit", the default.
+
+export const NO_LIMIT = 0;
+/** Quick picks in the limit editor and Settings. */
+export const LIMIT_PICKS = [50_000, 200_000, 1_000_000] as const;
+/** What the server takes: a task 1–5M, a mission 1000–5M (0 is no limit for both). */
+export const LIMIT_RANGE = { task: [1, 5_000_000], mission: [1_000, 5_000_000] } as const;
+export type LimitScope = keyof typeof LIMIT_RANGE;
+
+/** "50k", "1.5M", "200 000", "200,000" → tokens; null when it isn't a number. */
+export function parseLimit(raw: string): number | null {
+ const s = raw.trim().toLowerCase().replace(/[\s_,]/g, '').replace(/tokens?$/, '');
+ const m = /^(\d+(?:\.\d+)?)([km]?)$/.exec(s);
+ if (!m) return null;
+ const n = Math.round(Number(m[1]) * (m[2] === 'k' ? 1_000 : m[2] === 'm' ? 1_000_000 : 1));
+ return Number.isFinite(n) ? n : null;
+}
+
+/** Why a typed limit can't be used, or null. `above` is what's already spent: a lower limit would stop it at once. */
+export function limitError(raw: string, scope: LimitScope, above = 0): string | null {
+ const n = parseLimit(raw);
+ const [lo, hi] = LIMIT_RANGE[scope];
+ if (n === null) return 'Enter a number of tokens, like 300k or 2M.';
+ if (n < lo) return `At least ${formatTokens(lo)} tokens.`;
+ if (n > hi) return `At most ${formatTokens(hi)} tokens.`;
+ if (above > 0 && n <= above) return `It has already used ${formatTokens(above)}, so pick more than that.`;
+ return null;
+}
+
+/** "No limit" or "50k tokens". */
+export const limitLabel = (budget: number): string => (budget > 0 ? `${formatTokens(budget)} tokens` : 'No limit');
+
+/** Settings' default limits for new tasks and missions (0 = none); null on a server without them. */
+export interface DefaultLimits {
+ task: number;
+ mission: number;
+}
+export function parseDefaultLimits(d: { mission_default_task_budget_tokens?: unknown; mission_default_budget_tokens?: unknown }): DefaultLimits | null {
+ const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.round(v) : null);
+ const task = n(d.mission_default_task_budget_tokens);
+ if (task === null) return null;
+ return { task, mission: n(d.mission_default_budget_tokens) ?? NO_LIMIT };
+}
+export const defaultLimitsBody = (l: DefaultLimits) => ({ mission_default_task_budget_tokens: l.task, mission_default_budget_tokens: l.mission });
+
+/** The task stopped because it used up its own token limit. */
+export const outOfBudget = (t: Pick<Task, 'state' | 'blocked_reason'>): boolean => t.state === 'blocked' && t.blocked_reason === 'budget';
+
/** 0..1 for a spend bar. */
export const costRatio = (spent: number, budget: number): number => (budget > 0 ? Math.max(0, Math.min(1, spent / budget)) : 0);
@@ -631,7 +680,7 @@ export function cardStatus(t: Task, names: Record<string, string> = {}, now: num
switch (t.state) {
case 'blocked':
if (t.needs_you.some((n) => n.kind === ENGINE_CANT_SANDBOX)) return 'Blocked: its engine can’t be held to its tier';
- return t.blocked_reason === 'budget' ? 'Out of budget' : t.blocked_reason ? `Blocked: ${t.blocked_reason}` : 'Blocked';
+ return t.blocked_reason === 'budget' ? 'Reached its token limit' : t.blocked_reason ? `Blocked: ${t.blocked_reason}` : 'Blocked';
case 'failed': {
const auto = autofixCardText(t, now);
if (auto) return auto;
@@ -792,7 +841,7 @@ export const FAILURE_LABELS: Record<FailureClass, { label: string; tone: Tone }>
bad_spec: { label: 'A check can’t run as written', tone: 'amber' },
auth: { label: 'Signed out, or the key was rejected', tone: 'rose' },
quota: { label: 'Usage limit reached', tone: 'amber' },
- budget: { label: 'Out of budget', tone: 'rose' },
+ budget: { label: 'Reached its token limit', tone: 'rose' },
denied: { label: 'An action was denied', tone: 'rose' },
needs_input: { label: 'Waiting for you', tone: 'amber' },
unknown: { label: 'An unexpected error', tone: 'rose' },
@@ -1280,7 +1329,7 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
case 'review':
return `${Who} reviewed it: ${str(d.verdict) === 'pass' ? 'pass' : 'fail'}${note ? `. ${note}` : ''}`;
case 'budget':
- return 'It reached its token budget';
+ return 'It reached its token limit';
case 'edited':
return `${Who} edited it`;
case 'flagged':
@@ -1472,7 +1521,15 @@ export const missionsApi = {
cancelMission: (id: string) => call<Mission>(`/api/missions/${enc(id)}/cancel`, 'POST', {}),
/** Flight School: the person sets the task's kind of work (a slug). */
setTaskClass: (id: string, task_class: string) => call<Task>(`/api/tasks/${enc(id)}`, 'PATCH', { task_class }),
+ /** A mission's token limit; 0 removes it. */
setBudget: (id: string, budget_tokens: number) => call<Mission>(`/api/missions/${enc(id)}`, 'PATCH', { budget_tokens }),
+ /** A task's token limit; 0 removes it. */
+ setTaskBudget: (id: string, budget_tokens: number) => call<Task>(`/api/tasks/${enc(id)}`, 'PATCH', { budget_tokens }),
+ /** A task blocked by its limit: set the new one (0 = none), then unblock it, so it goes back to Ready. */
+ continueWithLimit: async (id: string, budget_tokens: number): Promise<Task> => {
+ await call<Task>(`/api/tasks/${enc(id)}`, 'PATCH', { budget_tokens });
+ return call<Task>(`/api/tasks/${enc(id)}/unblock`, 'POST', {});
+ },
tasks: () => call<{ tasks: Task[] }>('/api/tasks?limit=500').then((r) => r.tasks),
task: (id: string) => call<TaskDetail>(`/api/tasks/${enc(id)}`),
approveCheck: (id: string) => call<Check>(`/api/checks/${enc(id)}/approve`, 'POST', {}),
diff --git a/frontend/tests/missions.test.mjs b/frontend/tests/missions.test.mjs
index 315e20af..fa350229 100644
--- a/frontend/tests/missions.test.mjs
+++ b/frontend/tests/missions.test.mjs
@@ -83,7 +83,7 @@ test('the board renders every column, with Blocked and Failed as badges', () =>
assert.doesNotMatch(html, /data-column="blocked"|data-column="failed"/);
assert.match(html, />Blocked</);
assert.match(html, />Failed</);
- assert.match(html, /Out of budget/);
+ assert.match(html, /Reached its token limit/);
assert.match(html, /Checks failed 3 of 3 times/);
// Phone: tabs with counts drive one column at a time.
assert.match(html, /role="tablist"/);
@@ -111,7 +111,7 @@ test('checksText and costText read plainly', () => {
assert.equal(m.checksText({ status: 'passed', passed: 2, failed: 0, total: 3 }).text, '2 checks passed');
assert.equal(m.checksText({ status: 'passed', passed: 1, failed: 0, total: 1 }).text, 'Check passed');
assert.equal(m.costText(12400, 50000), '12.4k of 50k tokens');
- assert.equal(m.costText(2_000_000, 0), '2M tokens');
+ assert.equal(m.costText(2_000_000, 0), '2M tokens used');
assert.equal(m.costRatio(80, 50), 1);
});
@@ -431,8 +431,8 @@ test('a draft mission waits for the person; over budget says what it means', ()
assert.match(html, /Nothing runs until you approve it/);
assert.match(html, /Approve mission/);
const over = ui.mission({ mission: missionRow({ over_budget: true, spent_tokens: 210000 }), busy: false, onApprove: noop, onCancel: noop });
- assert.match(over, /Over budget/);
- assert.match(over, /raise the budget/);
+ assert.match(over, /Over its limit/);
+ assert.match(over, /raise or remove the mission’s token limit/);
// The board lists drafts on "All work".
assert.match(ui.view(viewProps({ missions: [missionRow({ status: 'draft' })] })), /Approve mission/);
});
diff --git a/frontend/tests/tokenLimits.test.mjs b/frontend/tests/tokenLimits.test.mjs
new file mode 100644
index 00000000..39a7c66a
--- /dev/null
+++ b/frontend/tests/tokenLimits.test.mjs
@@ -0,0 +1,213 @@
+// Token limits are opt-in (docs/mission-control.md §15): budget_tokens 0 means no limit, and it's the
+// default. With no limit the board shows plain usage and no bar; a limit is set or removed in place
+// on the task panel and the mission header; a task stopped by its limit gets "Remove limit and
+// continue", from the card and from the panel, which is one PATCH and one unblock.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'SubmitEvent', 'HTMLFormElement', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const m = await loadBundled(`export * from './src/missions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { TaskCard, TaskDetailBody, MissionSummary, LimitEditor } from './src/components/MissionBoardView';
+ export { createRoot } from 'react-dom/client';
+ export { React, TaskDetailBody, LimitEditor };
+ export const card = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(TaskCard, p)));
+ export const detail = (p) => renderToStaticMarkup(React.createElement(TaskDetailBody, p));
+ export const mission = (p) => renderToStaticMarkup(React.createElement(MissionSummary, p));
+`);
+
+const noop = () => {};
+const NOW = Date.parse('2026-10-28T12:00:00Z');
+const counts = { backlog: 0, ready: 1, working: 0, needs_you: 0, review: 0, verified: 0, blocked: 0, failed: 0, cancelled: 0 };
+const task = (over = {}) => ({
+ id: 't1', space_id: 's1', mission_id: null, mission_title: null, title: 'Write the launch notes', acceptance: 'Notes are in docs/launch.md.',
+ state: 'working', priority: 1, owner_kwant_id: 'k_qa', owner_name: 'QA', suggested_kwant_id: null, budget_tokens: 0, spent_tokens: 64_900,
+ attempts: 0, max_attempts: 3, blocked_reason: null, source_kind: 'delegation', source_id: 'd1', channel_id: 'c1', direct_kwant_id: null,
+ thread_id: null, created_by: 'k_lead', created_at: '2026-10-28T09:00:00Z', updated_at: '2026-10-28T11:00:00Z', finished_at: null,
+ depends_on: [], waiting_on: [], claim: null, needs_you: [], checks_summary: { status: 'not_checked', passed: 0, failed: 0, total: 0 },
+ ...over,
+});
+const outOfBudget = (over = {}) => task({ state: 'blocked', blocked_reason: 'budget', budget_tokens: 50_000, spent_tokens: 186_000, ...over });
+const missionRow = (over = {}) => ({
+ id: 'm1', space_id: 's1', title: 'Ship the pricing page', goal: 'A live pricing page', status: 'active', lead_kwant_id: 'k_lead', lead_name: 'Lead',
+ channel_id: 'c1', direct_kwant_id: null, thread_id: null, budget_tokens: 0, spent_tokens: 420_000, reserved_tokens: 0, over_budget: false,
+ created_by: 'k_lead', approved_at: null, approved_by: null, created_at: '2026-10-28T08:00:00Z', updated_at: '2026-10-28T11:00:00Z', finished_at: null,
+ counts, ...over,
+});
+const detailProps = (t, over = {}) => ({ detail: { task: t, checks: [], evidence: [], events: [] }, names: {}, now: NOW, onAction: noop, onApproveCheck: noop, ...over });
+
+test('no limit reads as plain usage; a limit as "of"', () => {
+ assert.equal(m.costText(64_900, 0), '64.9k tokens used');
+ assert.equal(m.costText(12_400, 50_000), '12.4k of 50k tokens');
+ assert.equal(m.costRatio(64_900, 0), 0);
+ assert.equal(m.limitLabel(0), 'No limit');
+ assert.equal(m.limitLabel(1_000_000), '1M tokens');
+ assert.equal(m.outOfBudget(outOfBudget()), true);
+ assert.equal(m.outOfBudget(task({ state: 'blocked', blocked_reason: 'waiting on legal' })), false);
+ assert.equal(m.cardStatus(outOfBudget()), 'Reached its token limit');
+});
+
+test('typed limits: k and M, separators, ranges, and above what it already used', () => {
+ assert.equal(m.parseLimit('300k'), 300_000);
+ assert.equal(m.parseLimit(' 1.5M '), 1_500_000);
+ assert.equal(m.parseLimit('200,000'), 200_000);
+ assert.equal(m.parseLimit('75 000 tokens'), 75_000);
+ assert.equal(m.parseLimit('lots'), null);
+ assert.equal(m.parseLimit('-5'), null);
+ assert.equal(m.limitError('300k', 'task'), null);
+ assert.match(m.limitError('abc', 'task'), /Enter a number/);
+ assert.match(m.limitError('6M', 'task'), /At most 5M/);
+ assert.match(m.limitError('500', 'mission'), /At least 1k/);
+ assert.equal(m.limitError('500', 'task'), null);
+ assert.match(m.limitError('100k', 'task', 186_000), /already used 186k/);
+ assert.equal(m.limitError('300k', 'task', 186_000), null);
+});
+
+test('Settings defaults: read from the server, sent back as the two settings', () => {
+ assert.deepEqual(m.parseDefaultLimits({ mission_default_task_budget_tokens: 0, mission_default_budget_tokens: 0 }), { task: 0, mission: 0 });
+ assert.deepEqual(m.parseDefaultLimits({ mission_default_task_budget_tokens: 50_000, mission_default_budget_tokens: 200_000 }), { task: 50_000, mission: 200_000 });
+ assert.equal(m.parseDefaultLimits({ mission_default_budget_tokens: 200_000 }), null, 'an older server without the task default');
+ assert.deepEqual(m.defaultLimitsBody({ task: 0, mission: 1_000_000 }), { mission_default_task_budget_tokens: 0, mission_default_budget_tokens: 1_000_000 });
+});
+
+test('the API: set or remove a limit is one PATCH; continuing is PATCH then unblock', async () => {
+ const seen = [];
+ const prev = globalThis.fetch;
+ globalThis.fetch = async (url, init = {}) => {
+ seen.push({ url: String(url), method: init.method ?? 'GET', body: init.body ? JSON.parse(init.body) : null });
+ return new Response(JSON.stringify(String(url).includes('/missions/') ? missionRow() : task({ state: 'ready' })), { status: 200, headers: { 'content-type': 'application/json' } });
+ };
+ try {
+ await m.missionsApi.setTaskBudget('t 1', 200_000);
+ await m.missionsApi.setTaskBudget('t1', 0);
+ await m.missionsApi.setBudget('m1', 0);
+ const t = await m.missionsApi.continueWithLimit('t1', 0);
+ assert.equal(t.state, 'ready');
+ } finally {
+ globalThis.fetch = prev;
+ }
+ assert.deepEqual(seen, [
+ { url: '/api/tasks/t%201', method: 'PATCH', body: { budget_tokens: 200_000 } },
+ { url: '/api/tasks/t1', method: 'PATCH', body: { budget_tokens: 0 } },
+ { url: '/api/missions/m1', method: 'PATCH', body: { budget_tokens: 0 } },
+ { url: '/api/tasks/t1', method: 'PATCH', body: { budget_tokens: 0 } },
+ { url: '/api/tasks/t1/unblock', method: 'POST', body: {} },
+ ]);
+});
+
+test('task panel with no limit: usage, no bar, "Set a limit"', () => {
+ const html = ui.detail(detailProps(task(), { onSetBudget: noop }));
+ assert.match(html, /64\.9k tokens used/);
+ assert.doesNotMatch(html, /role="meter"/);
+ assert.match(html, /data-limit-set[^>]*>Set a limit/);
+ assert.doesNotMatch(html, /rounded-full bg-rose-500/, "no red bar");
+});
+
+test('task panel with a limit: the bar, Change and Remove limit', () => {
+ const html = ui.detail(detailProps(task({ budget_tokens: 200_000 }), { onSetBudget: noop }));
+ assert.match(html, /64\.9k of 200k tokens/);
+ assert.match(html, /role="meter"/);
+ assert.match(html, />Change</);
+ assert.match(html, />Remove limit</);
+});
+
+test('out of budget: the panel offers Remove limit and continue and Raise limit, not a bare Unblock', () => {
+ const html = ui.detail(detailProps(outOfBudget(), { onSetBudget: noop, onContinueWithLimit: noop }));
+ assert.match(html, /stopped at its 50k token limit after using 186k/);
+ assert.match(html, /data-remove-limit-continue[^>]*>Remove limit and continue/);
+ assert.match(html, /data-raise-limit[^>]*>Raise limit/);
+ assert.doesNotMatch(html, />Unblock</);
+ assert.match(html, />Cancel task</);
+ // Any other block keeps its Unblock.
+ assert.match(ui.detail(detailProps(task({ state: 'blocked', blocked_reason: 'waiting on legal' }))), />Unblock</);
+});
+
+test('out of budget on the board: the card has the one-click button', () => {
+ const html = ui.card({ task: outOfBudget(), names: {}, now: NOW, onOpen: noop, onRemoveLimit: noop });
+ assert.match(html, /186k of 50k tokens/);
+ assert.match(html, /data-card-remove-limit[^>]*>Remove limit and continue/);
+ assert.doesNotMatch(ui.card({ task: task(), names: {}, now: NOW, onOpen: noop, onRemoveLimit: noop }), /Remove limit and continue/);
+});
+
+test('mission header: no limit shows usage and Set a limit; a limit shows the bar', () => {
+ const none = ui.mission({ mission: missionRow(), busy: false, onApprove: noop, onCancel: noop, onSetBudget: noop });
+ assert.match(none, /420k tokens used/);
+ assert.doesNotMatch(none, /role="meter"/);
+ assert.match(none, />Set a limit</);
+ const some = ui.mission({ mission: missionRow({ budget_tokens: 1_000_000 }), busy: false, onApprove: noop, onCancel: noop, onSetBudget: noop });
+ assert.match(some, /420k of 1M tokens/);
+ assert.match(some, /role="meter"/);
+ assert.match(some, />Remove limit</);
+});
+
+// ---- Pressing things, in a DOM ----
+
+const settle = async () => {
+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0));
+};
+async function mount(el) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = ui.createRoot(host);
+ root.render(el);
+ await settle();
+ return { host, done: () => (root.unmount(), host.remove()) };
+}
+const click = async (el) => {
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const type = async (input, text) => {
+ const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
+ set.call(input, text);
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+};
+
+test('Set a limit: a quick pick sets it in one press; Custom takes "300k"', async () => {
+ const set = [];
+ const v = await mount(ui.React.createElement(ui.LimitEditor, { budget: 0, spent: 64_900, scope: 'task', onSet: (n) => set.push(n) }));
+ try {
+ await click(v.host.querySelector('[data-limit-set]'));
+ const picks = [...v.host.querySelectorAll('[data-limit-pick]')].map((b) => b.textContent);
+ assert.deepEqual(picks, ['No limit', '50k', '200k', '1M'], 'with no limit every pick is offered');
+ await click(v.host.querySelector('[data-limit-pick="200000"]'));
+ assert.deepEqual(set, [200_000]);
+ assert.ok(v.host.querySelector('[data-limit-editor="closed"]'), 'it closes after a pick');
+ await click(v.host.querySelector('[data-limit-set]'));
+ await click(v.host.querySelector('[data-limit-custom]'));
+ const input = v.host.querySelector('input');
+ await type(input, '300k');
+ v.host.querySelector('form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.deepEqual(set, [200_000, 300_000]);
+ } finally {
+ v.done();
+ }
+});
+
+test('Out of budget: Remove limit and continue sends 0; Raise limit only offers more than it used', async () => {
+ const sent = [];
+ const v = await mount(ui.React.createElement(ui.TaskDetailBody, detailProps(outOfBudget(), { onContinueWithLimit: (n) => sent.push(n) })));
+ try {
+ await click(v.host.querySelector('[data-remove-limit-continue]'));
+ assert.deepEqual(sent, [0]);
+ await click(v.host.querySelector('[data-raise-limit]'));
+ const picks = [...v.host.querySelectorAll('[data-limit-pick]')].map((b) => b.getAttribute('data-limit-pick'));
+ assert.deepEqual(picks, ['200000', '1000000'], '50k is under the 186k it used, and "No limit" is the main button');
+ await click(v.host.querySelector('[data-limit-pick="1000000"]'));
+ assert.deepEqual(sent, [0, 1_000_000]);
+ } finally {
+ v.done();
+ }
+});