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.

Mission board: tasks per space with an evidence receipt

Pixelb0e8d6c4cf28
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a257e8aa..6e005605 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
evidence, or you), never on the bot's own word. Missions have a token budget that claims can't
exceed, tasks wait for the tasks they depend on, and anything waiting on you shows under **Needs
you**. Turn it on with `mission_board` in settings. API: `docs/mission-control.md`.
+- **Mission board.** One board per space with Ready, Working, Needs you, Review and Verified. Each
+ card shows its owner, cost and checks. Its evidence receipt lists every check with its result and
+ says "Not checked" when nothing has run. A strip shows this week's verified tasks, false successes
+ and blocked work. Turn it on in Settings → Mission board. It works on phone and desktop.
### Changed
- **Deciding for you costs fewer tokens.** Before deciding a choice itself, a bot now hears at most one
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 01677d34..6f48c174 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -29,6 +29,8 @@ import { HireCard, type HireDecision } from './components/HireCard';
import type { RoutineFocus } from './components/RoutinesPanel';
import { AwayPage } from './components/AwayView';
import { LooseEndsPage } from './components/LooseEndsView';
+import { MissionBoardPage } from './components/MissionBoardView';
+import { MISSION_BOARD_SETTING_EVENT, emitMission, parseMissionBoardSetting, sourceChat } from './missions';
import { ParallelPage } from './components/ParallelUniverseView';
import { ConnectionsPage } from './components/ConnectionsView';
import { AlertTriangle, Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
@@ -296,6 +298,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [showLoose, setShowLoose] = useState(false);
const [showConnections, setShowConnections] = useState(false);
const [showParallel, setShowParallel] = useState(false);
+ // Mission board: shown in the sidebar only when the server has it switched on.
+ const [showMissions, setShowMissions] = useState(false);
+ const [missionBoard, setMissionBoard] = useState(false);
const [awayCount, setAwayCount] = useState(0);
const awaySinceRef = useRef<string | null>(null);
const awayTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
@@ -373,6 +378,23 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
sw.addEventListener('message', onMessage);
return () => sw.removeEventListener('message', onMessage);
}, [space.id]);
+ // The Mission board is off unless the server says otherwise; Settings tells us when it changes.
+ useEffect(() => {
+ let live = true;
+ fetch('/api/settings')
+ .then((r) => (r.ok ? r.json() : null))
+ .then((d) => {
+ const on = parseMissionBoardSetting(d);
+ if (live && on !== null) setMissionBoard(on);
+ })
+ .catch(() => {});
+ const onSetting = (e: Event) => setMissionBoard(Boolean((e as CustomEvent<boolean>).detail));
+ window.addEventListener(MISSION_BOARD_SETTING_EVENT, onSetting);
+ return () => {
+ live = false;
+ window.removeEventListener(MISSION_BOARD_SETTING_EVENT, onSetting);
+ };
+ }, []);
const showNotificationRef = useRef(showNotification);
showNotificationRef.current = showNotification;
const refreshProfiles = useCallback(() => {
@@ -876,6 +898,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'MemoryChanged':
emitContinuity({ type: 'memory_changed', data: event.data });
break;
+ case 'task_updated':
+ if (event.data?.task) emitMission({ type: 'task_updated', data: { task: event.data.task } });
+ break;
+ case 'mission_updated':
+ if (event.data?.mission) emitMission({ type: 'mission_updated', data: { mission: event.data.mission } });
+ break;
case 'routine_run':
case 'RoutineRun':
emitContinuity({ type: 'routine_run', data: event.data });
@@ -1354,6 +1382,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
setPhoneView('chat');
setSelectedTeamId(team.id);
const targetChannel = teamChannelOf(channels, team);
@@ -1393,6 +1422,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
setPhoneView('chat');
setSelectedId(channel.id);
selectedIdRef.current = channel.id;
@@ -1410,6 +1440,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
setPhoneView('chat');
setSelectedId(kwant.id);
selectedIdRef.current = kwant.id;
@@ -1477,6 +1508,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
if (selectedIdRef.current !== kwant.id || isChannelRef.current) handleSelectKwant(kwant);
else playSfx('click');
setOpenThreadId(threadId);
@@ -1493,6 +1525,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
};
const openDirectChat = () => {
@@ -2728,6 +2761,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
parallelActive={showParallel}
onOpenParallel={() => {
setShowParallel(true);
+ setShowMissions(false);
setShowLoose(false);
setShowConnections(false);
setShowAway(false);
@@ -2739,6 +2773,18 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowConnections(true);
setShowLoose(false);
setShowParallel(false);
+ setShowMissions(false);
+ setShowAway(false);
+ setPhoneView('chat');
+ playSfx('click');
+ }}
+ missionBoard={missionBoard}
+ missionsActive={showMissions}
+ onOpenMissions={() => {
+ setShowMissions(true);
+ setShowConnections(false);
+ setShowLoose(false);
+ setShowParallel(false);
setShowAway(false);
setPhoneView('chat');
playSfx('click');
@@ -2747,6 +2793,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowConnections(false);
setShowLoose(true);
setShowParallel(false);
+ setShowMissions(false);
setShowAway(false);
setPhoneView('chat');
playSfx('click');
@@ -2756,6 +2803,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
setPhoneView('chat');
playSfx('click');
}}
@@ -2776,6 +2824,21 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onOpenLooseEnds={() => { setShowConnections(false); setShowLoose(true); }}
/>
);
+ const missionNames = Object.fromEntries(kwants.map((k) => [k.id, k.name]));
+ const missionsPage = (
+ <MissionBoardPage
+ key={space.id}
+ spaceId={space.id}
+ names={missionNames}
+ onBack={isPhone ? () => { setShowMissions(false); setPhoneView('list'); } : undefined}
+ onOpenChat={(t) => {
+ const c = sourceChat(t);
+ if (!c) return;
+ if (c.kwantId && c.threadId) return openThread(c.kwantId, c.threadId);
+ if (!openTarget({ channel_id: c.channelId, kwant_id: c.kwantId })) pushToast('That chat no longer exists.');
+ }}
+ />
+ );
const loose = <LooseEndsPage onBack={isPhone ? () => { setShowLoose(false); setPhoneView('list'); } : undefined} onOpenChat={openThread} />;
const chat = (
<ChatView
@@ -2880,7 +2943,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onChangeDecision={handleChangeDecision}
/>
);
- const mainPane = needsSetup ? setupChecklist : showParallel ? parallel : showConnections ? connectionsPage : showLoose ? loose : showAway ? away : !loaded ? (
+ const mainPane = needsSetup ? setupChecklist : showParallel ? parallel : showMissions && missionBoard ? missionsPage : showConnections ? connectionsPage : showLoose ? loose : showAway ? away : !loaded ? (
<main className="flex-1 flex items-center justify-center text-xs text-zinc-500">
<Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…
</main>
@@ -2931,6 +2994,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowLoose(false);
setShowConnections(false);
setShowParallel(false);
+ setShowMissions(false);
setPhoneView('chat');
return;
}
@@ -3095,6 +3159,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowConnections(true);
setShowLoose(false);
setShowParallel(false);
+ setShowMissions(false);
setShowAway(false);
setPhoneView('chat');
playSfx('click');
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
new file mode 100644
index 00000000..d7b23aa8
--- /dev/null
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -0,0 +1,1127 @@
+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
+import {
+ AlertTriangle,
+ CheckCircle2,
+ ChevronLeft,
+ Circle,
+ CircleDashed,
+ ExternalLink,
+ FileText,
+ Hand,
+ Image as ImageIcon,
+ Link2,
+ Loader2,
+ MessageSquare,
+ RefreshCw,
+ ShieldCheck,
+ StickyNote,
+ Target,
+ X,
+ XCircle,
+} from 'lucide-react';
+import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
+import { playSfx } from '../audio/chiptune';
+import {
+ ACTION_DONE,
+ ACTION_LABELS,
+ COLUMNS,
+ Check,
+ Column,
+ Evidence,
+ Insights,
+ Mission,
+ MissionError,
+ NEEDS_REASON,
+ Receipt,
+ Task,
+ TaskAction,
+ TaskDetail,
+ Tone,
+ actionsFor,
+ ago,
+ buildReceipt,
+ cardStatus,
+ checkKindLabel,
+ checksText,
+ columnOf,
+ costRatio,
+ costText,
+ eventText,
+ formatBytes,
+ formatTokens,
+ groupByColumn,
+ missionStatusLabel,
+ missionsApi,
+ onMission,
+ priorityLabel,
+ safeHttps,
+ sourceChat,
+ sourceLabel,
+ stateLabel,
+ untilText,
+ upsertMission,
+ upsertTask,
+} from '../missions';
+
+const TONES: Record<Tone, string> = {
+ emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',
+ amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
+ violet: 'border-violet-500/30 bg-violet-500/10 text-violet-200',
+ rose: 'border-rose-500/30 bg-rose-500/10 text-rose-200',
+ sky: 'border-sky-500/30 bg-sky-500/10 text-sky-200',
+ zinc: 'border-zinc-700 bg-zinc-800 text-zinc-300',
+};
+
+const actionBtn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[32px] px-3 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const quietBtn = `${actionBtn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;
+const mainBtn = `${actionBtn} bg-sky-600 text-white hover:bg-sky-500`;
+const goodBtn = `${actionBtn} bg-emerald-600 text-white hover:bg-emerald-500`;
+const dangerBtn = `${actionBtn} border border-rose-500/30 text-rose-200 hover:bg-rose-500/10`;
+const card = 'rounded-xl border border-zinc-800 bg-zinc-900/40';
+const field =
+ 'w-full min-h-[40px] sm:min-h-[36px] px-2.5 py-1.5 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-sky-500';
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+
+export const Badge: React.FC<{ tone: Tone; children: React.ReactNode; title?: string }> = ({ tone, children, title }) => (
+ <span title={title} className={`inline-flex items-center gap-1 shrink-0 px-1.5 py-px rounded border text-[10px] font-semibold uppercase tracking-wide ${TONES[tone]}`}>
+ {children}
+ </span>
+);
+
+const Notice: React.FC<{ text: string; error?: boolean }> = ({ text, error = false }) => (
+ <p role={error ? 'alert' : 'status'} className={`px-3 py-2 rounded-lg border text-xs ${error ? 'border-amber-500/30 bg-amber-500/10 text-amber-200' : 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200'}`}>
+ {text}
+ </p>
+);
+
+const SpendBar: React.FC<{ spent: number; budget: number; label: string }> = ({ spent, budget, label }) => {
+ const r = costRatio(spent, budget);
+ return (
+ <div
+ role="meter"
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={budget || 1}
+ aria-valuenow={Math.min(spent, budget || spent)}
+ aria-valuetext={costText(spent, budget)}
+ className="h-1.5 rounded-full bg-zinc-800 overflow-hidden"
+ >
+ <div className={`h-full rounded-full ${r >= 1 ? 'bg-rose-500' : r >= 0.8 ? 'bg-amber-500' : 'bg-sky-500'}`} style={{ width: `${Math.round(r * 100)}%` }} />
+ </div>
+ );
+};
+
+/** Two-letter initials for the owner chip. */
+const initials = (name: string) =>
+ name
+ .split(/\s+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map((w) => w[0]!.toUpperCase())
+ .join('') || '?';
+
+// ---------- Insights ----------
+
+export const InsightsStrip: React.FC<{ insights: Insights | null }> = ({ insights }) => {
+ if (!insights) return null;
+ const items: Array<{ label: string; value: string; hint: string; tone?: Tone }> = [
+ { label: 'Verified this week', value: String(insights.verified_7d), hint: 'Tasks a check confirmed in the last 7 days', tone: 'emerald' },
+ {
+ label: 'False successes',
+ value: String(insights.false_success_7d),
+ hint: 'A bot said done, then the check failed (last 7 days)',
+ tone: insights.false_success_7d > 0 ? 'rose' : undefined,
+ },
+ { label: 'Needs you now', value: String(insights.needs_you_now), hint: 'Waiting on a question, approval or step from you', tone: insights.needs_you_now > 0 ? 'amber' : undefined },
+ { label: 'Blocked now', value: String(insights.blocked_now), hint: 'Tasks that can’t move until something changes', tone: insights.blocked_now > 0 ? 'rose' : undefined },
+ {
+ label: 'Tokens per verified',
+ value: insights.tokens_per_verified_7d === null ? '—' : formatTokens(insights.tokens_per_verified_7d),
+ hint: `${formatTokens(insights.tokens_7d)} tokens used in the last 7 days`,
+ },
+ ];
+ const valueTone: Partial<Record<Tone, string>> = { emerald: 'text-emerald-300', rose: 'text-rose-300', amber: 'text-amber-300' };
+ return (
+ <section aria-label="This week" data-insights>
+ <dl className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
+ {items.map((it, i) => (
+ <div key={it.label} title={it.hint} className={`${card} px-3 py-2 ${i === items.length - 1 ? 'col-span-2 sm:col-span-1' : ''}`}>
+ <dt className="text-[11px] text-zinc-400 truncate">{it.label}</dt>
+ <dd className={`text-lg font-semibold tabular-nums ${it.tone ? valueTone[it.tone] ?? 'text-zinc-100' : 'text-zinc-100'}`}>{it.value}</dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ );
+};
+
+// ---------- Missions ----------
+
+export const MissionSummary: React.FC<{
+ mission: Mission;
+ busy: boolean;
+ onApprove: () => void;
+ onCancel: () => void;
+}> = ({ mission: m, busy, onApprove, onCancel }) => {
+ const st = missionStatusLabel(m.status);
+ const total = Object.entries(m.counts)
+ .filter(([k]) => k !== 'cancelled')
+ .reduce((n, [, v]) => n + v, 0);
+ return (
+ <section className={`${card} p-3 sm:p-4 space-y-2`} data-mission={m.id} aria-label={`Mission: ${m.title}`}>
+ <div className="flex flex-wrap items-start gap-2">
+ <Target size={16} className="mt-0.5 shrink-0 text-sky-400" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <h3 className="text-sm font-semibold text-zinc-100 break-words">{m.title}</h3>
+ {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>}
+ </div>
+ <div className="space-y-1">
+ <div className="flex flex-wrap justify-between gap-x-3 text-[11px] text-zinc-400">
+ <span>
+ {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>
+ </div>
+ <SpendBar spent={m.spent_tokens} budget={m.budget_tokens} label="Mission budget used" />
+ </div>
+ {m.over_budget && <p className="text-[11px] text-rose-300">No new task starts until you raise the budget.</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>
+ <button type="button" disabled={busy} onClick={onApprove} className={mainBtn}>
+ Approve mission
+ </button>
+ <button type="button" disabled={busy} onClick={onCancel} className={quietBtn}>
+ Don’t run it
+ </button>
+ </div>
+ )}
+ </section>
+ );
+};
+
+// ---------- Cards ----------
+
+export const TaskCard: React.FC<{
+ task: Task;
+ names: Record<string, string>;
+ now?: number;
+ showMission?: boolean;
+ onOpen: (t: Task) => void;
+}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen }) => {
+ const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
+ const checks = checksText(t.checks_summary);
+ const status = cardStatus(t, names, now);
+ const dimmed = t.state === 'backlog';
+ return (
+ <li data-task={t.id} data-state={t.state}>
+ <button
+ type="button"
+ onClick={() => onOpen(t)}
+ className={`${card} w-full text-left p-3 space-y-2 hover:border-zinc-700 hover:bg-zinc-900/70 ${focusRing} ${dimmed ? 'opacity-60' : ''}`}
+ >
+ <span className="flex flex-wrap items-center gap-1.5">
+ {t.state === 'blocked' && <Badge tone="rose">Blocked</Badge>}
+ {t.state === 'failed' && <Badge tone="rose">Failed</Badge>}
+ {t.state === 'backlog' && <Badge tone="zinc">Waiting</Badge>}
+ {t.priority >= 2 && <Badge tone={t.priority >= 3 ? 'rose' : 'amber'}>{priorityLabel(t.priority)}</Badge>}
+ {showMission && t.mission_title && <span className="min-w-0 truncate text-[11px] text-zinc-500">{t.mission_title}</span>}
+ </span>
+ <span className="block text-sm font-medium text-zinc-100 break-words">{t.title}</span>
+ {status && (
+ <span className={`block text-[11px] break-words line-clamp-2 ${t.state === 'needs_you' ? 'text-amber-200' : t.state === 'blocked' || t.state === 'failed' ? 'text-rose-300' : 'text-zinc-400'}`}>
+ {status}
+ </span>
+ )}
+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-zinc-400">
+ {owner ? (
+ <span className="inline-flex items-center gap-1 min-w-0">
+ <span aria-hidden="true" className="shrink-0 w-4 h-4 rounded-full bg-zinc-700 text-[8px] font-semibold text-zinc-100 grid place-items-center">
+ {initials(owner)}
+ </span>
+ <span className="truncate">{owner}</span>
+ </span>
+ ) : (
+ <span className="text-zinc-500">No owner yet</span>
+ )}
+ <span className="tabular-nums">{costText(t.spent_tokens, t.budget_tokens)}</span>
+ {(t.state === 'review' || t.state === 'verified' || t.state === 'failed' || t.checks_summary.total > 0) && (
+ <span className={`inline-flex items-center gap-1 ${checks.tone === 'emerald' ? 'text-emerald-300' : checks.tone === 'rose' ? 'text-rose-300' : checks.tone === 'amber' ? 'text-amber-200' : 'text-zinc-400'}`}>
+ {checks.tone === 'emerald' ? <CheckCircle2 size={11} aria-hidden="true" /> : checks.tone === 'rose' ? <XCircle size={11} aria-hidden="true" /> : <CircleDashed size={11} aria-hidden="true" />}
+ {checks.text}
+ </span>
+ )}
+ </span>
+ </button>
+ </li>
+ );
+};
+
+// ---------- Board ----------
+
+export const Board: React.FC<{
+ tasks: Task[];
+ names: Record<string, string>;
+ column: Column;
+ now?: number;
+ showMission?: boolean;
+ onColumn: (c: Column) => void;
+ onOpen: (t: Task) => void;
+}> = ({ tasks, names, column, now, showMission, onColumn, onOpen }) => {
+ const grouped = useMemo(() => groupByColumn(tasks), [tasks]);
+ const tabsId = useId();
+ const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
+ const onTabKey = (e: React.KeyboardEvent, i: number) => {
+ const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
+ if (!d) return;
+ e.preventDefault();
+ const next = (i + d + COLUMNS.length) % COLUMNS.length;
+ onColumn(COLUMNS[next].key);
+ tabRefs.current[next]?.focus();
+ };
+ const list = (key: Column) => {
+ const meta = COLUMNS.find((c) => c.key === key)!;
+ const items = grouped[key];
+ 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} />
+ ))}
+ </ul>
+ ) : (
+ <p className="px-3 py-6 rounded-xl border border-dashed border-zinc-800 text-center text-xs text-zinc-500" data-empty-column={key}>
+ {meta.empty}
+ </p>
+ );
+ };
+ return (
+ <>
+ {/* Phone and tablet: one column at a time, picked from tabs with counts */}
+ <div className="lg:hidden space-y-3" data-board="tabs">
+ <div role="tablist" aria-label="Board columns" className="flex gap-1 overflow-x-auto -mx-1 px-1 pb-1 [scrollbar-width:none]">
+ {COLUMNS.map((c, i) => {
+ const on = c.key === column;
+ const n = grouped[c.key].length;
+ return (
+ <button
+ key={c.key}
+ ref={(el) => (tabRefs.current[i] = el)}
+ type="button"
+ role="tab"
+ id={`${tabsId}-${c.key}`}
+ aria-selected={on}
+ aria-controls={`${tabsId}-panel`}
+ tabIndex={on ? 0 : -1}
+ onKeyDown={(e) => onTabKey(e, i)}
+ onClick={() => onColumn(c.key)}
+ className={`shrink-0 inline-flex items-center gap-1.5 min-h-[40px] px-3 rounded-lg text-xs font-medium ${focusRing} ${
+ on ? 'bg-zinc-800 text-zinc-100 border border-zinc-700' : 'text-zinc-400 border border-transparent hover:text-zinc-200'
+ }`}
+ >
+ {c.label}
+ <span className={`min-w-[18px] px-1 rounded-full text-[10px] text-center tabular-nums ${c.key === 'needs_you' && n > 0 ? 'bg-amber-500 text-zinc-950' : 'bg-zinc-700/70 text-zinc-200'}`}>{n}</span>
+ </button>
+ );
+ })}
+ </div>
+ <div role="tabpanel" id={`${tabsId}-panel`} aria-labelledby={`${tabsId}-${column}`}>
+ <p className="mb-2 text-[11px] text-zinc-500">{COLUMNS.find((c) => c.key === column)!.hint}</p>
+ {list(column)}
+ </div>
+ </div>
+ {/* Desktop: all five columns side by side */}
+ <div className="hidden lg:grid grid-cols-5 gap-3 items-start" data-board="columns">
+ {COLUMNS.map((c) => (
+ <section key={c.key} aria-labelledby={`${tabsId}-h-${c.key}`} className="min-w-0 space-y-2" data-column={c.key}>
+ <header className="px-1">
+ <h3 id={`${tabsId}-h-${c.key}`} className="flex items-center gap-2 text-xs font-semibold text-zinc-200">
+ {c.label}
+ <span className={`min-w-[18px] px-1 rounded-full text-[10px] text-center tabular-nums ${c.key === 'needs_you' && grouped[c.key].length > 0 ? 'bg-amber-500 text-zinc-950' : 'bg-zinc-800 text-zinc-300'}`}>
+ {grouped[c.key].length}
+ </span>
+ </h3>
+ <p className="text-[11px] text-zinc-500 truncate" title={c.hint}>
+ {c.hint}
+ </p>
+ </header>
+ {list(c.key)}
+ </section>
+ ))}
+ </div>
+ </>
+ );
+};
+
+// ---------- Evidence receipt ----------
+
+const statusIcon = (tone: Tone) =>
+ tone === 'emerald' ? (
+ <CheckCircle2 size={15} className="text-emerald-400" aria-hidden="true" />
+ ) : tone === 'rose' ? (
+ <XCircle size={15} className="text-rose-400" aria-hidden="true" />
+ ) : tone === 'violet' ? (
+ <Loader2 size={15} className="text-violet-300 animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : tone === 'amber' ? (
+ <Hand size={15} className="text-amber-300" aria-hidden="true" />
+ ) : (
+ <Circle size={15} className="text-zinc-500" aria-hidden="true" />
+ );
+
+const evidenceIcon = (k: Evidence['kind']) =>
+ k === 'url' ? <Link2 size={13} aria-hidden="true" /> : k === 'note' ? <StickyNote size={13} aria-hidden="true" /> : k === 'screenshot' ? <ImageIcon size={13} aria-hidden="true" /> : <FileText size={13} aria-hidden="true" />;
+
+const EvidenceItem: React.FC<{ e: Evidence; names: Record<string, string> }> = ({ e, names }) => {
+ const href = safeHttps(e.uri);
+ const size = formatBytes(e.bytes);
+ const by = e.captured_by === 'person' ? 'you' : e.captured_by === 'kwant' ? 'kwant' : names[e.captured_by] || 'a bot';
+ return (
+ <li className="flex items-start gap-2 text-xs" data-evidence={e.id}>
+ <span className="mt-0.5 text-zinc-400">{evidenceIcon(e.kind)}</span>
+ <div className="min-w-0 flex-1">
+ {href ? (
+ <a href={href} target="_blank" rel="noopener noreferrer" className={`inline-flex items-center gap-1 text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline break-all ${focusRing} rounded`}>
+ {e.label}
+ <ExternalLink size={11} aria-hidden="true" />
+ </a>
+ ) : (
+ <span className="text-zinc-200 break-words">{e.label}</span>
+ )}
+ {e.path && <code className="block mt-0.5 text-[11px] text-zinc-400 break-all">{e.path}</code>}
+ {e.excerpt && <p className="mt-0.5 text-[11px] text-zinc-400 whitespace-pre-wrap break-words line-clamp-4">{e.excerpt}</p>}
+ <p className="mt-0.5 text-[10px] text-zinc-500">
+ {[`Added by ${by}`, ago(e.captured_at), size, e.sha256 ? `SHA-256 ${e.sha256.slice(0, 12)}…` : null].filter(Boolean).join(' · ')}
+ </p>
+ </div>
+ </li>
+ );
+};
+
+export const EvidenceReceipt: React.FC<{
+ receipt: Receipt;
+ names: Record<string, string>;
+ busy?: boolean;
+ onApproveCheck?: (c: Check) => void;
+}> = ({ receipt, names, busy = false, onApproveCheck }) => (
+ <section aria-labelledby="receipt-h" className="space-y-3" data-receipt>
+ <h4 id="receipt-h" className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">
+ <ShieldCheck size={14} className="text-emerald-400" aria-hidden="true" /> Evidence receipt
+ </h4>
+ {receipt.verifiedBy && (
+ <p className="px-3 py-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 text-xs text-emerald-200" data-verified-by>
+ Verified: {checkKindLabel(receipt.verifiedBy.check.kind).toLowerCase()} passed
+ {receipt.verifiedBy.by ? `, checked by ${receipt.verifiedBy.by}` : ''}
+ {receipt.verifiedBy.check.finished_at ? ` ${ago(receipt.verifiedBy.check.finished_at)}` : ''}.
+ </p>
+ )}
+ {receipt.notChecked && (
+ <div className="px-3 py-2 rounded-lg border border-dashed border-zinc-700 text-xs" data-not-checked>
+ <p className="font-semibold text-zinc-200">Not checked</p>
+ <p className="mt-0.5 text-zinc-400">
+ No check has run on this task yet. It can’t be marked verified on a bot’s word: a check has to pass, a teammate has to review it with evidence, or you verify it yourself.
+ </p>
+ </div>
+ )}
+ {receipt.lines.length > 0 && (
+ <ol className="divide-y divide-zinc-800 rounded-xl border border-zinc-800">
+ {receipt.lines.map((l) => (
+ <li key={l.check.id} className="p-3 space-y-1.5" data-check={l.check.id} data-check-status={l.check.status}>
+ <div className="flex items-start gap-2">
+ <span className="mt-px">{statusIcon(l.status.tone)}</span>
+ <div className="min-w-0 flex-1">
+ <p className="flex flex-wrap items-center gap-1.5 text-xs">
+ <span className="font-medium text-zinc-100">{checkKindLabel(l.check.kind)}</span>
+ <Badge tone={l.status.tone}>{l.status.label}</Badge>
+ {!l.check.required && <span className="text-[10px] text-zinc-500">Optional</span>}
+ </p>
+ {l.target && <code className="block mt-1 text-[11px] text-zinc-300 break-all whitespace-pre-wrap">{l.target}</code>}
+ <p className="mt-1 text-[10px] text-zinc-500">
+ {[l.by ? `Checked by ${l.by}` : null, l.check.finished_at ? ago(l.check.finished_at) : null].filter(Boolean).join(' · ') || 'Hasn’t run yet'}
+ </p>
+ {l.ownClaim && <p className="mt-1 text-[11px] text-amber-200">This is the owner’s own check, so it doesn’t count toward Verified.</p>}
+ </div>
+ </div>
+ {l.check.status === 'needs_approval' && onApproveCheck && (
+ <div className="flex flex-wrap items-center gap-2 pl-6">
+ <p className="text-[11px] text-amber-200 flex-1 min-w-[10rem]">A bot added this check. It runs only after you OK it.</p>
+ <button type="button" disabled={busy} onClick={() => onApproveCheck(l.check)} className={quietBtn}>
+ Allow this check
+ </button>
+ </div>
+ )}
+ {(l.check.output_excerpt || l.output?.excerpt) && (
+ <details className="pl-6 group">
+ <summary className={`cursor-pointer text-[11px] text-zinc-400 hover:text-zinc-200 rounded ${focusRing}`}>Show output</summary>
+ <pre className="mt-1 max-h-48 overflow-auto p-2 rounded-lg bg-zinc-950 border border-zinc-800 text-[11px] text-zinc-300 whitespace-pre-wrap break-words">
+ {l.check.output_excerpt || l.output?.excerpt}
+ </pre>
+ </details>
+ )}
+ </li>
+ ))}
+ </ol>
+ )}
+ <div>
+ <h5 className="text-[11px] font-medium text-zinc-400 mb-1.5">Attached by the team</h5>
+ {receipt.attachments.length ? (
+ <ul className="space-y-2">
+ {receipt.attachments.map((e) => (
+ <EvidenceItem key={e.id} e={e} names={names} />
+ ))}
+ </ul>
+ ) : (
+ <p className="text-[11px] text-zinc-500">Nothing attached.</p>
+ )}
+ <p className="mt-2 text-[10px] text-zinc-500">Attached files and links are evidence to look at. They never mark a task verified on their own.</p>
+ </div>
+ </section>
+);
+
+// ---------- Task detail ----------
+
+const Fact: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
+ <div className="min-w-0">
+ <dt className="text-[11px] text-zinc-500">{label}</dt>
+ <dd className="text-xs text-zinc-200 break-words">{children}</dd>
+ </div>
+);
+
+export const TaskDetailBody: React.FC<{
+ detail: TaskDetail;
+ names: Record<string, string>;
+ tasksById?: Record<string, Task>;
+ now?: number;
+ busy?: boolean;
+ notice?: { text: string; error: boolean } | null;
+ onAction: (a: TaskAction, reason?: string) => void;
+ onApproveCheck: (c: Check) => void;
+ onOpenChat?: (t: Task) => void;
+ onOpenTask?: (id: string) => void;
+}> = ({ detail, names, tasksById = {}, now = Date.now(), busy = false, notice, onAction, onApproveCheck, onOpenChat, onOpenTask }) => {
+ const t = detail.task;
+ const receipt = useMemo(() => buildReceipt(detail, names), [detail, names]);
+ const [asking, setAsking] = useState<TaskAction | null>(null);
+ const [reason, setReason] = useState('');
+ 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);
+ const chat = sourceChat(t);
+ const [showAll, setShowAll] = useState(false);
+ const events = showAll ? detail.events : detail.events.slice(-12);
+
+ useEffect(() => {
+ setAsking(null);
+ setReason('');
+ }, [t.id, t.state]);
+
+ const press = (a: TaskAction) => {
+ if (NEEDS_REASON[a]) {
+ setAsking(a);
+ return;
+ }
+ onAction(a);
+ };
+
+ return (
+ <div className="space-y-5">
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <Badge tone={st.tone}>{st.label}</Badge>
+ {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') && (
+ <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} />}
+ {actions.length > 0 && !asking && (
+ <div className="flex flex-wrap gap-2" data-actions>
+ {actions.map((a) => (
+ <button
+ key={a}
+ type="button"
+ disabled={busy}
+ onClick={() => press(a)}
+ className={a === 'verify' ? goodBtn : a === 'retry' || a === 'unblock' ? mainBtn : a === 'cancel' ? dangerBtn : quietBtn}
+ >
+ {a === 'verify' && <CheckCircle2 size={13} aria-hidden="true" />}
+ {ACTION_LABELS[a]}
+ </button>
+ ))}
+ {busy && <Loader2 size={14} className="self-center animate-spin motion-reduce:animate-none text-zinc-400" aria-label="Working" />}
+ </div>
+ )}
+ {asking && (
+ <form
+ className="space-y-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!reason.trim()) return;
+ onAction(asking, reason.trim());
+ }}
+ >
+ <label htmlFor={reasonId} className="block text-[11px] font-medium text-zinc-300">
+ {NEEDS_REASON[asking]}
+ </label>
+ <textarea id={reasonId} autoFocus rows={2} value={reason} onChange={(e) => setReason(e.target.value)} className={`${field} resize-y`} />
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={busy || !reason.trim()} className={mainBtn}>
+ {ACTION_LABELS[asking]}
+ </button>
+ <button type="button" onClick={() => setAsking(null)} className={quietBtn}>
+ Never mind
+ </button>
+ </div>
+ </form>
+ )}
+ {t.state === 'review' && <p className="text-[11px] text-zinc-500">“Mark verified” records that you checked it yourself.</p>}
+ </div>
+
+ <section aria-labelledby="acc-h" className="space-y-1">
+ <h4 id="acc-h" className="text-xs font-semibold text-zinc-200">
+ What done looks like
+ </h4>
+ {t.acceptance.trim() ? (
+ <p className="text-xs text-zinc-300 whitespace-pre-wrap break-words">{t.acceptance}</p>
+ ) : (
+ <p className="text-xs text-zinc-500">No acceptance criteria were written for this task.</p>
+ )}
+ </section>
+
+ <dl className="grid grid-cols-2 gap-3">
+ <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>
+ {t.budget_tokens > 0 && (
+ <span className="block mt-1">
+ <SpendBar spent={t.spent_tokens} budget={t.budget_tokens} label="Task budget used" />
+ </span>
+ )}
+ </Fact>
+ <Fact label="Tries">
+ {t.attempts} of {t.max_attempts}
+ </Fact>
+ </dl>
+
+ {chat && onOpenChat && (
+ <button type="button" onClick={() => onOpenChat(t)} className={quietBtn} data-open-chat>
+ <MessageSquare size={13} aria-hidden="true" /> Open the chat it came from
+ </button>
+ )}
+
+ {t.claim && (
+ <section aria-labelledby="live-h" className="px-3 py-2 rounded-lg border border-violet-500/30 bg-violet-500/10 text-xs" data-live>
+ <h4 id="live-h" className="flex items-center gap-1.5 font-semibold text-violet-100">
+ <span className="relative flex w-2 h-2" aria-hidden="true">
+ <span className="absolute inline-flex w-full h-full rounded-full bg-violet-400 opacity-75 animate-ping motion-reduce:animate-none" />
+ <span className="relative inline-flex w-2 h-2 rounded-full bg-violet-400" />
+ </span>
+ Working now
+ </h4>
+ <p className="mt-0.5 text-violet-200">
+ {names[t.claim.kwant_id] || owner || 'A bot'} started {ago(t.claim.claimed_at, now)}. If nothing happens, it goes back to Ready {untilText(t.claim.expires_at, now)}.
+ </p>
+ </section>
+ )}
+
+ {t.needs_you.length > 0 && (
+ <section aria-labelledby="ny-h" className="space-y-2" data-needs-you>
+ <h4 id="ny-h" className="text-xs font-semibold text-amber-200">
+ Waiting for you
+ </h4>
+ <ul className="space-y-1.5">
+ {t.needs_you.map((n) => (
+ <li key={n.id} className="flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 text-xs text-amber-100">
+ <span className="flex-1 min-w-[10rem] break-words">
+ <span className="font-medium">{n.kind === 'approval' ? 'Approval' : n.kind === 'human_step' ? 'Step in the browser' : 'Question'}: </span>
+ {n.text}
+ </span>
+ {chat && onOpenChat && (
+ <button type="button" onClick={() => onOpenChat(t)} className="px-2 py-1 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[32px]">
+ Answer in chat
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ {t.waiting_on.length > 0 && (
+ <section aria-labelledby="wait-h" className="space-y-1">
+ <h4 id="wait-h" className="text-xs font-semibold text-zinc-200">
+ Waiting on
+ </h4>
+ <ul className="space-y-1">
+ {t.waiting_on.map((id) => {
+ const dep = tasksById[id];
+ return (
+ <li key={id} className="text-xs">
+ {dep && onOpenTask ? (
+ <button type="button" onClick={() => onOpenTask(id)} className={`text-left text-sky-300 hover:underline rounded ${focusRing}`}>
+ {dep.title}
+ </button>
+ ) : (
+ <span className="text-zinc-400">{dep?.title ?? 'Another task'}</span>
+ )}
+ {dep && <span className="text-zinc-500"> · {stateLabel(dep.state).label}</span>}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ )}
+
+ <EvidenceReceipt receipt={receipt} names={names} busy={busy} onApproveCheck={onApproveCheck} />
+
+ {detail.events.length > 0 && (
+ <section aria-labelledby="ev-h" className="space-y-1.5">
+ <h4 id="ev-h" className="text-xs font-semibold text-zinc-200">
+ Activity
+ </h4>
+ <ol className="space-y-1 border-l border-zinc-800 pl-3">
+ {events.map((e) => (
+ <li key={e.id} className="text-[11px] text-zinc-400 break-words">
+ {eventText(e, names)} <span className="text-zinc-600">· {ago(e.created_at, now)}</span>
+ </li>
+ ))}
+ </ol>
+ {!showAll && detail.events.length > events.length && (
+ <button type="button" onClick={() => setShowAll(true)} className={`text-[11px] text-sky-300 hover:underline rounded ${focusRing}`}>
+ Show all {detail.events.length}
+ </button>
+ )}
+ </section>
+ )}
+ </div>
+ );
+};
+
+/** The detail panel: a side sheet on desktop, the whole screen on a phone. */
+export const TaskPanel: React.FC<{
+ title: string;
+ onClose: () => void;
+ children: React.ReactNode;
+}> = ({ title, onClose, children }) => {
+ const closeRef = useRef<HTMLButtonElement>(null);
+ const headingId = useId();
+ useEffect(() => {
+ const back = document.activeElement as HTMLElement | null;
+ closeRef.current?.focus();
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => {
+ window.removeEventListener('keydown', onKey);
+ back?.focus?.();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ return (
+ <div className="fixed inset-0 z-40 flex justify-end" data-task-panel>
+ <button type="button" aria-label="Close task" tabIndex={-1} onClick={onClose} className="absolute inset-0 bg-black/50 cursor-default" />
+ <div role="dialog" aria-modal="true" aria-labelledby={headingId} className="relative w-full sm:max-w-xl h-full flex flex-col bg-zinc-950 sm:border-l border-zinc-800 shadow-2xl">
+ <div className="min-h-14 py-2 px-3 sm:px-5 border-b border-zinc-800/80 flex items-start gap-2 bg-zinc-900/30">
+ <h3 id={headingId} className="flex-1 min-w-0 pt-1.5 text-sm font-semibold text-zinc-100 break-words">
+ {title}
+ </h3>
+ <button ref={closeRef} type="button" onClick={onClose} aria-label="Close" className={`shrink-0 p-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 ${focusRing}`}>
+ <X size={18} aria-hidden="true" />
+ </button>
+ </div>
+ <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-5">{children}</div>
+ </div>
+ </div>
+ );
+};
+
+// ---------- Page ----------
+
+export interface MissionBoardViewProps {
+ tasks: Task[] | null;
+ missions: Mission[];
+ insights: Insights | null;
+ names: Record<string, string>;
+ missionId: string | null;
+ column: Column;
+ loading: boolean;
+ error: string | null;
+ needsToken?: boolean;
+ busyMission?: boolean;
+ notice?: { text: string; error: boolean } | null;
+ now?: number;
+ onMission: (id: string | null) => void;
+ onColumn: (c: Column) => void;
+ onOpenTask: (t: Task) => void;
+ onApproveMission: (m: Mission) => void;
+ onCancelMission: (m: Mission) => void;
+ onRefresh: () => void;
+ onBack?: () => void;
+}
+
+export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
+ tasks,
+ missions,
+ insights,
+ names,
+ missionId,
+ column,
+ loading,
+ error,
+ needsToken = false,
+ busyMission = false,
+ notice,
+ now,
+ onMission,
+ onColumn,
+ onOpenTask,
+ onApproveMission,
+ onCancelMission,
+ onRefresh,
+ onBack,
+}) => {
+ const selectId = useId();
+ const visibleMissions = missions.filter((m) => m.status !== 'cancelled');
+ const mission = missionId ? missions.find((m) => m.id === missionId) ?? null : null;
+ const drafts = mission ? [] : visibleMissions.filter((m) => m.status === 'draft');
+ const shown = (tasks ?? []).filter((t) => t.state !== 'cancelled' && (!missionId || t.mission_id === missionId));
+ const empty = tasks !== null && shown.length === 0 && !mission && drafts.length === 0;
+ return (
+ <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">
+ <div className={`h-14 shrink-0 border-b border-zinc-800/80 ${onBack ? 'px-2' : 'px-4'} sm:px-6 flex items-center justify-between gap-3 bg-zinc-900/30 backdrop-blur-sm select-none`}>
+ {onBack && (
+ <button type="button" onClick={onBack} aria-label="Back to chats" className={`shrink-0 p-2 -ml-0.5 -mr-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 ${focusRing}`}>
+ <ChevronLeft size={18} />
+ </button>
+ )}
+ <div className="min-w-0 flex-1">
+ <h2 className="text-sm font-semibold text-zinc-100 truncate">Mission board</h2>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">Your team’s work, and proof it’s done</p>
+ </div>
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={loading || needsToken}
+ aria-label="Refresh"
+ className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 disabled:opacity-60 ${focusRing}`}
+ >
+ <RefreshCw size={12} className={loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ <span className="hidden sm:inline">Refresh</span>
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-6" aria-busy={loading}>
+ <div className="max-w-[1500px] mx-auto space-y-4">
+ {needsToken && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 flex flex-wrap items-center gap-2 text-xs text-amber-100">
+ <span>Only you can change the board. Confirm it’s you to continue.</span>
+ <button type="button" onClick={requestPersonToken} className="ml-auto px-2 py-0.5 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[32px]">
+ Confirm it’s you
+ </button>
+ </div>
+ )}
+ {error && !needsToken && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">
+ <AlertTriangle size={14} className="shrink-0" aria-hidden="true" />
+ <span className="flex-1">{error}</span>
+ <button type="button" onClick={onRefresh} className="shrink-0 px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 min-h-[32px]">
+ Retry
+ </button>
+ </div>
+ )}
+ {notice && <Notice text={notice.text} error={notice.error} />}
+
+ {tasks === null && loading && (
+ <p className="flex items-center gap-2 text-xs text-zinc-400">
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading the board…
+ </p>
+ )}
+
+ {tasks !== null && (
+ <>
+ <InsightsStrip insights={insights} />
+
+ {visibleMissions.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor={selectId} className="text-[11px] font-medium text-zinc-400">
+ Show
+ </label>
+ <select
+ id={selectId}
+ value={missionId ?? ''}
+ onChange={(e) => onMission(e.target.value || null)}
+ className="min-h-[40px] sm:min-h-[32px] max-w-full bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none"
+ >
+ <option value="">All work</option>
+ {visibleMissions.map((m) => (
+ <option key={m.id} value={m.id}>
+ {m.title}
+ {m.status === 'draft' ? ' (waiting for your OK)' : m.status === 'done' ? ' (done)' : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {mission && <MissionSummary mission={mission} busy={busyMission} onApprove={() => onApproveMission(mission)} onCancel={() => onCancelMission(mission)} />}
+ {drafts.map((m) => (
+ <MissionSummary key={m.id} mission={m} busy={busyMission} onApprove={() => onApproveMission(m)} onCancel={() => onCancelMission(m)} />
+ ))}
+
+ {empty ? (
+ <div className="py-12 flex flex-col items-center text-center gap-2" data-empty>
+ <Target size={28} className="text-sky-400" aria-hidden="true" />
+ <p className="text-sm font-medium text-zinc-200">No tasks yet</p>
+ <p className="text-xs text-zinc-500 max-w-sm">
+ When a lead plans a mission, hands work to a teammate, or a routine runs, the task shows up here. It reaches Verified only when a check passes.
+ </p>
+ </div>
+ ) : (
+ <Board tasks={shown} names={names} column={column} now={now} showMission={!missionId} onColumn={onColumn} onOpen={onOpenTask} />
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+/** The live board for the open space. */
+export const MissionBoardPage: React.FC<{
+ spaceId: string;
+ names: Record<string, string>;
+ onBack?: () => void;
+ onOpenChat?: (t: Task) => void;
+}> = ({ spaceId, names, onBack, onOpenChat }) => {
+ const [tasks, setTasks] = useState<Task[] | null>(null);
+ const [missions, setMissions] = useState<Mission[]>([]);
+ const [insights, setInsights] = useState<Insights | null>(null);
+ const [missionId, setMissionId] = useState<string | null>(null);
+ const [column, setColumn] = useState<Column>('ready');
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [needsToken, setNeedsToken] = useState(false);
+ const [notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
+ const [busyMission, setBusyMission] = useState(false);
+ const [openId, setOpenId] = useState<string | null>(null);
+ const [detail, setDetail] = useState<TaskDetail | null>(null);
+ const [detailError, setDetailError] = useState<string | null>(null);
+ const [detailNotice, setDetailNotice] = useState<{ text: string; error: boolean } | null>(null);
+ const [busy, setBusy] = useState(false);
+ const alive = useRef(true);
+ const openIdRef = useRef<string | null>(null);
+ openIdRef.current = openId;
+
+ const failMsg = (e: unknown) => (e instanceof Error ? e.message : 'Something went wrong.');
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const [t, m] = await Promise.all([missionsApi.tasks(), missionsApi.missions()]);
+ if (!alive.current) return;
+ setTasks(t.filter((x) => x.state !== 'cancelled'));
+ setMissions(m);
+ setError(null);
+ setNeedsToken(false);
+ missionsApi.insights().then((i) => alive.current && setInsights(i), () => {});
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ else setError(failMsg(e));
+ } finally {
+ if (alive.current) setLoading(false);
+ }
+ }, []);
+
+ const loadDetail = useCallback(async (id: string) => {
+ try {
+ const d = await missionsApi.task(id);
+ if (!alive.current || openIdRef.current !== id) return;
+ setDetail(d);
+ setDetailError(null);
+ } catch (e) {
+ if (alive.current && openIdRef.current === id) setDetailError(failMsg(e));
+ }
+ }, []);
+
+ useEffect(() => {
+ alive.current = true;
+ load();
+ const again = () => load();
+ window.addEventListener(PERSON_SIGNED_IN_EVENT, again);
+ return () => {
+ alive.current = false;
+ window.removeEventListener(PERSON_SIGNED_IN_EVENT, again);
+ };
+ }, [load]);
+
+ // Live: patch the list from each event; the open card re-reads its checks and activity.
+ const insightsTimer = useRef<number | null>(null);
+ useEffect(() => {
+ const refreshInsights = () => {
+ if (insightsTimer.current) window.clearTimeout(insightsTimer.current);
+ insightsTimer.current = window.setTimeout(() => missionsApi.insights().then((i) => alive.current && setInsights(i), () => {}), 1500);
+ };
+ const offTask = onMission('task_updated', ({ task }) => {
+ if (!task || task.space_id !== spaceId) return;
+ setTasks((list) => (list ? upsertTask(list, task) : list));
+ if (openIdRef.current === task.id) loadDetail(task.id);
+ refreshInsights();
+ });
+ const offMission = onMission('mission_updated', ({ mission }) => {
+ if (!mission || mission.space_id !== spaceId) return;
+ setMissions((list) => upsertMission(list, mission));
+ });
+ return () => {
+ offTask();
+ offMission();
+ if (insightsTimer.current) window.clearTimeout(insightsTimer.current);
+ };
+ }, [spaceId, loadDetail]);
+
+ const openTask = (id: string) => {
+ setOpenId(id);
+ setDetail(null);
+ setDetailError(null);
+ setDetailNotice(null);
+ loadDetail(id);
+ playSfx('click');
+ };
+ const closeTask = () => {
+ setOpenId(null);
+ setDetail(null);
+ };
+
+ const act = async (a: TaskAction, reason?: string) => {
+ if (!openId) return;
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ const t = await missionsApi.act(openId, a, reason);
+ if (!alive.current) return;
+ setTasks((list) => (list ? upsertTask(list, t) : list));
+ setDetailNotice({ text: ACTION_DONE[a], error: false });
+ playSfx(a === 'verify' ? 'coin' : 'click');
+ if (t.state === 'cancelled') closeTask();
+ else 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);
+ }
+ };
+
+ const approveCheck = async (c: Check) => {
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ await missionsApi.approveCheck(c.id);
+ if (!alive.current) return;
+ setDetailNotice({ text: 'Allowed. The check runs now.', error: false });
+ if (openId) await loadDetail(openId);
+ } catch (e) {
+ if (alive.current) setDetailNotice({ text: failMsg(e), error: true });
+ } finally {
+ if (alive.current) setBusy(false);
+ }
+ };
+
+ const missionAction = async (m: Mission, approve: boolean) => {
+ setBusyMission(true);
+ setNotice(null);
+ try {
+ const next = approve ? await missionsApi.approveMission(m.id) : await missionsApi.cancelMission(m.id);
+ if (!alive.current) return;
+ setMissions((list) => upsertMission(list, next));
+ setNotice({ text: approve ? `Approved “${m.title}”. Its tasks can start now.` : `“${m.title}” won’t run.`, error: false });
+ if (!approve && missionId === m.id) setMissionId(null);
+ load();
+ } 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 tasksById = useMemo(() => Object.fromEntries((tasks ?? []).map((t) => [t.id, t])), [tasks]);
+ const listed = openId ? tasksById[openId] : undefined;
+
+ return (
+ <>
+ <MissionBoardView
+ tasks={tasks}
+ missions={missions}
+ insights={insights}
+ names={names}
+ missionId={missionId}
+ column={column}
+ loading={loading}
+ error={error}
+ needsToken={needsToken}
+ busyMission={busyMission}
+ notice={notice}
+ onMission={setMissionId}
+ onColumn={setColumn}
+ onOpenTask={(t) => openTask(t.id)}
+ onApproveMission={(m) => missionAction(m, true)}
+ onCancelMission={(m) => missionAction(m, false)}
+ onRefresh={load}
+ onBack={onBack}
+ />
+ {openId && (
+ <TaskPanel title={detail?.task.title ?? listed?.title ?? 'Task'} onClose={closeTask}>
+ {detail ? (
+ <TaskDetailBody
+ detail={detail}
+ names={names}
+ tasksById={tasksById}
+ busy={busy}
+ notice={detailNotice}
+ onAction={act}
+ onApproveCheck={approveCheck}
+ onOpenChat={
+ onOpenChat
+ ? (t) => {
+ closeTask();
+ onOpenChat(t);
+ }
+ : undefined
+ }
+ onOpenTask={(id) => {
+ const dep = tasksById[id];
+ if (dep) {
+ const c = columnOf(dep.state);
+ if (c) setColumn(c);
+ }
+ openTask(id);
+ }}
+ />
+ ) : detailError ? (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">
+ <span className="flex-1">{detailError}</span>
+ <button type="button" onClick={() => loadDetail(openId)} className="shrink-0 px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 min-h-[32px]">
+ Retry
+ </button>
+ </div>
+ ) : (
+ <p className="flex items-center gap-2 text-xs text-zinc-400">
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading…
+ </p>
+ )}
+ </TaskPanel>
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index e0986dd3..862273bf 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
-import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles } from 'lucide-react';
+import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles, KanbanSquare } from 'lucide-react';
import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';
import { budgetError, budgetValue } from '../chainBudget';
import { DailyUsagePanel } from './DailyUsage';
@@ -30,6 +30,7 @@ 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 { MISSION_BOARD_SETTING_EVENT, parseMissionBoardSetting } from '../missions';
/** One labelled switch row, like the others in this dialog. */
const SwitchRow: React.FC<{ id: string; label: string; hint: string; checked: boolean; onToggle: () => void; children?: React.ReactNode }> = ({
@@ -130,6 +131,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const [agentTools, setAgentTools] = useState<boolean | null>(null);
// Deciding and working ahead on their own; null on a server without these settings
const [proactive, setProactive] = useState<ProactiveSettings | null>(null);
+ // null: this server has no Mission board, so the switch stays hidden.
+ const [missionBoard, setMissionBoard] = useState<boolean | null>(null);
// null until loaded, and on a server without these settings
const [place, setPlace] = useState<{ timezone: string; location: string } | null>(null);
const [webhookUrl, setWebhookUrl] = useState('');
@@ -193,6 +196,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
setChainBudget(typeof data.chain_token_budget === 'number' ? String(data.chain_token_budget) : null);
setAgentTools(typeof data.agent_tools === 'boolean' ? data.agent_tools : null);
setProactive(parseProactiveSettings(data));
+ setMissionBoard(parseMissionBoardSetting(data));
setPlace(
typeof data.timezone === 'string'
? { timezone: data.timezone || defaultTimeZone(), location: typeof data.location === 'string' ? data.location : '' }
@@ -272,12 +276,14 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
...(chainBudget !== null ? { chain_token_budget: budgetValue(chainBudget) } : {}),
...(agentTools !== null ? { agent_tools: agentTools } : {}),
...(proactive ?? {}),
+ ...(missionBoard !== null ? { mission_board: missionBoard } : {}),
...(place ? { timezone: place.timezone.trim(), location: place.location.trim() } : {}),
}),
});
if (res.ok) {
setSaveSuccess(true);
+ if (missionBoard !== null) window.dispatchEvent(new CustomEvent(MISSION_BOARD_SETTING_EVENT, { detail: missionBoard }));
// Saving a key or the Ollama URL re-checks engines on the server; show the result.
window.setTimeout(engines.reload, 1500);
window.setTimeout(engines.reload, 6000);
@@ -677,6 +683,22 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</fieldset>
)}
+ {missionBoard !== null && (
+ <fieldset className="space-y-3 pt-2 border-t border-zinc-800" data-testid="mission-board-settings">
+ <legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">
+ <KanbanSquare size={14} className="text-sky-400" aria-hidden="true" />
+ <span>Mission board</span>
+ </legend>
+ <SwitchRow
+ id="mission-board"
+ label="Show the Mission board"
+ hint="One board for all your team’s work: Ready, Working, Needs you, Review and Verified. A task reaches Verified only when a check passes, not on a bot’s word."
+ checked={missionBoard}
+ onToggle={() => setMissionBoard((v) => !v)}
+ />
+ </fieldset>
+ )}
+
<fieldset className="space-y-3 pt-2 border-t border-zinc-800">
<legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">
<Bell size={14} className="text-amber-300" />
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 6b37baa3..02f5ed52 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useState } from 'react';
-import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split, Hand, Plug, MoreHorizontal, UserMinus, MessageSquare } from 'lucide-react';
+import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split, Hand, Plug, MoreHorizontal, UserMinus, MessageSquare, KanbanSquare } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { playSfx } from '../audio/chiptune';
import { badgeText } from '../away';
@@ -102,6 +102,10 @@ export interface SidebarProps {
onOpenLooseEnds?: () => void;
parallelActive?: boolean;
onOpenParallel?: () => void;
+ /** Shows the Mission board row; the server's mission_board setting decides. */
+ missionBoard?: boolean;
+ missionsActive?: boolean;
+ onOpenMissions?: () => void;
onOpenAway?: () => void;
/** Opens Space settings → Accounts from the footer. */
onOpenAccounts?: () => void;
@@ -160,6 +164,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
onOpenConnections,
parallelActive = false,
onOpenParallel,
+ missionBoard = false,
+ missionsActive = false,
+ onOpenMissions,
onOpenLooseEnds,
onOpenAway,
onOpenAccounts,
@@ -313,6 +320,12 @@ export const Sidebar: React.FC<SidebarProps> = ({
)}
</button>
)}
+ {missionBoard && onOpenMissions && (
+ <button type="button" onClick={onOpenMissions} aria-current={missionsActive ? 'page' : undefined} className={navRow(missionsActive)}>
+ <KanbanSquare size={15} className={missionsActive ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />
+ <span className="truncate flex-1">Mission board</span>
+ </button>
+ )}
{onOpenLooseEnds && (
<button type="button" onClick={onOpenLooseEnds} aria-current={looseActive ? 'page' : undefined} className={navRow(looseActive)}>
<ListChecks size={15} className={looseActive ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
new file mode 100644
index 00000000..15e6a814
--- /dev/null
+++ b/frontend/src/missions.ts
@@ -0,0 +1,658 @@
+// Mission board (Mission Control + Verified Outcomes, Phase A). Contract:
+// /home/maus/shared/ship-software-safely/mission-control/contract.md. Every unit of work (a mission
+// task, a hand-off, a routine run, a Loose End taken on, a work-ahead run) is one row in `tasks`.
+// Nothing here can mark a task verified on a bot's word: the board only shows what kwant checked,
+// and every non-GET route is person-only on the server.
+
+import { PersonCancelledError, personFetch } from './auth';
+import { relativeTime } from './away';
+
+export type TaskState = 'backlog' | 'ready' | 'working' | 'needs_you' | 'review' | 'verified' | 'blocked' | 'failed' | 'cancelled';
+export type MissionStatus = 'draft' | 'active' | 'done' | 'cancelled';
+export type SourceKind = 'mission' | 'person' | 'delegation' | 'routine' | 'zombie' | 'work_ahead' | 'chat';
+export type CheckKind = 'command' | 'http' | 'file_exists' | 'file_contains' | 'file_sha256' | 'peer_review' | 'person';
+export type CheckStatus = 'pending' | 'needs_approval' | 'running' | 'passed' | 'failed' | 'error';
+export type ChecksStatus = 'not_checked' | 'pending' | 'passed' | 'failed';
+
+export type StateCounts = Record<TaskState, number>;
+
+export interface Mission {
+ id: string;
+ space_id: string;
+ title: string;
+ goal: string;
+ status: MissionStatus;
+ lead_kwant_id: string;
+ lead_name: string | null;
+ channel_id: string | null;
+ direct_kwant_id: string | null;
+ thread_id: string | null;
+ budget_tokens: number;
+ spent_tokens: number;
+ reserved_tokens: number;
+ over_budget: boolean;
+ created_by: string;
+ approved_at: string | null;
+ approved_by: string | null;
+ created_at: string;
+ updated_at: string;
+ finished_at: string | null;
+ counts: StateCounts;
+}
+
+export interface NeedsYouItem {
+ kind: 'question' | 'approval' | 'human_step';
+ id: string;
+ text: string;
+}
+
+export interface Claim {
+ kwant_id: string;
+ claimed_at: string;
+ expires_at: string;
+}
+
+export interface ChecksSummary {
+ status: ChecksStatus;
+ passed: number;
+ failed: number;
+ total: number;
+}
+
+export interface Task {
+ id: string;
+ space_id: string;
+ mission_id: string | null;
+ mission_title: string | null;
+ title: string;
+ acceptance: string;
+ state: TaskState;
+ priority: number;
+ owner_kwant_id: string | null;
+ owner_name: string | null;
+ suggested_kwant_id: string | null;
+ budget_tokens: number;
+ spent_tokens: number;
+ attempts: number;
+ max_attempts: number;
+ blocked_reason: string | null;
+ source_kind: SourceKind;
+ source_id: string | null;
+ channel_id: string | null;
+ direct_kwant_id: string | null;
+ thread_id: string | null;
+ created_by: string;
+ created_at: string;
+ updated_at: string;
+ finished_at: string | null;
+ depends_on: string[];
+ waiting_on: string[];
+ claim: Claim | null;
+ needs_you: NeedsYouItem[];
+ checks_summary: ChecksSummary;
+}
+
+export interface Check {
+ id: string;
+ task_id: string;
+ kind: CheckKind;
+ spec: Record<string, unknown>;
+ required: boolean;
+ approved: boolean;
+ status: CheckStatus;
+ output_excerpt: string | null;
+ checked_by: string | null;
+ checked_by_name: string | null;
+ requested_by: string;
+ evidence_id: string | null;
+ created_at: string;
+ started_at: string | null;
+ finished_at: string | null;
+}
+
+export type EvidenceKind = 'file' | 'url' | 'note' | 'screenshot' | 'check_output';
+
+export interface Evidence {
+ id: string;
+ task_id: string;
+ kind: EvidenceKind;
+ label: string;
+ uri: string | null;
+ path: string | null;
+ sha256: string | null;
+ bytes: number | null;
+ excerpt: string | null;
+ captured_by: string;
+ run_id: string | null;
+ captured_at: string;
+}
+
+export interface TaskEvent {
+ id: number;
+ task_id: string;
+ mission_id: string | null;
+ kind: string;
+ actor: string;
+ actor_name: string | null;
+ from_state: TaskState | null;
+ to_state: TaskState | null;
+ detail: Record<string, unknown>;
+ created_at: string;
+}
+
+export interface TaskDetail {
+ task: Task;
+ checks: Check[];
+ evidence: Evidence[];
+ events: TaskEvent[];
+}
+
+export interface MissionDetail {
+ mission: Mission;
+ tasks: Task[];
+}
+
+export interface Insights {
+ verified_7d: number;
+ false_success_7d: number;
+ needs_you_now: number;
+ blocked_now: number;
+ interventions_7d: number;
+ tokens_7d: number;
+ tokens_per_verified_7d: number | null;
+}
+
+// ---------------------------------------------------------------------------
+// Board columns
+
+export type Column = 'ready' | 'working' | 'needs_you' | 'review' | 'verified';
+
+export const COLUMNS: Array<{ key: Column; label: string; hint: string; empty: string }> = [
+ { key: 'ready', label: 'Ready', hint: 'Can start, or waiting on another task', empty: 'Nothing waiting to start.' },
+ { key: 'working', label: 'Working', hint: 'A bot is on it now', empty: 'No bot is working on a task right now.' },
+ { key: 'needs_you', label: 'Needs you', hint: 'A question, approval or step only you can do', empty: 'Nothing needs you.' },
+ { key: 'review', label: 'Review', hint: 'Bot says done; waiting for a check', empty: 'Nothing waiting for a check.' },
+ { key: 'verified', label: 'Verified', hint: 'A check passed', empty: 'Nothing verified yet. A task gets here only when a check passes.' },
+];
+
+/**
+ * Which column a task sits in. Blocked and Failed are badges, not columns: the Task shape doesn't
+ * carry the state before it, so a blocked task waits in Ready (it can't start) and a failed one in
+ * Review (its checks failed; you decide whether to retry). Cancelled tasks are hidden (null).
+ */
+export function columnOf(state: TaskState): Column | null {
+ switch (state) {
+ case 'backlog':
+ case 'ready':
+ case 'blocked':
+ return 'ready';
+ case 'working':
+ return 'working';
+ case 'needs_you':
+ return 'needs_you';
+ case 'review':
+ case 'failed':
+ return 'review';
+ case 'verified':
+ return 'verified';
+ default:
+ return null;
+ }
+}
+
+/** Urgent first, then high; inside a priority, the most recently changed first. */
+export function sortTasks(tasks: Task[]): Task[] {
+ return [...tasks].sort((a, b) => b.priority - a.priority || Date.parse(b.updated_at) - Date.parse(a.updated_at));
+}
+
+export function groupByColumn(tasks: Task[]): Record<Column, Task[]> {
+ const out: Record<Column, Task[]> = { ready: [], working: [], needs_you: [], review: [], verified: [] };
+ for (const t of sortTasks(tasks)) {
+ const c = columnOf(t.state);
+ if (c) out[c].push(t);
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Labels
+
+export type Tone = 'emerald' | 'amber' | 'rose' | 'sky' | 'violet' | 'zinc';
+
+export const STATE_LABELS: Record<TaskState, { label: string; tone: Tone }> = {
+ backlog: { label: 'Waiting', tone: 'zinc' },
+ ready: { label: 'Ready', tone: 'sky' },
+ working: { label: 'Working', tone: 'violet' },
+ needs_you: { label: 'Needs you', tone: 'amber' },
+ review: { label: 'Review', tone: 'sky' },
+ verified: { label: 'Verified', tone: 'emerald' },
+ blocked: { label: 'Blocked', tone: 'rose' },
+ failed: { label: 'Failed', tone: 'rose' },
+ cancelled: { label: 'Cancelled', tone: 'zinc' },
+};
+
+export const stateLabel = (s: string): { label: string; tone: Tone } => STATE_LABELS[s as TaskState] ?? { label: humanize(s), tone: 'zinc' };
+
+export const PRIORITY_LABELS = ['Low', 'Normal', 'High', 'Urgent'];
+export const priorityLabel = (p: number): string => PRIORITY_LABELS[Math.max(0, Math.min(3, Math.round(p)))] ?? 'Normal';
+
+const SOURCES: Record<string, string> = {
+ mission: 'Mission plan',
+ person: 'Added by you',
+ delegation: 'Hand-off',
+ routine: 'Routine run',
+ zombie: 'Loose end',
+ work_ahead: 'Worked ahead',
+ chat: 'Chat',
+};
+export const sourceLabel = (k: string): string => SOURCES[k] ?? humanize(k);
+
+export const MISSION_STATUS: Record<MissionStatus, { label: string; tone: Tone }> = {
+ draft: { label: 'Waiting for your OK', tone: 'amber' },
+ active: { label: 'Active', tone: 'sky' },
+ done: { label: 'Done', tone: 'emerald' },
+ cancelled: { label: 'Cancelled', tone: 'zinc' },
+};
+export const missionStatusLabel = (s: string) => MISSION_STATUS[s as MissionStatus] ?? { label: humanize(s), tone: 'zinc' as Tone };
+
+export function humanize(s: string): string {
+ const t = s.replace(/[_-]+/g, ' ').trim();
+ return t ? t[0].toUpperCase() + t.slice(1) : 'Other';
+}
+
+/** 950 → "950", 12 400 → "12.4k", 2 000 000 → "2M". */
+export function formatTokens(n: number): string {
+ if (!Number.isFinite(n)) return '0';
+ const a = Math.abs(n);
+ if (a < 1000) return String(Math.round(n));
+ if (a < 1_000_000) return `${trim(n / 1000)}k`;
+ return `${trim(n / 1_000_000)}M`;
+}
+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. */
+export function costText(spent: number, budget: number): string {
+ return budget > 0 ? `${formatTokens(spent)} of ${formatTokens(budget)} tokens` : `${formatTokens(spent)} tokens`;
+}
+
+/** 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);
+
+/** The one-line check chip on a card. A task that has never been checked says so, plainly. */
+export function checksText(s: ChecksSummary): { text: string; tone: Tone } {
+ if (s.total === 0 || s.status === 'not_checked') return { text: 'Not checked', tone: 'zinc' };
+ if (s.status === 'failed') return { text: s.failed === 1 ? '1 check failed' : `${s.failed} checks failed`, tone: 'rose' };
+ if (s.status === 'pending') return { text: `${s.passed} of ${s.total} checks passed`, tone: 'amber' };
+ return { text: s.total === 1 ? 'Check passed' : `${s.passed} of ${s.total} checks passed`, tone: 'emerald' };
+}
+
+/** "in 12 min", "in 1 h", or "now" once it has passed. */
+export function untilText(iso: string, now: number = Date.now()): string {
+ const t = Date.parse(iso);
+ if (Number.isNaN(t)) return '';
+ const m = Math.round((t - now) / 60000);
+ if (m <= 0) return 'now';
+ if (m < 60) return `in ${m} min`;
+ const h = Math.round(m / 60);
+ return `in ${h} h`;
+}
+
+export const ago = relativeTime;
+
+/** Who did something: "you", "kwant", or the bot's name. */
+export function actorName(actor: string, name: string | null | undefined, names: Record<string, string> = {}): string {
+ if (actor === 'person') return 'you';
+ if (actor === 'kwant') return 'kwant';
+ return name || names[actor] || 'a bot';
+}
+
+/** The short status line under a card title. */
+export function cardStatus(t: Task, names: Record<string, string> = {}, now: number = Date.now()): string | null {
+ switch (t.state) {
+ case 'blocked':
+ return t.blocked_reason === 'budget' ? 'Out of budget' : t.blocked_reason ? `Blocked: ${t.blocked_reason}` : 'Blocked';
+ case 'failed':
+ return `Checks failed ${t.attempts} of ${t.max_attempts} times`;
+ case 'backlog':
+ if (t.waiting_on.length) return t.waiting_on.length === 1 ? 'Waiting on 1 task' : `Waiting on ${t.waiting_on.length} tasks`;
+ return 'Waiting for the mission to be approved';
+ case 'working':
+ return t.claim ? `${names[t.claim.kwant_id] || t.owner_name || 'A bot'} started ${ago(t.claim.claimed_at, now)}` : 'Starting';
+ case 'needs_you':
+ return t.needs_you[0]?.text ?? 'A bot is waiting for you';
+ case 'review':
+ return t.checks_summary.status === 'not_checked' ? 'Bot says done. Not checked yet' : 'Bot says done. Checking';
+ case 'verified':
+ return t.finished_at ? `Verified ${ago(t.finished_at, now)}` : 'Verified';
+ default:
+ return null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Evidence receipt
+
+export const CHECK_KINDS: Record<string, string> = {
+ command: 'Command',
+ http: 'Web address',
+ file_exists: 'File exists',
+ file_contains: 'File contains',
+ file_sha256: 'File fingerprint',
+ peer_review: 'Teammate review',
+ person: 'You verified',
+};
+export const checkKindLabel = (k: string): string => CHECK_KINDS[k] ?? humanize(k);
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v : null);
+
+/** What a check looks at, in one line: the command, the address, or the file. */
+export function checkTarget(c: Pick<Check, 'kind' | 'spec'>): string {
+ const s = c.spec ?? {};
+ switch (c.kind) {
+ case 'command':
+ return str(s.command) ?? 'a command';
+ case 'http': {
+ const url = str(s.url) ?? 'an address';
+ const status = typeof s.expect_status === 'number' ? ` answers ${s.expect_status}` : ' answers';
+ const has = str(s.contains);
+ return `${url}${status}${has ? ` and shows “${has}”` : ''}`;
+ }
+ case 'file_exists':
+ return str(s.path) ?? 'a file';
+ case 'file_contains':
+ return `${str(s.path) ?? 'a file'} has “${str(s.text) ?? ''}”`;
+ case 'file_sha256': {
+ const h = str(s.sha256);
+ return `${str(s.path) ?? 'a file'} matches ${h ? h.slice(0, 12) + '…' : 'its fingerprint'}`;
+ }
+ case 'peer_review':
+ case 'person':
+ return str(s.note) ?? '';
+ default:
+ return '';
+ }
+}
+
+export const CHECK_STATUS: Record<CheckStatus, { label: string; tone: Tone }> = {
+ passed: { label: 'Passed', tone: 'emerald' },
+ failed: { label: 'Failed', tone: 'rose' },
+ error: { label: 'Couldn’t run', tone: 'rose' },
+ running: { label: 'Running', tone: 'violet' },
+ pending: { label: 'Not run yet', tone: 'zinc' },
+ needs_approval: { label: 'Needs your OK', tone: 'amber' },
+};
+export const checkStatusLabel = (s: string) => CHECK_STATUS[s as CheckStatus] ?? { label: humanize(s), tone: 'zinc' as Tone };
+
+export interface ReceiptLine {
+ check: Check;
+ status: { label: string; tone: Tone };
+ target: string;
+ by: string | null;
+ output: Evidence | null;
+ /** The owner's own pass: shown, but it doesn't count toward Verified. */
+ ownClaim: boolean;
+}
+
+export interface Receipt {
+ lines: ReceiptLine[];
+ /** Evidence attached by bots (files, links, notes, screenshots); check output sits on its line. */
+ attachments: Evidence[];
+ /** No check has run (or none exists): the receipt says "Not checked", never hides it. */
+ notChecked: boolean;
+ /** The passing check that made it Verified, when there is one. */
+ verifiedBy: ReceiptLine | null;
+}
+
+/** Builds the evidence receipt: every check with its result and output, newest result first per check. */
+export function buildReceipt(d: Pick<TaskDetail, 'task' | 'checks' | 'evidence'>, names: Record<string, string> = {}): Receipt {
+ const byId = new Map(d.evidence.map((e) => [e.id, e]));
+ const owner = d.task.owner_kwant_id;
+ const lines = [...d.checks]
+ .sort((a, b) => Date.parse(b.finished_at ?? b.created_at) - Date.parse(a.finished_at ?? a.created_at))
+ .map<ReceiptLine>((c) => ({
+ check: c,
+ status: checkStatusLabel(c.status),
+ target: checkTarget(c),
+ by: c.checked_by ? actorName(c.checked_by, c.checked_by_name, names) : null,
+ output: c.evidence_id ? byId.get(c.evidence_id) ?? null : null,
+ ownClaim: !!owner && c.checked_by === owner,
+ }));
+ const ran = lines.some((l) => l.check.status === 'passed' || l.check.status === 'failed' || l.check.status === 'error');
+ const verifiedBy = d.task.state === 'verified' ? lines.find((l) => l.check.status === 'passed' && !l.ownClaim) ?? null : null;
+ return {
+ lines,
+ attachments: d.evidence.filter((e) => e.kind !== 'check_output').sort((a, b) => Date.parse(b.captured_at) - Date.parse(a.captured_at)),
+ notChecked: !ran,
+ verifiedBy,
+ };
+}
+
+/** 2 048 → "2 KB". */
+export function formatBytes(n: number | null | undefined): string | null {
+ if (typeof n !== 'number' || !Number.isFinite(n)) return null;
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(1).replace(/\.0$/, '')} MB`;
+}
+
+/** Only web links open from the board; file paths and anything else are shown, not linked. */
+export const safeHttps = (url: string | null | undefined): string | null => {
+ if (!url) return null;
+ try {
+ const u = new URL(url);
+ return u.protocol === 'https:' || u.protocol === 'http:' ? u.href : null;
+ } catch {
+ return null;
+ }
+};
+
+// ---------------------------------------------------------------------------
+// Activity
+
+/** One plain line per event for the activity list. */
+export function eventText(e: TaskEvent, names: Record<string, string> = {}): string {
+ const who = actorName(e.actor, e.actor_name, names);
+ const Who = who[0].toUpperCase() + who.slice(1);
+ const d = e.detail ?? {};
+ const note = str(d.note) ?? str(d.reason);
+ switch (e.kind) {
+ case 'created':
+ return `${Who} added this task`;
+ case 'state':
+ return `${Who} moved it to ${stateLabel(e.to_state ?? '').label}${note ? `: ${note}` : ''}`;
+ case 'claimed':
+ return `${Who} took it on`;
+ case 'released':
+ return `${Who} let it go${note ? `: ${note}` : ''}`;
+ case 'lease_expired':
+ return 'The claim ran out with no activity, so it went back to Ready';
+ case 'note':
+ return `${Who}: ${note ?? 'added a note'}`;
+ case 'evidence':
+ return `${Who} attached evidence${str(d.label) ? `: ${str(d.label)}` : ''}`;
+ case 'check_added':
+ return `${Who} added a check${str(d.kind) ? ` (${checkKindLabel(String(d.kind)).toLowerCase()})` : ''}`;
+ case 'check_started':
+ return 'A check started';
+ case 'check_result':
+ return `A check ${str(d.status) === 'passed' ? 'passed' : str(d.status) === 'error' ? 'couldn’t run' : 'failed'}`;
+ case 'review':
+ return `${Who} reviewed it: ${str(d.verdict) === 'pass' ? 'pass' : 'fail'}${note ? `. ${note}` : ''}`;
+ case 'budget':
+ return 'It reached its token budget';
+ case 'edited':
+ return `${Who} edited it`;
+ default:
+ return `${Who}: ${humanize(e.kind)}`;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Person actions
+
+export type TaskAction = 'verify' | 'reject' | 'block' | 'unblock' | 'retry' | 'cancel' | 'run_checks';
+
+/** The buttons the person gets on a task in its state. Verify only appears in Review. */
+export function actionsFor(t: Pick<Task, 'state'>): TaskAction[] {
+ switch (t.state) {
+ case 'review':
+ return ['verify', 'reject', 'run_checks', 'cancel'];
+ case 'failed':
+ return ['retry', 'cancel'];
+ case 'blocked':
+ return ['unblock', 'cancel'];
+ case 'backlog':
+ case 'ready':
+ case 'working':
+ case 'needs_you':
+ return ['block', 'cancel'];
+ default:
+ return [];
+ }
+}
+
+export const ACTION_LABELS: Record<TaskAction, string> = {
+ verify: 'Mark verified',
+ reject: 'Send back',
+ block: 'Block',
+ unblock: 'Unblock',
+ retry: 'Try again',
+ cancel: 'Cancel task',
+ run_checks: 'Run checks',
+};
+
+/** Actions that need a reason typed first. */
+export const NEEDS_REASON: Partial<Record<TaskAction, string>> = {
+ reject: 'What still needs doing?',
+ block: 'Why is it blocked?',
+};
+
+export const ACTION_DONE: Record<TaskAction, string> = {
+ verify: 'Marked verified by you.',
+ reject: 'Sent back to Ready.',
+ block: 'Blocked.',
+ unblock: 'Unblocked.',
+ retry: 'Back in Ready for another try.',
+ cancel: 'Cancelled.',
+ run_checks: 'Checks ran.',
+};
+
+// ---------------------------------------------------------------------------
+// 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 } };
+
+const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;
+
+export function emitMission(e: MissionEvent) {
+ bus?.dispatchEvent(new CustomEvent(e.type, { detail: e.data }));
+}
+
+export function onMission<T extends MissionEvent['type']>(type: T, fn: (data: Extract<MissionEvent, { type: T }>['data']) => void): () => void {
+ const listener = (ev: Event) => fn((ev as CustomEvent).detail);
+ bus?.addEventListener(type, listener);
+ return () => bus?.removeEventListener(type, listener);
+}
+
+/** Puts a changed task into the list (or drops it when it's cancelled and cancelled are hidden). */
+export function upsertTask(list: Task[], t: Task, showCancelled = false): Task[] {
+ const rest = list.filter((x) => x.id !== t.id);
+ if (t.state === 'cancelled' && !showCancelled) return rest;
+ return [t, ...rest];
+}
+
+export function upsertMission(list: Mission[], m: Mission): Mission[] {
+ return list.some((x) => x.id === m.id) ? list.map((x) => (x.id === m.id ? m : x)) : [m, ...list];
+}
+
+/** Fired by App settings after saving, so the sidebar shows or hides the board at once. */
+export const MISSION_BOARD_SETTING_EVENT = 'kwnt:mission-board-setting';
+
+/** `mission_board` from GET /api/settings; null on a server without Mission Control. */
+export function parseMissionBoardSetting(data: unknown): boolean | null {
+ if (!data || typeof data !== 'object') return null;
+ const v = (data as Record<string, unknown>).mission_board;
+ return typeof v === 'boolean' ? v : null;
+}
+
+// ---------------------------------------------------------------------------
+// API
+
+export class MissionError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ ) {
+ super(message);
+ }
+}
+
+const sentence = (s: string) => {
+ const t = s.trim();
+ if (!t) return t;
+ const c = t[0].toUpperCase() + t.slice(1);
+ return /[.!?]$/.test(c) ? c : `${c}.`;
+};
+
+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;
+ 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);
+}
+
+async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+ let res: Response;
+ try {
+ res = await personFetch(url, {
+ method,
+ cache: 'no-store',
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new MissionError(e.message, 401);
+ throw new MissionError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const answer = await res.json().catch(() => null);
+ if (res.ok) return answer as T;
+ throw errorFrom(res.status, answer);
+}
+
+const enc = encodeURIComponent;
+
+export const missionsApi = {
+ missions: () => call<{ missions: Mission[] }>('/api/missions').then((r) => r.missions),
+ mission: (id: string) => call<MissionDetail>(`/api/missions/${enc(id)}`),
+ insights: () => call<Insights>('/api/missions/insights'),
+ approveMission: (id: string) => call<Mission>(`/api/missions/${enc(id)}/approve`, 'POST', {}),
+ cancelMission: (id: string) => call<Mission>(`/api/missions/${enc(id)}/cancel`, 'POST', {}),
+ setBudget: (id: string, budget_tokens: number) => call<Mission>(`/api/missions/${enc(id)}`, 'PATCH', { budget_tokens }),
+ 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', {}),
+ /** One person action on a task. `run_checks` answers `{checks, task}`, the others the Task. */
+ act: async (id: string, action: TaskAction, reason?: string): Promise<Task> => {
+ const base = `/api/tasks/${enc(id)}`;
+ switch (action) {
+ case 'verify':
+ return call<Task>(`${base}/verify`, 'POST', reason ? { note: reason } : {});
+ case 'reject':
+ return call<Task>(`${base}/reject`, 'POST', { reason: reason ?? '' });
+ case 'block':
+ return call<Task>(`${base}/block`, 'POST', { reason: reason ?? '' });
+ case 'run_checks':
+ return call<{ task: Task }>(`${base}/checks/run`, 'POST', {}).then((r) => r.task);
+ default:
+ return call<Task>(`${base}/${action}`, 'POST', {});
+ }
+ },
+};
+
+/** Where a task came from in the app: a channel, a bot's thread, or a bot's direct chat. */
+export function sourceChat(t: Pick<Task, 'channel_id' | 'direct_kwant_id' | 'thread_id'>): { channelId: string | null; kwantId: string | null; threadId: string | null } | null {
+ if (t.channel_id) return { channelId: t.channel_id, kwantId: null, threadId: t.thread_id };
+ if (t.direct_kwant_id) return { channelId: null, kwantId: t.direct_kwant_id, threadId: t.thread_id };
+ return null;
+}
diff --git a/frontend/tests/missions.test.mjs b/frontend/tests/missions.test.mjs
new file mode 100644
index 00000000..a6327cde
--- /dev/null
+++ b/frontend/tests/missions.test.mjs
@@ -0,0 +1,274 @@
+// Mission board (Mission Control, Phase A): one board per space with Ready / Working / Needs you /
+// Review / Verified. Blocked and Failed are badges, never columns. A task's receipt lists every check
+// with its result, and says "Not checked" when nothing has run: Verified is never a bot's word.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const m = await loadBundled(`export * from './src/missions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { MissionBoardView, TaskCard, TaskDetailBody, EvidenceReceipt, InsightsStrip, MissionSummary } from './src/components/MissionBoardView';
+ import { buildReceipt } from './src/missions';
+ const r = (c, p) => renderToStaticMarkup(React.createElement(c, p));
+ export const view = (p) => r(MissionBoardView, p);
+ export const card = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(TaskCard, p)));
+ export const detail = (p) => r(TaskDetailBody, p);
+ export const receipt = (d, names = {}) => r(EvidenceReceipt, { receipt: buildReceipt(d, names), names });
+ export const insights = (p) => r(InsightsStrip, p);
+ export const mission = (p) => r(MissionSummary, p);
+`);
+
+const NOW = Date.parse('2026-10-27T12:00:00Z');
+const noop = () => {};
+const names = { k_ada: 'Ada', k_lin: 'Lin', k_rigel: 'Rigel' };
+const counts = (over = {}) => ({ backlog: 0, ready: 0, working: 0, needs_you: 0, review: 0, verified: 0, blocked: 0, failed: 0, cancelled: 0, ...over });
+
+// Shaped like Task in mission-control/contract.md §4.
+const task = (over = {}) => ({
+ id: 't1', space_id: 's1', mission_id: 'm1', mission_title: 'Launch the pricing page', title: 'Write the pricing copy',
+ acceptance: 'Copy for three plans is in docs/pricing.md and mentions the yearly discount.', state: 'ready', priority: 1,
+ owner_kwant_id: 'k_lin', owner_name: 'Lin', suggested_kwant_id: null, budget_tokens: 50000, spent_tokens: 12400,
+ attempts: 0, max_attempts: 3, blocked_reason: null, source_kind: 'mission', source_id: 'm1',
+ channel_id: 'c1', direct_kwant_id: null, thread_id: null, created_by: 'k_ada',
+ created_at: '2026-10-27T09:00:00Z', updated_at: '2026-10-27T11: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 check = (over = {}) => ({
+ id: 'ch1', task_id: 't1', kind: 'file_contains', spec: { path: 'docs/pricing.md', text: 'yearly' }, required: true, approved: true,
+ status: 'passed', output_excerpt: null, checked_by: 'kwant', checked_by_name: null, requested_by: 'k_ada', evidence_id: null,
+ created_at: '2026-10-27T10:00:00Z', started_at: '2026-10-27T11:00:00Z', finished_at: '2026-10-27T11:00:05Z', ...over,
+});
+const evidence = (over = {}) => ({
+ id: 'e1', task_id: 't1', kind: 'url', label: 'Preview', uri: 'https://preview.example/pricing', path: null, sha256: null, bytes: null,
+ excerpt: null, captured_by: 'k_lin', run_id: null, captured_at: '2026-10-27T11:00:00Z', ...over,
+});
+const missionRow = (over = {}) => ({
+ id: 'm1', space_id: 's1', title: 'Launch the pricing page', goal: 'A live pricing page with three plans', status: 'active',
+ lead_kwant_id: 'k_ada', lead_name: 'Ada', channel_id: 'c1', direct_kwant_id: null, thread_id: null,
+ budget_tokens: 200000, spent_tokens: 50000, reserved_tokens: 0, over_budget: false, created_by: 'k_ada',
+ approved_at: '2026-10-27T09:00:00Z', approved_by: 'person', created_at: '2026-10-27T08:00:00Z', updated_at: '2026-10-27T11:00:00Z',
+ finished_at: null, counts: counts({ ready: 1, verified: 1 }), ...over,
+});
+const insightsRow = { verified_7d: 4, false_success_7d: 1, needs_you_now: 2, blocked_now: 1, interventions_7d: 3, tokens_7d: 480000, tokens_per_verified_7d: 120000 };
+const viewProps = (over = {}) => ({
+ tasks: [task()], missions: [missionRow()], insights: insightsRow, names, missionId: null, column: 'ready', loading: false, error: null,
+ now: NOW, onMission: noop, onColumn: noop, onOpenTask: noop, onApproveMission: noop, onCancelMission: noop, onRefresh: noop, ...over,
+});
+
+test('five columns; blocked sits in Ready and failed in Review; cancelled is off the board', () => {
+ assert.deepEqual(m.COLUMNS.map((c) => c.label), ['Ready', 'Working', 'Needs you', 'Review', 'Verified']);
+ const want = { backlog: 'ready', ready: 'ready', blocked: 'ready', working: 'working', needs_you: 'needs_you', review: 'review', failed: 'review', verified: 'verified', cancelled: null };
+ for (const [s, c] of Object.entries(want)) assert.equal(m.columnOf(s), c, s);
+ const g = m.groupByColumn([
+ task({ id: 'a', priority: 1, updated_at: '2026-10-27T10:00:00Z' }),
+ task({ id: 'b', priority: 3 }),
+ task({ id: 'c', priority: 1, updated_at: '2026-10-27T11:30:00Z' }),
+ task({ id: 'x', state: 'cancelled' }),
+ ]);
+ assert.deepEqual(g.ready.map((t) => t.id), ['b', 'c', 'a'], 'urgent first, then newest');
+ assert.equal(Object.values(g).flat().length, 3);
+});
+
+test('the board renders every column, with Blocked and Failed as badges', () => {
+ const html = ui.view(viewProps({
+ tasks: [task({ id: 'r', state: 'blocked', blocked_reason: 'budget' }), task({ id: 'f', state: 'failed', attempts: 3 }), task({ id: 'v', state: 'verified', finished_at: '2026-10-27T11:00:00Z', checks_summary: { status: 'passed', passed: 1, failed: 0, total: 1 } })],
+ }));
+ for (const c of ['ready', 'working', 'needs_you', 'review', 'verified']) assert.match(html, new RegExp(`data-column="${c}"`));
+ 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, /Checks failed 3 of 3 times/);
+ // Phone: tabs with counts drive one column at a time.
+ assert.match(html, /role="tablist"/);
+ assert.match(html, /aria-selected="true"[^>]*>Ready/);
+ assert.match(html, /data-empty-column="working"/);
+});
+
+test('a card shows owner, cost and an honest check chip', () => {
+ const html = ui.card({ task: task({ state: 'review' }), names, now: NOW, onOpen: noop });
+ assert.match(html, /Lin/);
+ assert.match(html, /12\.4k of 50k tokens/);
+ assert.match(html, /Not checked/);
+ assert.match(html, /Bot says done\. Not checked yet/);
+ const working = ui.card({ task: task({ state: 'working', claim: { kwant_id: 'k_lin', claimed_at: '2026-10-27T11:50:00Z', expires_at: '2026-10-27T12:20:00Z' } }), names, now: NOW, onOpen: noop });
+ assert.match(working, /Lin started 10 min ago/);
+ const asks = ui.card({ task: task({ state: 'needs_you', needs_you: [{ kind: 'approval', id: 'a1', text: 'OK to publish the page?' }] }), names, now: NOW, onOpen: noop });
+ assert.match(asks, /OK to publish the page\?/);
+});
+
+test('checksText and costText read plainly', () => {
+ assert.deepEqual(m.checksText({ status: 'not_checked', passed: 0, failed: 0, total: 0 }), { text: 'Not checked', tone: 'zinc' });
+ assert.equal(m.checksText({ status: 'failed', passed: 1, failed: 2, total: 3 }).text, '2 checks failed');
+ assert.equal(m.checksText({ status: 'pending', passed: 1, failed: 0, total: 2 }).text, '1 of 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.costRatio(80, 50), 1);
+});
+
+test('the receipt says "Not checked" when no check has run, and never hides it', () => {
+ const d = { task: task({ state: 'review' }), checks: [check({ status: 'pending', finished_at: null, started_at: null, checked_by: null })], evidence: [evidence()], events: [] };
+ const r = m.buildReceipt(d, names);
+ assert.equal(r.notChecked, true);
+ assert.equal(r.verifiedBy, null);
+ const html = ui.receipt(d, names);
+ assert.match(html, /data-not-checked/);
+ assert.match(html, /Not run yet/);
+ assert.match(html, /Preview/);
+ assert.match(html, /never mark a task verified on their own/);
+ const none = ui.receipt({ task: task({ state: 'review' }), checks: [], evidence: [], events: [] });
+ assert.match(none, /Not checked/);
+ assert.match(none, /Nothing attached/);
+});
+
+test('each check shows its result, target, who ran it and output; Verified names the check', () => {
+ const out = evidence({ id: 'e2', kind: 'check_output', label: 'output', uri: null, excerpt: 'ok 12 tests' });
+ const d = {
+ task: task({ state: 'verified', finished_at: '2026-10-27T11:00:05Z' }),
+ checks: [
+ check({ id: 'c-pass' }),
+ check({ id: 'c-cmd', kind: 'command', spec: { command: 'npm test' }, status: 'failed', output_excerpt: '1 failing', finished_at: '2026-10-27T10:00:00Z', evidence_id: 'e2' }),
+ check({ id: 'c-own', kind: 'peer_review', spec: { note: 'looks fine' }, checked_by: 'k_lin', checked_by_name: 'Lin', finished_at: '2026-10-27T09:00:00Z' }),
+ ],
+ evidence: [out, evidence()],
+ events: [],
+ };
+ const r = m.buildReceipt(d, names);
+ assert.equal(r.notChecked, false);
+ assert.equal(r.verifiedBy.check.id, 'c-pass');
+ assert.deepEqual(r.lines.map((l) => l.check.id), ['c-pass', 'c-cmd', 'c-own'], 'newest result first');
+ assert.equal(r.lines[2].ownClaim, true, "owner's own review doesn't count");
+ assert.deepEqual(r.attachments.map((e) => e.id), ['e1'], 'check output sits on its line, not in attachments');
+ const html = ui.receipt(d, names);
+ assert.match(html, /data-verified-by/);
+ assert.match(html, /docs\/pricing\.md/);
+ assert.match(html, /npm test/);
+ assert.match(html, /1 failing/);
+ assert.match(html, /Checked by kwant/);
+ assert.match(html, /doesn’t count toward Verified/);
+ assert.doesNotMatch(html, /data-not-checked/);
+});
+
+test('a check a bot added waits for the person, with an Allow button', () => {
+ const html = ui.detail({
+ detail: { task: task({ state: 'review' }), checks: [check({ status: 'needs_approval', approved: false, finished_at: null, checked_by: null, kind: 'command', spec: { command: 'curl -sf https://x.example' } })], evidence: [], events: [] },
+ names, now: NOW, onAction: noop, onApproveCheck: noop,
+ });
+ assert.match(html, /Needs your OK/);
+ assert.match(html, /Allow this check/);
+});
+
+test('only web links open; file paths and other schemes are shown as text', () => {
+ assert.equal(m.safeHttps('https://a.example/x'), 'https://a.example/x');
+ assert.equal(m.safeHttps('javascript:alert(1)'), null);
+ assert.equal(m.safeHttps('file:///etc/passwd'), null);
+ assert.equal(m.safeHttps('/home/maus/out.png'), null);
+ const html = ui.receipt({ task: task({ state: 'review' }), checks: [], evidence: [evidence({ id: 'bad', label: 'Sneaky', uri: 'javascript:alert(1)' })], events: [] });
+ assert.match(html, /Sneaky/);
+ assert.doesNotMatch(html, /href="javascript/);
+});
+
+test('detail shows acceptance, owner, cost, tries, live run, source chat and the right actions', () => {
+ const t = task({ state: 'working', claim: { kwant_id: 'k_lin', claimed_at: '2026-10-27T11:50:00Z', expires_at: '2026-10-27T12:20:00Z' } });
+ const html = ui.detail({ detail: { task: t, checks: [], evidence: [], events: [] }, names, now: NOW, onAction: noop, onApproveCheck: noop, onOpenChat: noop });
+ assert.match(html, /What done looks like/);
+ assert.match(html, /mentions the yearly discount/);
+ assert.match(html, /12\.4k of 50k tokens/);
+ assert.match(html, /0 of 3/);
+ assert.match(html, /data-live/);
+ assert.match(html, /goes back to Ready in 20 min/);
+ assert.match(html, /Open the chat it came from/);
+ assert.match(html, />Block</);
+ assert.match(html, />Cancel task</);
+ assert.doesNotMatch(html, /Mark verified/);
+ const review = ui.detail({ detail: { task: task({ state: 'review' }), checks: [], evidence: [], events: [] }, names, now: NOW, onAction: noop, onApproveCheck: noop });
+ assert.match(review, /Mark verified/);
+ assert.match(review, /Send back/);
+ assert.match(review, /Run checks/);
+ assert.doesNotMatch(review, /Open the chat/, 'no chat link without a handler');
+ assert.deepEqual(m.actionsFor({ state: 'failed' }), ['retry', 'cancel']);
+ assert.deepEqual(m.actionsFor({ state: 'verified' }), []);
+ assert.ok(m.NEEDS_REASON.reject && m.NEEDS_REASON.block, 'send back and block ask why');
+});
+
+test('sourceChat points at the channel, thread or direct chat', () => {
+ assert.deepEqual(m.sourceChat(task()), { channelId: 'c1', kwantId: null, threadId: null });
+ assert.deepEqual(m.sourceChat(task({ channel_id: null, direct_kwant_id: 'k_lin', thread_id: 'th1' })), { channelId: null, kwantId: 'k_lin', threadId: 'th1' });
+ assert.equal(m.sourceChat(task({ channel_id: null })), null);
+});
+
+test('insights strip: verified this week, false successes, blocked', () => {
+ const html = ui.insights({ insights: insightsRow });
+ assert.match(html, /Verified this week/);
+ assert.match(html, /False successes/);
+ assert.match(html, /Blocked now/);
+ assert.match(html, /120k/);
+ assert.equal(ui.insights({ insights: null }), '');
+ assert.match(ui.insights({ insights: { ...insightsRow, tokens_per_verified_7d: null } }), /—/);
+});
+
+test('a draft mission waits for the person; over budget says what it means', () => {
+ const html = ui.mission({ mission: missionRow({ status: 'draft', approved_at: null }), busy: false, onApprove: noop, onCancel: noop });
+ assert.match(html, /Waiting for your OK/);
+ 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/);
+ // The board lists drafts on "All work".
+ assert.match(ui.view(viewProps({ missions: [missionRow({ status: 'draft' })] })), /Approve mission/);
+});
+
+test('board states: loading, empty, error, sign-in', () => {
+ assert.match(ui.view(viewProps({ tasks: null, loading: true })), /Loading the board/);
+ assert.match(ui.view(viewProps({ tasks: [], missions: [] })), /No tasks yet/);
+ const err = ui.view(viewProps({ error: 'Could not reach the server.' }));
+ assert.match(err, /role="alert"/);
+ assert.match(err, /Retry/);
+ assert.match(ui.view(viewProps({ needsToken: true })), /Confirm it’s you/);
+ assert.match(ui.view(viewProps({ onBack: noop })), /aria-label="Back to chats"/);
+});
+
+test('mission filter narrows the board to one mission', () => {
+ const html = ui.view(viewProps({ tasks: [task(), task({ id: 't2', mission_id: 'm2', title: 'Other mission task' })], missions: [missionRow(), missionRow({ id: 'm2', title: 'Other' })], missionId: 'm1' }));
+ assert.doesNotMatch(html, /Other mission task/);
+ assert.match(html, /data-mission="m1"/);
+});
+
+test('live events upsert tasks and missions; cancelled tasks drop off', () => {
+ const list = [task({ id: 'a' }), task({ id: 'b' })];
+ const moved = m.upsertTask(list, task({ id: 'b', state: 'working' }));
+ assert.equal(moved.length, 2);
+ assert.equal(moved.find((t) => t.id === 'b').state, 'working');
+ assert.deepEqual(m.upsertTask(list, task({ id: 'a', state: 'cancelled' })).map((t) => t.id), ['b']);
+ assert.equal(m.upsertTask(list, task({ id: 'n' })).length, 3);
+ const ms = m.upsertMission([missionRow()], missionRow({ status: 'done' }));
+ assert.equal(ms.length, 1);
+ assert.equal(ms[0].status, 'done');
+ let got = null;
+ const off = m.onMission('task_updated', (d) => (got = d.task.id));
+ m.emitMission({ type: 'task_updated', data: { task: task({ id: 'live' }) } });
+ off();
+ m.emitMission({ type: 'task_updated', data: { task: task({ id: 'after' }) } });
+ assert.equal(got, 'live');
+});
+
+test('the setting is read only when the server has it', () => {
+ assert.equal(m.parseMissionBoardSetting({ mission_board: true }), true);
+ assert.equal(m.parseMissionBoardSetting({ mission_board: false }), false);
+ assert.equal(m.parseMissionBoardSetting({ decide_first: true }), null);
+ assert.equal(m.parseMissionBoardSetting(null), null);
+});
+
+test('errors read plainly', () => {
+ assert.match(m.errorFrom(403, null).message, /Only you can change tasks/);
+ assert.match(m.errorFrom(404, null).message, /doesn’t have the Mission board/);
+ assert.equal(m.errorFrom(400, { error: 'reason is required' }).message, 'Reason is required.');
+});