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: Live now strip, group by team or bot, Review actions, Verified fades

Pixel (kwant bot)5ae51529f753
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 653e4464..7ed22b98 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -2874,6 +2874,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
const missionNames = Object.fromEntries(kwants.map((k) => [k.id, k.name]));
const missionAvatars = Object.fromEntries(kwants.map((k) => [k.id, k.avatar_sprite ?? '']));
+ const missionTurns = useMemo(() => Object.values(turns), [turns]);
+ const missionRooms = useMemo(() => Object.fromEntries(channels.map((c) => [c.id, c.name])), [channels]);
+ const missionThreadTitles = useMemo(
+ () => Object.fromEntries(Object.values(threadsByKwant).flatMap((list) => (list ?? []).map((t) => [t.id, t.title]))),
+ [threadsByKwant],
+ );
const missionsPage = (
<MissionBoardPage
key={space.id}
@@ -2887,6 +2893,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
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.');
}}
+ turns={missionTurns}
+ teams={teams}
+ rooms={missionRooms}
+ threadTitles={missionThreadTitles}
+ onOpenPlace={(c) => {
+ 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} />;
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index bda23b00..e2c8fc0f 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -22,7 +22,12 @@ import {
ShieldCheck,
StickyNote,
Target,
+ Undo2,
+ Users,
Wrench,
+ ChevronDown,
+ ChevronRight,
+ Trash2,
X,
XCircle,
} from 'lucide-react';
@@ -36,6 +41,30 @@ import { playSfx } from '../audio/chiptune';
import {
ACTION_DONE,
ACTION_LABELS,
+ BoardTeam,
+ BoardTurn,
+ DEFAULT_SEND_BACK,
+ GroupBy,
+ LiveBot,
+ QUICK_LABELS,
+ QuickAction,
+ UNDO_MS,
+ collapseRepeats,
+ elapsedText,
+ filterByTeams,
+ groupIntoLanes,
+ liveBots,
+ liveByTeam,
+ liveSummary,
+ oldAutoReviews,
+ quickActionsFor,
+ quickDoneText,
+ readGroupBy,
+ saveGroupBy,
+ splitVerified,
+ teamOfBots,
+ verifiedCountText,
+ NO_TEAM,
AutofixAttempt,
Checkpoint,
NeedsYouItem,
@@ -141,6 +170,12 @@ 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';
+// Card-sized buttons: compact on desktop, a full 40px tap target on the phone.
+const cardBtn =
+ 'inline-flex items-center justify-center gap-1 min-h-[40px] sm:min-h-[28px] px-2.5 rounded-lg text-[11px] font-medium disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const cardGoodBtn = 'bg-emerald-600/90 text-white hover:bg-emerald-500';
+const cardPlainBtn = 'border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700';
+const cardQuietBtn = 'text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800';
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';
@@ -325,6 +360,7 @@ const initials = (name: string) =>
/** Bot id → avatar sprite, so owner chips show the same creature as the sidebar and chat. */
const NO_AVATARS: Record<string, string> = {};
+const NO_TEAMS: BoardTeam[] = [];
export const AvatarsContext = React.createContext<Record<string, string>>(NO_AVATARS);
/** The owner's avatar: the bot's own creature, or their initials when the bot isn't known (removed, or no id). */
@@ -484,7 +520,13 @@ export const TaskCard: React.FC<{
busy?: boolean;
/** Unresolved Auditor risks on this task. */
openRisks?: number;
-}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen, onRemoveLimit, busy = false, openRisks = 0 }) => {
+ /** Older runs of the same routine folded under this card, newest first. */
+ older?: Task[];
+ /** Review's one-tap actions on the card (Mark verified, Send back, Dismiss; Try again when it failed). */
+ onQuick?: (t: Task, a: QuickAction, note?: string) => void;
+ /** Dismiss the folded older runs together. */
+ onDismissMany?: (ts: Task[]) => void;
+}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen, onRemoveLimit, busy = false, openRisks = 0, older = [], onQuick, onDismissMany }) => {
const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
const checks = checksText(t.checks_summary);
const optionalNote = optionalChecksNote(t.checks_summary);
@@ -492,8 +534,12 @@ export const TaskCard: React.FC<{
const flags = openFlags(t);
const dimmed = t.state === 'backlog' && !flags.length && !t.held_at;
const autofixLive = !!autofixCardText(t, now);
+ const quick = onQuick && columnOfTask(t) === 'review' ? quickActionsFor(t) : [];
+ const [sending, setSending] = useState(false);
+ const [note, setNote] = useState('');
+ const noteId = useId();
return (
- <li data-task={t.id} data-state={t.state}>
+ <li data-task={t.id} data-state={t.state} data-repeats={older.length ? older.length + 1 : undefined}>
<button
type="button"
onClick={() => onOpen(t)}
@@ -533,7 +579,18 @@ export const TaskCard: React.FC<{
)}
{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>
+ <span className="flex items-start gap-2 text-sm font-medium text-zinc-100 break-words">
+ <span className="min-w-0 flex-1">{t.title}</span>
+ {older.length > 0 && (
+ <span
+ className="shrink-0 mt-0.5 px-1.5 rounded-md bg-zinc-800 border border-zinc-700 text-[11px] font-semibold tabular-nums text-zinc-300"
+ title={`${older.length + 1} runs; the newest is shown`}
+ data-repeat-count
+ >
+ ×{older.length + 1}
+ </span>
+ )}
+ </span>
{status && (
<span className={`block text-[11px] break-words line-clamp-2 ${t.state === 'needs_you' || t.held_at || (t.state === 'review' && approvalHolds(t.checks_summary)) ? 'text-amber-200' : autofixLive ? 'text-violet-200' : t.state === 'blocked' || t.state === 'failed' ? 'text-rose-300' : 'text-zinc-400'}`}>
{status}
@@ -577,6 +634,65 @@ export const TaskCard: React.FC<{
Remove limit and continue
</button>
)}
+ {quick.length > 0 && !sending && (
+ <div className="mt-1.5 flex flex-wrap gap-1.5" data-card-actions>
+ {quick.map((a) => (
+ <button
+ key={a}
+ type="button"
+ disabled={busy}
+ onClick={() => (a === 'reject' ? setSending(true) : onQuick!(t, a))}
+ className={`${cardBtn} ${a === 'verify' || a === 'retry' ? cardGoodBtn : a === 'cancel' ? cardQuietBtn : cardPlainBtn}`}
+ data-card-action={a}
+ >
+ {a === 'verify' ? <CheckCircle2 size={12} aria-hidden="true" /> : a === 'reject' ? <Undo2 size={12} aria-hidden="true" /> : a === 'retry' ? <RotateCcw size={12} aria-hidden="true" /> : <X size={12} aria-hidden="true" />}
+ {QUICK_LABELS[a]}
+ </button>
+ ))}
+ {older.length > 0 && onDismissMany && (
+ <button type="button" disabled={busy} onClick={() => onDismissMany(older)} className={`${cardBtn} ${cardQuietBtn}`} data-card-dismiss-older>
+ Dismiss {older.length} older
+ </button>
+ )}
+ </div>
+ )}
+ {sending && (
+ <form
+ className="mt-1.5 space-y-1.5 rounded-xl border border-zinc-800 bg-zinc-900/60 p-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ onQuick!(t, 'reject', note);
+ setSending(false);
+ setNote('');
+ }}
+ data-card-send-back
+ >
+ <label htmlFor={noteId} className="block text-[11px] text-zinc-400">
+ What still needs doing? <span className="text-zinc-500">(optional)</span>
+ </label>
+ <textarea
+ id={noteId}
+ autoFocus
+ rows={2}
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') setSending(false);
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) e.currentTarget.form?.requestSubmit();
+ }}
+ className={`${field} w-full resize-none text-xs`}
+ placeholder="e.g. The links in section 2 are broken"
+ />
+ <div className="flex gap-1.5">
+ <button type="submit" disabled={busy} className={`${cardBtn} ${cardGoodBtn}`}>
+ Send back
+ </button>
+ <button type="button" onClick={() => setSending(false)} className={`${cardBtn} ${cardQuietBtn}`}>
+ Cancel
+ </button>
+ </div>
+ </form>
+ )}
</li>
);
};
@@ -595,8 +711,16 @@ export const Board: React.FC<{
busy?: boolean;
/** Task id → unresolved Auditor risks. */
openRisks?: Record<string, number>;
-}> = ({ tasks, names, column, now, showMission, onColumn, onOpen, onRemoveLimit, busy, openRisks = {} }) => {
+ /** Rows by team or bot across the five columns; 'none' is the plain board. */
+ groupBy?: GroupBy;
+ teams?: BoardTeam[];
+ onQuick?: (t: Task, a: QuickAction, note?: string) => void;
+ onDismissMany?: (ts: Task[]) => void;
+}> = ({ tasks, names, column, now = Date.now(), showMission, onColumn, onOpen, onRemoveLimit, busy, openRisks = {}, groupBy = 'none', teams = [], onQuick, onDismissMany }) => {
const grouped = useMemo(() => groupByColumn(tasks), [tasks]);
+ const lanes = useMemo(() => (groupBy === 'none' ? null : groupIntoLanes(tasks, groupBy, teams, names)), [tasks, groupBy, teams, names]);
+ const [showOlder, setShowOlder] = useState(false);
+ const [folded, setFolded] = useState<Record<string, boolean>>({});
const tabsId = useId();
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
const onTabKey = (e: React.KeyboardEvent, i: number) => {
@@ -607,21 +731,109 @@ export const Board: React.FC<{
onColumn(COLUMNS[next].key);
tabRefs.current[next]?.focus();
};
- const list = (key: Column) => {
+ const verifiedAll = grouped.verified.length;
+ const verifiedRecent = useMemo(() => splitVerified(grouped.verified, now).recent.length, [grouped.verified, now]);
+ const countText = (key: Column) => (key === 'verified' && !showOlder ? verifiedCountText(verifiedRecent, verifiedAll) : String(grouped[key].length));
+
+ /** One column's cards: Review folds repeated runs; Verified hides what's older than a day. */
+ const list = (key: Column, items: Task[], compactEmpty = false) => {
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} onRemoveLimit={onRemoveLimit} busy={busy} openRisks={openRisks[t.id] ?? 0} />
- ))}
- </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>
+ let shown = items;
+ let hidden = 0;
+ let olderCount = 0;
+ if (key === 'verified') {
+ const split = splitVerified(items, now);
+ olderCount = split.older.length;
+ if (!showOlder) {
+ shown = split.recent;
+ hidden = olderCount;
+ }
+ }
+ const cards = key === 'review' ? collapseRepeats(shown) : shown.map((t) => ({ task: t, older: [] as Task[] }));
+ const more =
+ olderCount > 0 ? (
+ <button type="button" onClick={() => setShowOlder((v) => !v)} className={`${subtleBtn} ml-0 w-full justify-center`} data-show-older={hidden}>
+ {showOlder ? 'Show the last 24 hours only' : `Show older (${hidden})`}
+ </button>
+ ) : null;
+ if (!cards.length) {
+ if (compactEmpty) return more ?? <p className="px-2 py-3 text-center text-[11px] text-zinc-600" data-empty-column={key}>—</p>;
+ return (
+ <div className="space-y-2">
+ <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}>
+ {key === 'verified' && hidden > 0 ? 'Nothing verified in the last 24 hours.' : meta.empty}
+ </p>
+ {more}
+ </div>
+ );
+ }
+ return (
+ <div className="space-y-2">
+ <ul className="space-y-2">
+ {cards.map(({ task: t, older }) => (
+ <TaskCard
+ key={t.id}
+ task={t}
+ names={names}
+ now={now}
+ showMission={showMission}
+ onOpen={onOpen}
+ onRemoveLimit={onRemoveLimit}
+ busy={busy}
+ openRisks={openRisks[t.id] ?? 0}
+ older={older}
+ onQuick={onQuick}
+ onDismissMany={onDismissMany}
+ />
+ ))}
+ </ul>
+ {more}
+ </div>
+ );
+ };
+
+ const countPill = (key: Column, n: number | string, dark = false) => (
+ <span
+ className={`min-w-[18px] px-1 rounded-full text-[10px] text-center tabular-nums ${
+ key === 'needs_you' && Number(n) > 0 ? 'bg-amber-500 text-zinc-950' : dark ? 'bg-zinc-700/70 text-zinc-200' : 'bg-zinc-800 text-zinc-300'
+ }`}
+ >
+ {n}
+ </span>
+ );
+
+ const laneHeader = (l: NonNullable<typeof lanes>[number], key: Column | null) => {
+ const open = !folded[l.key];
+ return (
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setFolded((f) => ({ ...f, [l.key]: open }))}
+ className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-lg text-left hover:bg-zinc-900/70 ${focusRing}`}
+ data-lane-header={l.key}
+ >
+ {open ? <ChevronDown size={14} className="text-zinc-500" aria-hidden="true" /> : <ChevronRight size={14} className="text-zinc-500" aria-hidden="true" />}
+ {groupBy === 'bot' && l.key !== '__no_owner__' ? <OwnerAvatar kwantId={l.key} name={l.label} size={18} /> : <Users size={14} className="text-zinc-400" aria-hidden="true" />}
+ <span className="min-w-0 truncate text-xs font-semibold text-zinc-100">{l.label}</span>
+ <span className="text-[11px] tabular-nums text-zinc-500">{key ? l.columns[key].length : l.total}</span>
+ {l.needsYou > 0 && (
+ <span className="ml-1" data-lane-needs-you={l.needsYou}>
+ <Badge tone="amber">{l.needsYou} needs you</Badge>
+ </span>
+ )}
+ {!open && key === null && (
+ <span className="ml-auto hidden lg:flex items-center gap-3 text-[11px] text-zinc-500 tabular-nums">
+ {COLUMNS.map((c) => (
+ <span key={c.key}>
+ {c.label} {l.columns[c.key].length}
+ </span>
+ ))}
+ </span>
+ )}
+ </button>
);
};
+
return (
<>
{/* Phone and tablet: one column at a time, picked from tabs with counts */}
@@ -629,7 +841,6 @@ export const Board: React.FC<{
<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}
@@ -647,39 +858,236 @@ export const Board: React.FC<{
}`}
>
{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>
+ {countPill(c.key, c.key === 'verified' ? (showOlder ? verifiedAll : verifiedRecent) : grouped[c.key].length, true)}
</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)}
+ {lanes ? (
+ <div className="space-y-3" data-lanes={groupBy}>
+ {lanes.filter((l) => l.columns[column].length > 0).map((l) => (
+ <section key={l.key} className="space-y-1.5" data-lane={l.key}>
+ {laneHeader(l, column)}
+ {!folded[l.key] && list(column, l.columns[column])}
+ </section>
+ ))}
+ {lanes.every((l) => l.columns[column].length === 0) && list(column, [])}
+ </div>
+ ) : (
+ list(column, grouped[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">
+ {/* Desktop: all five columns side by side, as one board or as a row per team or bot */}
+ {lanes ? (
+ <div className="hidden lg:block space-y-2" data-board="lanes" data-lanes={groupBy}>
+ <div className="grid grid-cols-5 gap-3 sticky top-0 z-10 -mx-1 px-1 py-1.5 bg-zinc-950/95 backdrop-blur-sm border-b border-zinc-800/80">
+ {COLUMNS.map((c) => (
+ <h3 key={c.key} className="flex items-center gap-2 px-1 text-xs font-semibold text-zinc-200" data-column={c.key} title={c.hint}>
{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>
+ {countPill(c.key, countText(c.key))}
</h3>
- <p className="text-[11px] text-zinc-500 truncate" title={c.hint}>
- {c.hint}
- </p>
- </header>
- {list(c.key)}
- </section>
- ))}
- </div>
+ ))}
+ </div>
+ {lanes.map((l) => (
+ <section key={l.key} className="rounded-2xl border border-zinc-800/80 bg-zinc-900/20 p-2 space-y-2" data-lane={l.key}>
+ {laneHeader(l, null)}
+ {!folded[l.key] && (
+ <div className="grid grid-cols-5 gap-3 items-start">
+ {COLUMNS.map((c) => (
+ <div key={c.key} className="min-w-0" data-lane-column={c.key}>
+ {list(c.key, l.columns[c.key], true)}
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+ ))}
+ </div>
+ ) : (
+ <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}
+ {countPill(c.key, countText(c.key))}
+ </h3>
+ <p className="text-[11px] text-zinc-500 truncate" title={c.hint}>
+ {c.hint}
+ </p>
+ </header>
+ {list(c.key, grouped[c.key])}
+ </section>
+ ))}
+ </div>
+ )}
</>
);
};
+// ---------- Live now ----------
+
+/** Every bot running something right now, by team: chats, rooms and routines too, not only tasks. */
+export const LiveStrip: React.FC<{
+ bots: LiveBot[];
+ teams: BoardTeam[];
+ workingCards: number;
+ now?: number;
+ onOpen?: (b: LiveBot) => void;
+}> = ({ bots, teams, workingCards, now = Date.now(), onOpen }) => {
+ const groups = liveByTeam(bots, teams);
+ const idle = bots.length === 0;
+ return (
+ <section aria-label="Live now" className={`${card} px-3 py-2.5`} data-live={bots.length}>
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-zinc-100">
+ <span className="relative flex h-2 w-2" aria-hidden="true">
+ {!idle && <span className="absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-60 animate-ping motion-reduce:animate-none" />}
+ <span className={`relative inline-flex h-2 w-2 rounded-full ${idle ? 'bg-zinc-600' : 'bg-emerald-400'}`} />
+ </span>
+ Live now
+ </span>
+ <span className="text-[11px] text-zinc-400" data-live-summary>
+ {liveSummary(bots, workingCards)}
+ </span>
+ </div>
+ {!idle && (
+ <div className="mt-2 flex gap-4 overflow-x-auto -mx-3 px-3 scroll-px-3 pb-1 snap-x lg:snap-none [scrollbar-width:thin] lg:flex-wrap lg:overflow-visible">
+ {groups.map((g) => (
+ <div key={g.teamId} className="shrink-0 snap-start min-w-0" data-live-team={g.teamId}>
+ <p className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-zinc-500">{g.teamName}</p>
+ <ul className="flex gap-1.5">
+ {g.bots.map((b) => (
+ <li key={b.kwantId}>
+ <button
+ type="button"
+ onClick={onOpen ? () => onOpen(b) : undefined}
+ disabled={!onOpen}
+ title={`${b.name}: ${b.what}${b.more ? ` (+${b.more} more)` : ''}. Open the conversation.`}
+ className={`group flex items-center gap-2 w-[220px] sm:w-[240px] min-h-[44px] px-2 py-1.5 rounded-xl border text-left ${
+ b.kind === 'task' ? 'border-sky-500/30 bg-sky-500/5 hover:bg-sky-500/10' : 'border-emerald-500/25 bg-emerald-500/5 hover:bg-emerald-500/10'
+ } ${focusRing}`}
+ data-live-bot={b.kwantId}
+ data-live-kind={b.kind}
+ >
+ <span className="relative shrink-0">
+ <OwnerAvatar kwantId={b.kwantId} name={b.name} size={26} />
+ <span className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-zinc-950 bg-emerald-400" aria-hidden="true" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex items-baseline gap-1.5">
+ <span className="truncate text-xs font-medium text-zinc-100">{b.name}</span>
+ <span className="ml-auto shrink-0 text-[10px] tabular-nums text-zinc-400" data-live-elapsed>
+ {elapsedText(b.since, now)}
+ </span>
+ </span>
+ <span className="block truncate text-[11px] text-zinc-400">
+ {b.kind === 'task' && <span className="text-sky-300">Task · </span>}
+ {b.what}
+ {b.more > 0 && <span className="text-zinc-500"> · +{b.more}</span>}
+ </span>
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+ );
+};
+
+/** Board controls: Group by, team chips, and clearing old automatic reviews. */
+export const BoardToolbar: React.FC<{
+ groupBy: GroupBy;
+ onGroupBy: (g: GroupBy) => void;
+ teamChips: Array<{ id: string; name: string; count: number }>;
+ picked: string[];
+ onPick: (ids: string[]) => void;
+ oldReviews: number;
+ onClearOld?: () => void;
+}> = ({ groupBy, onGroupBy, teamChips, picked, onPick, oldReviews, onClearOld }) => (
+ <div className="space-y-2" data-board-toolbar>
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-[11px] font-medium text-zinc-400" id="board-group-label">
+ Group
+ </span>
+ <div role="group" aria-labelledby="board-group-label" className="inline-flex rounded-lg border border-zinc-800 p-0.5" data-group-by={groupBy}>
+ {(['none', 'team', 'bot'] as const).map((g) => (
+ <button
+ key={g}
+ type="button"
+ aria-pressed={groupBy === g}
+ onClick={() => onGroupBy(g)}
+ className={`min-h-[40px] sm:min-h-[30px] px-3 rounded-md text-xs font-medium ${focusRing} ${groupBy === g ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200'}`}
+ >
+ {g === 'none' ? 'None' : g === 'team' ? 'Team' : 'Bot'}
+ </button>
+ ))}
+ </div>
+ {oldReviews > 0 && onClearOld && (
+ <button
+ type="button"
+ onClick={onClearOld}
+ className={`ml-auto inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[30px] px-3 rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 ${focusRing}`}
+ data-clear-old={oldReviews}
+ >
+ <Trash2 size={12} aria-hidden="true" />
+ Clear old reviews ({oldReviews})
+ </button>
+ )}
+ </div>
+ {teamChips.length > 1 && (
+ <div role="group" aria-label="Show teams" className="flex gap-1.5 overflow-x-auto -mx-1 px-1 pb-1 [scrollbar-width:none]" data-team-chips>
+ <button
+ type="button"
+ aria-pressed={picked.length === 0}
+ onClick={() => onPick([])}
+ className={`shrink-0 min-h-[36px] sm:min-h-[28px] px-3 rounded-full text-xs border ${focusRing} ${picked.length === 0 ? 'bg-sky-500/15 border-sky-500/40 text-sky-100' : 'border-zinc-800 text-zinc-400 hover:text-zinc-200'}`}
+ >
+ All teams
+ </button>
+ {teamChips.map((c) => {
+ const on = picked.includes(c.id);
+ return (
+ <button
+ key={c.id}
+ type="button"
+ aria-pressed={on}
+ onClick={() => onPick(on ? picked.filter((p) => p !== c.id) : [...picked, c.id])}
+ className={`shrink-0 inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[28px] px-3 rounded-full text-xs border ${focusRing} ${on ? 'bg-sky-500/15 border-sky-500/40 text-sky-100' : 'border-zinc-800 text-zinc-400 hover:text-zinc-200'}`}
+ data-team-chip={c.id}
+ >
+ {c.name}
+ <span className="tabular-nums text-[10px] text-zinc-500">{c.count}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+);
+
+/** One pending card action: it waits UNDO_MS before reaching the server, so Undo can take it back. */
+export const UndoToast: React.FC<{ text: string; onUndo: () => void; onClose: () => void }> = ({ text, onUndo, onClose }) => (
+ <div className="fixed inset-x-0 bottom-4 z-40 flex justify-center px-4 pointer-events-none" data-undo-toast>
+ <div role="status" aria-live="polite" className="pointer-events-auto flex items-center gap-3 max-w-md w-full sm:w-auto px-4 py-2.5 rounded-xl border border-zinc-700 bg-zinc-900 shadow-2xl shadow-black/50">
+ <span className="min-w-0 flex-1 text-xs text-zinc-100 break-words">{text}</span>
+ <button type="button" onClick={onUndo} className={`shrink-0 min-h-[36px] px-3 rounded-lg text-xs font-semibold text-sky-300 hover:bg-sky-500/10 ${focusRing}`} data-undo>
+ Undo
+ </button>
+ <button type="button" onClick={onClose} aria-label="Close" className={`shrink-0 p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 ${focusRing}`}>
+ <X size={14} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+);
+
// ---------- Evidence receipt ----------
const statusIcon = (tone: Tone) =>
@@ -2064,6 +2472,22 @@ export interface MissionBoardViewProps {
refreshCount?: number;
/** Task id → unresolved Auditor risks, for the card badges. */
openRisks?: Record<string, number>;
+ /** Bots running anything right now; leave out to hide the Live strip. */
+ live?: LiveBot[] | null;
+ onOpenLive?: (b: LiveBot) => void;
+ teams?: BoardTeam[];
+ groupBy?: GroupBy;
+ onGroupBy?: (g: GroupBy) => void;
+ /** Picked team ids (none = all); `NO_TEAM` is cards without a team. */
+ teamFilter?: string[];
+ onTeamFilter?: (ids: string[]) => void;
+ onQuick?: (t: Task, a: QuickAction, note?: string) => void;
+ onDismissMany?: (ts: Task[]) => void;
+ /** Dismiss automatic cards that sat in Review over a week; the view asks first. */
+ onClearOld?: (ts: Task[]) => void;
+ undo?: { text: string } | null;
+ onUndo?: () => void;
+ onCloseUndo?: () => void;
}
export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
@@ -2100,14 +2524,46 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
showPerformance = false,
refreshCount = 0,
openRisks,
+ live = null,
+ onOpenLive,
+ teams = [],
+ groupBy = 'none',
+ onGroupBy,
+ teamFilter = [],
+ onTeamFilter,
+ onQuick,
+ onDismissMany,
+ onClearOld,
+ undo = null,
+ onUndo,
+ onCloseUndo,
}) => {
const selectId = useId();
+ const [confirmClear, setConfirmClear] = useState(false);
const visibleMissions = missions.filter((m) => m.status !== 'cancelled');
const mission = missionId ? missions.find((m) => m.id === missionId) ?? null : null;
const showGraph = !!mission && !!onView && view === 'graph';
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;
+ const inMission = (tasks ?? []).filter((t) => t.state !== 'cancelled' && (!missionId || t.mission_id === missionId));
+ const shown = filterByTeams(inMission, teamFilter, teams);
+ const empty = tasks !== null && inMission.length === 0 && !mission && drafts.length === 0;
+ const teamOf = teamOfBots(teams);
+ const liveShown = live ? (teamFilter.length ? live.filter((b) => teamFilter.includes(b.teamId)) : live) : null;
+ // Chips for the teams on the board or busy now, in the person's order; "No team" when some cards have none.
+ const teamChips = (() => {
+ const counts = new Map<string, number>();
+ for (const t of inMission) {
+ const bot = t.owner_kwant_id ?? t.claim?.kwant_id ?? null;
+ const id = (bot && teamOf[bot]?.id) || NO_TEAM;
+ counts.set(id, (counts.get(id) ?? 0) + 1);
+ }
+ for (const b of live ?? []) if (!counts.has(b.teamId)) counts.set(b.teamId, 0);
+ const chips = teams.filter((t) => counts.has(t.id)).map((t) => ({ id: t.id, name: t.name, count: counts.get(t.id) ?? 0 }));
+ if (counts.has(NO_TEAM)) chips.push({ id: NO_TEAM, name: 'No team', count: counts.get(NO_TEAM) ?? 0 });
+ return chips;
+ })();
+ const oldReviews = oldAutoReviews(shown, now);
+ const workingCards = shown.filter((t) => columnOfTask(t) === 'working').length;
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`}>
@@ -2166,6 +2622,8 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
{tasks !== null && (
<>
+ {liveShown && <LiveStrip bots={liveShown} teams={teams} workingCards={workingCards} now={now} onOpen={onOpenLive} />}
+
<InsightsStrip insights={insights} needsYou={needsYouCount(tasks)} />
{visibleMissions.length > 0 && (
@@ -2225,6 +2683,40 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
/>
))}
+ {!showGraph && !empty && onGroupBy && (
+ <BoardToolbar
+ groupBy={groupBy}
+ onGroupBy={onGroupBy}
+ teamChips={teamChips}
+ picked={teamFilter}
+ onPick={onTeamFilter ?? (() => {})}
+ oldReviews={oldReviews.length}
+ onClearOld={onClearOld ? () => setConfirmClear(true) : undefined}
+ />
+ )}
+ {confirmClear && onClearOld && (
+ <div role="alertdialog" aria-labelledby="clear-old-title" className="px-3 py-2.5 rounded-xl border border-amber-500/30 bg-amber-500/5 flex flex-wrap items-center gap-2" data-clear-confirm={oldReviews.length}>
+ <p id="clear-old-title" className="flex-1 min-w-[200px] text-xs text-amber-100">
+ {oldReviews.length === 1 ? 'Dismiss 1 automatic card' : `Dismiss ${oldReviews.length} automatic cards`} (routine runs, worked-ahead and loose ends) that have been in Review for more than 7 days? They leave the board; your other cards stay.
+ </p>
+ <button
+ type="button"
+ autoFocus
+ disabled={oldReviews.length === 0}
+ onClick={() => {
+ setConfirmClear(false);
+ onClearOld(oldReviews);
+ }}
+ className={`${cardBtn} ${cardGoodBtn}`}
+ >
+ Dismiss {oldReviews.length}
+ </button>
+ <button type="button" onClick={() => setConfirmClear(false)} className={`${cardBtn} ${cardQuietBtn}`}>
+ Keep them
+ </button>
+ </div>
+ )}
+
{showGraph ? (
<WorkGraphView
graph={graph}
@@ -2260,14 +2752,27 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
onRemoveLimit={onRemoveLimit}
busy={busyCard}
openRisks={openRisks}
+ groupBy={groupBy}
+ teams={teams}
+ onQuick={onQuick}
+ onDismissMany={onDismissMany}
/>
)}
+ {!showGraph && !empty && shown.length === 0 && teamFilter.length > 0 && (
+ <p className="text-xs text-zinc-500" data-filter-empty>
+ No cards for the picked teams.{' '}
+ <button type="button" onClick={() => onTeamFilter?.([])} className="underline underline-offset-2 hover:text-zinc-300">
+ Show all teams
+ </button>
+ </p>
+ )}
{showPerformance && !mission && !needsToken && <PerformancePanel names={names} refreshKey={refreshCount} />}
</>
)}
</div>
</div>
+ {undo && onUndo && <UndoToast text={undo.text} onUndo={onUndo} onClose={onCloseUndo ?? (() => {})} />}
</div>
);
};
@@ -2280,7 +2785,15 @@ export const MissionBoardPage: React.FC<{
avatars?: Record<string, string>;
onBack?: () => void;
onOpenChat?: (t: Task, place?: ChatPlace | null) => void;
-}> = ({ spaceId, names, avatars, onBack, onOpenChat }) => {
+ /** The space's running and queued turns, for the Live strip. */
+ turns?: BoardTurn[];
+ teams?: BoardTeam[];
+ /** Room id → name, and thread id → title, so the Live strip can say where each bot is. */
+ rooms?: Record<string, string>;
+ threadTitles?: Record<string, string>;
+ /** Opens a Live bot's conversation. */
+ onOpenPlace?: (place: ChatPlace) => void;
+}> = ({ spaceId, names, avatars, onBack, onOpenChat, turns, teams = NO_TEAMS, rooms, threadTitles, onOpenPlace }) => {
const [tasks, setTasks] = useState<Task[] | null>(null);
const [missions, setMissions] = useState<Mission[]>([]);
const [insights, setInsights] = useState<Insights | null>(null);
@@ -2810,13 +3323,100 @@ export const MissionBoardPage: React.FC<{
}
};
+ // Card actions from the board wait UNDO_MS before they reach the server: Undo just drops them.
+ const [groupBy, setGroupBy] = useState<GroupBy>(readGroupBy);
+ const [teamFilter, setTeamFilter] = useState<string[]>([]);
+ const [undo, setUndo] = useState<{ id: number; text: string } | null>(null);
+ const pending = useRef<{ id: number; tasks: Task[]; run: () => Promise<void>; timer: number } | null>(null);
+ const [hidden, setHidden] = useState<Set<string>>(() => new Set());
+ const pendingSeq = useRef(0);
+
+ const commitPending = useCallback(() => {
+ const p = pending.current;
+ if (!p) return;
+ pending.current = null;
+ window.clearTimeout(p.timer);
+ if (alive.current) setUndo((u) => (u?.id === p.id ? null : u));
+ p.run().finally(() => {
+ if (!alive.current) return;
+ setHidden((h) => {
+ const next = new Set(h);
+ p.tasks.forEach((t) => next.delete(t.id));
+ return next;
+ });
+ });
+ }, []);
+
+ // Leaving the board sends what's still waiting: the person saw it done.
+ useEffect(() => () => commitPending(), [commitPending]);
+
+ const runCardActions = useCallback(async (list: Task[], a: QuickAction, note?: string) => {
+ let failed = 0;
+ let lastError = '';
+ for (const t of list) {
+ try {
+ const next = await missionsApi.act(t.id, a, a === 'reject' ? note?.trim() || DEFAULT_SEND_BACK : undefined);
+ if (alive.current) setTasks((l) => (l ? (next.state === 'cancelled' ? l.filter((x) => x.id !== next.id) : upsertTask(l, next)) : l));
+ } catch (e) {
+ failed++;
+ lastError = failMsg(e);
+ if (e instanceof MissionError && e.status === 401 && alive.current) setNeedsToken(true);
+ }
+ }
+ if (!alive.current) return;
+ if (failed) setNotice({ text: list.length === 1 ? `Couldn’t do that: ${lastError}` : `${failed} of ${list.length} didn’t go through: ${lastError}`, error: true });
+ else if (a === 'verify') playSfx('coin');
+ missionsApi.insights().then((i) => alive.current && setInsights(i), () => {});
+ }, []);
+
+ const queueCardAction = (list: Task[], a: QuickAction, note?: string) => {
+ if (!list.length) return;
+ commitPending();
+ const id = ++pendingSeq.current;
+ setHidden((h) => {
+ const next = new Set(h);
+ list.forEach((t) => next.add(t.id));
+ return next;
+ });
+ const timer = window.setTimeout(() => commitPending(), UNDO_MS);
+ pending.current = { id, tasks: list, run: () => runCardActions(list, a, note), timer };
+ setUndo({ id, text: quickDoneText(a, list.length, list[0]?.title) });
+ setNotice(null);
+ playSfx('click');
+ };
+
+ const undoPending = () => {
+ const p = pending.current;
+ if (!p) return setUndo(null);
+ pending.current = null;
+ window.clearTimeout(p.timer);
+ setUndo(null);
+ setHidden((h) => {
+ const next = new Set(h);
+ p.tasks.forEach((t) => next.delete(t.id));
+ return next;
+ });
+ };
+
+ // The Live strip's elapsed times tick on their own.
+ const [tick, setTick] = useState(() => Date.now());
+ useEffect(() => {
+ const timer = window.setInterval(() => setTick(Date.now()), 15_000);
+ return () => window.clearInterval(timer);
+ }, []);
+ const live = useMemo(
+ () => (turns ? liveBots(turns, { names, teams, rooms, threadTitles, tasks: tasks ?? [] }) : null),
+ [turns, names, teams, rooms, threadTitles, tasks],
+ );
+ const boardTasks = useMemo(() => (tasks && hidden.size ? tasks.filter((t) => !hidden.has(t.id)) : tasks), [tasks, hidden]);
+
const tasksById = useMemo(() => Object.fromEntries((tasks ?? []).map((t) => [t.id, t])), [tasks]);
const listed = openId ? tasksById[openId] : undefined;
return (
<AvatarsContext.Provider value={avatars ?? NO_AVATARS}>
<MissionBoardView
- tasks={tasks}
+ tasks={boardTasks}
missions={missions}
insights={insights}
names={names}
@@ -2852,6 +3452,23 @@ export const MissionBoardPage: React.FC<{
showPerformance
refreshCount={refreshCount}
openRisks={riskCounts}
+ now={tick}
+ live={live}
+ onOpenLive={onOpenPlace ? (b) => onOpenPlace(b.place) : undefined}
+ teams={teams}
+ groupBy={groupBy}
+ onGroupBy={(g) => {
+ setGroupBy(g);
+ saveGroupBy(g);
+ }}
+ teamFilter={teamFilter}
+ onTeamFilter={setTeamFilter}
+ onQuick={(t, a, note) => queueCardAction([t], a, note)}
+ onDismissMany={(ts) => queueCardAction(ts, 'cancel')}
+ onClearOld={(ts) => queueCardAction(ts, 'cancel')}
+ undo={undo}
+ onUndo={undoPending}
+ onCloseUndo={commitPending}
/>
{openId && (
<TaskPanel title={detail?.task.title ?? listed?.title ?? 'Task'} onClose={closeTask}>
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 36d3ee8a..ca961dfd 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -1642,3 +1642,329 @@ export function sourceChat(t: Pick<Task, 'channel_id' | 'direct_kwant_id' | 'thr
if (t.direct_kwant_id) return { channelId: null, kwantId: t.direct_kwant_id, threadId: t.thread_id };
return null;
}
+
+// ---------------------------------------------------------------------------
+// Live board: who is busy right now, lanes by team or bot, repeated runs folded, Verified fading out
+
+/** A running or queued turn, as GET /api/turns lists it. */
+export interface BoardTurn {
+ turn_id: string;
+ kwant_id: string;
+ context_id: string;
+ thread_id: string | null;
+ state: 'queued' | 'running';
+ since?: string;
+ purpose?: string;
+}
+
+export interface BoardTeam {
+ id: string;
+ name: string;
+ lead_kwant_id: string;
+ member_kwants: string[];
+}
+
+export type GroupBy = 'none' | 'team' | 'bot';
+export const GROUP_BY_KEY = 'kwnt.missionBoard.groupBy';
+export const NO_TEAM = '__no_team__';
+export const NO_OWNER = '__no_owner__';
+
+export function readGroupBy(): GroupBy {
+ try {
+ const v = localStorage.getItem(GROUP_BY_KEY);
+ return v === 'team' || v === 'bot' ? v : 'none';
+ } catch {
+ return 'none';
+ }
+}
+
+export function saveGroupBy(g: GroupBy): void {
+ try {
+ localStorage.setItem(GROUP_BY_KEY, g);
+ } catch {
+ // Private mode: the choice lasts until the page closes.
+ }
+}
+
+/** Bot id → its team. A bot in several teams goes to the first one it leads, else the first it's in. */
+export function teamOfBots(teams: BoardTeam[]): Record<string, BoardTeam> {
+ const out: Record<string, BoardTeam> = {};
+ for (const t of teams) if (t.lead_kwant_id) out[t.lead_kwant_id] ??= t;
+ for (const t of teams) for (const k of t.member_kwants ?? []) out[k] ??= t;
+ return out;
+}
+
+/** The bot a card belongs to: its owner, else the bot holding it. */
+export const taskBot = (t: Pick<Task, 'owner_kwant_id' | 'claim'>): string | null => t.owner_kwant_id ?? t.claim?.kwant_id ?? null;
+
+/** Sources the person didn't ask for one by one: they pile up, so they fold and can be cleared in bulk. */
+const AUTO_SOURCES = new Set<SourceKind>(['routine', 'work_ahead', 'zombie']);
+export const isAutoTask = (t: Pick<Task, 'source_kind'>): boolean => AUTO_SOURCES.has(t.source_kind);
+
+/** One card on the board: the newest task, and older repeats of the same routine folded under it. */
+export interface BoardItem {
+ task: Task;
+ older: Task[];
+}
+
+/**
+ * What makes two cards "the same run again": the same automatic source, bot and title. A routine
+ * card's source is its run, not the routine, so its title ("Routine: Morning overview") stands in.
+ */
+export function repeatKey(t: Task): string | null {
+ if (!isAutoTask(t)) return null;
+ return `${t.source_kind}:${taskBot(t) ?? ''}:${t.title.trim().toLowerCase()}`;
+}
+
+/**
+ * Folds repeated automatic runs into one card, newest first, keeping the input's order otherwise.
+ * Only cards in the same column fold together, so callers pass one column's tasks.
+ */
+export function collapseRepeats(tasks: Task[]): BoardItem[] {
+ const out: BoardItem[] = [];
+ const at = new Map<string, number>();
+ const newest = (t: Task) => Date.parse(t.finished_at ?? t.updated_at) || 0;
+ for (const t of tasks) {
+ const k = repeatKey(t);
+ const i = k === null ? undefined : at.get(k);
+ if (i === undefined) {
+ if (k !== null) at.set(k, out.length);
+ out.push({ task: t, older: [] });
+ continue;
+ }
+ const item = out[i];
+ if (newest(t) > newest(item.task)) out[i] = { task: t, older: [item.task, ...item.older] };
+ else item.older.push(t);
+ }
+ for (const item of out) item.older.sort((a, b) => newest(b) - newest(a));
+ return out;
+}
+
+export const VERIFIED_WINDOW_HOURS = 24;
+export const OLD_REVIEW_DAYS = 7;
+
+/** Verified cards from the last day show; older ones wait behind "Show older". Nothing is deleted. */
+export function splitVerified(tasks: Task[], now: number = Date.now(), hours = VERIFIED_WINDOW_HOURS): { recent: Task[]; older: Task[] } {
+ const cutoff = now - hours * 3_600_000;
+ const recent: Task[] = [];
+ const older: Task[] = [];
+ for (const t of tasks) {
+ const at = Date.parse(t.finished_at ?? t.updated_at);
+ (Number.isNaN(at) || at >= cutoff ? recent : older).push(t);
+ }
+ return { recent, older };
+}
+
+/** Automatic cards (routine runs, worked-ahead, loose ends) sitting in Review for more than a week. */
+export function oldAutoReviews(tasks: Task[], now: number = Date.now(), days = OLD_REVIEW_DAYS): Task[] {
+ const cutoff = now - days * 86_400_000;
+ return tasks.filter((t) => columnOfTask(t) === 'review' && isAutoTask(t) && Date.parse(t.updated_at) < cutoff);
+}
+
+export interface Lane {
+ key: string;
+ label: string;
+ columns: Record<Column, Task[]>;
+ total: number;
+ needsYou: number;
+}
+
+/**
+ * Splits the board into rows (by team or bot), each with the five columns. Teams keep the order the
+ * person made them in; bots go alphabetically; "No team" / "No owner" come last. Rows without a card
+ * are left out.
+ */
+export function groupIntoLanes(tasks: Task[], by: Exclude<GroupBy, 'none'>, teams: BoardTeam[], names: Record<string, string>): Lane[] {
+ const teamOf = teamOfBots(teams);
+ const lanes = new Map<string, Lane>();
+ const laneOf = (t: Task): { key: string; label: string } => {
+ const bot = taskBot(t);
+ if (by === 'team') {
+ const team = bot ? teamOf[bot] : undefined;
+ return team ? { key: team.id, label: team.name } : { key: NO_TEAM, label: 'No team' };
+ }
+ return bot ? { key: bot, label: names[bot] ?? t.owner_name ?? 'Unknown bot' } : { key: NO_OWNER, label: 'No owner yet' };
+ };
+ for (const t of sortTasks(tasks)) {
+ const c = columnOfTask(t);
+ if (!c) continue;
+ const { key, label } = laneOf(t);
+ let lane = lanes.get(key);
+ if (!lane) {
+ lane = { key, label, columns: { ready: [], working: [], needs_you: [], review: [], verified: [] }, total: 0, needsYou: 0 };
+ lanes.set(key, lane);
+ }
+ lane.columns[c].push(t);
+ lane.total++;
+ if (c === 'needs_you') lane.needsYou++;
+ }
+ const order = by === 'team' ? new Map(teams.map((t, i) => [t.id, i])) : null;
+ const last = (k: string) => k === NO_TEAM || k === NO_OWNER;
+ return [...lanes.values()].sort((a, b) => {
+ if (last(a.key) !== last(b.key)) return last(a.key) ? 1 : -1;
+ if (order) return (order.get(a.key) ?? 1e9) - (order.get(b.key) ?? 1e9);
+ return a.label.localeCompare(b.label);
+ });
+}
+
+/** Keeps the cards of the picked teams (none picked = all). `NO_TEAM` picks cards without one. */
+export function filterByTeams(tasks: Task[], picked: string[], teams: BoardTeam[]): Task[] {
+ if (!picked.length) return tasks;
+ const teamOf = teamOfBots(teams);
+ const want = new Set(picked);
+ return tasks.filter((t) => {
+ const bot = taskBot(t);
+ return want.has((bot && teamOf[bot]?.id) || NO_TEAM);
+ });
+}
+
+/** "45s", "12m", "1h 05m", "2d 3h": how long a turn has been running. */
+export function elapsedText(since: string | undefined, now: number = Date.now()): string {
+ const t = since ? Date.parse(since) : NaN;
+ if (Number.isNaN(t)) return '';
+ const s = Math.max(0, Math.floor((now - t) / 1000));
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h ${String(m % 60).padStart(2, '0')}m`;
+ return `${Math.floor(h / 24)}d ${h % 24}h`;
+}
+
+export interface LiveBot {
+ kwantId: string;
+ name: string;
+ teamId: string;
+ teamName: string;
+ /** One line: what it is doing. */
+ what: string;
+ kind: 'task' | 'room' | 'thread' | 'chat' | 'deciding';
+ since?: string;
+ /** Where clicking it goes. */
+ place: ChatPlace;
+ /** Its other running turns. */
+ more: number;
+ /** The card it's working on, when the turn is a task's. */
+ taskId: string | null;
+}
+
+export interface LiveContext {
+ names: Record<string, string>;
+ teams: BoardTeam[];
+ /** Room id → name. */
+ rooms?: Record<string, string>;
+ /** Thread id → title. */
+ threadTitles?: Record<string, string>;
+ tasks?: Task[];
+}
+
+/** What one running turn is about, and where it happens. */
+export function describeTurn(turn: BoardTurn, ctx: LiveContext): Pick<LiveBot, 'what' | 'kind' | 'place' | 'taskId'> {
+ const room = ctx.rooms?.[turn.context_id];
+ const place: ChatPlace = room !== undefined
+ ? { channelId: turn.context_id, kwantId: null, threadId: turn.thread_id }
+ : { channelId: null, kwantId: turn.kwant_id, threadId: turn.thread_id };
+ // A task's chat is the turn's: its thread, else its room, else its bot's direct chat.
+ const task = (ctx.tasks ?? []).find(
+ (t) => t.state === 'working' && taskBot(t) === turn.kwant_id && (turn.thread_id ? t.thread_id === turn.thread_id : !t.thread_id && (t.channel_id ?? t.direct_kwant_id) === turn.context_id),
+ );
+ if (task) return { what: task.title, kind: 'task', place, taskId: task.id };
+ if (turn.purpose === 'decide') return { what: 'Deciding how to answer', kind: 'deciding', place, taskId: null };
+ if (room !== undefined) return { what: `In ${room || 'a room'}`, kind: 'room', place, taskId: null };
+ if (turn.thread_id) {
+ const title = ctx.threadTitles?.[turn.thread_id];
+ return { what: title ? title : 'In a side conversation', kind: 'thread', place, taskId: null };
+ }
+ return { what: 'In your chat', kind: 'chat', place, taskId: null };
+}
+
+/**
+ * Every bot running something right now, one row per bot (its longest-running turn, "+N more" for
+ * the rest), longest first. Queued turns aren't running, so they're left out.
+ */
+export function liveBots(turns: BoardTurn[], ctx: LiveContext): LiveBot[] {
+ const teamOf = teamOfBots(ctx.teams);
+ const byBot = new Map<string, BoardTurn[]>();
+ for (const t of turns) {
+ if (t.state !== 'running' || !t.kwant_id) continue;
+ byBot.set(t.kwant_id, [...(byBot.get(t.kwant_id) ?? []), t]);
+ }
+ const started = (t: BoardTurn) => (t.since ? Date.parse(t.since) || Infinity : Infinity);
+ const out: LiveBot[] = [];
+ for (const [kwantId, list] of byBot) {
+ // Prefer a task's turn (it says the most), then the longest-running.
+ const described = list.map((t) => ({ t, d: describeTurn(t, ctx) }));
+ described.sort((a, b) => Number(b.d.kind === 'task') - Number(a.d.kind === 'task') || started(a.t) - started(b.t));
+ const { t, d } = described[0];
+ const team = teamOf[kwantId];
+ out.push({
+ kwantId,
+ name: ctx.names[kwantId] ?? 'A bot',
+ teamId: team?.id ?? NO_TEAM,
+ teamName: team?.name ?? 'No team',
+ ...d,
+ since: list.map((x) => x.since).filter(Boolean).sort()[0] ?? t.since,
+ more: list.length - 1,
+ });
+ }
+ return out.sort((a, b) => (a.since ?? '').localeCompare(b.since ?? '') || a.name.localeCompare(b.name));
+}
+
+/** Live bots by team, in the order the person made their teams; "No team" last. */
+export function liveByTeam(bots: LiveBot[], teams: BoardTeam[]): Array<{ teamId: string; teamName: string; bots: LiveBot[] }> {
+ const order = new Map(teams.map((t, i) => [t.id, i]));
+ const groups = new Map<string, { teamId: string; teamName: string; bots: LiveBot[] }>();
+ for (const b of bots) {
+ const g = groups.get(b.teamId) ?? { teamId: b.teamId, teamName: b.teamName, bots: [] };
+ g.bots.push(b);
+ groups.set(b.teamId, g);
+ }
+ return [...groups.values()].sort((a, b) => (order.get(a.teamId) ?? 1e9) - (order.get(b.teamId) ?? 1e9));
+}
+
+/** The Live strip's summary, so it and the Working column never seem to disagree. */
+export function liveSummary(bots: LiveBot[], workingCards: number): string {
+ if (!bots.length) return workingCards ? `All bots idle · ${workingCards === 1 ? '1 task waits' : `${workingCards} tasks wait`} in Working for its bot’s next turn` : 'All bots idle';
+ const onTasks = bots.filter((b) => b.kind === 'task').length;
+ const head = bots.length === 1 ? '1 bot busy' : `${bots.length} bots busy`;
+ const rest = bots.length - onTasks;
+ if (!rest) return `${head}, all on board tasks`;
+ return `${head} · ${onTasks} on board tasks, ${rest} in chats, rooms or routines`;
+}
+
+/** The Verified column's header count: "5 · 37 all" once older cards are hidden. */
+export function verifiedCountText(recent: number, all: number): string {
+ return recent === all ? String(all) : `${recent} · ${all} all`;
+}
+
+/** The one-tap actions a Review card carries. Dismiss is the server's cancel. */
+export type QuickAction = 'verify' | 'reject' | 'cancel' | 'retry';
+
+export function quickActionsFor(t: Pick<Task, 'state'>): QuickAction[] {
+ if (t.state === 'review') return ['verify', 'reject', 'cancel'];
+ if (t.state === 'failed') return ['retry', 'cancel'];
+ return [];
+}
+
+export const QUICK_LABELS: Record<QuickAction, string> = { verify: 'Mark verified', reject: 'Send back', cancel: 'Dismiss', retry: 'Try again' };
+
+/** Sending back needs a reason on the server; an empty note sends this one. */
+export const DEFAULT_SEND_BACK = 'Take another look: it isn’t done yet.';
+
+/** The undo toast's line for an action on `n` cards. */
+export function quickDoneText(a: QuickAction, n: number, title?: string): string {
+ const what = n === 1 && title ? `“${title}”` : n === 1 ? '1 card' : `${n} cards`;
+ switch (a) {
+ case 'verify':
+ return `Marked ${what} verified.`;
+ case 'reject':
+ return `Sent ${what} back to its bot.`;
+ case 'retry':
+ return `${what} goes back to Ready for another try.`;
+ default:
+ return `Dismissed ${what}.`;
+ }
+}
+
+/** How long Undo stays on screen before the action goes to the server. */
+export const UNDO_MS = 6000;
diff --git a/frontend/tests/missionBoardLive.test.mjs b/frontend/tests/missionBoardLive.test.mjs
new file mode 100644
index 00000000..8d17f09a
--- /dev/null
+++ b/frontend/tests/missionBoardLive.test.mjs
@@ -0,0 +1,325 @@
+// Mission board, live: who is busy right now (chats, rooms and routines too, not just tasks), lanes by
+// team or bot, repeated routine runs folded into one card, one-tap Review actions, and Verified
+// showing only the last day unless the person asks for older.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const store = new Map();
+globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
+
+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, Board, LiveStrip } from './src/components/MissionBoardView';
+ const r = (c, p) => renderToStaticMarkup(React.createElement(c, p));
+ export const view = (p) => r(MissionBoardView, p);
+ export const board = (p) => r(Board, p);
+ export const live = (p) => r(LiveStrip, p);
+ export const card = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(TaskCard, p)));
+`);
+
+const NOW = Date.parse('2026-10-31T16:00:00Z');
+const H = 3_600_000;
+const iso = (ms) => new Date(ms).toISOString();
+const noop = () => {};
+const names = { k_ada: 'Ada', k_lin: 'Lin', k_pixel: 'Pixel', k_tw: 'TechWriter', k_solo: 'Solo' };
+const teams = [
+ { id: 'tm_ship', name: 'Ship Software Safely', lead_kwant_id: 'k_ada', member_kwants: ['k_lin', 'k_pixel'] },
+ { id: 'tm_docs', name: 'Docs', lead_kwant_id: 'k_tw', member_kwants: ['k_lin'] },
+];
+
+let n = 0;
+const task = (over = {}) => ({
+ id: `t${++n}`, space_id: 's1', mission_id: null, mission_title: null, title: 'Write the pricing copy', acceptance: '',
+ state: 'ready', priority: 1, owner_kwant_id: 'k_lin', owner_name: 'Lin', suggested_kwant_id: null, budget_tokens: 0,
+ spent_tokens: 0, attempts: 0, max_attempts: 3, blocked_reason: null, source_kind: 'person', source_id: null,
+ channel_id: null, direct_kwant_id: 'k_lin', thread_id: null, created_by: 'person', created_at: iso(NOW - 2 * H),
+ updated_at: iso(NOW - H), finished_at: null, depends_on: [], waiting_on: [], claim: null, needs_you: [],
+ checks_summary: { status: 'not_checked', passed: 0, failed: 0, total: 0 },
+ ...over,
+});
+const routineRun = (hoursAgo, over = {}) =>
+ task({ title: 'Routine: Morning overview', source_kind: 'routine', source_id: `run_${hoursAgo}`, state: 'review', owner_kwant_id: 'k_tw', owner_name: 'TechWriter', updated_at: iso(NOW - hoursAgo * H), finished_at: iso(NOW - hoursAgo * H), ...over });
+
+// ---------- Folding repeated runs ----------
+
+test('repeated runs of one routine fold into one card, newest on top, older ones newest first', () => {
+ const runs = [routineRun(50), routineRun(2), routineRun(26), routineRun(74)];
+ const other = task({ state: 'review', title: 'Fix the login page' });
+ const items = m.collapseRepeats([...runs, other]);
+ assert.equal(items.length, 2);
+ const folded = items.find((i) => i.task.title.startsWith('Routine'));
+ assert.equal(folded.task.source_id, 'run_2', 'the newest run is the card');
+ assert.deepEqual(folded.older.map((t) => t.source_id), ['run_26', 'run_50', 'run_74']);
+ assert.deepEqual(items.find((i) => i.task === other).older, []);
+});
+
+test('a routine card folds by routine name and bot, not by its run id (each run has its own)', () => {
+ const a = routineRun(1);
+ const b = routineRun(3);
+ assert.notEqual(a.source_id, b.source_id);
+ assert.equal(m.repeatKey(a), m.repeatKey(b));
+ assert.notEqual(m.repeatKey(a), m.repeatKey(routineRun(1, { owner_kwant_id: 'k_ada' })), 'another bot’s routine of the same name stays apart');
+ assert.notEqual(m.repeatKey(a), m.repeatKey(routineRun(1, { title: 'Routine: Evening wrap-up' })));
+});
+
+test('work the person asked for never folds, even with the same title', () => {
+ const items = m.collapseRepeats([task({ state: 'review' }), task({ state: 'review' })]);
+ assert.equal(items.length, 2);
+ assert.equal(m.repeatKey(task()), null);
+ assert.equal(m.repeatKey(task({ source_kind: 'delegation' })), null);
+});
+
+test('worked-ahead and loose-end cards fold by bot and title (case and spaces ignored)', () => {
+ const a = task({ source_kind: 'work_ahead', title: 'Worked ahead: API Error 529', state: 'review' });
+ const b = task({ source_kind: 'work_ahead', title: ' worked ahead: api error 529 ', state: 'review' });
+ assert.equal(m.collapseRepeats([a, b]).length, 1);
+});
+
+// ---------- Verified fades out ----------
+
+test('Verified keeps the last 24 hours; older cards wait behind Show older, none deleted', () => {
+ const fresh = task({ state: 'verified', finished_at: iso(NOW - 3 * H) });
+ const edge = task({ state: 'verified', finished_at: iso(NOW - 24 * H) });
+ const old = task({ state: 'verified', finished_at: iso(NOW - 25 * H) });
+ const noFinish = task({ state: 'verified', finished_at: null, updated_at: iso(NOW - 48 * H) });
+ const { recent, older } = m.splitVerified([fresh, edge, old, noFinish], NOW);
+ assert.deepEqual(recent, [fresh, edge]);
+ assert.deepEqual(older, [old, noFinish], 'falls back to updated_at');
+ assert.equal(recent.length + older.length, 4);
+});
+
+test('the Verified header count shows both numbers only when some are hidden', () => {
+ assert.equal(m.verifiedCountText(5, 37), '5 · 37 all');
+ assert.equal(m.verifiedCountText(4, 4), '4');
+});
+
+test('the board renders only recent Verified cards with a Show older link and both counts', () => {
+ const fresh = task({ state: 'verified', title: 'Fresh one', finished_at: iso(NOW - H) });
+ const olds = [30, 40, 50].map((h) => task({ state: 'verified', title: `Old ${h}`, finished_at: iso(NOW - h * H) }));
+ const html = ui.board({ tasks: [fresh, ...olds], names, column: 'verified', now: NOW, onColumn: noop, onOpen: noop });
+ assert.match(html, /Fresh one/);
+ assert.doesNotMatch(html, /Old 30/);
+ assert.match(html, /Show older \(3\)/);
+ assert.match(html, /1 · 4 all/);
+});
+
+test('with nothing verified today, Verified says so instead of looking empty forever', () => {
+ const html = ui.board({ tasks: [task({ state: 'verified', finished_at: iso(NOW - 72 * H) })], names, column: 'verified', now: NOW, onColumn: noop, onOpen: noop });
+ assert.match(html, /Nothing verified in the last 24 hours\./);
+ assert.match(html, /Show older \(1\)/);
+});
+
+// ---------- Old automatic reviews ----------
+
+test('Clear old reviews picks only automatic Review cards older than 7 days', () => {
+ const oldRoutine = routineRun(8 * 24);
+ const oldAhead = task({ source_kind: 'work_ahead', state: 'failed', updated_at: iso(NOW - 10 * 24 * H) });
+ const newRoutine = routineRun(6 * 24);
+ const oldPerson = task({ state: 'review', updated_at: iso(NOW - 30 * 24 * H) });
+ const oldVerified = routineRun(9 * 24, { state: 'verified' });
+ const oldButNeedsYou = routineRun(9 * 24, { needs_you: [{ kind: 'check_approval', text: 'Allow?' }] });
+ const picked = m.oldAutoReviews([oldRoutine, oldAhead, newRoutine, oldPerson, oldVerified, oldButNeedsYou], NOW);
+ assert.deepEqual(picked, [oldRoutine, oldAhead]);
+});
+
+// ---------- Lanes by team or bot ----------
+
+test('a bot belongs to the team it leads first, then the first team it is in', () => {
+ const of = m.teamOfBots(teams);
+ assert.equal(of.k_ada.id, 'tm_ship');
+ assert.equal(of.k_tw.id, 'tm_docs');
+ assert.equal(of.k_lin.id, 'tm_ship', 'Lin is in both; the first team wins');
+ assert.equal(of.k_solo, undefined);
+});
+
+test('lanes by team keep the person’s team order, carry per-column cards and a Needs you count; No team is last', () => {
+ const tasks = [
+ task({ owner_kwant_id: 'k_solo', state: 'ready' }),
+ task({ owner_kwant_id: 'k_tw', state: 'working' }),
+ task({ owner_kwant_id: 'k_lin', state: 'needs_you' }),
+ task({ owner_kwant_id: 'k_pixel', state: 'review' }),
+ task({ owner_kwant_id: null, claim: { kwant_id: 'k_tw', claimed_at: '', expires_at: '' }, state: 'working' }),
+ task({ owner_kwant_id: null, state: 'cancelled' }),
+ ];
+ const lanes = m.groupIntoLanes(tasks, 'team', teams, names);
+ assert.deepEqual(lanes.map((l) => l.label), ['Ship Software Safely', 'Docs', 'No team']);
+ const ship = lanes[0];
+ assert.equal(ship.total, 2);
+ assert.equal(ship.needsYou, 1);
+ assert.equal(ship.columns.needs_you.length, 1);
+ assert.equal(ship.columns.review.length, 1);
+ assert.equal(lanes[1].columns.working.length, 2, 'an unowned card goes with the bot holding it');
+ assert.equal(lanes[2].key, m.NO_TEAM);
+});
+
+test('lanes by bot go alphabetically with No owner last', () => {
+ const lanes = m.groupIntoLanes([task({ owner_kwant_id: 'k_pixel' }), task({ owner_kwant_id: null }), task({ owner_kwant_id: 'k_ada' })], 'bot', teams, names);
+ assert.deepEqual(lanes.map((l) => l.label), ['Ada', 'Pixel', 'No owner yet']);
+});
+
+test('team chips filter cards; none picked shows all; No team picks unteamed cards', () => {
+ const a = task({ owner_kwant_id: 'k_ada' });
+ const b = task({ owner_kwant_id: 'k_tw' });
+ const c = task({ owner_kwant_id: 'k_solo' });
+ assert.deepEqual(m.filterByTeams([a, b, c], [], teams), [a, b, c]);
+ assert.deepEqual(m.filterByTeams([a, b, c], ['tm_docs'], teams), [b]);
+ assert.deepEqual(m.filterByTeams([a, b, c], ['tm_ship', m.NO_TEAM], teams), [a, c]);
+});
+
+test('Group by is remembered on this device and falls back to None', () => {
+ store.clear();
+ assert.equal(m.readGroupBy(), 'none');
+ m.saveGroupBy('team');
+ assert.equal(m.readGroupBy(), 'team');
+ store.set(m.GROUP_BY_KEY, 'nonsense');
+ assert.equal(m.readGroupBy(), 'none');
+});
+
+test('the board grouped by team renders one row per team with the column headers once', () => {
+ const html = ui.board({
+ tasks: [task({ owner_kwant_id: 'k_tw', state: 'working' }), task({ owner_kwant_id: 'k_lin', state: 'needs_you' })],
+ names, column: 'ready', now: NOW, onColumn: noop, onOpen: noop, groupBy: 'team', teams,
+ });
+ assert.match(html, /data-board="lanes"/);
+ assert.match(html, /data-lane="tm_ship"/);
+ assert.match(html, /data-lane="tm_docs"/);
+ assert.match(html, /data-lane-needs-you="1"/);
+ assert.doesNotMatch(html, /data-board="columns"/);
+});
+
+// ---------- Live now ----------
+
+const turn = (over = {}) => ({ turn_id: `u${++n}`, kwant_id: 'k_tw', context_id: 'k_tw', thread_id: null, state: 'running', since: iso(NOW - 5 * 60_000), ...over });
+
+test('a bot chatting (no task) is live: the board no longer says nobody is working', () => {
+ const bots = m.liveBots([turn()], { names, teams, tasks: [] });
+ assert.equal(bots.length, 1);
+ assert.equal(bots[0].name, 'TechWriter');
+ assert.equal(bots[0].kind, 'chat');
+ assert.equal(bots[0].teamName, 'Docs');
+ assert.deepEqual(bots[0].place, { channelId: null, kwantId: 'k_tw', threadId: null });
+ assert.equal(m.liveSummary(bots, 0), '1 bot busy · 0 on board tasks, 1 in chats, rooms or routines');
+});
+
+test('a live turn says what it is: the task it runs, the room, the thread, or a decide round', () => {
+ const working = task({ state: 'working', owner_kwant_id: 'k_tw', title: 'Routine: Morning overview', channel_id: null, direct_kwant_id: 'k_tw', source_kind: 'routine' });
+ const ctx = { names, teams, rooms: { c_eng: 'Engineering Room' }, threadTitles: { th1: 'Release notes draft' }, tasks: [working] };
+ assert.deepEqual(m.describeTurn(turn(), ctx).what, 'Routine: Morning overview');
+ assert.equal(m.describeTurn(turn(), ctx).taskId, working.id);
+ const room = m.describeTurn(turn({ kwant_id: 'k_ada', context_id: 'c_eng' }), ctx);
+ assert.equal(room.what, 'In Engineering Room');
+ assert.deepEqual(room.place, { channelId: 'c_eng', kwantId: null, threadId: null });
+ assert.equal(m.describeTurn(turn({ kwant_id: 'k_lin', context_id: 'th1', thread_id: 'th1' }), ctx).what, 'Release notes draft');
+ assert.equal(m.describeTurn(turn({ kwant_id: 'k_lin', context_id: 'th9', thread_id: 'th9' }), ctx).what, 'In a side conversation');
+ assert.equal(m.describeTurn(turn({ kwant_id: 'k_lin', purpose: 'decide' }), ctx).kind, 'deciding');
+});
+
+test('one row per bot: a task turn wins, the rest count as +N; queued turns are not live', () => {
+ const working = task({ state: 'working', owner_kwant_id: 'k_lin', thread_id: 'th2', title: 'Fix the flaky test' });
+ const bots = m.liveBots(
+ [
+ turn({ kwant_id: 'k_lin', since: iso(NOW - 30 * 60_000) }),
+ turn({ kwant_id: 'k_lin', context_id: 'th2', thread_id: 'th2', since: iso(NOW - 2 * 60_000) }),
+ turn({ kwant_id: 'k_ada', state: 'queued' }),
+ ],
+ { names, teams, tasks: [working] },
+ );
+ assert.equal(bots.length, 1);
+ assert.equal(bots[0].what, 'Fix the flaky test');
+ assert.equal(bots[0].more, 1);
+ assert.equal(bots[0].since, iso(NOW - 30 * 60_000), 'busy since its first running turn');
+});
+
+test('live bots group by team in the person’s order with No team last', () => {
+ const bots = m.liveBots([turn({ kwant_id: 'k_solo' }), turn({ kwant_id: 'k_tw' }), turn({ kwant_id: 'k_ada' })], { names, teams });
+ assert.deepEqual(m.liveByTeam(bots, teams).map((g) => g.teamName), ['Ship Software Safely', 'Docs', 'No team']);
+});
+
+test('elapsed time reads short', () => {
+ assert.equal(m.elapsedText(iso(NOW - 45_000), NOW), '45s');
+ assert.equal(m.elapsedText(iso(NOW - 12 * 60_000), NOW), '12m');
+ assert.equal(m.elapsedText(iso(NOW - 65 * 60_000), NOW), '1h 05m');
+ assert.equal(m.elapsedText(iso(NOW - 51 * H), NOW), '2d 3h');
+ assert.equal(m.elapsedText(undefined, NOW), '');
+});
+
+test('the summary explains idle bots and Working cards so the strip and column agree', () => {
+ assert.equal(m.liveSummary([], 0), 'All bots idle');
+ assert.match(m.liveSummary([], 2), /^All bots idle · 2 tasks wait in Working/);
+ const onTask = { kind: 'task' };
+ assert.equal(m.liveSummary([onTask, onTask], 2), '2 bots busy, all on board tasks');
+});
+
+test('the Live strip renders each busy bot under its team, with elapsed time; idle shows All bots idle', () => {
+ const bots = m.liveBots([turn()], { names, teams });
+ const html = ui.live({ bots, teams, workingCards: 0, now: NOW, onOpen: noop });
+ assert.match(html, /aria-label="Live now"/);
+ assert.match(html, /data-live-team="tm_docs"/);
+ assert.match(html, /TechWriter/);
+ assert.match(html, /5m/);
+ assert.match(ui.live({ bots: [], teams, workingCards: 0, now: NOW }), /All bots idle/);
+});
+
+// ---------- Review card actions ----------
+
+test('a Review card carries Mark verified, Send back and Dismiss; a failed one Try again and Dismiss', () => {
+ assert.deepEqual(m.quickActionsFor({ state: 'review' }), ['verify', 'reject', 'cancel']);
+ assert.deepEqual(m.quickActionsFor({ state: 'failed' }), ['retry', 'cancel']);
+ assert.deepEqual(m.quickActionsFor({ state: 'working' }), []);
+ const html = ui.card({ task: task({ state: 'review' }), names, now: NOW, onOpen: noop, onQuick: noop });
+ assert.match(html, /data-card-action="verify"[^>]*>.*Mark verified/);
+ assert.match(html, /data-card-action="reject"/);
+ assert.match(html, /data-card-action="cancel"[^>]*>.*Dismiss/);
+ assert.doesNotMatch(ui.card({ task: task({ state: 'review' }), names, now: NOW, onOpen: noop }), /data-card-actions/, 'no actions without a handler');
+});
+
+test('a Review card waiting on the person (Needs you column) gets no quick actions', () => {
+ const t = task({ state: 'review', needs_you: [{ kind: 'check_approval', text: 'Allow the check?' }] });
+ assert.doesNotMatch(ui.card({ task: t, names, now: NOW, onOpen: noop, onQuick: noop }), /data-card-actions/);
+});
+
+test('a folded card shows ×N and offers to dismiss the older runs together', () => {
+ const html = ui.card({ task: routineRun(1), older: [routineRun(25), routineRun(49), routineRun(73)], names, now: NOW, onOpen: noop, onQuick: noop, onDismissMany: noop });
+ assert.match(html, /×4/);
+ assert.match(html, /Dismiss 3 older/);
+});
+
+test('the Review column folds four Morning overview runs into one card on the board', () => {
+ const html = ui.board({ tasks: [routineRun(1), routineRun(25), routineRun(49), routineRun(73)], names, column: 'review', now: NOW, onColumn: noop, onOpen: noop, onQuick: noop });
+ assert.equal((html.match(/data-repeats="4"/g) ?? []).length, 2, 'one folded card in the phone tab and one on desktop');
+});
+
+test('undo text names the card or counts them', () => {
+ assert.equal(m.quickDoneText('verify', 1, 'Fix login'), 'Marked “Fix login” verified.');
+ assert.equal(m.quickDoneText('cancel', 12), 'Dismissed 12 cards.');
+ assert.equal(m.quickDoneText('reject', 1, 'X'), 'Sent “X” back to its bot.');
+ assert.ok(m.DEFAULT_SEND_BACK.length > 0, 'the server needs a reason, so an empty note still sends one');
+});
+
+// ---------- The page ----------
+
+test('the board view shows Live now, the Group control and Clear old reviews with its count', () => {
+ const tasks = [routineRun(9 * 24), routineRun(10 * 24, { title: 'Routine: Weekly digest' }), task({ owner_kwant_id: 'k_ada' })];
+ const html = ui.view({
+ tasks, missions: [], insights: null, names, missionId: null, column: 'review', loading: false, error: null, now: NOW,
+ onMission: noop, onColumn: noop, onOpenTask: noop, onApproveMission: noop, onCancelMission: noop, onRefresh: noop,
+ live: m.liveBots([turn()], { names, teams }), teams, groupBy: 'none', onGroupBy: noop, onTeamFilter: noop, onQuick: noop, onClearOld: noop,
+ });
+ assert.match(html, /Live now/);
+ assert.match(html, /data-group-by="none"/);
+ assert.match(html, /Clear old reviews \(2\)/);
+ assert.match(html, /data-team-chip="tm_docs"/);
+ assert.match(html, /data-team-chip="tm_ship"/);
+});
+
+test('without live data the view stays as before: no strip, no toolbar', () => {
+ const html = ui.view({
+ tasks: [task()], missions: [], insights: null, names, missionId: null, column: 'ready', loading: false, error: null, now: NOW,
+ onMission: noop, onColumn: noop, onOpenTask: noop, onApproveMission: noop, onCancelMission: noop, onRefresh: noop,
+ });
+ assert.doesNotMatch(html, /Live now/);
+ assert.doesNotMatch(html, /data-board-toolbar/);
+});