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.

UI: Flight School scorecards and tier requests (C4, #182)

Pixel (kwant bot)ae6dd1e29c21
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index cc66791c..62165249 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -344,6 +344,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Opens the chat of a bot's newest open browser step; false when it has none.
const openHumanStepRef = useRef<(kwantId: string) => boolean>(() => false);
const openTargetRef = useRef<(t: ChatTarget) => boolean>(() => false);
+ // A tier request is decided on the board's Needs-you list.
+ const openBoardForTier = () => {
+ setShowMissions(true);
+ setShowConnections(false);
+ setShowLoose(false);
+ setShowParallel(false);
+ setShowAway(false);
+ setPhoneView('chat');
+ };
const showNotification = (n: NotifyEvent) => {
// Another space's news is the shell's to show, with a way to switch there.
if (n.space_id && n.space_id !== space.id) return;
@@ -351,7 +360,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
// Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
- if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && n.kind !== 'tier_proposed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
const id = ++toastIdRef.current;
const action =
n.kind === 'routine_failed'
@@ -360,6 +369,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
? { label: 'Review', onClick: () => openSkillsRef.current(n.kwant_id) }
: n.kind === 'automation_suggested'
? { label: 'Review', onClick: () => setIsRoutinesOpen(true) }
+ : n.kind === 'tier_proposed'
+ ? { label: 'Review', onClick: openBoardForTier }
: n.kind === 'question_asked'
? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openTargetRef.current(target) }
: n.kind === 'human_step'
@@ -378,6 +389,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);
// A suggested routine is decided in Routines, not in the bot's chat
else if (n.kind === 'automation_suggested') setIsRoutinesOpen(true);
+ else if (n.kind === 'tier_proposed') openBoardForTier();
else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) {
setIsVmPaneOpen(true);
// A CAPTCHA lands straight in the solve view
@@ -928,6 +940,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'mission_updated':
if (event.data?.mission) emitMission({ type: 'mission_updated', data: { mission: event.data.mission } });
break;
+ case 'capability_changed':
+ case 'CapabilityChanged':
+ if (event.data?.capability?.kwant_id) emitMission({ type: 'capability_changed', data: { capability: event.data.capability } });
+ break;
case 'routine_run':
case 'RoutineRun':
emitContinuity({ type: 'routine_run', data: event.data });
diff --git a/frontend/src/components/FlightSchoolPanel.tsx b/frontend/src/components/FlightSchoolPanel.tsx
index 619458dd..ff183831 100644
--- a/frontend/src/components/FlightSchoolPanel.tsx
+++ b/frontend/src/components/FlightSchoolPanel.tsx
@@ -1,8 +1,9 @@
-// A bot's Flight School tiers (Phase C3, docs/mission-control.md §14): one tier for all its work, one
-// per kind of work, where each comes from, a one-click Revoke, and the recent changes. Only shown with
-// Flight School on; on a server without it, or with it off, this renders nothing.
+// A bot's Flight School tiers (Phase C3/C4, docs/mission-control.md §14): one tier for all its work,
+// one per kind of work, where each comes from, a one-click Revoke, its scorecard per kind of work, the
+// tiers it is asking for, and the recent changes. Only shown with Flight School on; on a server without
+// it, or with it off, this renders nothing. Changes made elsewhere arrive live (`capability_changed`).
-import React, { useEffect, useId, useState } from 'react';
+import React, { useCallback, useEffect, useId, useState } from 'react';
import { AlertTriangle, GraduationCap, Loader2 } from 'lucide-react';
import {
ANY_CLASS,
@@ -15,17 +16,27 @@ import {
capabilityEventText,
classLabel,
fromText,
+ isOpenProposal,
isTier,
+ openProposals,
+ ProposalDecision,
+ Scorecard,
+ TierProposal,
revokeTarget,
toClass,
validClass,
} from '../flightSchool';
-import { ago, capabilitiesApi } from '../missions';
+import { ago, capabilitiesApi, onMission } from '../missions';
+import { ProposalCard, ScorecardDisclosure, useProposalDecisions } from './TierProposals';
export interface CapabilitiesApi {
get: (kwantId: string) => Promise<Capabilities>;
set: (kwantId: string, taskClass: string, tier: Tier) => Promise<CapabilityChange>;
revoke: (kwantId: string, taskClass: string, toTier: Tier) => Promise<CapabilityChange>;
+ scorecard: (kwantId: string, taskClass: string) => Promise<Scorecard>;
+ proposals: (status?: string, kwantId?: string) => Promise<TierProposal[]>;
+ grant: (id: string, key: string) => Promise<ProposalDecision>;
+ decline: (id: string, key: string, note?: string) => Promise<ProposalDecision>;
}
const select =
@@ -67,9 +78,20 @@ export const FlightSchoolPanel: React.FC<{
const [note, setNote] = useState<string | null>(null);
const [newClass, setNewClass] = useState('');
const [newTier, setNewTier] = useState<Tier>('sandbox');
+ // Bumped by a live change so open scorecards read again.
+ const [version, setVersion] = useState(0);
+ // Decided here this session, shown with what happened until the panel closes.
+ const [decided, setDecided] = useState<TierProposal[]>([]);
const allId = useId();
const newId = useId();
+ const reload = useCallback(() => {
+ api
+ .get(kwantId)
+ .then(setCaps)
+ .catch(() => {});
+ }, [api, kwantId]);
+
useEffect(() => {
if (initial !== undefined) return;
let live = true;
@@ -83,8 +105,43 @@ export const FlightSchoolPanel: React.FC<{
};
}, [kwantId, initial, api]);
+ // A grant, decline, revoke or new request from another tab, device or the bot itself.
+ useEffect(
+ () =>
+ onMission('capability_changed', ({ capability }) => {
+ if (capability.kwant_id !== kwantId) return;
+ reload();
+ setVersion((v) => v + 1);
+ }),
+ [kwantId, reload],
+ );
+
+ const onDecided = useCallback(
+ (p: TierProposal, d: ProposalDecision | null) => {
+ if (d) {
+ setCaps(d.capabilities);
+ setDecided((cur) => [d.proposal, ...cur.filter((x) => x.id !== p.id)]);
+ } else {
+ // 409: someone else decided. Keep the card with the conflict, and read what holds now.
+ setDecided((cur) => [p, ...cur.filter((x) => x.id !== p.id)]);
+ api.get(kwantId).then(
+ (c) => {
+ setCaps(c);
+ const now = c.proposals?.find((x) => x.id === p.id);
+ if (now) setDecided((cur) => cur.map((x) => (x.id === p.id ? now : x)));
+ },
+ () => {},
+ );
+ }
+ },
+ [api, kwantId],
+ );
+ const decisions = useProposalDecisions(api, onDecided);
+
// Nothing while loading, on an older server, or with Flight School off: the bot's settings look as before.
if (!caps || !caps.flight_school) return null;
+ const decidedIds = new Set(decided.map((p) => p.id));
+ const asking = [...openProposals(caps.proposals ?? []).filter((p) => !decidedIds.has(p.id)), ...decided];
const change = async (run: () => Promise<CapabilityChange>, done: string) => {
setBusy(true);
@@ -97,8 +154,8 @@ export const FlightSchoolPanel: React.FC<{
return true;
} catch (e) {
setError(e instanceof Error ? e.message : 'Couldn’t change the tier.');
- // There's no live update for tiers: read them again so the screen shows what holds.
- api.get(kwantId).then(setCaps).catch(() => {});
+ // Read them again so the screen shows what holds.
+ reload();
return false;
} finally {
setBusy(false);
@@ -139,6 +196,23 @@ export const FlightSchoolPanel: React.FC<{
</div>
<p className="text-[11px] text-zinc-500">{TIER_HINTS[caps.default_tier]}</p>
+ {asking.length > 0 && (
+ <ul className="space-y-2" aria-label={`Tiers ${kwantName} is asking for`} data-bot-proposals={asking.filter(isOpenProposal).length}>
+ {asking.map((p) => (
+ <ProposalCard
+ key={p.id}
+ proposal={p}
+ bot={kwantName}
+ now={now}
+ busy={decisions.busyId === p.id}
+ error={decisions.errors[p.id] ?? null}
+ onGrant={decisions.grant}
+ onDecline={decisions.decline}
+ />
+ ))}
+ </ul>
+ )}
+
<ul className="divide-y divide-zinc-800 rounded-lg border border-zinc-800" aria-label="Tier per kind of work">
{caps.effective.map((e) => (
<li key={e.task_class} className="flex flex-wrap items-center gap-2 px-2.5 py-2" data-class={e.task_class} data-tier={e.tier} data-from={e.from}>
@@ -148,6 +222,7 @@ export const FlightSchoolPanel: React.FC<{
</span>
<TierSelect label={`Tier for ${classLabel(e.task_class)}`} value={e.tier} disabled={busy} onChange={(t) => setTier(e.task_class, t)} />
<RevokeButton what={classLabel(e.task_class)} tier={e.tier} disabled={busy} onRevoke={(to) => revoke(e.task_class, to)} />
+ {e.task_class !== ANY_CLASS && <ScorecardDisclosure kwantId={kwantId} taskClass={e.task_class} api={api} version={version} />}
</li>
))}
</ul>
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index edae9dc6..fb33d4a9 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -34,6 +34,7 @@ import {
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { ModernAvatar } from './ModernAvatar';
import { PerformancePanel } from './PerformancePanel';
+import { TierRequests } from './TierProposals';
import { RisksSection } from './RisksSection';
import { AuditWaiting, Risk, RiskResolution, TaskRisks, auditCardPlace, auditLive, auditWaiting, openRiskCounts, riskBadgeText, riskResolvedText } from '../auditor';
import { awayApi } from '../away';
@@ -2628,6 +2629,8 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
<InsightsStrip insights={insights} needsYou={needsYouCount(tasks)} />
+ <TierRequests names={names} now={now} />
+
{visibleMissions.length > 0 && (
<div className="flex flex-wrap items-center gap-2">
<label htmlFor={selectId} className="text-[11px] font-medium text-zinc-400">
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 29fd2a7a..80e44caa 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -459,7 +459,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
openai_api_key: openaiKey,
ollama_url: ollamaUrl,
notify_webhook_url: webhookUrl.trim(),
- notify_on: notifyOnToSave(notifyOn, appUpdates, !!proactive, !!discovery),
+ notify_on: notifyOnToSave(notifyOn, appUpdates, !!proactive, !!discovery, flightSchool !== null),
...(limits
? {
max_turns_per_agent: Number(limits.max_turns_per_agent),
@@ -1089,7 +1089,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<div className="space-y-1.5" role="group" aria-labelledby="notify-kinds-label">
<p id="notify-kinds-label" className="text-xs font-medium text-zinc-400">Tell me when</p>
- {notifyKindsFor(appUpdates, !!proactive, !!discovery).map((k) => (
+ {notifyKindsFor(appUpdates, !!proactive, !!discovery, !!flightSchool?.flight_school).map((k) => (
<label key={k.id} className="flex items-center gap-2 text-[11px] text-zinc-300">
<input
type="checkbox"
diff --git a/frontend/src/components/TierProposals.tsx b/frontend/src/components/TierProposals.tsx
new file mode 100644
index 00000000..30d0af8e
--- /dev/null
+++ b/frontend/src/components/TierProposals.tsx
@@ -0,0 +1,384 @@
+// Flight School scorecards and proposals (Phase C4, docs/mission-control.md §14). A bot that has
+// earned the next tier asks for it; only the person grants or declines, and revoking stays one tap
+// in the bot's settings. A grant or decline that another tab or device got to first (409) says so
+// and shows what holds now. With Flight School off the server has no open proposals, so nothing shows.
+
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { AlertTriangle, Check, GraduationCap, Loader2, X } from 'lucide-react';
+import {
+ ProposalDecision,
+ Scorecard,
+ TierProposal,
+ classLabel,
+ isOpenProposal,
+ openProposals,
+ proposalChange,
+ proposalConflictText,
+ proposalOutcome,
+ proposalTitle,
+ scorecardRows,
+ scorecardStatus,
+ upsertProposal,
+} from '../flightSchool';
+import { MissionError, ago, capabilitiesApi, newIdempotencyKey, onMission } from '../missions';
+
+export interface ProposalsApi {
+ proposals: typeof capabilitiesApi.proposals;
+ grant: (id: string, key: string) => Promise<ProposalDecision>;
+ decline: (id: string, key: string, note?: string) => Promise<ProposalDecision>;
+}
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';
+const btn = `inline-flex items-center justify-center gap-1 px-3 min-h-[40px] sm:min-h-[32px] rounded-lg text-xs font-medium disabled:opacity-50 ${focusRing}`;
+
+/** A scorecard's numbers as a small definition list, with what it can ask for under them. */
+export const ScorecardView: React.FC<{ card: Partial<Scorecard>; compact?: boolean }> = ({ card, compact = false }) => {
+ const rows = scorecardRows(card);
+ const status = card.tier && card.missing ? scorecardStatus(card as Scorecard) : null;
+ return (
+ <div className="space-y-1.5" data-scorecard={card.task_class ?? ''}>
+ {rows.length === 0 ? (
+ <p className="text-[11px] text-zinc-500">No settled work in this kind yet.</p>
+ ) : (
+ <dl className={`grid gap-x-3 gap-y-0.5 text-[11px] ${compact ? 'grid-cols-[auto_1fr]' : 'grid-cols-[auto_1fr] sm:grid-cols-[auto_1fr_auto_1fr]'}`}>
+ {rows.map((r) => (
+ <React.Fragment key={r.label}>
+ <dt className="text-zinc-500">{r.label}</dt>
+ <dd className={`tabular-nums ${r.bad ? 'text-rose-300' : 'text-zinc-200'}`}>{r.value}</dd>
+ </React.Fragment>
+ ))}
+ </dl>
+ )}
+ {status && (
+ <p className={`text-[11px] ${status.ready ? 'text-emerald-300' : 'text-zinc-400'}`} data-scorecard-status={status.ready ? 'ready' : 'not-yet'}>
+ {status.text}
+ </p>
+ )}
+ {card.window_days ? <p className="text-[10px] text-zinc-600">From the board’s own records of the last {card.window_days} days.</p> : null}
+ </div>
+ );
+};
+
+/**
+ * One proposal: who asks for what and why, its scorecard when it asked, and Grant / Decline. A
+ * decided one shows what happened instead of the buttons.
+ */
+export const ProposalCard: React.FC<{
+ proposal: TierProposal;
+ bot: string;
+ now?: number;
+ busy?: boolean;
+ /** Set while this card's decision failed or someone else decided first. */
+ error?: string | null;
+ onGrant: (p: TierProposal) => void;
+ onDecline: (p: TierProposal, note: string) => void;
+}> = ({ proposal: p, bot, now = Date.now(), busy = false, error = null, onGrant, onDecline }) => {
+ const id = useId();
+ const [declining, setDeclining] = useState(false);
+ const [note, setNote] = useState('');
+ const noteRef = useRef<HTMLInputElement>(null);
+ const open = isOpenProposal(p);
+ useEffect(() => {
+ if (declining) noteRef.current?.focus();
+ }, [declining]);
+ const submitDecline = () => {
+ if (!busy) onDecline(p, note.trim());
+ };
+ // No <form>: in a bot's settings this card sits inside the Edit bot form, and forms can't nest.
+ const onNoteKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ setDeclining(false);
+ } else if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ submitDecline();
+ }
+ };
+ return (
+ <li
+ aria-labelledby={`${id}-t`}
+ className={`rounded-xl border px-3 py-2.5 space-y-2 ${open ? 'border-amber-500/30 bg-amber-500/5' : 'border-zinc-800 bg-zinc-900/40'}`}
+ data-proposal={p.id}
+ data-status={p.status}
+ >
+ <div className="flex items-start gap-2">
+ <GraduationCap size={16} className={`mt-0.5 shrink-0 ${open ? 'text-amber-300' : 'text-zinc-500'}`} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p id={`${id}-t`} className="text-xs font-medium text-zinc-100 break-words">
+ {proposalTitle(p, bot)}
+ </p>
+ <p className="text-[11px] text-zinc-400">
+ {proposalChange(p)} <span className="text-zinc-600">· asked {ago(p.created_at, now)}</span>
+ </p>
+ </div>
+ </div>
+
+ {p.reason && (
+ <blockquote className="border-l-2 border-zinc-700 pl-2 text-[11px] text-zinc-300 break-words">
+ <span className="sr-only">{bot} says: </span>
+ {p.reason}
+ </blockquote>
+ )}
+
+ {p.scorecard && (
+ <details className="text-[11px]">
+ <summary className={`cursor-pointer text-zinc-400 hover:text-zinc-200 rounded ${focusRing}`}>Its scorecard when it asked</summary>
+ <div className="mt-1.5">
+ <ScorecardView card={{ ...p.scorecard, task_class: p.task_class }} />
+ </div>
+ </details>
+ )}
+
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 text-[11px] text-rose-300" data-proposal-error>
+ <AlertTriangle size={12} className="mt-px shrink-0" aria-hidden="true" /> <span>{error}</span>
+ </p>
+ )}
+
+ {!open ? (
+ <p className={`text-[11px] ${p.status === 'granted' ? 'text-emerald-300' : 'text-zinc-400'}`} data-outcome={p.status}>
+ {proposalOutcome(p, bot)}
+ </p>
+ ) : declining ? (
+ <div role="group" aria-label={`Decline: ${proposalTitle(p, bot)}`} className="flex flex-wrap items-center gap-2" data-decline-form>
+ <label htmlFor={`${id}-n`} className="sr-only">
+ Why not? Optional, {bot} sees it
+ </label>
+ <input
+ ref={noteRef}
+ id={`${id}-n`}
+ value={note}
+ maxLength={500}
+ onChange={(e) => setNote(e.target.value)}
+ onKeyDown={onNoteKey}
+ placeholder="Why not? (optional)"
+ className="flex-1 min-w-[10rem] bg-zinc-950 border border-zinc-800 rounded-lg px-2.5 min-h-[40px] sm:min-h-[32px] text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none"
+ />
+ <button type="button" disabled={busy} onClick={submitDecline} className={`${btn} border border-rose-500/40 text-rose-200 hover:bg-rose-500/10`} data-confirm-decline>
+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : null} Decline
+ </button>
+ <button type="button" disabled={busy} onClick={() => setDeclining(false)} className={`${btn} text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800`}>
+ Cancel
+ </button>
+ </div>
+ ) : (
+ <div className="flex flex-wrap items-center gap-2" role="group" aria-label={`Decide: ${proposalTitle(p, bot)}`}>
+ <button type="button" disabled={busy} onClick={() => onGrant(p)} className={`${btn} bg-emerald-600/90 text-white hover:bg-emerald-500`} data-grant>
+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={12} aria-hidden="true" />}
+ Grant {p.to_tier === 'act' ? 'Act' : p.to_tier === 'sandbox' ? 'Sandbox' : 'Observe'}
+ </button>
+ <button type="button" disabled={busy} onClick={() => setDeclining(true)} className={`${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700`} data-decline>
+ <X size={12} aria-hidden="true" /> Decline…
+ </button>
+ <span className="text-[10px] text-zinc-500">Payments always ask you, whatever the tier.</span>
+ </div>
+ )}
+ </li>
+ );
+};
+
+/**
+ * Grant/decline with one key per proposal and press, conflict handling and the decided proposal
+ * kept on screen. Shared by the board's Needs you list and the bot's settings.
+ */
+export function useProposalDecisions(api: ProposalsApi, onDecided: (p: TierProposal, d: ProposalDecision | null) => void) {
+ const [busyId, setBusyId] = useState<string | null>(null);
+ const [errors, setErrors] = useState<Record<string, string>>({});
+ const keys = useRef<Record<string, string>>({});
+ const decide = useCallback(
+ async (p: TierProposal, run: (key: string) => Promise<ProposalDecision>, what: 'grant' | 'decline') => {
+ if (busyId) return;
+ const k = `${what}:${p.id}`;
+ const key = (keys.current[k] ??= newIdempotencyKey());
+ setBusyId(p.id);
+ setErrors(({ [p.id]: _gone, ...rest }) => rest);
+ try {
+ onDecided(p, await run(key));
+ } catch (e) {
+ if (e instanceof MissionError && e.status === 409) {
+ setErrors((x) => ({ ...x, [p.id]: proposalConflictText(e.code, e.message) }));
+ onDecided(p, null);
+ } else {
+ // Another press is a new try with the same key: a lost answer replays, not repeats.
+ setErrors((x) => ({ ...x, [p.id]: e instanceof Error ? e.message : 'Couldn’t save that. Try again.' }));
+ }
+ } finally {
+ setBusyId(null);
+ }
+ },
+ [busyId, onDecided],
+ );
+ return {
+ busyId,
+ errors,
+ grant: (p: TierProposal) => decide(p, (key) => api.grant(p.id, key), 'grant'),
+ decline: (p: TierProposal, note: string) => decide(p, (key) => api.decline(p.id, key, note || undefined), 'decline'),
+ };
+}
+
+/**
+ * The board's Needs-you list of tier requests. Loads its own list, keeps it live, and shows nothing
+ * when no bot is asking (which is always the case with Flight School off).
+ */
+export const TierRequests: React.FC<{
+ names: Record<string, string>;
+ now?: number;
+ /** Tests pass the loaded list and the API. */
+ initial?: TierProposal[];
+ api?: ProposalsApi;
+}> = ({ names, now, initial, api = capabilitiesApi }) => {
+ const headId = useId();
+ const [list, setList] = useState<TierProposal[]>(initial ?? []);
+ // Decided here this session: kept on screen with their outcome until the board reloads.
+ const [decided, setDecided] = useState<TierProposal[]>([]);
+ const alive = useRef(true);
+ useEffect(
+ () => () => {
+ alive.current = false;
+ },
+ [],
+ );
+
+ const reload = useCallback(() => {
+ api.proposals('proposed').then(
+ (ps) => alive.current && setList(ps),
+ // An older server (404) or Flight School off: nothing to ask about.
+ () => {},
+ );
+ }, [api]);
+
+ useEffect(() => {
+ if (initial === undefined) reload();
+ return onMission('capability_changed', ({ capability }) => {
+ const p = capability.proposal;
+ if (p?.id) {
+ setList((cur) => (isOpenProposal(p) ? upsertProposal(cur, p) : cur.filter((x) => x.id !== p.id)));
+ if (!isOpenProposal(p)) setDecided((cur) => (cur.some((x) => x.id === p.id) ? cur.map((x) => (x.id === p.id ? p : x)) : cur));
+ } else reload();
+ });
+ }, [initial, reload]);
+
+ const onDecided = useCallback(
+ (p: TierProposal, d: ProposalDecision | null) => {
+ if (d) {
+ setList((cur) => cur.filter((x) => x.id !== p.id));
+ setDecided((cur) => [d.proposal, ...cur.filter((x) => x.id !== p.id)]);
+ } else {
+ // 409: someone else decided. Read what holds now; the error stays on the card.
+ setDecided((cur) => [{ ...p }, ...cur.filter((x) => x.id !== p.id)]);
+ setList((cur) => cur.filter((x) => x.id !== p.id));
+ api.proposals(undefined).then(
+ (all) => {
+ if (!alive.current) return;
+ const now = all.find((x) => x.id === p.id);
+ if (now) setDecided((cur) => cur.map((x) => (x.id === p.id ? now : x)));
+ setList(openProposals(all));
+ },
+ () => {},
+ );
+ }
+ },
+ [api],
+ );
+ const { busyId, errors, grant, decline } = useProposalDecisions(api, onDecided);
+
+ const open = openProposals(list);
+ if (!open.length && !decided.length) return null;
+ const bot = (p: TierProposal) => names[p.kwant_id] ?? 'A bot';
+ return (
+ <section aria-labelledby={headId} className="space-y-2" data-tier-requests={open.length}>
+ <h3 id={headId} className="flex items-center gap-1.5 text-xs font-medium text-amber-200">
+ <GraduationCap size={14} aria-hidden="true" /> Needs you: {open.length === 1 ? 'a bot asks' : open.length > 1 ? `${open.length} bots ask` : 'tier requests'} for more freedom
+ </h3>
+ <ul className="grid gap-2 md:grid-cols-2">
+ {[...open, ...decided].map((p) => (
+ <ProposalCard key={p.id} proposal={p} bot={bot(p)} now={now} busy={busyId === p.id} error={errors[p.id] ?? null} onGrant={grant} onDecline={decline} />
+ ))}
+ </ul>
+ {open.length === 0 && (
+ <p className="text-[11px] text-zinc-500" data-requests-done>
+ Nothing else is waiting.{' '}
+ <button type="button" onClick={() => setDecided([])} className={`underline hover:text-zinc-300 rounded ${focusRing}`}>
+ Hide
+ </button>
+ </p>
+ )}
+ </section>
+ );
+};
+
+/** Keeps a bot's scorecard for one kind of work, loaded when first shown. */
+export function useScorecard(kwantId: string, taskClass: string, shown: boolean, api: Pick<typeof capabilitiesApi, 'scorecard'> = capabilitiesApi) {
+ const [card, setCard] = useState<Scorecard | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
+ const load = useCallback(() => {
+ setLoading(true);
+ setError(null);
+ let live = true;
+ api
+ .scorecard(kwantId, taskClass)
+ .then((c) => live && setCard(c))
+ .catch((e) => live && setError(e instanceof Error ? e.message : 'Couldn’t load the scorecard.'))
+ .finally(() => live && setLoading(false));
+ return () => {
+ live = false;
+ };
+ }, [api, kwantId, taskClass]);
+ useEffect(() => {
+ if (shown) return load();
+ }, [shown, load]);
+ return { card, error, loading, reload: load };
+}
+
+export const ScorecardDisclosure: React.FC<{
+ kwantId: string;
+ taskClass: string;
+ api?: Pick<typeof capabilitiesApi, 'scorecard'>;
+ /** Tests open it with a loaded card. */
+ initial?: Scorecard;
+ /** Bumped by live updates so an open scorecard reads again. */
+ version?: number;
+}> = ({ kwantId, taskClass, api, initial, version = 0 }) => {
+ const [shown, setShown] = useState(Boolean(initial));
+ const id = useId();
+ const { card, error, loading, reload } = useScorecard(kwantId, taskClass, shown && !initial, api);
+ useEffect(() => {
+ if (shown && !initial && version > 0) reload();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [version]);
+ const c = initial ?? card;
+ return (
+ <div className="w-full">
+ <button
+ type="button"
+ aria-expanded={shown}
+ aria-controls={`${id}-c`}
+ onClick={() => setShown((v) => !v)}
+ className={`text-[11px] text-sky-300 hover:text-sky-200 rounded ${focusRing}`}
+ data-scorecard-toggle={taskClass}
+ >
+ {shown ? 'Hide scorecard' : 'Scorecard'}
+ <span className="sr-only"> for {classLabel(taskClass)}</span>
+ </button>
+ {shown && (
+ <div id={`${id}-c`} className="mt-1.5 rounded-lg bg-zinc-950/60 px-2.5 py-2">
+ {loading && !c ? (
+ <p className="flex items-center gap-1.5 text-[11px] text-zinc-400">
+ <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading the scorecard…
+ </p>
+ ) : error && !c ? (
+ <p role="alert" className="flex flex-wrap items-center gap-2 text-[11px] text-rose-300">
+ <AlertTriangle size={12} aria-hidden="true" /> {error}
+ <button type="button" onClick={reload} className={`underline hover:text-rose-200 rounded ${focusRing}`}>
+ Try again
+ </button>
+ </p>
+ ) : c ? (
+ <ScorecardView card={c} compact />
+ ) : null}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index f3fcb345..81372135 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -142,21 +142,32 @@ export const WORK_AHEAD_KIND: { id: NotifyKind; label: string } = { id: 'work_ah
/** Sent by servers with Automation Discovery (`automation_discovery` in GET /api/settings). Not a Needs-you item. */
export const AUTOMATION_SUGGESTED_KIND: { id: NotifyKind; label: string } = { id: 'automation_suggested', label: 'A routine was suggested' };
+/** Sent by servers with Flight School (C4) when a bot asks for a higher tier. A Needs-you item. */
+export const TIER_PROPOSED_KIND: { id: NotifyKind; label: string } = { id: 'tier_proposed', label: 'A bot asks for a higher tier' };
+
/**
* The checkboxes under "Tell me when": App updates only in the Mac app, work ahead and suggested
- * routines only where the server has them.
+ * routines only where the server has them, tier requests only with Flight School on.
*/
-export const notifyKindsFor = (appUpdates: boolean, workAhead = false, discovery = false) => [
+export const notifyKindsFor = (appUpdates: boolean, workAhead = false, discovery = false, tiers = false) => [
...NOTIFY_KINDS,
+ ...(tiers ? [TIER_PROPOSED_KIND] : []),
...(workAhead ? [WORK_AHEAD_KIND] : []),
...(discovery ? [AUTOMATION_SUGGESTED_KIND] : []),
...(appUpdates ? [APP_UPDATE_KIND] : []),
];
-/** What to save: never a kind the server doesn't know (it would refuse the whole list). */
-export const notifyOnToSave = (on: NotifyKind[], appUpdates: boolean, workAhead = false, discovery = false) =>
+/**
+ * What to save: never a kind the server doesn't know (it would refuse the whole list). `flightSchool`
+ * is whether the server has Flight School at all: a hidden tier-request choice is kept while it's off.
+ */
+export const notifyOnToSave = (on: NotifyKind[], appUpdates: boolean, workAhead = false, discovery = false, flightSchool = false) =>
on.filter(
- (k) => (k !== APP_UPDATE_KIND.id || appUpdates) && (k !== WORK_AHEAD_KIND.id || workAhead) && (k !== AUTOMATION_SUGGESTED_KIND.id || discovery),
+ (k) =>
+ (k !== APP_UPDATE_KIND.id || appUpdates) &&
+ (k !== WORK_AHEAD_KIND.id || workAhead) &&
+ (k !== AUTOMATION_SUGGESTED_KIND.id || discovery) &&
+ (k !== TIER_PROPOSED_KIND.id || flightSchool),
);
/** Kinds also shown as an in-app toast while kwnt is visible (the others only matter in the background). */
@@ -168,6 +179,7 @@ export const TOAST_KINDS: NotifyKind[] = [
'question_asked',
'human_step',
'automation_suggested',
+ 'tier_proposed',
];
export interface NotifyEvent {
diff --git a/frontend/src/flightSchool.ts b/frontend/src/flightSchool.ts
index 160380e6..84c10505 100644
--- a/frontend/src/flightSchool.ts
+++ b/frontend/src/flightSchool.ts
@@ -51,6 +51,8 @@ export interface Capabilities {
policies: CapabilityPolicy[];
effective: Array<{ task_class: string; tier: Tier; from: TierFrom | string }>;
events: CapabilityEvent[];
+ /** C4: the bot's last 20 proposals, newest first (older servers leave it out). */
+ proposals?: TierProposal[];
}
/** POST /api/capabilities and …/revoke. `unchanged`: it already had that tier (safe to repeat). */
@@ -144,3 +146,163 @@ export interface TaskTier {
/** Whether a task shows its kind of work and tier: only with Flight School on (the server sends `owner_tier`). */
export const showsTier = (t: TaskTier): t is { task_class?: string; owner_tier: Tier } => isTier(t.owner_tier);
+
+// ---------------------------------------------------------------------------
+// Scorecards and proposals (Phase C4, docs/mission-control.md §14): a bot earns the next tier from
+// its own verified work, asks for it, and only the person grants or declines. Revoke stays one tap.
+
+export interface Ratio {
+ k: number;
+ n: number;
+ /** Null when n is 0. */
+ rate: number | null;
+}
+
+export interface Scorecard {
+ kwant_id: string;
+ task_class: string;
+ window_days: number;
+ since: string;
+ tier: Tier;
+ tier_from: TierFrom | string;
+ next_tier: Tier | null;
+ eligible: boolean;
+ /** Ready-to-show sentences, e.g. "2 more verified task(s) (has 3, needs 5)". */
+ missing: string[];
+ tasks: { settled: number; verified: number; failed: number; cancelled: number };
+ first_try: Ratio;
+ verified_rate: Ratio;
+ false_success: Ratio;
+ failures?: { total: number; by_class: Record<string, number> };
+ cards?: { shown: number; approved: number; denied: number; approved_rate: Ratio };
+ calls?: number;
+ external_calls?: number;
+ interventions?: number;
+ tokens?: { spent: number; recovery: number };
+ /** Null at Act: there is no next step to earn. */
+ recent_denials: { n: number; of: number; with_denial: number } | null;
+}
+
+export type ProposalStatus = 'proposed' | 'granted' | 'declined' | 'stale';
+
+export interface TierProposal {
+ kind: 'tier_proposal';
+ id: string;
+ space_id: string;
+ kwant_id: string;
+ task_class: string;
+ from_tier: Tier;
+ to_tier: Tier;
+ reason: string | null;
+ status: ProposalStatus;
+ note: string | null;
+ decided_at: string | null;
+ created_at: string;
+ /** The scorecard when the bot asked. */
+ scorecard: Partial<Scorecard> | null;
+}
+
+/** POST …/grant and …/decline answer the decided proposal and the bot's tiers after it. */
+export interface ProposalDecision {
+ proposal: TierProposal;
+ capabilities: Capabilities;
+}
+
+/** The SSE `capability_changed` payload: reload that bot's tiers and the open proposals. */
+export interface CapabilityChangedEvent {
+ space_id?: string;
+ kwant_id: string;
+ task_class?: string;
+ proposal?: TierProposal | null;
+}
+
+export const isOpenProposal = (p: Pick<TierProposal, 'status'>): boolean => p.status === 'proposed';
+
+/** Open proposals, oldest first: the first to ask is the first in line. */
+export const openProposals = (list: TierProposal[] | null | undefined): TierProposal[] =>
+ (list ?? []).filter(isOpenProposal).sort((a, b) => a.created_at.localeCompare(b.created_at));
+
+/** Puts a changed proposal into the list by id, newest first. */
+export function upsertProposal(list: TierProposal[], p: TierProposal): TierProposal[] {
+ return [p, ...list.filter((x) => x.id !== p.id)].sort((a, b) => b.created_at.localeCompare(a.created_at));
+}
+
+const pct = (r: number) => `${Math.round(r * 100)}%`;
+
+/** "2 of 3 (67%)", or "None yet" when there's nothing to count. */
+export function ratioText(r: Ratio | null | undefined): string {
+ if (!r || r.n <= 0) return 'None yet';
+ return r.rate === null ? `${r.k} of ${r.n}` : `${r.k} of ${r.n} (${pct(r.rate)})`;
+}
+
+/** "Sandy asks for Sandbox on Code" (the card's heading). */
+export const proposalTitle = (p: Pick<TierProposal, 'task_class' | 'to_tier'>, bot: string): string =>
+ `${bot} asks for ${tierLabel(p.to_tier)} on ${classLabel(p.task_class)}`;
+
+/** "From Observe to Sandbox: …" (what changes if you grant it). */
+export const proposalChange = (p: Pick<TierProposal, 'from_tier' | 'to_tier'>): string =>
+ `${tierLabel(p.from_tier)} → ${tierLabel(p.to_tier)}. ${TIER_HINTS[isTier(p.to_tier) ? p.to_tier : 'act']}`;
+
+/** What happened to a proposal that's no longer open, for the line that replaces its buttons. */
+export function proposalOutcome(p: Pick<TierProposal, 'status' | 'to_tier' | 'task_class' | 'note'>, bot: string): string {
+ const where = classLabel(p.task_class);
+ switch (p.status) {
+ case 'granted':
+ return `Granted: ${bot} is now ${tierLabel(p.to_tier)} on ${where}. You can revoke it in one tap from ${bot}’s settings.`;
+ case 'declined':
+ return `Declined. ${bot} can ask again in 7 days.`;
+ case 'stale':
+ return `No longer holds${p.note ? `: ${p.note.replace(/[.\s]+$/, '')}` : ''}. ${bot} has to ask again.`;
+ default:
+ return 'Waiting for you.';
+ }
+}
+
+/**
+ * A 409 on grant or decline: someone (another tab or device) decided first, or the proposal went
+ * stale. The server's `status` arrives as the error's code.
+ */
+export function proposalConflictText(status: string | null, message: string): string {
+ switch (status) {
+ case 'granted':
+ return 'Someone got there first: it’s already granted.';
+ case 'declined':
+ return 'Someone got there first: it’s already declined.';
+ case 'stale': {
+ const why = /^this proposal is stale:\s*(.+?)[.\s]*$/i.exec(message.trim())?.[1];
+ return `This request no longer holds${why ? `: ${why}` : ''}. The bot has to ask again.`;
+ }
+ default:
+ return message;
+ }
+}
+
+export interface ScorecardRow {
+ label: string;
+ value: string;
+ /** Rose when it holds the bot back. */
+ bad?: boolean;
+}
+
+/** The scorecard as label/value rows, in the order the rules read. */
+export function scorecardRows(c: Partial<Scorecard>): ScorecardRow[] {
+ const rows: ScorecardRow[] = [];
+ const t = c.tasks;
+ if (t) rows.push({ label: 'Verified', value: t.settled > 0 ? `${t.verified} of ${t.settled} settled` : 'None settled yet' });
+ if (c.first_try) rows.push({ label: 'Verified on the first try', value: ratioText(c.first_try) });
+ if (c.false_success) rows.push({ label: 'Said done, check failed', value: c.false_success.n > 0 ? `${c.false_success.k} of ${c.false_success.n}` : 'None yet', bad: c.false_success.k > 0 });
+ if (c.recent_denials) {
+ const d = c.recent_denials;
+ rows.push({ label: `Denied in its last ${d.of}`, value: d.n > 0 ? `${d.with_denial} of ${d.n}` : 'None yet', bad: d.with_denial > 0 });
+ }
+ if (c.cards && c.cards.shown > 0) rows.push({ label: 'Approval cards', value: `${c.cards.approved} approved, ${c.cards.denied} denied`, bad: c.cards.denied > 0 });
+ return rows;
+}
+
+/** One line under the scorecard: what it can ask for, or what it still needs. */
+export function scorecardStatus(c: Pick<Scorecard, 'tier' | 'next_tier' | 'eligible' | 'missing'>): { text: string; ready: boolean } {
+ if (!c.next_tier) return { text: `${tierLabel(c.tier)} is the top tier: nothing more to earn here.`, ready: false };
+ if (c.eligible) return { text: `Qualifies to ask for ${tierLabel(c.next_tier)}. Only you can grant it.`, ready: true };
+ const need = c.missing.map((m) => m.replace(/[.\s]+$/, '')).join('; ');
+ return { text: `Not yet ready for ${tierLabel(c.next_tier)}${need ? `: needs ${need}` : ''}.`, ready: false };
+}
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index bdf235a0..58129485 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -6,7 +6,7 @@
import { PersonCancelledError, personFetch } from './auth';
import { relativeTime } from './away';
-import { Capabilities, CapabilityChange, ENGINE_CANT_SANDBOX, TaskTier, Tier } from './flightSchool';
+import { Capabilities, CapabilityChange, CapabilityChangedEvent, ENGINE_CANT_SANDBOX, ProposalDecision, ProposalStatus, Scorecard, TaskTier, Tier, TierProposal } from './flightSchool';
import type { Risk, RiskResolution, TaskRisks } from './auditor';
export type TaskState = 'backlog' | 'ready' | 'working' | 'needs_you' | 'review' | 'verified' | 'blocked' | 'failed' | 'cancelled';
@@ -1479,7 +1479,11 @@ export const ACTION_DONE: Record<TaskAction, string> = {
// ---------------------------------------------------------------------------
// Live updates: App's EventSource re-broadcasts `task_updated` and `mission_updated` here.
-export type MissionEvent = { type: 'task_updated'; data: { task: Task } } | { type: 'mission_updated'; data: { mission: Mission } };
+export type MissionEvent =
+ | { type: 'task_updated'; data: { task: Task } }
+ | { type: 'mission_updated'; data: { mission: Mission } }
+ /** Flight School C4: a bot asked for a tier, or a proposal was granted, declined or went stale. */
+ | { type: 'capability_changed'; data: { capability: CapabilityChangedEvent } };
const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;
@@ -1538,7 +1542,8 @@ const sentence = (s: string) => {
export function errorFrom(status: number, answer: unknown): MissionError {
const a = answer && typeof answer === 'object' ? (answer as Record<string, unknown>) : {};
const err = typeof a.error === 'string' && a.error.trim() ? sentence(a.error) : null;
- const code = typeof a.code === 'string' && a.code ? a.code : null;
+ // A 409 without a `code` may name the state it found instead (Flight School proposals).
+ const code = typeof a.code === 'string' && a.code ? a.code : status === 409 && typeof a.status === 'string' && a.status ? a.status : null;
if (status === 403) return new MissionError('Only you can change tasks on the board.', 403);
if (status === 404 && !err) return new MissionError('This server doesn’t have the Mission board yet. Update the app and try again.', 404);
return new MissionError(err ?? `Something went wrong (HTTP ${status}).`, status, code);
@@ -1643,6 +1648,17 @@ export const capabilitiesApi = {
set: (kwantId: string, task_class: string, tier: Tier) => call<CapabilityChange>('/api/capabilities', 'POST', { kwant_id: kwantId, task_class, tier }),
revoke: (kwantId: string, task_class: string, to_tier: Tier) =>
call<CapabilityChange>(`/api/capabilities/${enc(kwantId)}/revoke`, 'POST', { task_class, to_tier }),
+ /** C4: one bot's live scorecard for a kind of work (the server defaults to general). */
+ scorecard: (kwantId: string, taskClass: string) => call<Scorecard>(`/api/capabilities/${enc(kwantId)}/scorecard?class=${enc(taskClass)}`),
+ /** C4: the space's proposals, newest first; stale ones are marked on read. */
+ proposals: (status?: ProposalStatus, kwantId?: string) => {
+ const q = [status ? `status=${status}` : '', kwantId ? `kwant_id=${enc(kwantId)}` : ''].filter(Boolean).join('&');
+ return call<{ proposals: TierProposal[] }>(`/api/capabilities/proposals${q ? `?${q}` : ''}`).then((r) => r.proposals);
+ },
+ /** Person only. The same key replays the first answer; a 409 carries the state found as `code`. */
+ grant: (id: string, key: string) => call<ProposalDecision>(`/api/capabilities/proposals/${enc(id)}/grant`, 'POST', {}, { 'Idempotency-Key': key }),
+ decline: (id: string, key: string, note?: string) =>
+ call<ProposalDecision>(`/api/capabilities/proposals/${enc(id)}/decline`, 'POST', note ? { note } : {}, { 'Idempotency-Key': key }),
};
/** Where a task came from in the app: a channel, a bot's thread, or a bot's direct chat. */
diff --git a/frontend/tests/appUpdate.test.mjs b/frontend/tests/appUpdate.test.mjs
index 86c3fdff..d8b9c571 100644
--- a/frontend/tests/appUpdate.test.mjs
+++ b/frontend/tests/appUpdate.test.mjs
@@ -357,7 +357,7 @@ test('app_update is saved in the Mac app and never sent to a server without it',
test('App settings shows the switch only when the update API is supported', () => {
const s = src('components/SettingsModal.tsx');
assert.match(s, /const appUpdates = useAppUpdate\(\)\.model\.status !== null;/);
- assert.match(s, /notifyKindsFor\(appUpdates, !!proactive, !!discovery\)\.map/);
- assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery\)/);
+ assert.match(s, /notifyKindsFor\(appUpdates, !!proactive, !!discovery(, [^)]+)?\)\.map/);
+ assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery(, [^)]+)?\)/);
assert.doesNotMatch(s, /\{NOTIFY_KINDS\.map/);
});
diff --git a/frontend/tests/automationDiscovery.test.mjs b/frontend/tests/automationDiscovery.test.mjs
index 09614f6d..3faee9de 100644
--- a/frontend/tests/automationDiscovery.test.mjs
+++ b/frontend/tests/automationDiscovery.test.mjs
@@ -263,8 +263,8 @@ test('the automation_suggested notification: a toggle where the server has it, a
assert.match(app, /n\.kind === 'automation_suggested'\) setIsRoutinesOpen\(true\)/, 'a tapped notification opens Routines');
assert.doesNotMatch(readFileSync(new URL('../src/missions.ts', import.meta.url), 'utf8'), /automation_suggested/, 'not on the Needs-you list');
const settings = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');
- assert.match(settings, /notifyKindsFor\(appUpdates, !!proactive, !!discovery\)/);
- assert.match(settings, /notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery\)/);
+ assert.match(settings, /notifyKindsFor\(appUpdates, !!proactive, !!discovery[,)]/);
+ assert.match(settings, /notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery[,)]/);
assert.match(settings, /\.\.\.\(discovery \?\? \{\}\)/, 'the switch and cap are saved');
});
diff --git a/frontend/tests/flightSchoolProposals.test.mjs b/frontend/tests/flightSchoolProposals.test.mjs
new file mode 100644
index 00000000..17998b2e
--- /dev/null
+++ b/frontend/tests/flightSchoolProposals.test.mjs
@@ -0,0 +1,302 @@
+// Flight School, Phase C4 (docs/mission-control.md §14): a bot that earned the next tier asks for it,
+// and only the person grants or declines. Requests show on the board's Needs-you list and in the bot's
+// settings with its scorecard; a decision another tab made first (409) says so; revoking stays one tap;
+// changes arrive live. With Flight School off nothing new shows.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/s1', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const b = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { TierRequests, ScorecardView, ScorecardDisclosure } from './src/components/TierProposals';
+ import { FlightSchoolPanel } from './src/components/FlightSchoolPanel';
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { TierRequests, ScorecardDisclosure } from './src/components/TierProposals';
+ export { FlightSchoolPanel } from './src/components/FlightSchoolPanel';
+ export * from './src/flightSchool';
+ export { MissionError, errorFrom, emitMission } from './src/missions';
+ export { notifyKindsFor, notifyOnToSave, TOAST_KINDS } from './src/continuity';
+ const r = (c, p) => renderToStaticMarkup(React.createElement(c, p));
+ export const requestsHtml = (p) => r(TierRequests, p);
+ export const scorecardHtml = (p) => r(ScorecardView, p);
+ export const panelHtml = (p) => r(FlightSchoolPanel, p);
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const settle = async () => {
+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const NOW = Date.parse('2026-11-01T12:00:00Z');
+const names = { k_sandy: 'Sandy', k_cody: 'Cody' };
+
+const card = (over = {}) => ({
+ kwant_id: 'k_sandy', task_class: 'code', window_days: 30, since: '2026-10-02T12:00:00Z', tier: 'observe', tier_from: 'class', next_tier: 'sandbox',
+ eligible: true, missing: [], tasks: { settled: 6, verified: 5, failed: 1, cancelled: 0 }, first_try: { k: 4, n: 5, rate: 0.8 },
+ verified_rate: { k: 5, n: 6, rate: 5 / 6 }, false_success: { k: 0, n: 5, rate: 0 }, cards: { shown: 9, approved: 9, denied: 0, approved_rate: { k: 9, n: 9, rate: 1 } },
+ recent_denials: { n: 5, of: 5, with_denial: 0 }, ...over,
+});
+const proposal = (over = {}) => ({
+ kind: 'tier_proposal', id: 'p1', space_id: 's1', kwant_id: 'k_sandy', task_class: 'code', from_tier: 'observe', to_tier: 'sandbox',
+ reason: 'Five verified code tasks this month, none denied.', status: 'proposed', note: null, decided_at: null, created_at: '2026-11-01T11:00:00Z',
+ scorecard: card(), ...over,
+});
+const caps = (over = {}) => ({
+ flight_school: true, kwant_id: 'k_sandy', default_tier: 'observe', policies: [],
+ effective: [{ task_class: 'general', tier: 'observe', from: 'any_class' }, { task_class: 'code', tier: 'observe', from: 'class' }],
+ events: [], proposals: [proposal()], ...over,
+});
+
+function fakeApi(over = {}) {
+ const calls = [];
+ const api = {
+ calls,
+ get: async (id) => (calls.push(['get', id]), caps()),
+ set: async () => ({ unchanged: false, capabilities: caps() }),
+ revoke: async () => ({ unchanged: false, capabilities: caps() }),
+ scorecard: async (id, cls) => (calls.push(['scorecard', id, cls]), card({ task_class: cls })),
+ proposals: async (status) => (calls.push(['proposals', status ?? null]), []),
+ grant: async (id, key) => (calls.push(['grant', id, key]), { proposal: proposal({ status: 'granted' }), capabilities: caps({ proposals: [] }) }),
+ decline: async (id, key, note) => (calls.push(['decline', id, key, note ?? null]), { proposal: proposal({ status: 'declined', note }), capabilities: caps({ proposals: [] }) }),
+ ...over,
+ };
+ return api;
+}
+
+async function mount(Component, props) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = b.createRoot(host);
+ root.render(b.React.createElement(Component, props));
+ await settle();
+ return {
+ host,
+ text: () => host.textContent.replace(/\s+/g, ' '),
+ click: async (sel) => {
+ const el = host.querySelector(sel);
+ assert.ok(el, `no ${sel}`);
+ el.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ },
+ done: () => {
+ root.unmount();
+ host.remove();
+ },
+ };
+}
+
+test('with nobody asking (always the case with Flight School off) the board shows nothing new', () => {
+ assert.equal(b.requestsHtml({ names, initial: [], api: fakeApi() }), '');
+ // Decided ones alone don't make a list either.
+ assert.equal(b.requestsHtml({ names, initial: [proposal({ status: 'granted' })], api: fakeApi() }), '');
+ // The bot's settings stay as before with Flight School off, even if old proposals exist.
+ assert.equal(b.panelHtml({ kwantId: 'k_sandy', kwantName: 'Sandy', initial: caps({ flight_school: false }), api: fakeApi() }), '');
+});
+
+test('a request reads as who asks for what, why, its scorecard, and Grant / Decline', () => {
+ const html = b.requestsHtml({ names, now: NOW, initial: [proposal()], api: fakeApi() });
+ const t = text(html);
+ assert.match(t, /Needs you: a bot asks for more freedom/);
+ assert.match(t, /Sandy asks for Sandbox on Code/);
+ assert.match(t, /Observe → Sandbox\./);
+ assert.match(t, /asked 1 ?h ago/);
+ assert.match(t, /Sandy says: Five verified code tasks this month, none denied\./);
+ assert.match(t, /Its scorecard when it asked/);
+ assert.match(t, /Verified 5 of 6 settled/);
+ assert.match(t, /Grant Sandbox/);
+ assert.match(t, /Decline…/);
+ assert.match(t, /Payments always ask you/);
+ // Named for screen readers: the card by its title, the buttons as one decision.
+ assert.match(html, /<li aria-labelledby="[^"]+"[^>]*data-proposal="p1" data-status="proposed"/);
+ assert.match(html, /role="group" aria-label="Decide: Sandy asks for Sandbox on Code"/);
+ // Several bots asking say so; an unknown bot still reads.
+ const two = text(b.requestsHtml({ names: {}, now: NOW, initial: [proposal(), proposal({ id: 'p2', kwant_id: 'k_x', created_at: '2026-11-01T10:00:00Z' })], api: fakeApi() }));
+ assert.match(two, /2 bots ask for more freedom/);
+ assert.match(two, /A bot asks for Sandbox on Code/);
+});
+
+test('scorecards: plain rows, what holds it back in rose, and what it still needs', () => {
+ const ready = b.scorecardHtml({ card: card() });
+ assert.match(text(ready), /Verified on the first try 4 of 5 \(80%\)/);
+ assert.match(text(ready), /Said done, check failed 0 of 5/);
+ assert.match(text(ready), /Denied in its last 5 0 of 5/);
+ assert.match(text(ready), /Approval cards 9 approved, 0 denied/);
+ assert.match(ready, /data-scorecard-status="ready"[^>]*>Qualifies to ask for Sandbox\. Only you can grant it\./);
+ assert.match(text(ready), /From the board’s own records of the last 30 days/);
+
+ const notYet = b.scorecardHtml({ card: card({ eligible: false, false_success: { k: 1, n: 5, rate: 0.2 }, missing: ['2 more verified task(s) (has 3, needs 5).', 'no false successes'] }) });
+ assert.match(notYet, /text-rose-300[^>]*>1 of 5/);
+ assert.match(text(notYet), /Not yet ready for Sandbox: needs 2 more verified task\(s\) \(has 3, needs 5\); no false successes\./);
+
+ assert.match(text(b.scorecardHtml({ card: card({ tier: 'act', next_tier: null, recent_denials: null }) })), /Act is the top tier: nothing more to earn here\./);
+ assert.match(text(b.scorecardHtml({ card: { task_class: 'docs' } })), /No settled work in this kind yet\./);
+});
+
+test('a 409 names the state the server found, and stale says why', () => {
+ const e = b.errorFrom(409, { error: 'this proposal is already declined', status: 'declined' });
+ assert.equal(e.status, 409);
+ assert.equal(e.code, 'declined');
+ assert.equal(b.proposalConflictText(e.code, e.message), 'Someone got there first: it’s already declined.');
+ assert.equal(b.proposalConflictText('granted', 'x'), 'Someone got there first: it’s already granted.');
+ const stale = b.errorFrom(409, { error: 'this proposal is stale: the bot is already at Sandbox', status: 'stale' });
+ assert.equal(b.proposalConflictText(stale.code, stale.message), 'This request no longer holds: the bot is already at Sandbox. The bot has to ask again.');
+ // A 409 with neither code nor status keeps the server's words.
+ const off = b.errorFrom(409, { error: 'Flight School is off; switch it on to grant tiers' });
+ assert.equal(off.code, null);
+ assert.equal(b.proposalConflictText(off.code, off.message), off.message);
+});
+
+test('Grant is one tap and says how to undo it; a retry reuses the same key', async () => {
+ let fail = true;
+ const api = fakeApi();
+ const grant = api.grant;
+ api.grant = async (id, key) => {
+ if (fail) {
+ fail = false;
+ api.calls.push(['grant-failed', id, key]);
+ throw new Error('Couldn’t reach kwnt.');
+ }
+ return grant(id, key);
+ };
+ const v = await mount(b.TierRequests, { names, now: NOW, initial: [proposal()], api });
+ await v.click('[data-grant]');
+ assert.match(v.host.querySelector('[data-proposal-error]').textContent, /Couldn’t reach/);
+ await v.click('[data-grant]');
+ const [first, second] = api.calls.filter((c) => c[0].startsWith('grant'));
+ assert.equal(first[2], second[2], 'the same Idempotency-Key, so a lost answer replays');
+ assert.equal(v.host.querySelector('[data-proposal-error]'), null);
+ assert.match(v.text(), /Granted: Sandy is now Sandbox on Code\. You can revoke it in one tap from Sandy’s settings\./);
+ assert.equal(v.host.querySelector('[data-grant]'), null);
+ assert.match(v.text(), /Nothing else is waiting\./);
+ v.done();
+});
+
+test('Decline asks for an optional note, Escape backs out, and the note is sent', async () => {
+ const api = fakeApi();
+ const v = await mount(b.TierRequests, { names, now: NOW, initial: [proposal()], api });
+ await v.click('[data-decline]');
+ const input = v.host.querySelector('[data-decline-form] input');
+ assert.equal(document.activeElement, input, 'the note field takes focus');
+ assert.equal(v.host.querySelector('[data-decline-form] label').textContent.trim(), 'Why not? Optional, Sandy sees it');
+ input.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.equal(v.host.querySelector('[data-decline-form]'), null);
+ assert.ok(v.host.querySelector('[data-grant]'));
+
+ await v.click('[data-decline]');
+ const field = v.host.querySelector('[data-decline-form] input');
+ const setter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value').set;
+ setter.call(field, ' Not on the release branch yet ');
+ field.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
+ await settle();
+ await v.click('[data-confirm-decline]');
+ const call = api.calls.find((c) => c[0] === 'decline');
+ assert.equal(call[3], 'Not on the release branch yet');
+ assert.match(v.text(), /Declined\. Sandy can ask again in 7 days\./);
+ v.done();
+});
+
+test('someone got there first: the card says so and shows what holds now', async () => {
+ const api = fakeApi({
+ grant: async () => {
+ throw new b.MissionError('This proposal is already declined.', 409, 'declined');
+ },
+ proposals: async (status) => (status ? [] : [proposal({ status: 'declined', note: 'Not yet' })]),
+ });
+ const v = await mount(b.TierRequests, { names, now: NOW, initial: [proposal()], api });
+ await v.click('[data-grant]');
+ const err = v.host.querySelector('[data-proposal-error]');
+ assert.equal(err.getAttribute('role'), 'alert');
+ assert.match(err.textContent, /Someone got there first: it’s already declined\./);
+ assert.equal(v.host.querySelector('[data-proposal]').dataset.status, 'declined');
+ assert.match(v.text(), /Declined\. Sandy can ask again in 7 days\./);
+ assert.equal(v.host.querySelector('[data-grant]'), null);
+ v.done();
+});
+
+test('requests arrive and leave live', async () => {
+ const api = fakeApi();
+ const v = await mount(b.TierRequests, { names, now: NOW, initial: [], api });
+ assert.equal(v.host.innerHTML, '');
+ b.emitMission({ type: 'capability_changed', data: { capability: { kwant_id: 'k_cody', proposal: proposal({ id: 'p9', kwant_id: 'k_cody', task_class: 'docs' }) } } });
+ await settle();
+ assert.match(v.text(), /Cody asks for Sandbox on Docs/);
+ // Decided elsewhere: it leaves the list.
+ b.emitMission({ type: 'capability_changed', data: { capability: { kwant_id: 'k_cody', proposal: proposal({ id: 'p9', kwant_id: 'k_cody', status: 'granted' }) } } });
+ await settle();
+ assert.equal(v.host.innerHTML, '');
+ // A change without a proposal (a revoke) reads the list again.
+ b.emitMission({ type: 'capability_changed', data: { capability: { kwant_id: 'k_cody' } } });
+ await settle();
+ assert.deepEqual(api.calls.at(-1), ['proposals', 'proposed']);
+ v.done();
+});
+
+test('the bot’s settings: its request, a scorecard per kind of work, one-tap Revoke, and live reloads', async () => {
+ const api = fakeApi();
+ const v = await mount(b.FlightSchoolPanel, { kwantId: 'k_sandy', kwantName: 'Sandy', now: NOW, initial: caps({ default_tier: 'sandbox' }), api });
+ assert.match(v.text(), /Sandy asks for Sandbox on Code/);
+ assert.ok(v.host.querySelector('[data-revoke]'), 'Revoke is still one tap');
+ // No scorecard for "all work": scorecards are per kind of work.
+ const toggles = [...v.host.querySelectorAll('[data-scorecard-toggle]')].map((x) => x.dataset.scorecardToggle);
+ assert.deepEqual(toggles, ['general', 'code']);
+ const code = v.host.querySelector('[data-scorecard-toggle="code"]');
+ assert.equal(code.getAttribute('aria-expanded'), 'false');
+ assert.match(code.textContent, /Scorecard for Code/);
+ await v.click('[data-scorecard-toggle="code"]');
+ assert.equal(code.getAttribute('aria-expanded'), 'true');
+ assert.deepEqual(api.calls.filter((c) => c[0] === 'scorecard'), [['scorecard', 'k_sandy', 'code']]);
+ assert.ok(v.host.querySelector('[data-scorecard="code"]'));
+
+ // Granted elsewhere: tiers read again and the open scorecard too. Another bot's change is ignored.
+ b.emitMission({ type: 'capability_changed', data: { capability: { kwant_id: 'k_cody' } } });
+ await settle();
+ assert.equal(api.calls.filter((c) => c[0] === 'get').length, 0);
+ b.emitMission({ type: 'capability_changed', data: { capability: { kwant_id: 'k_sandy' } } });
+ await settle();
+ assert.equal(api.calls.filter((c) => c[0] === 'get').length, 1);
+ assert.equal(api.calls.filter((c) => c[0] === 'scorecard').length, 2);
+
+ await v.click('[data-grant]');
+ assert.match(v.text(), /Granted: Sandy is now Sandbox on Code/);
+ v.done();
+});
+
+test('a scorecard that fails to load says so and can be tried again', async () => {
+ let n = 0;
+ const api = { scorecard: async () => (++n === 1 ? Promise.reject(new Error('Couldn’t reach kwnt.')) : card()) };
+ const v = await mount(b.ScorecardDisclosure, { kwantId: 'k_sandy', taskClass: 'code', api });
+ await v.click('[data-scorecard-toggle]');
+ assert.match(v.host.querySelector('[role="alert"]').textContent, /Couldn’t reach.*Try again/);
+ await v.click('[role="alert"] button');
+ assert.ok(v.host.querySelector('[data-scorecard="code"]'));
+ v.done();
+});
+
+test('tier requests can notify, only with Flight School on, and open the board', () => {
+ const ids = (on) => b.notifyKindsFor(false, false, false, on).map((k) => k.id);
+ assert.ok(!ids(false).includes('tier_proposed'));
+ assert.ok(ids(true).includes('tier_proposed'));
+ assert.equal(b.notifyKindsFor(false, false, false, true).find((k) => k.id === 'tier_proposed').label, 'A bot asks for a higher tier');
+ // Kept while Flight School is merely off; dropped for a server without it.
+ assert.deepEqual(b.notifyOnToSave(['turn_finished', 'tier_proposed'], false, false, false, true), ['turn_finished', 'tier_proposed']);
+ assert.deepEqual(b.notifyOnToSave(['turn_finished', 'tier_proposed'], false, false, false, false), ['turn_finished']);
+ assert.ok(b.TOAST_KINDS.includes('tier_proposed'));
+
+ const src = (f) => readFileSync(new URL(`../src/${f}`, import.meta.url), 'utf8');
+ const app = src('App.tsx');
+ assert.match(app, /n\.kind === 'tier_proposed'\) openBoardForTier\(\)/);
+ assert.match(app, /case 'capability_changed':/);
+ assert.match(src('components/MissionBoardView.tsx'), /<TierRequests names=\{names\} now=\{now\} \/>/);
+ assert.match(src('components/SettingsModal.tsx'), /notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery, flightSchool !== null\)/);
+});