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 B1 UI: may-be-invalid flags, resolve, copies, work graph

pixel-bot1ff4888f5866
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 020de5ce..c409de2e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
outside the folder (commands, web, messages) is listed as not undone. Every tool call of a task's
turns is now recorded with its effect. Snapshots stay private on the server. The board UI follows
separately.
+- **Mission board: "May be invalid" flags, redo copies and how tasks connect.** A flagged task shows
+ a "May be invalid" badge and the reason on its card, waits under **Needs you**, and stays Verified
+ until you pick Still valid, Redo or Cancel on the task (Cancel is off for a verified task). Redo on a
+ verified task makes a copy that starts running on its own; the copy links back with "Copied from". A
+ new **How tasks connect** view lists a mission's tasks step by step, with open flags and how many
+ tasks further down weren't flagged, plus a **Check files now** button. In Review, an optional check
+ waiting for you now uses the same quiet grey row as on Verified.
- **Mission Control: work graph and "may be invalid" flags (backend).** When a verified task's evidence
file changes or disappears, or a verified task is redone, kwant flags that task and the started tasks
that directly depend on it as "may be invalid". Their state never changes, and only you decide:
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 7a244d93..6e323fdb 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -5,8 +5,10 @@ import {
ChevronLeft,
Circle,
CircleDashed,
+ Copy,
ExternalLink,
FileText,
+ GitBranch,
Hand,
Image as ImageIcon,
Link2,
@@ -28,15 +30,19 @@ import {
Check,
Column,
Evidence,
+ GraphLevel,
Insights,
Mission,
MissionError,
+ OpenFlag,
+ ResolveChoice,
NEEDS_REASON,
Receipt,
Task,
TaskAction,
TaskDetail,
Tone,
+ WorkGraph,
actionsFor,
ago,
buildReceipt,
@@ -45,7 +51,14 @@ import {
checksText,
optionalChecksNote,
approvalHolds,
- columnOf,
+ columnOfTask,
+ flagText,
+ flagErrorText,
+ graphLevels,
+ newIdempotencyKey,
+ openFlags,
+ resolveOptions,
+ resolvedText,
costRatio,
costText,
durationText,
@@ -233,7 +246,8 @@ export const TaskCard: React.FC<{
const checks = checksText(t.checks_summary);
const optionalNote = optionalChecksNote(t.checks_summary);
const status = cardStatus(t, names, now);
- const dimmed = t.state === 'backlog';
+ const flags = openFlags(t);
+ const dimmed = t.state === 'backlog' && !flags.length;
return (
<li data-task={t.id} data-state={t.state}>
<button
@@ -246,6 +260,12 @@ export const TaskCard: React.FC<{
{t.state === 'failed' && <Badge tone="rose">Failed</Badge>}
{t.state === 'backlog' && <Badge tone="zinc">Waiting</Badge>}
{t.state === 'review' && approvalHolds(t.checks_summary) && <Badge tone="amber">Needs you</Badge>}
+ {flags.length > 0 && (
+ <span data-flag-badge>
+ <Badge tone="amber">May be invalid</Badge>
+ </span>
+ )}
+ {t.state === 'verified' && flags.length > 0 && <Badge tone="emerald">Verified</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>
@@ -255,6 +275,16 @@ export const TaskCard: React.FC<{
{status}
</span>
)}
+ {flags.length > 0 && (
+ <span className="flex items-start gap-1 text-[11px] text-amber-200 break-words" data-flag-line>
+ <AlertTriangle size={11} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span className="line-clamp-2">
+ {flags[0].text}
+ {flags.length > 1 ? ` (+${flags.length - 1} more)` : ''}
+ </span>
+ </span>
+ )}
+ {t.forked_from && <span className="block text-[11px] text-zinc-500" data-forked-from>A copy, made to redo an earlier task</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">
@@ -464,11 +494,11 @@ export const EvidenceReceipt: React.FC<{
{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(receipt.settledVerified && l.check.status === 'needs_approval' && !l.check.required ? 'zinc' : l.status.tone)}</span>
+ <span className="mt-px">{statusIcon(receipt.quietOptional(l.check) ? 'zinc' : 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>
- {receipt.settledVerified && l.check.status === 'needs_approval' && !l.check.required ? (
+ {receipt.quietOptional(l.check) ? (
<Badge tone="zinc">Not run</Badge>
) : (
<Badge tone={l.status.tone}>{l.status.label}</Badge>
@@ -479,7 +509,7 @@ export const EvidenceReceipt: React.FC<{
<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.notCounting && !l.ownClaim && !(receipt.settledVerified && !l.check.required) && (
+ {l.notCounting && !l.ownClaim && !receipt.quietOptional(l.check) && !(receipt.settledVerified && !l.check.required) && (
<p className="mt-1 text-[11px] text-amber-200" data-not-counting>
{l.notCounting}
</p>
@@ -487,7 +517,7 @@ export const EvidenceReceipt: React.FC<{
{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 && receipt.settledVerified && !l.check.required ? (
+ {onApproveCheck && receipt.quietOptional(l.check) ? (
<div className="pl-6">
<button type="button" disabled={busy} onClick={() => onApproveCheck(l.check)} className={subtleBtn} data-run-optional>
Run this optional check
@@ -529,6 +559,76 @@ export const EvidenceReceipt: React.FC<{
</section>
);
+// ---------- May be invalid ----------
+
+/** One open flag with the person's three choices. Choices that would be refused are off, with why. */
+export const FlagBox: React.FC<{
+ flag: OpenFlag;
+ state: Task['state'];
+ causeTitle?: string | null;
+ busy?: boolean;
+ onResolve?: (f: OpenFlag, choice: ResolveChoice) => void;
+ onOpenTask?: (id: string) => void;
+}> = ({ flag, state, causeTitle, busy = false, onResolve, onOpenTask }) => {
+ const opts = resolveOptions(state);
+ const hintId = useId();
+ const off = opts.filter((o) => o.disabled);
+ return (
+ <li className="px-3 py-2.5 rounded-lg border border-amber-500/30 bg-amber-500/10 text-xs text-amber-100 space-y-2" data-flag={flag.id} data-flag-cause={flag.cause ?? ''}>
+ <p className="flex items-start gap-1.5 break-words">
+ <AlertTriangle size={14} className="mt-px shrink-0 text-amber-300" aria-hidden="true" />
+ <span>
+ <span className="font-semibold">May be invalid: </span>
+ {flag.text}.{' '}
+ {state === 'verified' ? 'It stays Verified until you decide.' : 'Nothing has changed on the task until you decide.'}
+ {flag.causeTaskId && flag.cause !== 'evidence_changed' && onOpenTask && (
+ <>
+ {' '}
+ <button type="button" onClick={() => onOpenTask(flag.causeTaskId!)} className={`text-sky-300 hover:underline rounded ${focusRing}`} data-flag-cause-link>
+ Open {causeTitle ? `“${causeTitle}”` : 'that task'}
+ </button>
+ </>
+ )}
+ </span>
+ </p>
+ {onResolve && (
+ <>
+ <div className="flex flex-wrap gap-2" role="group" aria-label="Decide on this flag" aria-describedby={hintId}>
+ {opts.map((o) => (
+ <button
+ key={o.choice}
+ type="button"
+ disabled={busy || !!o.disabled}
+ title={o.disabled ?? o.hint}
+ onClick={() => onResolve(flag, o.choice)}
+ className={o.choice === 'still_valid' ? goodBtn : o.choice === 'redo' ? mainBtn : dangerBtn}
+ data-resolve={o.choice}
+ >
+ {o.choice === 'redo' && state === 'verified' && <Copy size={13} aria-hidden="true" />}
+ {o.label}
+ </button>
+ ))}
+ </div>
+ <ul id={hintId} className="space-y-0.5 text-[11px] text-amber-100/80">
+ {opts
+ .filter((o) => !o.disabled && o.hint)
+ .map((o) => (
+ <li key={o.choice} data-resolve-hint={o.choice}>
+ <span className="font-medium">{o.label}:</span> {o.hint}
+ </li>
+ ))}
+ {off.map((o) => (
+ <li key={o.choice} className="text-zinc-400" data-resolve-off={o.choice}>
+ {o.disabled}
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ </li>
+ );
+};
+
// ---------- Task detail ----------
const Fact: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
@@ -549,8 +649,18 @@ export const TaskDetailBody: React.FC<{
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 }) => {
+ onResolveFlag?: (f: OpenFlag, choice: ResolveChoice) => void;
+ /** Copy a verified task to redo it, with the reason typed. */
+ onFork?: (reason: string) => void;
+}> = ({ detail, names, tasksById = {}, now = Date.now(), busy = false, notice, onAction, onApproveCheck, onOpenChat, onOpenTask, onResolveFlag, onFork }) => {
const t = detail.task;
+ const flags = openFlags(t);
+ const others = t.needs_you.filter((n) => n.kind !== 'may_be_invalid');
+ const copies = Object.values(tasksById).filter((x) => x.forked_from === t.id && x.id !== t.id);
+ const source = t.forked_from ? tasksById[t.forked_from] : undefined;
+ const [forking, setForking] = useState(false);
+ const [forkReason, setForkReason] = useState('');
+ const forkId = useId();
const receipt = useMemo(() => buildReceipt(detail, names), [detail, names]);
const [asking, setAsking] = useState<TaskAction | null>(null);
const [reason, setReason] = useState('');
@@ -565,6 +675,8 @@ export const TaskDetailBody: React.FC<{
useEffect(() => {
setAsking(null);
setReason('');
+ setForking(false);
+ setForkReason('');
}, [t.id, t.state]);
const press = (a: TaskAction) => {
@@ -628,8 +740,92 @@ export const TaskDetailBody: React.FC<{
</form>
)}
{t.state === 'review' && <p className="text-[11px] text-zinc-500">“Mark verified” records that you checked it yourself.</p>}
+ {t.state === 'verified' && onFork && !forking && (
+ <button type="button" disabled={busy} onClick={() => setForking(true)} className={quietBtn} data-fork>
+ <Copy size={13} aria-hidden="true" /> Redo as a copy
+ </button>
+ )}
+ {t.state === 'verified' && onFork && forking && (
+ <form
+ className="space-y-2"
+ data-fork-form
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!forkReason.trim()) return;
+ onFork(forkReason.trim());
+ }}
+ >
+ <label htmlFor={forkId} className="block text-[11px] font-medium text-zinc-300">
+ Why redo it?
+ </label>
+ <textarea id={forkId} autoFocus rows={2} maxLength={500} value={forkReason} onChange={(e) => setForkReason(e.target.value)} className={`${field} resize-y`} />
+ <p className="text-[11px] text-zinc-400">The copy starts running on its own. This task stays Verified, and tasks that build on it get a “May be invalid” flag.</p>
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={busy || !forkReason.trim()} className={mainBtn}>
+ Make the copy
+ </button>
+ <button type="button" onClick={() => setForking(false)} className={quietBtn}>
+ Never mind
+ </button>
+ </div>
+ </form>
+ )}
</div>
+ {flags.length > 0 && (
+ <section aria-labelledby="flag-h" className="space-y-2" data-flags>
+ <h4 id="flag-h" className="text-xs font-semibold text-amber-200">
+ May be invalid
+ </h4>
+ <ul className="space-y-2">
+ {flags.map((f) => (
+ <FlagBox
+ key={f.id}
+ flag={f}
+ state={t.state}
+ causeTitle={(t.flags ?? []).find((x) => x.id === f.id)?.cause_title ?? (f.causeTaskId ? tasksById[f.causeTaskId]?.title : null)}
+ busy={busy}
+ onResolve={onResolveFlag}
+ onOpenTask={onOpenTask}
+ />
+ ))}
+ </ul>
+ </section>
+ )}
+
+ {(t.forked_from || copies.length > 0) && (
+ <section aria-label="Copies" className="space-y-1 text-xs" data-copies>
+ {t.forked_from && (
+ <p className="flex flex-wrap items-center gap-1.5 text-zinc-400" data-copied-from>
+ <GitBranch size={13} aria-hidden="true" />
+ Copied from{' '}
+ {onOpenTask ? (
+ <button type="button" onClick={() => onOpenTask(t.forked_from!)} className={`text-left text-sky-300 hover:underline rounded ${focusRing}`}>
+ {source ? `“${source.title}”` : 'an earlier task'}
+ </button>
+ ) : (
+ <span className="text-zinc-200">{source ? `“${source.title}”` : 'an earlier task'}</span>
+ )}
+ {source && <span className="text-zinc-500">· {stateLabel(source.state).label}</span>}
+ </p>
+ )}
+ {copies.map((c) => (
+ <p key={c.id} className="flex flex-wrap items-center gap-1.5 text-zinc-400" data-redone-as={c.id}>
+ <Copy size={13} aria-hidden="true" />
+ Redone as{' '}
+ {onOpenTask ? (
+ <button type="button" onClick={() => onOpenTask(c.id)} className={`text-left text-sky-300 hover:underline rounded ${focusRing}`}>
+ “{c.title}”
+ </button>
+ ) : (
+ <span className="text-zinc-200">“{c.title}”</span>
+ )}
+ <span className="text-zinc-500">· {stateLabel(c.state).label}</span>
+ </p>
+ ))}
+ </section>
+ )}
+
<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
@@ -678,13 +874,13 @@ export const TaskDetailBody: React.FC<{
</section>
)}
- {t.needs_you.length > 0 && (
+ {others.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) => (
+ {others.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">
@@ -801,6 +997,119 @@ export const TaskPanel: React.FC<{
);
};
+// ---------- Work graph ----------
+
+/** How a mission's tasks connect, as steps: each task sits one step after what it builds on. */
+export const WorkGraphView: React.FC<{
+ graph: WorkGraph | null;
+ names: Record<string, string>;
+ loading?: boolean;
+ error?: string | null;
+ scanning?: boolean;
+ now?: number;
+ onOpenTask: (id: string) => void;
+ onScan?: () => void;
+ onRetry?: () => void;
+}> = ({ graph, names, loading = false, error = null, scanning = false, now = Date.now(), onOpenTask, onScan, onRetry }) => {
+ const levels: GraphLevel[] = useMemo(() => (graph ? graphLevels(graph) : []), [graph]);
+ const titles = useMemo(() => Object.fromEntries((graph?.nodes ?? []).map((n) => [n.id, n.title])), [graph]);
+ const flagged = (graph?.nodes ?? []).filter((n) => n.flags.length > 0).length;
+ return (
+ <section aria-labelledby="graph-h" className="space-y-3" data-graph>
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="min-w-0 flex-1">
+ <h3 id="graph-h" className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">
+ <GitBranch size={14} className="text-sky-400" aria-hidden="true" /> How the tasks connect
+ </h3>
+ <p className="text-[11px] text-zinc-500">
+ {graph?.scanned_at ? `Files last checked for changes ${ago(graph.scanned_at, now)}` : 'Files haven’t been checked for changes yet'}
+ {flagged > 0 ? ` · ${flagged} may be invalid` : ''}
+ </p>
+ </div>
+ {onScan && (
+ <button type="button" disabled={scanning || loading} onClick={onScan} className={quietBtn} data-scan>
+ <RefreshCw size={12} className={scanning ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ Check files now
+ </button>
+ )}
+ </div>
+ {error && (
+ <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 min-w-0 break-words">Couldn’t load how the tasks connect. {error}</span>
+ {onRetry && (
+ <button type="button" onClick={onRetry} 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>
+ )}
+ {!graph && 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…
+ </p>
+ )}
+ {graph && graph.nodes.length === 0 && <p className="px-3 py-6 rounded-xl border border-dashed border-zinc-800 text-center text-xs text-zinc-500" data-graph-empty>This mission has no tasks yet.</p>}
+ {graph && graph.scan_skipped.length > 0 && (
+ <p className="text-[11px] text-zinc-500" data-scan-skipped>
+ {graph.scan_skipped.length === 1 ? '1 file wasn’t checked' : `${graph.scan_skipped.length} files weren’t checked`} (too big, too many, or outside the task folder). A file that isn’t checked never counts as changed.
+ </p>
+ )}
+ {levels.length > 0 && (
+ <ol className="grid gap-3 lg:grid-flow-col lg:auto-cols-[minmax(13rem,1fr)] lg:overflow-x-auto pb-1">
+ {levels.map((lv) => (
+ <li key={lv.step} className="min-w-0 space-y-2" data-graph-step={lv.step}>
+ <h4 className="px-1 text-[11px] font-medium text-zinc-500">{lv.step === 1 ? 'Step 1 · builds on nothing' : `Step ${lv.step}`}</h4>
+ <ul className="space-y-2">
+ {lv.rows.map(({ node: n, after, notFlaggedText }) => {
+ const st = stateLabel(n.state);
+ const owner = (n.owner_kwant_id && names[n.owner_kwant_id]) || n.owner_name;
+ return (
+ <li key={n.id} data-graph-node={n.id} data-state={n.state}>
+ <button
+ type="button"
+ onClick={() => onOpenTask(n.id)}
+ className={`${card} w-full text-left p-2.5 space-y-1 hover:border-zinc-700 hover:bg-zinc-900/70 ${focusRing} ${n.flags.length ? 'border-amber-500/40' : ''}`}
+ >
+ <span className="flex flex-wrap items-center gap-1.5">
+ <Badge tone={st.tone}>{st.label}</Badge>
+ {n.flags.length > 0 && <Badge tone="amber">May be invalid</Badge>}
+ </span>
+ <span className="block text-xs font-medium text-zinc-100 break-words">{n.title}</span>
+ {after.length > 0 && (
+ <span className="block text-[11px] text-zinc-400 break-words" data-graph-after>
+ After {after.map((a) => `“${a.title}”`).join(', ')}
+ </span>
+ )}
+ {n.forked_from && (
+ <span className="block text-[11px] text-zinc-500 break-words" data-graph-forked>
+ Copied from {titles[n.forked_from] ? `“${titles[n.forked_from]}”` : 'an earlier task'}
+ </span>
+ )}
+ {n.flags.map((f) => (
+ <span key={f.id} className="flex items-start gap-1 text-[11px] text-amber-200 break-words" data-graph-flag={f.cause}>
+ <AlertTriangle size={11} className="mt-0.5 shrink-0" aria-hidden="true" />
+ {flagText(f)}
+ </span>
+ ))}
+ {notFlaggedText && (
+ <span className="block text-[11px] text-zinc-500" data-graph-not-flagged>
+ {notFlaggedText}
+ </span>
+ )}
+ {owner && <span className="block text-[11px] text-zinc-500 truncate">{owner}</span>}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </li>
+ ))}
+ </ol>
+ )}
+ </section>
+ );
+};
+
// ---------- Page ----------
export interface MissionBoardViewProps {
@@ -823,6 +1132,15 @@ export interface MissionBoardViewProps {
onCancelMission: (m: Mission) => void;
onRefresh: () => void;
onBack?: () => void;
+ /** With a mission picked: the board, or how its tasks connect. */
+ view?: 'board' | 'graph';
+ onView?: (v: 'board' | 'graph') => void;
+ graph?: WorkGraph | null;
+ graphLoading?: boolean;
+ graphError?: string | null;
+ scanning?: boolean;
+ onScan?: () => void;
+ onRetryGraph?: () => void;
}
export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
@@ -845,10 +1163,19 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
onCancelMission,
onRefresh,
onBack,
+ view = 'board',
+ onView,
+ graph = null,
+ graphLoading = false,
+ graphError = null,
+ scanning = false,
+ onScan,
+ onRetryGraph,
}) => {
const selectId = useId();
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;
@@ -935,11 +1262,41 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
)}
{mission && <MissionSummary mission={mission} busy={busyMission} onApprove={() => onApproveMission(mission)} onCancel={() => onCancelMission(mission)} />}
+ {mission && onView && (
+ <div role="group" aria-label="Show as" className="inline-flex rounded-lg border border-zinc-800 p-0.5" data-view-toggle>
+ {(['board', 'graph'] as const).map((v) => (
+ <button
+ key={v}
+ type="button"
+ aria-pressed={view === v}
+ onClick={() => onView(v)}
+ className={`min-h-[40px] sm:min-h-[32px] px-3 rounded-md text-xs font-medium ${focusRing} ${view === v ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200'}`}
+ >
+ {v === 'board' ? 'Board' : 'How tasks connect'}
+ </button>
+ ))}
+ </div>
+ )}
{drafts.map((m) => (
<MissionSummary key={m.id} mission={m} busy={busyMission} onApprove={() => onApproveMission(m)} onCancel={() => onCancelMission(m)} />
))}
- {empty ? (
+ {showGraph ? (
+ <WorkGraphView
+ graph={graph}
+ names={names}
+ loading={graphLoading}
+ error={graphError}
+ scanning={scanning}
+ now={now}
+ onOpenTask={(id) => {
+ const t = (tasks ?? []).find((x) => x.id === id);
+ if (t) onOpenTask(t);
+ }}
+ onScan={onScan}
+ onRetry={onRetryGraph}
+ />
+ ) : 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>
@@ -980,6 +1337,18 @@ export const MissionBoardPage: React.FC<{
const [detailError, setDetailError] = useState<string | null>(null);
const [detailNotice, setDetailNotice] = useState<{ text: string; error: boolean } | null>(null);
const [busy, setBusy] = useState(false);
+ const [view, setView] = useState<'board' | 'graph'>('board');
+ const [graph, setGraph] = useState<WorkGraph | null>(null);
+ const [graphLoading, setGraphLoading] = useState(false);
+ const [graphError, setGraphError] = useState<string | null>(null);
+ const [scanning, setScanning] = useState(false);
+ // One key per intent: a repeat of the same press (double click, retry after a dropped answer) reuses it.
+ const pendingKey = useRef<{ what: string; key: string } | null>(null);
+ const inFlight = useRef(false);
+ const keyFor = (what: string) => {
+ if (pendingKey.current?.what !== what) pendingKey.current = { what, key: newIdempotencyKey() };
+ return pendingKey.current.key;
+ };
const alive = useRef(true);
const openIdRef = useRef<string | null>(null);
openIdRef.current = openId;
@@ -1027,9 +1396,35 @@ export const MissionBoardPage: React.FC<{
};
}, [load]);
+ const loadGraph = useCallback(async (id: string) => {
+ setGraphLoading(true);
+ try {
+ const g = await missionsApi.graph(id);
+ if (!alive.current) return;
+ setGraph(g.mission_id === id ? g : { ...g, mission_id: id });
+ setGraphError(null);
+ } catch (e) {
+ if (alive.current) setGraphError(failMsg(e));
+ } finally {
+ if (alive.current) setGraphLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (view === 'graph' && missionId) loadGraph(missionId);
+ if (!missionId) setGraph(null);
+ }, [view, missionId, loadGraph]);
+
// Live: patch the list from each event; the open card re-reads its checks and activity.
const insightsTimer = useRef<number | null>(null);
+ const graphTimer = useRef<number | null>(null);
+ const graphMission = useRef<string | null>(null);
+ graphMission.current = view === 'graph' ? missionId : null;
useEffect(() => {
+ const refreshGraph = () => {
+ if (graphTimer.current) window.clearTimeout(graphTimer.current);
+ graphTimer.current = window.setTimeout(() => graphMission.current && loadGraph(graphMission.current), 800);
+ };
const refreshInsights = () => {
if (insightsTimer.current) window.clearTimeout(insightsTimer.current);
insightsTimer.current = window.setTimeout(() => missionsApi.insights().then((i) => alive.current && setInsights(i), () => {}), 1500);
@@ -1038,6 +1433,7 @@ export const MissionBoardPage: React.FC<{
if (!task || task.space_id !== spaceId) return;
setTasks((list) => (list ? upsertTask(list, task) : list));
if (openIdRef.current === task.id) loadDetail(task.id);
+ if (graphMission.current && task.mission_id === graphMission.current) refreshGraph();
refreshInsights();
});
const offMission = onMission('mission_updated', ({ mission }) => {
@@ -1048,8 +1444,9 @@ export const MissionBoardPage: React.FC<{
offTask();
offMission();
if (insightsTimer.current) window.clearTimeout(insightsTimer.current);
+ if (graphTimer.current) window.clearTimeout(graphTimer.current);
};
- }, [spaceId, loadDetail]);
+ }, [spaceId, loadDetail, loadGraph]);
const openTask = (id: string) => {
setOpenId(id);
@@ -1100,6 +1497,86 @@ export const MissionBoardPage: React.FC<{
}
};
+ const afterChange = async (changed: Task[], openNext: string | null) => {
+ setTasks((list) => (list ? changed.reduce((l, x) => upsertTask(l, x), list) : list));
+ if (graphMission.current) loadGraph(graphMission.current);
+ missionsApi.insights().then((i) => alive.current && setInsights(i), () => {});
+ if (openNext) await loadDetail(openNext);
+ };
+
+ const resolveFlag = async (f: OpenFlag, choice: ResolveChoice) => {
+ if (!openId || inFlight.current) return;
+ const taskId = openId;
+ inFlight.current = true;
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ const r = await missionsApi.resolveFlag(taskId, f.id, choice, keyFor(`resolve:${f.id}:${choice}`));
+ pendingKey.current = null;
+ if (!alive.current) return;
+ setDetailNotice({ text: resolvedText(choice, r), error: false });
+ playSfx('click');
+ if (r.task.state === 'cancelled') {
+ await afterChange([r.task], null);
+ closeTask();
+ } else await afterChange(r.fork ? [r.task, r.fork] : [r.task], taskId);
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ if (e instanceof MissionError && e.status === 409) pendingKey.current = null;
+ setDetailNotice({ text: flagErrorText(e), error: true });
+ // A 409 means the task moved on: show what it is now.
+ if (e instanceof MissionError && e.status === 409) await loadDetail(taskId);
+ } finally {
+ inFlight.current = false;
+ if (alive.current) setBusy(false);
+ }
+ };
+
+ const forkTask = async (reason: string) => {
+ if (!openId || inFlight.current) return;
+ const taskId = openId;
+ inFlight.current = true;
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ const fork = await missionsApi.fork(taskId, reason, keyFor(`fork:${taskId}`));
+ pendingKey.current = null;
+ if (!alive.current) return;
+ setDetailNotice({ text: `Made a copy to redo it: “${fork.title}”. It starts running on its own; this task stays Verified.`, error: false });
+ playSfx('click');
+ await afterChange([fork], taskId);
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ if (e instanceof MissionError && e.status >= 400 && e.status < 500 && e.status !== 401) pendingKey.current = null;
+ setDetailNotice({ text: flagErrorText(e), error: true });
+ } finally {
+ inFlight.current = false;
+ if (alive.current) setBusy(false);
+ }
+ };
+
+ const scan = async () => {
+ if (!missionId) return;
+ setScanning(true);
+ setNotice(null);
+ try {
+ const r = await missionsApi.scan(missionId);
+ if (!alive.current) return;
+ const n = r.flagged.length;
+ setNotice({ text: n === 0 ? `Checked ${r.scanned === 1 ? '1 file' : `${r.scanned} files`}. Nothing changed.` : n === 1 ? 'A file changed: 1 new “May be invalid” flag.' : `Files changed: ${n} new “May be invalid” flags.`, error: false });
+ await loadGraph(missionId);
+ 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) setScanning(false);
+ }
+ };
+
const missionAction = async (m: Mission, approve: boolean) => {
setBusyMission(true);
setNotice(null);
@@ -1141,8 +1618,19 @@ export const MissionBoardPage: React.FC<{
onOpenTask={(t) => openTask(t.id)}
onApproveMission={(m) => missionAction(m, true)}
onCancelMission={(m) => missionAction(m, false)}
- onRefresh={load}
+ onRefresh={() => {
+ load();
+ if (view === 'graph' && missionId) loadGraph(missionId);
+ }}
onBack={onBack}
+ view={view}
+ onView={setView}
+ graph={graph && graph.mission_id === missionId ? graph : null}
+ graphLoading={graphLoading}
+ graphError={graphError}
+ scanning={scanning}
+ onScan={scan}
+ onRetryGraph={() => missionId && loadGraph(missionId)}
/>
{openId && (
<TaskPanel title={detail?.task.title ?? listed?.title ?? 'Task'} onClose={closeTask}>
@@ -1155,6 +1643,8 @@ export const MissionBoardPage: React.FC<{
notice={detailNotice}
onAction={act}
onApproveCheck={approveCheck}
+ onResolveFlag={resolveFlag}
+ onFork={forkTask}
onOpenChat={
onOpenChat
? (t) => {
@@ -1166,7 +1656,7 @@ export const MissionBoardPage: React.FC<{
onOpenTask={(id) => {
const dep = tasksById[id];
if (dep) {
- const c = columnOf(dep.state);
+ const c = columnOfTask(dep);
if (c) setColumn(c);
}
openTask(id);
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 3d395656..dc2317ab 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -367,10 +367,19 @@ 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));
}
+/**
+ * Which column a task card sits in: its state's column, except that an open "may be invalid" flag puts
+ * it in Needs you (the flag waits for the person in any state, and Insights counts it there).
+ */
+export function columnOfTask(t: Pick<Task, 'state' | 'flags' | 'needs_you'>): Column | null {
+ const c = columnOf(t.state);
+ return c && openFlags(t).length ? 'needs_you' : c;
+}
+
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);
+ const c = columnOfTask(t);
if (c) out[c].push(t);
}
return out;
@@ -549,6 +558,192 @@ export function cardStatus(t: Task, names: Record<string, string> = {}, now: num
}
}
+// ---------------------------------------------------------------------------
+// "May be invalid" flags and forks (Phase B1, docs/mission-control.md §11)
+
+/** An open flag as the board shows it; `cause` is null when only the needs_you item arrived. */
+export interface OpenFlag {
+ id: string;
+ cause: FlagCause | null;
+ causeTaskId: string | null;
+ text: string;
+ createdAt: string | null;
+}
+
+const quote = (s: string | null | undefined) => (s && s.trim() ? `“${s.trim()}”` : 'a task it builds on');
+
+/** One plain sentence for why a task may no longer hold. */
+export function flagText(f: Pick<TaskFlag, 'cause' | 'cause_title' | 'detail'>): string {
+ const d = f.detail ?? {};
+ const path = str(d.path);
+ switch (f.cause) {
+ case 'evidence_changed':
+ if (path && d.new_sha256 === null) return `Its file ${path} is gone since it was verified`;
+ return path ? `Its file ${path} changed since it was verified` : 'A file it was verified with changed';
+ case 'upstream_evidence_changed':
+ return `A file from ${quote(f.cause_title)}, which this builds on, changed`;
+ case 'upstream_forked':
+ return `${quote(f.cause_title)}, which this builds on, is being redone`;
+ default:
+ return 'Something it depends on changed';
+ }
+}
+
+/**
+ * The task's open flags: from `flags` when the server sends them, plus any `may_be_invalid` needs_you
+ * item without one (so a flag is never hidden). Older servers send neither: no flags.
+ */
+export function openFlags(t: Pick<Task, 'flags' | 'needs_you'>): OpenFlag[] {
+ const out: OpenFlag[] = (t.flags ?? [])
+ .filter((f) => !f.resolved_at)
+ .map((f) => ({ id: f.id, cause: f.cause, causeTaskId: f.cause_task_id, text: flagText(f), createdAt: f.created_at }));
+ for (const n of t.needs_you ?? []) {
+ if (n.kind === 'may_be_invalid' && !out.some((f) => f.id === n.id)) {
+ out.push({ id: n.id, cause: null, causeTaskId: null, text: n.text.replace(/^Check this still holds:\s*/i, '') || 'Something it depends on changed', createdAt: null });
+ }
+ }
+ return out;
+}
+
+export type ResolveChoice = FlagResolution;
+
+export interface ResolveOption {
+ choice: ResolveChoice;
+ label: string;
+ /** What it does, in one line, for this task's state. */
+ hint: string;
+ /** Why it's off (it would get a 409), or null when it can be pressed. */
+ disabled: string | null;
+}
+
+/** The three ways the person can settle a flag, worded and enabled for the task's state (§11 table). */
+export function resolveOptions(state: TaskState): ResolveOption[] {
+ const running = state === 'working' || state === 'needs_you';
+ const redoHint: Partial<Record<TaskState, string>> = {
+ verified: 'Makes a copy of this task that starts running on its own. This one stays as it is.',
+ review: 'Sends it back to Ready for another try, with its tries reset.',
+ failed: 'Sends it back to Ready for another try, with its tries reset.',
+ blocked: 'Moves it back to Waiting so it can run again.',
+ backlog: 'It hasn’t run yet, so it will run again anyway. This just closes the flag.',
+ ready: 'It hasn’t run yet, so it will run again anyway. This just closes the flag.',
+ };
+ return [
+ { choice: 'still_valid', label: 'Still valid', hint: 'You checked: it still holds. Nothing else changes.', disabled: null },
+ {
+ choice: 'redo',
+ label: 'Redo',
+ hint: redoHint[state] ?? '',
+ disabled: running ? 'A bot is working on it. Decide once it stops.' : state === 'cancelled' ? 'It’s cancelled, so there’s nothing to redo.' : null,
+ },
+ {
+ choice: 'cancelled',
+ label: 'Cancel',
+ hint: state === 'cancelled' ? 'It’s already cancelled. This just closes the flag.' : 'Cancels the task.',
+ disabled: state === 'verified' ? 'A verified task can’t be cancelled. Choose Still valid or Redo.' : null,
+ },
+ ];
+}
+
+export const RESOLVE_DONE: Record<ResolveChoice, string> = {
+ still_valid: 'Marked still valid.',
+ redo: 'Sent back for another try.',
+ cancelled: 'Cancelled.',
+};
+
+/** What happened after a resolve, in one sentence. A fork says plainly that it runs on its own. */
+export function resolvedText(choice: ResolveChoice, r: Pick<ResolveFlagResult, 'fork' | 'task'>): string {
+ if (choice === 'redo' && r.fork) return `Made a copy to redo it: “${r.fork.title}”. It starts running on its own; this task stays as it was.`;
+ if (choice === 'redo' && (r.task.state === 'backlog' || r.task.state === 'ready')) return 'Flag closed. It will run again.';
+ if (choice === 'cancelled' && r.task.state === 'cancelled') return 'Cancelled.';
+ return RESOLVE_DONE[choice];
+}
+
+/** A plain message for a refused resolve or fork; 409 says what changed instead of the raw reason. */
+export function flagErrorText(e: unknown): string {
+ if (e instanceof MissionError && e.status === 409) {
+ const msg = e.message.toLowerCase();
+ if (msg.includes('already resolved')) return 'This flag was already settled, maybe in another tab. The board now shows the latest.';
+ if (msg.includes('running')) return 'A bot is working on it now. Decide once it stops.';
+ if (msg.includes('verified task can')) return 'A verified task can’t be cancelled. Choose Still valid or Redo.';
+ if (msg.includes('mission is cancelled')) return 'Its mission is cancelled, so it can’t be redone.';
+ if (msg.includes('cancelled')) return 'The task is cancelled, so there’s nothing to redo.';
+ return 'The task changed while you were deciding. The board now shows the latest; try again.';
+ }
+ return e instanceof Error ? e.message : 'Something went wrong.';
+}
+
+/** A fresh Idempotency-Key for one press, so a repeat of the same press can't make a second copy. */
+export function newIdempotencyKey(): string {
+ const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
+ if (c?.randomUUID) return c.randomUUID();
+ return `k-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
+}
+
+// ---------------------------------------------------------------------------
+// Work graph view
+
+export interface GraphRow {
+ node: GraphNode;
+ /** Tasks this one builds on (edge `from`), in graph order. */
+ after: GraphNode[];
+ /** How many tasks were flagged because of this one (open flags whose cause is this task, itself excluded). */
+ flaggedBecause: number;
+ /** "2 more tasks further down weren't flagged" when this task caused flags, else null. */
+ notFlaggedText: string | null;
+}
+
+export interface GraphLevel {
+ /** 1 for tasks that build on nothing, 2 for what follows them, and so on. */
+ step: number;
+ rows: GraphRow[];
+}
+
+/**
+ * Lays the graph out as steps: each task one step after the latest task it builds on. A list reads at
+ * 390 px where a drawn graph wouldn't. A loop (it shouldn't happen) lands in a last step, never lost.
+ */
+export function graphLevels(g: Pick<WorkGraph, 'nodes' | 'edges'>): GraphLevel[] {
+ const byId = new Map(g.nodes.map((n) => [n.id, n]));
+ const parents = new Map<string, string[]>(g.nodes.map((n) => [n.id, []]));
+ for (const e of g.edges) if (byId.has(e.from) && byId.has(e.to)) parents.get(e.to)!.push(e.from);
+ const level = new Map<string, number>();
+ const visiting = new Set<string>();
+ const depth = (id: string): number => {
+ const known = level.get(id);
+ if (known !== undefined) return known;
+ if (visiting.has(id)) return Number.POSITIVE_INFINITY;
+ visiting.add(id);
+ const ps = parents.get(id) ?? [];
+ const d = ps.length ? Math.max(...ps.map(depth)) + 1 : 1;
+ visiting.delete(id);
+ level.set(id, d);
+ return d;
+ };
+ const flaggedBy = new Map<string, number>();
+ for (const n of g.nodes) for (const f of n.flags ?? []) if (!f.resolved_at && f.cause_task_id !== n.id) flaggedBy.set(f.cause_task_id, (flaggedBy.get(f.cause_task_id) ?? 0) + 1);
+ const causes = new Set<string>();
+ for (const n of g.nodes) for (const f of n.flags ?? []) if (!f.resolved_at) causes.add(f.cause_task_id);
+ const steps = new Map<number, GraphRow[]>();
+ const finite = g.nodes.map((n) => depth(n.id)).filter(Number.isFinite);
+ const last = (finite.length ? Math.max(...finite) : 0) + 1;
+ for (const n of g.nodes) {
+ const d = Number.isFinite(depth(n.id)) ? depth(n.id) : last;
+ const flagged = flaggedBy.get(n.id) ?? 0;
+ const rest = Math.max(0, (n.downstream ?? 0) - flagged);
+ const row: GraphRow = {
+ node: n,
+ after: (parents.get(n.id) ?? []).map((id) => byId.get(id)!),
+ flaggedBecause: flagged,
+ notFlaggedText: causes.has(n.id) && rest > 0 ? (rest === 1 ? '1 more task further down wasn’t flagged' : `${rest} more tasks further down weren’t flagged`) : null,
+ };
+ if (!steps.has(d)) steps.set(d, []);
+ steps.get(d)!.push(row);
+ }
+ return [...steps.entries()]
+ .sort(([a], [b]) => a - b)
+ .map(([, rows], i) => ({ step: i + 1, rows: rows.sort((a, b) => a.node.title.localeCompare(b.node.title)) }));
+}
+
// ---------------------------------------------------------------------------
// Evidence receipt
@@ -629,6 +824,9 @@ export interface Receipt {
optionalWaiting: string | null;
/** The task is Verified: a waiting optional check is offered quietly ("Run this optional check"). */
settledVerified: boolean;
+ /** Whether a check's row is the quiet optional one: grey "Not run" and "Run this optional check". It
+ * can't hold the task in any state, so it never gets the amber hand or "Allow this check". */
+ quietOptional: (c: Pick<Check, 'status' | 'required'>) => boolean;
}
/** Builds the evidence receipt: every check with its result and output, newest result first per check. */
@@ -666,9 +864,13 @@ export function buildReceipt(d: Pick<TaskDetail, 'task' | 'checks' | 'evidence'>
waitingOnYou: review ? waitingApprovalText(requiredWaiting) : null,
optionalWaiting: settled ? optionalWaitingText(waitingChecks.length - requiredWaiting) : null,
settledVerified: d.task.state === 'verified',
+ quietOptional: isQuietOptional,
};
}
+/** An optional check waiting for the person: it can run, but it never holds the task. */
+export const isQuietOptional = (c: Pick<Check, 'status' | 'required'>): boolean => c.status === 'needs_approval' && !c.required;
+
/** 2 048 → "2 KB". */
export function formatBytes(n: number | null | undefined): string | null {
if (typeof n !== 'number' || !Number.isFinite(n)) return null;
@@ -724,6 +926,14 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
return 'It reached its token budget';
case 'edited':
return `${Who} edited it`;
+ case 'flagged':
+ return 'Flagged: it may no longer hold';
+ case 'flag_resolved': {
+ const r = str(d.resolution);
+ return `${Who} settled a flag: ${r === 'still_valid' ? 'still valid' : r === 'redo' ? 'redo' : r === 'cancelled' ? 'cancel' : 'decided'}`;
+ }
+ case 'forked':
+ return `${Who} made a copy to redo it${note ? `: ${note}` : ''}`;
default:
return `${Who}: ${humanize(e.kind)}`;
}
@@ -844,13 +1054,14 @@ export function errorFrom(status: number, answer: unknown): MissionError {
return new MissionError(err ?? `Something went wrong (HTTP ${status}).`, status);
}
-async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+async function call<T>(url: string, method = 'GET', body?: unknown, extra?: Record<string, string>): Promise<T> {
let res: Response;
+ const headers = { ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...extra };
try {
res = await personFetch(url, {
method,
cache: 'no-store',
- headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ headers: Object.keys(headers).length ? headers : undefined,
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (e) {
@@ -874,6 +1085,13 @@ export const missionsApi = {
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', {}),
+ graph: (missionId: string) => call<WorkGraph>(`/api/missions/${enc(missionId)}/graph`),
+ scan: (missionId: string) => call<GraphScanResult>(`/api/missions/${enc(missionId)}/graph/scan`, 'POST', {}),
+ /** Settle a flag. The key rides along on `redo` too, since a verified task's redo makes a copy. */
+ resolveFlag: (taskId: string, flagId: string, resolution: FlagResolution, key: string, note?: string) =>
+ call<ResolveFlagResult>(`/api/tasks/${enc(taskId)}/flags/${enc(flagId)}/resolve`, 'POST', note ? { resolution, note } : { resolution }, { 'Idempotency-Key': key }),
+ /** Copy a task to redo it; the same key returns the same copy. */
+ fork: (taskId: string, reason: string, key: string) => call<Task>(`/api/tasks/${enc(taskId)}/fork`, 'POST', { reason }, { 'Idempotency-Key': key }),
/** 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)}`;
diff --git a/frontend/tests/missionGraph.test.mjs b/frontend/tests/missionGraph.test.mjs
new file mode 100644
index 00000000..3f306a69
--- /dev/null
+++ b/frontend/tests/missionGraph.test.mjs
@@ -0,0 +1,253 @@
+// Mission board, Phase B1 (docs/mission-control.md §11): a verified task whose inputs may have changed
+// gets a "May be invalid" flag. It stays Verified; it waits in Needs you until the person says Still
+// valid, Redo or Cancel. Redo on a verified task makes a copy (a fork) that runs on its own.
+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, WorkGraphView, FlagBox } from './src/components/MissionBoardView';
+ 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 graph = (p) => r(WorkGraphView, p);
+ export const flagBox = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(FlagBox, p)));
+`);
+
+const NOW = Date.parse('2026-10-27T12:00:00Z');
+const noop = () => {};
+const names = { k_lin: 'Lin' };
+const passed = { status: 'passed', passed: 1, failed: 0, needs_approval: 0, required_needs_approval: 0, total: 1 };
+const task = (over = {}) => ({
+ id: 'a', space_id: 's1', mission_id: 'm1', mission_title: 'Pricing page', title: 'Write the copy', acceptance: 'docs/pricing.md exists',
+ state: 'verified', priority: 1, owner_kwant_id: 'k_lin', owner_name: 'Lin', suggested_kwant_id: null, budget_tokens: 0, spent_tokens: 18000,
+ attempts: 1, 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_lin', created_at: '2026-10-27T09:00:00Z', updated_at: '2026-10-27T11:00:00Z', finished_at: '2026-10-27T11:00:00Z',
+ depends_on: [], waiting_on: [], claim: null, needs_you: [], checks_summary: passed, forked_from: null, flags: [], ...over,
+});
+const flag = (over = {}) => ({
+ id: 'f1', kind: 'may_be_invalid', cause: 'evidence_changed', cause_task_id: 'a', cause_title: 'Write the copy',
+ detail: { path: 'docs/pricing.md', old_sha256: 'aa', new_sha256: 'bb' }, created_at: '2026-10-27T11:50:00Z', resolved_at: null, resolution: null, ...over,
+});
+const flagged = (f = flag(), over = {}) => task({ flags: [f], needs_you: [{ kind: 'may_be_invalid', id: f.id, text: 'Check this still holds: …' }], ...over });
+const detailProps = (t, over = {}) => ({ detail: { task: t, checks: [], evidence: [], events: [] }, names, now: NOW, onAction: noop, onApproveCheck: noop, onOpenTask: noop, onResolveFlag: noop, onFork: noop, ...over });
+
+test('flag wording covers each cause, a gone file, and a missing title', () => {
+ assert.equal(m.flagText(flag()), 'Its file docs/pricing.md changed since it was verified');
+ assert.equal(m.flagText(flag({ detail: { path: 'docs/pricing.md', old_sha256: 'aa', new_sha256: null } })), 'Its file docs/pricing.md is gone since it was verified');
+ assert.equal(m.flagText(flag({ detail: {} })), 'A file it was verified with changed');
+ assert.equal(m.flagText(flag({ cause: 'upstream_evidence_changed' })), 'A file from “Write the copy”, which this builds on, changed');
+ assert.equal(m.flagText(flag({ cause: 'upstream_forked' })), '“Write the copy”, which this builds on, is being redone');
+ assert.equal(m.flagText(flag({ cause: 'upstream_forked', cause_title: null })), 'a task it builds on, which this builds on, is being redone');
+ assert.equal(m.flagText(flag({ cause: 'something_new' })), 'Something it depends on changed');
+});
+
+test('open flags come from `flags`, fall back to the needs_you item, and missing fields mean none', () => {
+ assert.deepEqual(m.openFlags(task({ flags: undefined, needs_you: [] })), []);
+ assert.deepEqual(m.openFlags({ needs_you: [] }), [], 'an older server sends no flags field');
+ assert.equal(m.openFlags(task({ flags: [flag({ resolved_at: '2026-10-27T11:55:00Z', resolution: 'still_valid' })] })).length, 0, 'a resolved flag is not open');
+ const both = m.openFlags(flagged());
+ assert.equal(both.length, 1, 'the needs_you item for a listed flag is not counted twice');
+ assert.equal(both[0].cause, 'evidence_changed');
+ const only = m.openFlags(task({ flags: undefined, needs_you: [{ kind: 'may_be_invalid', id: 'f9', text: 'Check this still holds: the file changed' }] }));
+ assert.deepEqual(only.map((f) => [f.id, f.cause, f.text]), [['f9', null, 'the file changed']]);
+});
+
+test('a flagged task sits in Needs you, stays Verified, and the card says why', () => {
+ const t = flagged();
+ assert.equal(m.columnOf(t.state), 'verified');
+ assert.equal(m.columnOfTask(t), 'needs_you');
+ assert.equal(m.columnOfTask(task()), 'verified');
+ assert.equal(m.columnOfTask(task({ state: 'cancelled', flags: [flag()] })), null, 'cancelled stays off the board');
+ const g = m.groupByColumn([t, task({ id: 'b' })]);
+ assert.deepEqual(g.needs_you.map((x) => x.id), ['a']);
+ assert.deepEqual(g.verified.map((x) => x.id), ['b']);
+ const c = ui.card({ task: t, names, now: NOW, onOpen: noop });
+ assert.match(c, /data-flag-badge[^>]*><span[^>]*>May be invalid</);
+ assert.match(c, />Verified</, 'the card still says Verified');
+ assert.match(c, /data-flag-line[\s\S]*Its file docs\/pricing\.md changed since it was verified/);
+ const plain = ui.card({ task: task({ flags: undefined }), names, now: NOW, onOpen: noop });
+ assert.doesNotMatch(plain, /May be invalid|data-flag-line/);
+ const html = ui.view({ tasks: [t], missions: [], insights: null, names, missionId: null, column: 'needs_you', loading: false, error: null, now: NOW, onMission: noop, onColumn: noop, onOpenTask: noop, onApproveMission: noop, onCancelMission: noop, onRefresh: noop });
+ assert.doesNotMatch(html.slice(html.indexOf('data-column="needs_you"')).split('data-column="review"')[0], /Nothing needs you/);
+});
+
+test('resolve choices follow the server rules: Cancel is off on Verified, Redo off while running', () => {
+ const by = (s) => Object.fromEntries(m.resolveOptions(s).map((o) => [o.choice, o]));
+ const v = by('verified');
+ assert.deepEqual(m.resolveOptions('verified').map((o) => o.label), ['Still valid', 'Redo', 'Cancel']);
+ assert.equal(v.still_valid.disabled, null);
+ assert.equal(v.redo.disabled, null);
+ assert.match(v.redo.hint, /copy of this task that starts running on its own/);
+ assert.match(v.cancelled.disabled, /verified task can’t be cancelled/);
+ for (const s of ['working', 'needs_you']) {
+ assert.match(by(s).redo.disabled, /working on it/, s);
+ assert.equal(by(s).cancelled.disabled, null, s);
+ }
+ assert.match(by('cancelled').redo.disabled, /cancelled/);
+ assert.match(by('review').redo.hint, /back to Ready/);
+ assert.match(by('blocked').redo.hint, /back to Waiting/);
+ assert.match(by('ready').redo.hint, /just closes the flag/);
+});
+
+test('the detail shows the flag with three choices; Cancel is disabled on a verified task', () => {
+ const html = ui.detail(detailProps(flagged()));
+ const box = html.slice(html.indexOf('data-flags'));
+ assert.match(box, /May be invalid: <\/span>Its file docs\/pricing\.md changed since it was verified\. It stays Verified until you decide\./);
+ assert.match(box, /<button[^>]*data-resolve="still_valid"[^>]*>Still valid</);
+ assert.doesNotMatch(box.match(/<button[^>]*data-resolve="still_valid"[^>]*>/)[0], /\sdisabled=""/);
+ assert.doesNotMatch(box.match(/<button[^>]*data-resolve="redo"[^>]*>/)[0], /\sdisabled=""/);
+ assert.match(box.match(/<button[^>]*data-resolve="cancelled"[^>]*>/)[0], /\sdisabled=""/);
+ assert.match(box, /data-resolve-off="cancelled"[^>]*>A verified task can’t be cancelled/);
+ assert.match(box, /starts running on its own/);
+ // The flag isn't also listed as a question with "Answer in chat".
+ assert.doesNotMatch(html, /data-needs-you/);
+ assert.doesNotMatch(html, /Question: Check this still holds/);
+ // Running: Redo off. Upstream cause: a link to the task it builds on.
+ const running = ui.detail(detailProps(flagged(flag({ cause: 'upstream_evidence_changed', cause_task_id: 'up' }), { state: 'working' })));
+ assert.match(running.match(/<button[^>]*data-resolve="redo"[^>]*>/)[0], /\sdisabled=""/);
+ assert.match(running, /data-flag-cause-link[^>]*>Open “Write the copy”</);
+ // Without a resolve handler (e.g. read-only), no buttons.
+ const ro = ui.flagBox({ flag: m.openFlags(flagged())[0], state: 'verified' });
+ assert.doesNotMatch(ro, /data-resolve=/);
+});
+
+test('after resolving: a fork says plainly it runs on its own; 409s read as what changed', () => {
+ const fork = task({ id: 'a2', title: 'Write the copy', state: 'backlog', forked_from: 'a' });
+ assert.match(m.resolvedText('redo', { task: task(), fork }), /Made a copy to redo it: “Write the copy”\. It starts running on its own; this task stays as it was\./);
+ assert.equal(m.resolvedText('redo', { task: task({ state: 'ready' }), fork: null }), 'Flag closed. It will run again.');
+ assert.equal(m.resolvedText('still_valid', { task: task(), fork: null }), 'Marked still valid.');
+ assert.equal(m.resolvedText('cancelled', { task: task({ state: 'cancelled' }), fork: null }), 'Cancelled.');
+ const e409 = (msg) => m.errorFrom(409, { error: msg });
+ assert.match(m.flagErrorText(e409('this flag is already resolved')), /already settled, maybe in another tab/);
+ assert.match(m.flagErrorText(e409("it's running; resolve when it stops")), /working on it now/);
+ assert.match(m.flagErrorText(e409("a verified task can't be cancelled; choose still_valid or redo")), /A verified task can’t be cancelled\. Choose Still valid or Redo\./);
+ assert.match(m.flagErrorText(e409('the mission is cancelled')), /mission is cancelled/);
+ assert.match(m.flagErrorText(e409('the task is cancelled; fork it to redo it')), /The task is cancelled/);
+ assert.match(m.flagErrorText(e409('')), /changed while you were deciding/);
+ assert.match(m.flagErrorText(m.errorFrom(400, { error: 'reason is required' })), /Reason is required/);
+});
+
+test('fork and resolve send an Idempotency-Key; the same key is reused on a repeat', async () => {
+ const calls = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async (url, init) => {
+ calls.push({ url: String(url), init });
+ const body = String(url).includes('/fork') ? task({ id: 'a2', forked_from: 'a', state: 'backlog' }) : { flag: flag({ resolved_at: 'x', resolution: 'redo' }), task: task(), fork: task({ id: 'a2', forked_from: 'a' }) };
+ return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } });
+ };
+ try {
+ const k = m.newIdempotencyKey();
+ assert.ok(k.length >= 8 && k.length <= 200);
+ assert.notEqual(k, m.newIdempotencyKey());
+ const f = await m.missionsApi.fork('a', 'the file changed', k);
+ assert.equal(f.forked_from, 'a');
+ await m.missionsApi.fork('a', 'the file changed', k);
+ await m.missionsApi.resolveFlag('a', 'f1', 'redo', 'key-2');
+ const hdr = (c) => new Headers(c.init.headers).get('Idempotency-Key');
+ assert.equal(calls[0].url, '/api/tasks/a/fork');
+ assert.equal(calls[0].init.method, 'POST');
+ assert.deepEqual(JSON.parse(calls[0].init.body), { reason: 'the file changed' });
+ assert.equal(hdr(calls[0]), k);
+ assert.equal(hdr(calls[1]), k, 'a repeat carries the same key');
+ assert.equal(calls[2].url, '/api/tasks/a/flags/f1/resolve');
+ assert.deepEqual(JSON.parse(calls[2].init.body), { resolution: 'redo' });
+ assert.equal(hdr(calls[2]), 'key-2');
+ assert.equal(new Headers(calls[2].init.headers).get('Content-Type'), 'application/json');
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
+
+test('"Copied from" links to the original; the original lists its copy; Redo as a copy is on Verified only', () => {
+ const orig = task();
+ const fork = task({ id: 'a2', state: 'ready', forked_from: 'a', finished_at: null });
+ const byId = { a: orig, a2: fork };
+ const fh = ui.detail(detailProps(fork, { tasksById: byId }));
+ assert.match(fh, /data-copied-from[\s\S]*Copied from[\s\S]*<button[^>]*>“Write the copy”<\/button>/);
+ const oh = ui.detail(detailProps(orig, { tasksById: byId }));
+ assert.match(oh, /data-redone-as="a2"[\s\S]*Redone as[\s\S]*“Write the copy”/);
+ assert.match(oh, /data-fork[^>]*>[\s\S]*Redo as a copy</);
+ // Original not loaded (another space, or cancelled): still a link, without a title.
+ const lone = ui.detail(detailProps(fork, { tasksById: {} }));
+ assert.match(lone, /Copied from[\s\S]*>an earlier task</);
+ // Missing field: nothing about copies.
+ const old = ui.detail(detailProps(task({ forked_from: undefined, state: 'review' })));
+ assert.doesNotMatch(old, /data-copies|Redo as a copy/);
+ const c = ui.card({ task: fork, names, now: NOW, onOpen: noop });
+ assert.match(c, /data-forked-from[^>]*>A copy, made to redo an earlier task</);
+});
+
+const node = (over = {}) => ({ id: 'a', title: 'A', state: 'verified', owner_kwant_id: 'k_lin', owner_name: 'Lin', attempts: 1, max_attempts: 3, forked_from: null, downstream: 0, flags: [], checks_summary: passed, ...over });
+
+test('graph steps follow the edges; the cause shows how many further down were not flagged', () => {
+ // A → B → C, A → D (not started); A's file changed: A and B flagged, C and D not.
+ const g = {
+ mission_id: 'm1', scanned_at: '2026-10-27T11:50:00Z', scan_skipped: [],
+ nodes: [
+ node({ id: 'c', title: 'C' }),
+ node({ id: 'b', title: 'B', downstream: 1, flags: [flag({ id: 'fb', cause: 'upstream_evidence_changed', cause_task_id: 'a', cause_title: 'A' })] }),
+ node({ id: 'a', title: 'A', downstream: 3, flags: [flag({ cause_title: 'A' })] }),
+ node({ id: 'd', title: 'D', state: 'backlog' }),
+ node({ id: 'a2', title: 'A', state: 'ready', forked_from: 'a' }),
+ ],
+ edges: [{ from: 'a', to: 'b' }, { from: 'b', to: 'c' }, { from: 'a', to: 'd' }],
+ };
+ const lv = m.graphLevels(g);
+ assert.deepEqual(lv.map((l) => [l.step, l.rows.map((r) => r.node.id)]), [[1, ['a', 'a2']], [2, ['b', 'd']], [3, ['c']]]);
+ const a = lv[0].rows[0];
+ assert.equal(a.flaggedBecause, 1);
+ assert.equal(a.notFlaggedText, '2 more tasks further down weren’t flagged');
+ assert.equal(lv[1].rows[0].notFlaggedText, null, 'B caused no flags');
+ assert.deepEqual(lv[2].rows[0].after.map((n) => n.id), ['b']);
+ assert.equal(m.graphLevels({ nodes: [node({ downstream: 2, flags: [flag()] }), node({ id: 'b', flags: [flag({ id: 'x', cause: 'upstream_evidence_changed', cause_task_id: 'a' })] })], edges: [{ from: 'a', to: 'b' }] })[0].rows[0].notFlaggedText, '1 more task further down wasn’t flagged');
+ // A loop (shouldn't happen) still lists every task.
+ const loop = m.graphLevels({ nodes: [node({ id: 'x' }), node({ id: 'y' })], edges: [{ from: 'x', to: 'y' }, { from: 'y', to: 'x' }] });
+ assert.equal(loop.flatMap((l) => l.rows).length, 2);
+
+ const html = ui.graph({ graph: g, names, now: NOW, onOpenTask: noop, onScan: noop });
+ assert.match(html, /How the tasks connect/);
+ assert.match(html, /Files last checked for changes 10 min ago · 2 may be invalid/);
+ assert.match(html, /data-graph-step="1"[\s\S]*Step 1 · builds on nothing/);
+ assert.match(html, /data-graph-node="c"[\s\S]*?data-graph-after[^>]*>After “B”</);
+ assert.match(html, /data-graph-node="a2"[\s\S]*?data-graph-forked[^>]*>Copied from “A”</);
+ assert.match(html, /data-graph-node="b"[\s\S]*?data-graph-flag="upstream_evidence_changed"/);
+ assert.match(html, /data-graph-not-flagged[^>]*>2 more tasks further down weren’t flagged</);
+ assert.match(html, /data-scan[^>]*>[\s\S]*Check files now/);
+});
+
+test('graph states: loading, error, empty, never scanned, skipped files', () => {
+ assert.match(ui.graph({ graph: null, names, loading: true, onOpenTask: noop }), /Loading…/);
+ const err = ui.graph({ graph: null, names, error: 'Couldn’t reach the server.', onOpenTask: noop, onRetry: noop });
+ assert.match(err, /role="alert"[\s\S]*Couldn’t load how the tasks connect\. Couldn’t reach the server\.[\s\S]*Retry/);
+ const empty = ui.graph({ graph: { mission_id: 'm1', nodes: [], edges: [], scanned_at: null, scan_skipped: [] }, names, onOpenTask: noop });
+ assert.match(empty, /data-graph-empty[^>]*>This mission has no tasks yet\./);
+ assert.match(empty, /Files haven’t been checked for changes yet/);
+ const skipped = ui.graph({ graph: { mission_id: 'm1', nodes: [node()], edges: [], scanned_at: null, scan_skipped: [{ task_id: 'a', path: 'big.bin', why: 'over 50 MB' }] }, names, onOpenTask: noop });
+ assert.match(skipped, /1 file wasn’t checked/);
+});
+
+test('the board offers "How tasks connect" only with a mission picked', () => {
+ const mission = { id: 'm1', space_id: 's1', title: 'Pricing page', goal: '', status: 'active', lead_kwant_id: 'k_lin', lead_name: 'Lin', channel_id: null, direct_kwant_id: null, thread_id: null, budget_tokens: 0, spent_tokens: 0, reserved_tokens: 0, over_budget: false, created_by: 'k_lin', approved_at: null, approved_by: null, created_at: '', updated_at: '', finished_at: null, counts: { backlog: 0, ready: 0, working: 0, needs_you: 0, review: 0, verified: 1, blocked: 0, failed: 0, cancelled: 0 } };
+ const base = { tasks: [task()], missions: [mission], insights: null, names, column: 'ready', loading: false, error: null, now: NOW, onMission: noop, onColumn: noop, onOpenTask: noop, onApproveMission: noop, onCancelMission: noop, onRefresh: noop, onView: noop };
+ assert.doesNotMatch(ui.view({ ...base, missionId: null }), /data-view-toggle/);
+ const board = ui.view({ ...base, missionId: 'm1', view: 'board' });
+ assert.match(board, /data-view-toggle[\s\S]*aria-pressed="true"[^>]*>Board</);
+ assert.match(board, /data-board="tabs"/);
+ const g = ui.view({ ...base, missionId: 'm1', view: 'graph', graph: { mission_id: 'm1', nodes: [node()], edges: [], scanned_at: null, scan_skipped: [] } });
+ assert.match(g, /data-graph/);
+ assert.doesNotMatch(g, /data-board="tabs"/);
+});
+
+test('activity reads flag and fork events plainly', () => {
+ const ev = (kind, detail = {}, actor = 'person') => ({ id: 1, task_id: 'a', mission_id: 'm1', kind, actor, actor_name: null, from_state: null, to_state: null, detail, created_at: '' });
+ assert.equal(m.eventText(ev('flagged', {}, 'kwant')), 'Flagged: it may no longer hold');
+ assert.equal(m.eventText(ev('flag_resolved', { resolution: 'still_valid' })), 'You settled a flag: still valid');
+ assert.equal(m.eventText(ev('forked', { reason: 'the file changed' })), 'You made a copy to redo it: the file changed');
+});
diff --git a/frontend/tests/missions.test.mjs b/frontend/tests/missions.test.mjs
index 885f1cce..315e20af 100644
--- a/frontend/tests/missions.test.mjs
+++ b/frontend/tests/missions.test.mjs
@@ -295,8 +295,11 @@ test('a Review task with a required check still running and an optional one wait
const html = ui.detail({ detail: d, names, now: NOW, onAction: noop, onApproveCheck: noop, onOpenChat: noop });
assert.match(html, /Optional check waiting for your OK\. It doesn’t hold the task/);
assert.doesNotMatch(html, /Not verified yet\. Waiting for you/);
- assert.match(html, /Allow this check/, 'in Review the normal Allow button stays');
- assert.doesNotMatch(html, /Run this optional check/);
+ // Rigel eval 6: an optional check can't hold the task, so in Review it's the quiet row too.
+ const row = html.slice(html.indexOf('data-check="ch3"'));
+ assert.match(row, /data-run-optional[^>]*>Run this optional check</);
+ assert.doesNotMatch(row, /Allow this check/);
+ assert.doesNotMatch(row, /A bot added this check\. It runs only after you OK it/);
});
test('the card says "Needs you" only when a required check waits for your OK (required_needs_approval)', () => {
@@ -346,10 +349,14 @@ test('the quiet "Not run" optional row on a Verified task has a grey icon, not t
const row = html.slice(html.indexOf('data-check="ch3"'));
assert.match(row, /Not run/);
assert.doesNotMatch(row.slice(0, row.indexOf('Not run')), /text-amber-300/);
- // In Review the same check still shows the amber hand: it is waiting on you there.
+ // In Review an optional check is quiet too (it can't hold the task); a required one keeps the amber hand.
const review = ui.receipt({ task: task({ state: 'review' }), checks: [optional], evidence: [], events: [] }, names);
const rrow = review.slice(review.indexOf('data-check="ch3"'));
- assert.match(rrow.slice(0, rrow.indexOf('Needs your OK')), /text-amber-300/);
+ assert.match(rrow, /Not run/);
+ assert.doesNotMatch(rrow, /text-amber-300|text-amber-200|Needs your OK/);
+ const req = ui.receipt({ task: task({ state: 'review' }), checks: [{ ...optional, required: true }], evidence: [], events: [] }, names);
+ const qrow = req.slice(req.indexOf('data-check="ch3"'));
+ assert.match(qrow.slice(0, qrow.indexOf('Needs your OK')), /text-amber-300/);
});
test('only web links open; file paths and other schemes are shown as text', () => {