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: AutoFix, workflow-change approvals and restore holds (B3 UI + D10/D11)

Pixele396b04d7cc1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1dc40f8a..ea008922 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
+- **Mission board: AutoFix, change approvals and restore.** A failed task shows why it failed in plain
+ words, what AutoFix plans, its tries and what retries cost, with Retry now and Don't retry. Proposed
+ changes to a check, the acceptance or a routine appear in Needs you with before and after, and only
+ you can approve them. A task's checkpoints can be previewed and restored from its panel; a restore
+ puts the task on hold until you press Run, or pick "Restore and run again". Settings has an AutoFix
+ switch (off by default) and the retry budget; Insights counts what AutoFix fixed.
- **Mission Control: AutoFix (backend).** Every failed task now records why it failed, with secrets
masked. Turn on the new `autofix` setting (off by default, or "suggest" to approve each retry) and
kwant retries what is safe to retry: after a temporary error it waits 1, 5, then 25 minutes; after a
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 6e323fdb..a1c36d75 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -9,15 +9,20 @@ import {
ExternalLink,
FileText,
GitBranch,
+ History,
Hand,
Image as ImageIcon,
Link2,
Loader2,
MessageSquare,
+ PauseCircle,
+ Play,
RefreshCw,
+ RotateCcw,
ShieldCheck,
StickyNote,
Target,
+ Wrench,
X,
XCircle,
} from 'lucide-react';
@@ -26,6 +31,26 @@ import { playSfx } from '../audio/chiptune';
import {
ACTION_DONE,
ACTION_LABELS,
+ AutofixAttempt,
+ Checkpoint,
+ NeedsYouItem,
+ RESTORE_ACTION_LABELS,
+ RestorePreview,
+ RestoreResult,
+ TaskFailure,
+ WorkflowChange,
+ autofixCardText,
+ autofixStatusText,
+ changeRows,
+ checkpointLabel,
+ conflictText,
+ failureClassLabel,
+ failureTone,
+ autofixErrorText,
+ recoveryText,
+ restoreErrorText,
+ restoredText,
+ workflowTargetLabel,
COLUMNS,
Check,
Column,
@@ -168,12 +193,26 @@ export const InsightsStrip: React.FC<{ insights: Insights | null }> = ({ insight
hint: `${formatTokens(insights.tokens_7d)} tokens used in the last 7 days`,
},
];
+ const af = insights.autofix_7d;
+ if (af) {
+ const byClass = Object.entries(insights.failures_by_class_7d ?? {})
+ .filter(([, n]) => (n ?? 0) > 0)
+ .sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0))
+ .map(([c, n]) => `${failureClassLabel(c)}: ${n}`);
+ items.push({
+ label: 'Fixed by AutoFix',
+ value: af.attempts > 0 ? `${af.succeeded} of ${af.attempts}` : '0',
+ hint: `Retries AutoFix ran in the last 7 days, and how many ended Verified.${byClass.length ? ` Failures: ${byClass.join(', ')}.` : ''}`,
+ tone: af.succeeded > 0 ? 'emerald' : undefined,
+ sub: af.attempts > 0 ? `${formatTokens(af.tokens)} tokens on retries` : 'No retries this week',
+ });
+ }
const valueTone: Partial<Record<Tone, string>> = { emerald: 'text-emerald-300', rose: 'text-rose-300', amber: 'text-amber-300' };
return (
<section aria-label="This week" data-insights>
- <dl className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
+ <dl className={`grid grid-cols-2 sm:grid-cols-3 ${items.length > 5 ? 'lg:grid-cols-6' : 'lg:grid-cols-5'} gap-2`}>
{items.map((it, i) => (
- <div key={it.label} title={it.hint} className={`${card} px-3 py-2 ${i === items.length - 1 ? 'col-span-2 sm:col-span-1' : ''}`}>
+ <div key={it.label} title={it.hint} className={`${card} px-3 py-2 ${i === items.length - 1 && items.length % 2 === 1 ? 'col-span-2 sm:col-span-1' : ''}`}>
<dt className="text-[11px] text-zinc-400 truncate">{it.label}</dt>
<dd className={`text-lg font-semibold tabular-nums ${it.tone ? valueTone[it.tone] ?? 'text-zinc-100' : 'text-zinc-100'}`}>{it.value}</dd>
{it.sub && <dd className="text-[10px] text-zinc-400 truncate">{it.sub}</dd>}
@@ -247,7 +286,8 @@ export const TaskCard: React.FC<{
const optionalNote = optionalChecksNote(t.checks_summary);
const status = cardStatus(t, names, now);
const flags = openFlags(t);
- const dimmed = t.state === 'backlog' && !flags.length;
+ const dimmed = t.state === 'backlog' && !flags.length && !t.held_at;
+ const autofixLive = !!autofixCardText(t, now);
return (
<li data-task={t.id} data-state={t.state}>
<button
@@ -258,7 +298,17 @@ export const TaskCard: React.FC<{
<span className="flex flex-wrap items-center gap-1.5">
{t.state === 'blocked' && <Badge tone="rose">Blocked</Badge>}
{t.state === 'failed' && <Badge tone="rose">Failed</Badge>}
- {t.state === 'backlog' && <Badge tone="zinc">Waiting</Badge>}
+ {t.state === 'backlog' && !t.held_at && <Badge tone="zinc">Waiting</Badge>}
+ {t.held_at && (t.state === 'ready' || t.state === 'backlog') && (
+ <span data-held-badge>
+ <Badge tone="amber">On hold</Badge>
+ </span>
+ )}
+ {autofixLive && (
+ <span data-autofix-badge>
+ <Badge tone="violet">AutoFix</Badge>
+ </span>
+ )}
{t.state === 'review' && approvalHolds(t.checks_summary) && <Badge tone="amber">Needs you</Badge>}
{flags.length > 0 && (
<span data-flag-badge>
@@ -271,7 +321,7 @@ export const TaskCard: React.FC<{
</span>
<span className="block text-sm font-medium text-zinc-100 break-words">{t.title}</span>
{status && (
- <span className={`block text-[11px] break-words line-clamp-2 ${t.state === 'needs_you' || (t.state === 'review' && approvalHolds(t.checks_summary)) ? 'text-amber-200' : t.state === 'blocked' || t.state === 'failed' ? 'text-rose-300' : 'text-zinc-400'}`}>
+ <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}
</span>
)}
@@ -629,8 +679,482 @@ export const FlagBox: React.FC<{
);
};
+// ---------- AutoFix, workflow changes and restore holds ----------
+
+/** A task a restore put on hold: nothing picks it up until the person presses Run (D10). */
+export const HeldBox: React.FC<{ task: Task; busy?: boolean; now?: number; onRun?: () => void }> = ({ task, busy = false, now = Date.now(), onRun }) => (
+ <section aria-labelledby="held-h" 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-held>
+ <h4 id="held-h" className="flex items-center gap-1.5 font-semibold">
+ <PauseCircle size={14} className="shrink-0 text-amber-300" aria-hidden="true" />
+ On hold after restore
+ </h4>
+ <p>
+ You restored its files {task.held_at ? ago(task.held_at, now) : ''}. No bot picks it up until you press Run, so you can look at the files first.
+ </p>
+ {onRun && (
+ <button type="button" disabled={busy} onClick={onRun} className={mainBtn} data-run-held>
+ <Play size={13} aria-hidden="true" /> Run
+ </button>
+ )}
+ </section>
+);
+
+/** Why the task failed last, what AutoFix is doing about it, and what retries cost. */
+export const FailureBox: React.FC<{
+ task: Task;
+ failures?: TaskFailure[];
+ /** The "fix it yourself" text for a failure AutoFix never retries. */
+ fixText?: string | null;
+ busy?: boolean;
+ now?: number;
+ onRetry?: (failureId?: string) => void;
+ onSkip?: (a: AutofixAttempt) => void;
+}> = ({ task, failures = [], fixText, busy = false, now = Date.now(), onRetry, onSkip }) => {
+ const f = task.last_failure;
+ const a = task.autofix ?? null;
+ const recovery = recoveryText(task);
+ if (!f && !a) return null;
+ const tone = f ? failureTone(f.class) : 'violet';
+ const status = a ? autofixStatusText(a, now) : null;
+ const waiting = a && a.status === 'suggested' && a.strategy !== 'propose_change' && (task.state === 'failed' || task.state === 'blocked');
+ const scheduled = a && a.status === 'scheduled';
+ const earlier = failures.slice(0, -1).reverse();
+ const latest = failures[failures.length - 1];
+ return (
+ <section aria-labelledby="fail-h" className="space-y-2" data-failure>
+ <h4 id="fail-h" className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">
+ <Wrench size={13} className="text-zinc-400" aria-hidden="true" />
+ What went wrong
+ </h4>
+ <div className={`${card} px-3 py-2.5 space-y-2 text-xs`}>
+ {f && (
+ <p className="flex flex-wrap items-start gap-1.5 break-words">
+ <span data-failure-class={f.class}>
+ <Badge tone={tone}>{failureClassLabel(f.class)}</Badge>
+ </span>
+ <span className="flex-1 min-w-[10rem] text-zinc-200">{f.summary}</span>
+ <span className="text-[11px] text-zinc-500">{ago(f.created_at, now)}</span>
+ </p>
+ )}
+ {fixText && (
+ <p className="px-2.5 py-2 rounded-md border border-amber-500/30 bg-amber-500/10 text-amber-100" data-fix-needed>
+ <span className="font-medium">To fix: </span>
+ {fixText}
+ </p>
+ )}
+ {latest?.excerpt && (
+ <details className="text-[11px]">
+ <summary className={`cursor-pointer text-zinc-400 hover:text-zinc-200 rounded ${focusRing}`}>Show the output</summary>
+ <pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded bg-zinc-950 p-2 text-zinc-300">{latest.excerpt}</pre>
+ </details>
+ )}
+ {status && (
+ <p className="flex items-start gap-1.5 text-violet-200" data-autofix-status={a!.status}>
+ <RefreshCw size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{status}</span>
+ </p>
+ )}
+ {(waiting || scheduled) && (onRetry || onSkip) && (
+ <div className="flex flex-wrap gap-2">
+ {onRetry && (
+ <button type="button" disabled={busy} onClick={() => onRetry(latest?.id)} className={mainBtn} data-autofix-retry>
+ <RefreshCw size={13} aria-hidden="true" /> Retry now
+ </button>
+ )}
+ {onSkip && (
+ <button type="button" disabled={busy} onClick={() => onSkip(a!)} className={quietBtn} data-autofix-skip>
+ Don’t retry
+ </button>
+ )}
+ </div>
+ )}
+ <dl className="grid grid-cols-2 gap-3 pt-1">
+ <Fact label="AutoFix tries">
+ {failures.filter((x) => x.autofix && x.autofix.status !== 'suggested' && x.autofix.status !== 'skipped').length || (a && a.status !== 'suggested' && a.status !== 'skipped' ? 1 : 0)}
+ </Fact>
+ {recovery && <Fact label="Spent on retries">{recovery}</Fact>}
+ </dl>
+ {earlier.length > 0 && (
+ <details className="text-[11px]" data-earlier-failures>
+ <summary className={`cursor-pointer text-zinc-400 hover:text-zinc-200 rounded ${focusRing}`}>Earlier failures ({earlier.length})</summary>
+ <ul className="mt-1 space-y-1.5">
+ {earlier.map((x) => (
+ <li key={x.id} className="break-words text-zinc-400">
+ <span className="text-zinc-300">Try {x.attempt}:</span> {failureClassLabel(x.class)}. {x.summary}
+ {x.autofix && <span className="block text-zinc-500">{autofixStatusText(x.autofix, now)}</span>}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ </div>
+ </section>
+ );
+};
+
+/** A change AutoFix proposes to the task's setup, before and after; only the person approves it. */
+export const WorkflowChangeBox: React.FC<{
+ item: NeedsYouItem;
+ change?: WorkflowChange | null;
+ names?: Record<string, string>;
+ busy?: boolean;
+ now?: number;
+ onDecide?: (id: string, approve: boolean) => void;
+}> = ({ item, change, names = {}, busy = false, now = Date.now(), onDecide }) => {
+ const rows = change ? changeRows(change.before, change.after) : [];
+ const changed = rows.filter((r) => r.changed);
+ const same = rows.filter((r) => !r.changed);
+ const by = change ? (change.proposed_by === 'kwant' ? 'AutoFix' : change.proposed_by_name || names[change.proposed_by] || 'A bot') : null;
+ const Cell: React.FC<{ label: string; value: string; tone: 'before' | 'after' }> = ({ label, value, tone }) => (
+ <div className={`min-w-0 rounded-md px-2 py-1.5 ${tone === 'before' ? 'bg-zinc-950/60 text-zinc-400' : 'bg-emerald-500/10 text-emerald-100'}`}>
+ <p className="text-[10px] uppercase tracking-wide opacity-70">{label}</p>
+ <p className="whitespace-pre-wrap break-words font-mono text-[11px]">{value}</p>
+ </div>
+ );
+ 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-workflow-change={item.id}>
+ <p className="break-words">
+ <span className="font-semibold">Proposed change{change ? ` to ${workflowTargetLabel(change.target).toLowerCase()}` : ''}: </span>
+ {change ? change.reason : item.text}
+ </p>
+ {change && by && (
+ <p className="text-[11px] text-amber-100/70">
+ {by} proposed it {ago(change.created_at, now)}.
+ </p>
+ )}
+ {changed.length > 0 && (
+ <ul className="space-y-2" aria-label="What changes">
+ {changed.map((r) => (
+ <li key={r.key} className="space-y-1" data-change-row={r.key}>
+ <p className="text-[11px] font-medium text-amber-100">{r.label}</p>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
+ <Cell label="Now" value={r.before} tone="before" />
+ <Cell label="After" value={r.after} tone="after" />
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ {same.length > 0 && (
+ <details className="text-[11px]">
+ <summary className={`cursor-pointer text-amber-100/70 hover:text-amber-100 rounded ${focusRing}`}>Unchanged ({same.length})</summary>
+ <dl className="mt-1 space-y-1">
+ {same.map((r) => (
+ <div key={r.key} className="min-w-0">
+ <dt className="text-amber-100/70">{r.label}</dt>
+ <dd className="whitespace-pre-wrap break-words font-mono text-zinc-300">{r.before}</dd>
+ </div>
+ ))}
+ </dl>
+ </details>
+ )}
+ {!change && <p className="text-[11px] text-amber-100/70">Loading the details…</p>}
+ {onDecide && (
+ <>
+ <div className="flex flex-wrap gap-2" role="group" aria-label="Decide on this change">
+ <button type="button" disabled={busy || !change} onClick={() => onDecide(item.id, true)} className={goodBtn} data-change-approve>
+ <CheckCircle2 size={13} aria-hidden="true" /> Approve and apply
+ </button>
+ <button type="button" disabled={busy || !change} onClick={() => onDecide(item.id, false)} className={dangerBtn} data-change-reject>
+ Reject
+ </button>
+ </div>
+ <p className="text-[11px] text-amber-100/70">Nothing changes until you approve.</p>
+ </>
+ )}
+ </li>
+ );
+};
+
+/** A restore preview with the person's choices: which conflicting files to overwrite, and run again or not. */
+export const RestorePreviewForm: React.FC<{
+ preview: RestorePreview;
+ checkpoint?: Checkpoint | null;
+ titleOf?: (id: string) => string | undefined;
+ busy?: boolean;
+ onRestore?: (opts: { force_paths: string[]; rerun: boolean }) => void;
+ onCancel?: () => void;
+}> = ({ preview, checkpoint, titleOf, busy = false, onRestore, onCancel }) => {
+ const [force, setForce] = useState<string[]>([]);
+ useEffect(() => setForce([]), [preview.preview_sha256]);
+ const toggle = (p: string) => setForce((xs) => (xs.includes(p) ? xs.filter((x) => x !== p) : [...xs, p]));
+ const nothing = preview.changes.length === 0 && force.length === 0;
+ return (
+ <div className="space-y-3 text-xs" data-restore-preview>
+ {checkpoint && (
+ <p className="text-zinc-400">
+ Back to: <span className="text-zinc-200">{checkpointLabel(checkpoint.kind)}</span>, try {checkpoint.attempt}
+ </p>
+ )}
+ {preview.refused && (
+ <p className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-rose-200" data-restore-refused={preview.refused}>
+ {preview.refused === 'running' ? 'A bot is working on it now. Restore once it stops.' : 'A verified task isn’t restored. Use “Redo as a copy” instead.'}
+ </p>
+ )}
+ <section aria-label="Files that change" className="space-y-1">
+ <h5 className="text-[11px] font-semibold text-zinc-300">Files that change ({preview.changes.length})</h5>
+ {preview.changes.length ? (
+ <ul className="space-y-0.5 max-h-40 overflow-auto">
+ {preview.changes.map((c) => (
+ <li key={c.path} className="flex gap-2 min-w-0" data-restore-change={c.action}>
+ <span className="shrink-0 w-20 text-zinc-500">{RESTORE_ACTION_LABELS[c.action]}</span>
+ <span className="min-w-0 break-all font-mono text-zinc-200">{c.path}</span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-zinc-500">No files need changing.</p>
+ )}
+ </section>
+ {preview.conflicts.length > 0 && (
+ <fieldset className="space-y-1.5" data-restore-conflicts>
+ <legend className="text-[11px] font-semibold text-amber-200">Changed since then ({preview.conflicts.length})</legend>
+ <p className="text-[11px] text-zinc-400">These are left alone unless you tick them.</p>
+ <ul className="space-y-1">
+ {preview.conflicts.map((c) => (
+ <li key={c.path}>
+ <label className="flex items-start gap-2 min-h-[32px] cursor-pointer">
+ <input type="checkbox" className="mt-0.5 shrink-0 accent-amber-500" checked={force.includes(c.path)} onChange={() => toggle(c.path)} data-force={c.path} />
+ <span className="min-w-0">
+ <span className="block break-all font-mono text-zinc-200">{c.path}</span>
+ <span className="block text-[11px] text-amber-200/80" data-conflict-by>
+ {conflictText(c, titleOf)}. Tick to put it back anyway.
+ </span>
+ </span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ </fieldset>
+ )}
+ {preview.skipped.length > 0 && (
+ <details className="text-[11px]">
+ <summary className={`cursor-pointer text-zinc-400 hover:text-zinc-200 rounded ${focusRing}`}>Not restored ({preview.skipped.length})</summary>
+ <ul className="mt-1 space-y-0.5">
+ {preview.skipped.map((s) => (
+ <li key={s.path} className="break-all text-zinc-400">
+ <span className="font-mono text-zinc-300">{s.path}</span>: {s.why}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ {(preview.external_not_undone.length > 0 || !preview.effects_known) && (
+ <section className="px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 text-amber-100 space-y-1" data-not-undone>
+ <p className="font-medium">{preview.not_undone_note}</p>
+ {preview.external_not_undone.length > 0 && (
+ <ul className="space-y-0.5 text-[11px]">
+ {preview.external_not_undone.map((x, i) => (
+ <li key={`${x.at}-${i}`} className="break-words">
+ {x.summary}
+ </li>
+ ))}
+ </ul>
+ )}
+ {!preview.effects_known && <p className="text-[11px]" data-effects-unknown>Side effects unknown: a run changed files without a logged tool call, so something else may have happened too.</p>}
+ </section>
+ )}
+ {preview.task_state_after && (
+ <p className="text-[11px] text-zinc-400">
+ The task goes back to {stateLabel(preview.task_state_after).label}. With “Restore”, it stays on hold until you press Run.
+ </p>
+ )}
+ {onRestore && !preview.refused && (
+ <div className="flex flex-wrap gap-2">
+ <button type="button" disabled={busy || nothing} onClick={() => onRestore({ force_paths: force, rerun: false })} className={mainBtn} data-restore>
+ <RotateCcw size={13} aria-hidden="true" /> Restore
+ </button>
+ <button type="button" disabled={busy || nothing} onClick={() => onRestore({ force_paths: force, rerun: true })} className={quietBtn} data-restore-rerun>
+ Restore and run again
+ </button>
+ {onCancel && (
+ <button type="button" onClick={onCancel} className={quietBtn}>
+ Never mind
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+type RestoreApi = Pick<typeof missionsApi, 'checkpoints' | 'restorePreview' | 'restore'>;
+
+/** Time Machine for one task: pick a checkpoint, look at the preview, restore. */
+export const RestoreSection: React.FC<{
+ task: Task;
+ api?: RestoreApi;
+ titleOf?: (id: string) => string | undefined;
+ now?: number;
+ onRestored?: (r: RestoreResult, rerun: boolean) => void;
+ onError?: (e: unknown) => void;
+}> = ({ task, api = missionsApi, titleOf, now = Date.now(), onRestored, onError }) => {
+ const [open, setOpen] = useState(false);
+ const [list, setList] = useState<Checkpoint[] | null>(null);
+ const [picked, setPicked] = useState<Checkpoint | null>(null);
+ const [preview, setPreview] = useState<RestorePreview | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+ const [undoId, setUndoId] = useState<string | null>(null);
+ const keys = useRef<Record<string, string>>({});
+ const inFlight = useRef(false);
+
+ useEffect(() => {
+ setOpen(false);
+ setList(null);
+ setPicked(null);
+ setPreview(null);
+ setErr(null);
+ setUndoId(null);
+ }, [task.id]);
+
+ const load = async () => {
+ setErr(null);
+ try {
+ setList(await api.checkpoints(task.id));
+ } catch (e) {
+ setErr(restoreErrorText(e));
+ onError?.(e);
+ }
+ };
+ const pick = async (c: Checkpoint) => {
+ setPicked(c);
+ setPreview(null);
+ setErr(null);
+ try {
+ setPreview(await api.restorePreview(task.id, c.id));
+ } catch (e) {
+ setErr(restoreErrorText(e));
+ onError?.(e);
+ }
+ };
+ const restore = async (opts: { force_paths: string[]; rerun: boolean }) => {
+ if (!picked || !preview || inFlight.current) return;
+ inFlight.current = true;
+ setBusy(true);
+ setErr(null);
+ const k = `${picked.id}|${preview.preview_sha256}|${[...opts.force_paths].sort().join(',')}|${opts.rerun}`;
+ keys.current[k] ??= newIdempotencyKey();
+ try {
+ const r = await api.restore(task.id, picked.id, { preview_sha256: preview.preview_sha256, force_paths: opts.force_paths, rerun: opts.rerun }, keys.current[k]);
+ setUndoId(r.before_restore_checkpoint_id);
+ setPicked(null);
+ setPreview(null);
+ setList(null);
+ onRestored?.(r, opts.rerun);
+ } catch (e) {
+ setErr(restoreErrorText(e));
+ if (e instanceof MissionError && e.code === 'stale_preview') void pick(picked);
+ onError?.(e);
+ } finally {
+ inFlight.current = false;
+ setBusy(false);
+ }
+ };
+ const undo = async () => {
+ if (!undoId) return;
+ const cps = list ?? (await api.checkpoints(task.id).catch(() => [] as Checkpoint[]));
+ setList(cps);
+ setOpen(true);
+ const c = cps.find((x) => x.id === undoId);
+ if (c) void pick(c);
+ else setErr('The checkpoint taken before the restore isn’t there any more.');
+ };
+
+ if (!task.checkpoint_count) return null;
+ const blocked = task.state === 'verified' || task.state === 'cancelled';
+
+ return (
+ <section aria-labelledby="tm-h" className="space-y-2" data-restore-section>
+ <h4 id="tm-h" className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">
+ <History size={13} className="text-zinc-400" aria-hidden="true" />
+ Checkpoints
+ </h4>
+ {err && <Notice text={err} error />}
+ {undoId && !picked && (
+ <button type="button" onClick={() => void undo()} className={quietBtn} data-restore-undo>
+ <RotateCcw size={13} aria-hidden="true" /> Undo this restore
+ </button>
+ )}
+ {blocked ? (
+ <p className="text-[11px] text-zinc-500">
+ {task.state === 'verified' ? 'A verified task isn’t restored. Use “Redo as a copy” to work on it again.' : 'A cancelled task isn’t restored.'}
+ </p>
+ ) : task.state === 'working' ? (
+ <p className="text-[11px] text-zinc-500">A bot is working on it now. You can restore once it stops.</p>
+ ) : !open ? (
+ <button
+ type="button"
+ onClick={() => {
+ setOpen(true);
+ void load();
+ }}
+ className={quietBtn}
+ data-restore-open
+ >
+ <History size={13} aria-hidden="true" /> Restore files from a checkpoint ({task.checkpoint_count})
+ </button>
+ ) : picked ? (
+ preview ? (
+ <RestorePreviewForm
+ preview={preview}
+ checkpoint={picked}
+ titleOf={titleOf}
+ busy={busy}
+ onRestore={(o) => void restore(o)}
+ onCancel={() => {
+ setPicked(null);
+ setPreview(null);
+ }}
+ />
+ ) : (
+ <p className="flex items-center gap-1.5 text-[11px] text-zinc-400">
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Working out what would change…
+ </p>
+ )
+ ) : list === null ? (
+ <p className="flex items-center gap-1.5 text-[11px] text-zinc-400">
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading checkpoints…
+ </p>
+ ) : (
+ <ul className="space-y-1" data-checkpoints>
+ {[...list].reverse().map((c) => (
+ <li key={c.id}>
+ <button
+ type="button"
+ disabled={!c.restorable}
+ onClick={() => void pick(c)}
+ title={c.error ?? undefined}
+ className={`w-full text-left px-3 py-2 min-h-[44px] rounded-lg border border-zinc-800 bg-zinc-900/40 hover:border-zinc-600 disabled:opacity-50 disabled:hover:border-zinc-800 ${focusRing}`}
+ data-checkpoint={c.id}
+ >
+ <span className="block text-xs text-zinc-200">
+ {checkpointLabel(c.kind)} · try {c.attempt}
+ </span>
+ <span className="block text-[11px] text-zinc-500">
+ {ago(c.created_at, now)} · {c.files} {c.files === 1 ? 'file' : 'files'}
+ {c.effects_after.external.length > 0 && ` · ${c.effects_after.external.length} outside actions after it`}
+ {!c.restorable && ' · can’t be restored'}
+ </span>
+ </button>
+ </li>
+ ))}
+ <li>
+ <button type="button" onClick={() => setOpen(false)} className={subtleBtn}>
+ Close
+ </button>
+ </li>
+ </ul>
+ )}
+ </section>
+ );
+};
+
// ---------- Task detail ----------
+/** Needs-you kinds shown in their own section, not under "Waiting for you". */
+const OWN_SECTION = new Set<NeedsYouItem['kind']>(['may_be_invalid', 'autofix_suggested', 'fix_needed', 'workflow_change']);
+
const Fact: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
<div className="min-w-0">
<dt className="text-[11px] text-zinc-500">{label}</dt>
@@ -652,10 +1176,46 @@ export const TaskDetailBody: React.FC<{
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 }) => {
+ /** GET /api/tasks/:id/failures, oldest first. */
+ failures?: TaskFailure[];
+ /** Proposed workflow changes for this task. */
+ changes?: WorkflowChange[];
+ onRunHeld?: () => void;
+ onRetryAutofix?: (failureId?: string) => void;
+ onSkipAutofix?: (a: AutofixAttempt) => void;
+ onDecideChange?: (id: string, approve: boolean) => void;
+ restoreApi?: RestoreApi;
+ onRestored?: (r: RestoreResult, rerun: boolean) => void;
+ onRestoreError?: (e: unknown) => void;
+}> = ({
+ detail,
+ names,
+ tasksById = {},
+ now = Date.now(),
+ busy = false,
+ notice,
+ onAction,
+ onApproveCheck,
+ onOpenChat,
+ onOpenTask,
+ onResolveFlag,
+ onFork,
+ failures = [],
+ changes = [],
+ onRunHeld,
+ onRetryAutofix,
+ onSkipAutofix,
+ onDecideChange,
+ restoreApi,
+ onRestored,
+ onRestoreError,
+}) => {
const t = detail.task;
const flags = openFlags(t);
- const others = t.needs_you.filter((n) => n.kind !== 'may_be_invalid');
+ const others = t.needs_you.filter((n) => !OWN_SECTION.has(n.kind));
+ const changeItems = t.needs_you.filter((n) => n.kind === 'workflow_change');
+ const fixText = t.needs_you.find((n) => n.kind === 'fix_needed')?.text ?? null;
+ const held = !!t.held_at && (t.state === 'ready' || t.state === 'backlog');
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);
@@ -699,6 +1259,7 @@ export const TaskDetailBody: React.FC<{
<p className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200">{cardStatus(t, names, now)}</p>
)}
{notice && <Notice text={notice.text} error={notice.error} />}
+ {held && <HeldBox task={t} busy={busy} now={now} onRun={onRunHeld} />}
{actions.length > 0 && !asking && (
<div className="flex flex-wrap gap-2" data-actions>
{actions.map((a) => (
@@ -793,6 +1354,21 @@ export const TaskDetailBody: React.FC<{
</section>
)}
+ {changeItems.length > 0 && (
+ <section aria-labelledby="wc-h" className="space-y-2" data-workflow-changes>
+ <h4 id="wc-h" className="text-xs font-semibold text-amber-200">
+ Change to approve
+ </h4>
+ <ul className="space-y-2">
+ {changeItems.map((n) => (
+ <WorkflowChangeBox key={n.id} item={n} change={changes.find((c) => c.id === n.id)} names={names} busy={busy} now={now} onDecide={onDecideChange} />
+ ))}
+ </ul>
+ </section>
+ )}
+
+ <FailureBox task={t} failures={failures} fixText={fixText} busy={busy} now={now} onRetry={onRetryAutofix} onSkip={onSkipAutofix} />
+
{(t.forked_from || copies.length > 0) && (
<section aria-label="Copies" className="space-y-1 text-xs" data-copies>
{t.forked_from && (
@@ -935,6 +1511,8 @@ export const TaskDetailBody: React.FC<{
<EvidenceReceipt receipt={receipt} names={names} busy={busy} onApproveCheck={onApproveCheck} />
+ <RestoreSection task={t} api={restoreApi} titleOf={(id) => tasksById[id]?.title} now={now} onRestored={onRestored} onError={onRestoreError} />
+
{detail.events.length > 0 && (
<section aria-labelledby="ev-h" className="space-y-1.5">
<h4 id="ev-h" className="text-xs font-semibold text-zinc-200">
@@ -1336,6 +1914,8 @@ export const MissionBoardPage: React.FC<{
const [detail, setDetail] = useState<TaskDetail | null>(null);
const [detailError, setDetailError] = useState<string | null>(null);
const [detailNotice, setDetailNotice] = useState<{ text: string; error: boolean } | null>(null);
+ const [failures, setFailures] = useState<TaskFailure[]>([]);
+ const [changes, setChanges] = useState<WorkflowChange[]>([]);
const [busy, setBusy] = useState(false);
const [view, setView] = useState<'board' | 'graph'>('board');
const [graph, setGraph] = useState<WorkGraph | null>(null);
@@ -1380,6 +1960,14 @@ export const MissionBoardPage: React.FC<{
if (!alive.current || openIdRef.current !== id) return;
setDetail(d);
setDetailError(null);
+ // AutoFix extras: never block the panel on them.
+ const t = d.task;
+ if (t.last_failure || t.autofix) {
+ missionsApi.failures(id).then((f) => alive.current && openIdRef.current === id && setFailures(f), () => {});
+ } else setFailures([]);
+ if (t.needs_you.some((n) => n.kind === 'workflow_change')) {
+ missionsApi.workflowChanges('proposed').then((cs) => alive.current && openIdRef.current === id && setChanges(cs.filter((c) => c.task_id === id)), () => {});
+ } else setChanges([]);
} catch (e) {
if (alive.current && openIdRef.current === id) setDetailError(failMsg(e));
}
@@ -1451,6 +2039,8 @@ export const MissionBoardPage: React.FC<{
const openTask = (id: string) => {
setOpenId(id);
setDetail(null);
+ setFailures([]);
+ setChanges([]);
setDetailError(null);
setDetailNotice(null);
loadDetail(id);
@@ -1557,6 +2147,80 @@ export const MissionBoardPage: React.FC<{
}
};
+ /** One person action on the open task: keyed, one at a time, 401 asks for the token, 409 shows what it is now. */
+ const personAction = async (what: string, run: (taskId: string, key: string) => Promise<string>, errorText: (e: unknown) => string) => {
+ if (!openId || inFlight.current) return;
+ const taskId = openId;
+ inFlight.current = true;
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ const text = await run(taskId, keyFor(what));
+ pendingKey.current = null;
+ if (!alive.current) return;
+ setDetailNotice({ text, error: false });
+ playSfx('click');
+ await afterChange([], taskId);
+ load();
+ } 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: errorText(e), error: true });
+ if (e instanceof MissionError && e.status === 409) await loadDetail(taskId);
+ } finally {
+ inFlight.current = false;
+ if (alive.current) setBusy(false);
+ }
+ };
+
+ const runHeld = () =>
+ personAction(
+ `run:${openId}`,
+ async (id, key) => {
+ const t = await missionsApi.runHeld(id, key);
+ setTasks((list) => (list ? upsertTask(list, t) : list));
+ return 'Off hold. A bot picks it up next.';
+ },
+ restoreErrorText,
+ );
+ const retryAutofix = (failureId?: string) =>
+ personAction(
+ `autofix:${openId}:${failureId ?? ''}`,
+ async (id, key) => {
+ await missionsApi.runAutofix(id, key, failureId);
+ return 'AutoFix retries it now.';
+ },
+ autofixErrorText,
+ );
+ const skipAutofix = (a: AutofixAttempt) =>
+ personAction(
+ `autofix-skip:${a.id}`,
+ async (id) => {
+ await missionsApi.cancelAutofix(id, a.id);
+ return 'AutoFix won’t retry it. It stays failed until you try again.';
+ },
+ autofixErrorText,
+ );
+ const decideChange = (cid: string, approve: boolean) =>
+ personAction(
+ `change:${cid}:${approve}`,
+ async () => {
+ const c = await missionsApi.decideChange(cid, approve);
+ if (!approve) return 'Rejected. Nothing changed.';
+ return c.status === 'stale' ? 'This change no longer fits: what it changes was edited since. Nothing changed.' : 'Approved and applied.';
+ },
+ (e) => (e instanceof MissionError && e.status === 409 ? 'Someone already decided on this change.' : failMsg(e)),
+ );
+ const restored = async (r: RestoreResult, rerun: boolean) => {
+ setDetailNotice({ text: restoredText(r, rerun), error: false });
+ playSfx('click');
+ await afterChange([r.task], r.task.id);
+ };
+ const restoreError = (e: unknown) => {
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ };
+
const scan = async () => {
if (!missionId) return;
setScanning(true);
@@ -1645,6 +2309,14 @@ export const MissionBoardPage: React.FC<{
onApproveCheck={approveCheck}
onResolveFlag={resolveFlag}
onFork={forkTask}
+ failures={failures}
+ changes={changes}
+ onRunHeld={runHeld}
+ onRetryAutofix={retryAutofix}
+ onSkipAutofix={skipAutofix}
+ onDecideChange={decideChange}
+ onRestored={restored}
+ onRestoreError={restoreError}
onOpenChat={
onOpenChat
? (t) => {
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 862273bf..d544fe43 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -30,7 +30,9 @@ import { useEngines } from '../useEngines';
import { LayaStatusRow } from './LayaStatus';
import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';
import { ProactiveSettings, WORK_AHEAD_CAP_MAX, WORK_AHEAD_CAP_MIN, parseProactiveSettings } from '../decideFirst';
-import { MISSION_BOARD_SETTING_EVENT, parseMissionBoardSetting } from '../missions';
+import { AUTOFIX_MODES, AutofixSettings, MISSION_BOARD_SETTING_EVENT, parseAutofixSettings, parseMissionBoardSetting } from '../missions';
+
+const RECOVERY_PCTS = [0, 10, 25, 50, 100];
/** One labelled switch row, like the others in this dialog. */
const SwitchRow: React.FC<{ id: string; label: string; hint: string; checked: boolean; onToggle: () => void; children?: React.ReactNode }> = ({
@@ -133,6 +135,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const [proactive, setProactive] = useState<ProactiveSettings | null>(null);
// null: this server has no Mission board, so the switch stays hidden.
const [missionBoard, setMissionBoard] = useState<boolean | null>(null);
+ const [autofix, setAutofix] = useState<AutofixSettings | null>(null);
// null until loaded, and on a server without these settings
const [place, setPlace] = useState<{ timezone: string; location: string } | null>(null);
const [webhookUrl, setWebhookUrl] = useState('');
@@ -197,6 +200,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
setAgentTools(typeof data.agent_tools === 'boolean' ? data.agent_tools : null);
setProactive(parseProactiveSettings(data));
setMissionBoard(parseMissionBoardSetting(data));
+ setAutofix(parseAutofixSettings(data));
setPlace(
typeof data.timezone === 'string'
? { timezone: data.timezone || defaultTimeZone(), location: typeof data.location === 'string' ? data.location : '' }
@@ -277,6 +281,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
...(agentTools !== null ? { agent_tools: agentTools } : {}),
...(proactive ?? {}),
...(missionBoard !== null ? { mission_board: missionBoard } : {}),
+ ...(autofix !== null ? { autofix: autofix.autofix, recovery_budget_pct: autofix.recovery_budget_pct } : {}),
...(place ? { timezone: place.timezone.trim(), location: place.location.trim() } : {}),
}),
});
@@ -696,6 +701,58 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
checked={missionBoard}
onToggle={() => setMissionBoard((v) => !v)}
/>
+ {autofix !== null && (
+ <SwitchRow
+ id="autofix"
+ label="Retry failed tasks with AutoFix"
+ hint="When a task fails, AutoFix works out why and plans a retry that fits: wait a bit, start from a checkpoint, or pass along what the check said. It never retries a missing login, a denied action or a spent budget."
+ checked={autofix.autofix !== 'off'}
+ onToggle={() => setAutofix((a) => (a ? { ...a, autofix: a.autofix === 'off' ? 'suggest' : 'off' } : a))}
+ >
+ {autofix.autofix !== 'off' && (
+ <div className="mt-2 space-y-2" data-testid="autofix-options">
+ <div role="radiogroup" aria-label="How AutoFix retries" className="space-y-1">
+ {AUTOFIX_MODES.filter((m) => m.value !== 'off').map((m) => (
+ <label key={m.value} className="flex items-start gap-2 min-h-[32px] cursor-pointer text-[11px]">
+ <input
+ type="radio"
+ name="autofix-mode"
+ value={m.value}
+ checked={autofix.autofix === m.value}
+ onChange={() => setAutofix((a) => (a ? { ...a, autofix: m.value } : a))}
+ className="mt-0.5 accent-sky-500"
+ />
+ <span>
+ <span className="block font-medium text-zinc-200">{m.value === 'suggest' ? 'Ask me first' : 'Retry on its own'}</span>
+ <span className="block text-zinc-500">{m.hint}</span>
+ </span>
+ </label>
+ ))}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor="recovery-pct" className="text-[11px] text-zinc-300">
+ Retries may spend up to
+ </label>
+ <select
+ id="recovery-pct"
+ value={autofix.recovery_budget_pct}
+ onChange={(e) => setAutofix((a) => (a ? { ...a, recovery_budget_pct: Number(e.target.value) } : a))}
+ className="bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none"
+ >
+ {[...new Set([...RECOVERY_PCTS, autofix.recovery_budget_pct])]
+ .sort((x, y) => x - y)
+ .map((n) => (
+ <option key={n} value={n}>
+ {n}%
+ </option>
+ ))}
+ </select>
+ <span className="text-[11px] text-zinc-300">of each task’s budget</span>
+ </div>
+ </div>
+ )}
+ </SwitchRow>
+ )}
</fieldset>
)}
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index c571a915..48026d2a 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -448,14 +448,18 @@ export function sortTasks(tasks: Task[]): Task[] {
}
/**
- * 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).
+ * Which column a task card sits in: its state's column, except that an open "may be invalid" flag, or an
+ * AutoFix item (a retry to OK, something to fix, a proposed change), puts it in Needs you: they wait for
+ * the person in any state.
*/
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;
+ return c && (openFlags(t).length || (t.needs_you ?? []).some((n) => PERSON_ITEMS.has(n.kind))) ? 'needs_you' : c;
}
+/** AutoFix items that wait for the person whatever the task's state, so its card sits in Needs you. */
+const PERSON_ITEMS = new Set<NeedsYouItem['kind']>(['autofix_suggested', 'fix_needed', 'workflow_change']);
+
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)) {
@@ -616,9 +620,14 @@ export function cardStatus(t: Task, names: Record<string, string> = {}, now: num
switch (t.state) {
case 'blocked':
return t.blocked_reason === 'budget' ? 'Out of budget' : t.blocked_reason ? `Blocked: ${t.blocked_reason}` : 'Blocked';
- case 'failed':
+ case 'failed': {
+ const auto = autofixCardText(t, now);
+ if (auto) return auto;
+ if (t.last_failure) return `${failureClassLabel(t.last_failure.class)} (try ${t.attempts} of ${t.max_attempts})`;
return `Checks failed ${t.attempts} of ${t.max_attempts} times`;
+ }
case 'backlog':
+ if (t.held_at) return 'On hold after restore. Press Run to start it';
if (t.waiting_on.length) return t.waiting_on.length === 1 ? 'Waiting on 1 task' : `Waiting on ${t.waiting_on.length} tasks`;
return 'Waiting for the mission to be approved';
case 'working':
@@ -633,6 +642,8 @@ export function cardStatus(t: Task, names: Record<string, string> = {}, now: num
return optionalWaitingText(optionalWaitingCount(t.checks_summary)) ?? 'Bot says done. Checking';
case 'verified':
return t.finished_at ? `Verified ${ago(t.finished_at, now)}` : 'Verified';
+ case 'ready':
+ return t.held_at ? 'On hold after restore. Press Run to start it' : null;
default:
return null;
}
@@ -759,6 +770,225 @@ export function newIdempotencyKey(): string {
return `k-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
}
+// ---------------------------------------------------------------------------
+// AutoFix and restore holds (Phase B3, docs/mission-control.md §12–§13)
+
+export const FAILURE_LABELS: Record<FailureClass, { label: string; tone: Tone }> = {
+ transient: { label: 'A temporary error', tone: 'amber' },
+ stalled: { label: 'Stopped before finishing', tone: 'amber' },
+ check_failed: { label: 'A check failed', tone: 'rose' },
+ bad_spec: { label: 'A check can’t run as written', tone: 'amber' },
+ auth: { label: 'Signed out, or the key was rejected', tone: 'rose' },
+ budget: { label: 'Out of budget', tone: 'rose' },
+ denied: { label: 'An action was denied', tone: 'rose' },
+ needs_input: { label: 'Waiting for you', tone: 'amber' },
+ unknown: { label: 'An unexpected error', tone: 'rose' },
+};
+export const failureClassLabel = (c: string): string => FAILURE_LABELS[c as FailureClass]?.label ?? humanize(c);
+export const failureTone = (c: string): Tone => FAILURE_LABELS[c as FailureClass]?.tone ?? 'rose';
+
+const STRATEGY_LABELS: Record<AutofixStrategy, string> = {
+ wait_and_retry: 'Wait, then try again',
+ retry_from_checkpoint: 'Carry on from where it stopped',
+ retry_with_diagnostics: 'Try again with the check’s output',
+ retry_same: 'Try again',
+ propose_change: 'Propose a change for you to approve',
+ none: 'No retry',
+};
+export const strategyLabel = (s: string): string => STRATEGY_LABELS[s as AutofixStrategy] ?? (s ? humanize(s) : 'Try again');
+
+/** Why AutoFix didn't retry, in words: the server's reason starts with a code. */
+export function skipText(reason: string): string {
+ const r = reason.trim();
+ if (r.startsWith('no_attempts_left')) return 'no tries left';
+ if (r.startsWith('over_recovery_budget')) return 'another try would go over its retry budget';
+ if (r.startsWith('not_retryable')) return 'this kind of failure isn’t retried';
+ return r || 'it wasn’t retried';
+}
+
+/** One line for an AutoFix attempt: what it does, and when. */
+export function autofixStatusText(a: Pick<AutofixAttempt, 'status' | 'strategy' | 'not_before' | 'reason'>, now: number = Date.now()): string {
+ switch (a.status) {
+ case 'suggested':
+ return a.strategy === 'propose_change' ? 'AutoFix proposed a change. It waits for your OK.' : `AutoFix suggests: ${strategyLabel(a.strategy).toLowerCase()}. It waits for your OK.`;
+ case 'scheduled': {
+ const when = a.not_before ? untilText(a.not_before, now) : 'now';
+ return `AutoFix will ${strategyLabel(a.strategy).toLowerCase()} ${when === 'now' ? 'shortly' : when}.`;
+ }
+ case 'running':
+ return 'AutoFix is retrying it now.';
+ case 'succeeded':
+ return 'AutoFix’s retry worked.';
+ case 'failed':
+ return 'AutoFix’s retry failed too.';
+ default:
+ return `AutoFix didn’t retry: ${skipText(a.reason)}.`;
+ }
+}
+
+/** The card line for a failed task AutoFix is handling, else null. */
+export function autofixCardText(t: Pick<Task, 'autofix'>, now: number = Date.now()): string | null {
+ const a = t.autofix;
+ if (!a) return null;
+ if (a.status === 'running') return 'AutoFix is retrying';
+ if (a.status === 'scheduled') {
+ const when = a.not_before ? untilText(a.not_before, now) : 'now';
+ return when === 'now' ? 'AutoFix retries shortly' : `AutoFix retries ${when}`;
+ }
+ if (a.status === 'suggested' && a.strategy !== 'propose_change') return 'AutoFix suggests a retry';
+ return null;
+}
+
+/** "3.2k of 12.5k tokens for retries"; null on a server without AutoFix. */
+export function recoveryText(t: Pick<Task, 'recovery_spent_tokens' | 'recovery_budget_tokens'>): string | null {
+ if (typeof t.recovery_spent_tokens !== 'number') return null;
+ const spent = formatTokens(t.recovery_spent_tokens);
+ return typeof t.recovery_budget_tokens === 'number' && t.recovery_budget_tokens > 0
+ ? `${spent} of ${formatTokens(t.recovery_budget_tokens)} tokens`
+ : `${spent} tokens`;
+}
+
+/** A plain message for a refused AutoFix retry. */
+export function autofixErrorText(e: unknown): string {
+ if (e instanceof MissionError && e.status === 409) {
+ if (e.code === 'no_attempts_left') return 'No tries left. You can still try it again yourself.';
+ if (e.code === 'over_recovery_budget') return 'Another retry would go over this task’s retry budget. You can still try it again yourself.';
+ if (e.code === 'not_retryable') return 'AutoFix can’t retry this kind of failure. See what to fix above.';
+ return 'The retry changed while you were deciding. The task now shows the latest.';
+ }
+ return e instanceof Error ? e.message : 'Something went wrong.';
+}
+
+export const AUTOFIX_MODES: { value: AutofixMode; label: string; hint: string }[] = [
+ { value: 'off', label: 'Off', hint: 'Failures are recorded. Nothing is retried on its own.' },
+ { value: 'suggest', label: 'Suggest', hint: 'AutoFix plans a retry and waits for your OK in Needs you.' },
+ { value: 'on', label: 'On', hint: 'AutoFix retries within each task’s tries and retry budget.' },
+];
+
+export interface AutofixSettings {
+ autofix: AutofixMode;
+ recovery_budget_pct: number;
+}
+
+/** `autofix` and `recovery_budget_pct` from GET /api/settings; null on a server without AutoFix. */
+export function parseAutofixSettings(data: unknown): AutofixSettings | null {
+ if (!data || typeof data !== 'object') return null;
+ const d = data as Record<string, unknown>;
+ if (d.autofix !== 'off' && d.autofix !== 'suggest' && d.autofix !== 'on') return null;
+ const pct = typeof d.recovery_budget_pct === 'number' ? Math.max(0, Math.min(100, Math.round(d.recovery_budget_pct))) : 25;
+ return { autofix: d.autofix, recovery_budget_pct: pct };
+}
+
+export const WORKFLOW_TARGET_LABELS: Record<WorkflowTarget, string> = {
+ check_spec: 'A check',
+ task_acceptance: 'What done looks like',
+ max_attempts: 'Max tries',
+ routine_instructions: 'The routine’s instructions',
+ routine_schedule: 'The routine’s schedule',
+};
+export const workflowTargetLabel = (t: string): string => WORKFLOW_TARGET_LABELS[t as WorkflowTarget] ?? humanize(t);
+
+export interface ChangeRow {
+ key: string;
+ label: string;
+ before: string;
+ after: string;
+ changed: boolean;
+}
+
+const FIELD_LABELS: Record<string, string> = {
+ kind: 'Kind',
+ spec: 'Check',
+ required: 'Required',
+ instructions: 'Instructions',
+ schedule: 'Schedule',
+ acceptance: 'What done looks like',
+ max_attempts: 'Max tries',
+};
+
+const showValue = (v: unknown): string => {
+ if (v === undefined) return '—';
+ if (v === null) return 'none';
+ if (typeof v === 'boolean') return v ? 'Yes' : 'No';
+ if (typeof v === 'string') return v;
+ if (typeof v === 'number') return String(v);
+ return JSON.stringify(v, null, 2);
+};
+
+/**
+ * A proposed change as rows of before and after, changed rows first. Ids (`check_id`) aren't shown;
+ * a bare value (a number, some text) is one row.
+ */
+export function changeRows(before: unknown, after: unknown): ChangeRow[] {
+ const obj = (v: unknown) => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null);
+ const b = obj(before);
+ const a = obj(after);
+ if (!b || !a) {
+ const x = showValue(before);
+ const y = showValue(after);
+ return [{ key: 'value', label: 'Value', before: x, after: y, changed: x !== y }];
+ }
+ const keys = [...new Set([...Object.keys(b), ...Object.keys(a)])].filter((k) => !k.endsWith('_id'));
+ const rows = keys.map((k) => {
+ const x = showValue(b[k]);
+ const y = showValue(a[k]);
+ return { key: k, label: FIELD_LABELS[k] ?? humanize(k), before: x, after: y, changed: x !== y };
+ });
+ return [...rows.filter((r) => r.changed), ...rows.filter((r) => !r.changed)];
+}
+
+export const CHECKPOINT_LABELS: Record<CheckpointKind, string> = {
+ before_run: 'Before a run',
+ after_run: 'After a run',
+ manual: 'Saved by you',
+ before_restore: 'Before a restore',
+};
+export const checkpointLabel = (k: string): string => CHECKPOINT_LABELS[k as CheckpointKind] ?? humanize(k);
+
+/** Who changed a conflicting file: a task only on proof (D11), else "outside this task". */
+export function conflictText(c: RestorePreview['conflicts'][number], titleOf: (id: string) => string | undefined = () => undefined): string {
+ if (!c.changed_by_task) return 'Changed outside this task';
+ const t = titleOf(c.changed_by_task);
+ return t ? `Changed by “${t}”` : 'Changed by another task';
+}
+
+export const RESTORE_ACTION_LABELS: Record<RestoreAction, string> = { overwrite: 'Put back', create: 'Bring back', delete: 'Remove' };
+
+/** A plain message for a refused restore or Run. */
+export function restoreErrorText(e: unknown): string {
+ if (e instanceof MissionError) {
+ switch (e.code) {
+ case 'stale_preview':
+ return 'Files changed since this preview. Look at the new preview, then restore.';
+ case 'running':
+ return 'A bot is working on it now. Restore once it stops.';
+ case 'fork_instead':
+ return 'A verified task isn’t restored. Use “Redo as a copy” instead.';
+ case 'not_restorable':
+ return 'This checkpoint can’t be restored: its snapshot failed or was cleared out.';
+ case 'unknown_force_path':
+ return 'A file you picked isn’t in the preview any more. Look at the new preview.';
+ case 'checkpoint_failed':
+ return 'The safety checkpoint couldn’t be taken, so nothing was restored.';
+ case 'not_held':
+ return 'It isn’t on hold any more, maybe Run was pressed in another tab.';
+ default:
+ break;
+ }
+ }
+ return e instanceof Error ? e.message : 'Something went wrong.';
+}
+
+/** What a restore did, in one sentence. */
+export function restoredText(r: Pick<RestoreResult, 'restored' | 'deleted' | 'failed' | 'task'>, rerun: boolean): string {
+ const n = (k: number, one: string, many: string) => (k === 1 ? one : many.replace('#', String(k)));
+ const parts = [r.restored.length ? n(r.restored.length, '1 file put back', '# files put back') : null, r.deleted.length ? n(r.deleted.length, '1 file removed', '# files removed') : null].filter(Boolean);
+ const what = parts.length ? `Restored: ${parts.join(', ')}.` : 'Restored. No files needed changing.';
+ const failed = r.failed.length ? ` ${n(r.failed.length, '1 file couldn’t be written', '# files couldn’t be written')}.` : '';
+ const next = r.task.held_at ? ' It’s on hold until you press Run.' : rerun && (r.task.state === 'ready' || r.task.state === 'backlog') ? ' It will run again.' : '';
+ return `${what}${failed}${next}`;
+}
+
// ---------------------------------------------------------------------------
// Work graph view
@@ -987,6 +1217,7 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
case 'claimed':
return `${Who} took it on`;
case 'released':
+ if (e.actor === 'person' && !note) return 'You let it run again';
return `${Who} let it go${note ? `: ${note}` : ''}`;
case 'lease_expired':
return 'The claim ran out with no activity, so it went back to Ready';
@@ -1014,6 +1245,33 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
}
case 'forked':
return `${Who} made a copy to redo it${note ? `: ${note}` : ''}`;
+ case 'held':
+ return 'On hold after the restore, until you press Run';
+ case 'restored': {
+ const n = (k: unknown, one: string, many: string) => (typeof k === 'number' && k > 0 ? (k === 1 ? one : many.replace('#', String(k))) : null);
+ const parts = [n(d.restored, '1 file put back', '# files put back'), n(d.deleted, '1 removed', '# removed')].filter(Boolean);
+ return `${Who} restored it from a checkpoint${parts.length ? `: ${parts.join(', ')}` : ''}`;
+ }
+ case 'failure':
+ return `It failed: ${failureClassLabel(str(d.class) ?? 'unknown').toLowerCase()}${str(d.summary) ? `. ${str(d.summary)}` : ''}`;
+ case 'autofix':
+ return `AutoFix sent it back to Ready: ${strategyLabel(str(d.strategy) ?? '').toLowerCase()}`;
+ case 'autofix_scheduled':
+ return str(d.status) === 'suggested' ? 'AutoFix suggested a retry. It waits for your OK' : `AutoFix planned a retry: ${strategyLabel(str(d.strategy) ?? '').toLowerCase()}`;
+ case 'autofix_started':
+ return 'AutoFix started a retry';
+ case 'autofix_finished': {
+ const s = str(d.status);
+ if (s === 'succeeded') return 'AutoFix’s retry worked';
+ if (s === 'skipped') return `AutoFix didn’t retry: ${skipText(str(d.reason) ?? '')}`;
+ return 'AutoFix’s retry failed';
+ }
+ case 'workflow_change_proposed':
+ return `${Who} proposed a change for you to approve`;
+ case 'workflow_change_decided':
+ return str(d.status) === 'stale' ? 'A proposed change went out of date, so nothing changed' : `${Who} ${str(d.status) === 'rejected' ? 'rejected' : 'approved'} a proposed change`;
+ case 'workflow_change_applied':
+ return 'The approved change was applied';
default:
return `${Who}: ${humanize(e.kind)}`;
}
@@ -1114,6 +1372,8 @@ export class MissionError extends Error {
constructor(
message: string,
public status: number,
+ /** The server's `code` on a refusal (e.g. `stale_preview`, `no_attempts_left`), when it sends one. */
+ public code: string | null = null,
) {
super(message);
}
@@ -1129,9 +1389,10 @@ const sentence = (s: string) => {
export function errorFrom(status: number, answer: unknown): MissionError {
const a = answer && typeof answer === 'object' ? (answer as Record<string, unknown>) : {};
const err = typeof a.error === 'string' && a.error.trim() ? sentence(a.error) : null;
+ const code = typeof a.code === 'string' && a.code ? a.code : null;
if (status === 403) return new MissionError('Only you can change tasks on the board.', 403);
if (status === 404 && !err) return new MissionError('This server doesn’t have the Mission board yet. Update the app and try again.', 404);
- return new MissionError(err ?? `Something went wrong (HTTP ${status}).`, status);
+ return new MissionError(err ?? `Something went wrong (HTTP ${status}).`, status, code);
}
async function call<T>(url: string, method = 'GET', body?: unknown, extra?: Record<string, string>): Promise<T> {
@@ -1172,6 +1433,19 @@ export const missionsApi = {
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 }),
+ /** Let a task a restore held run again (person only). */
+ runHeld: (id: string, key: string) => call<{ task: Task }>(`/api/tasks/${enc(id)}/run`, 'POST', {}, { 'Idempotency-Key': key }).then((r) => r.task),
+ checkpoints: (id: string) => call<Checkpoint[]>(`/api/tasks/${enc(id)}/checkpoints`),
+ restorePreview: (id: string, cid: string) => call<RestorePreview>(`/api/tasks/${enc(id)}/checkpoints/${enc(cid)}/restore-preview`),
+ restore: (id: string, cid: string, body: { preview_sha256: string; force_paths?: string[]; rerun?: boolean }, key: string) =>
+ call<RestoreResult>(`/api/tasks/${enc(id)}/checkpoints/${enc(cid)}/restore`, 'POST', body, { 'Idempotency-Key': key }),
+ failures: (id: string) => call<TaskFailure[]>(`/api/tasks/${enc(id)}/failures`),
+ /** Run the suggested retry now (or plan one). The same key returns the same attempt. */
+ runAutofix: (id: string, key: string, failureId?: string) =>
+ call<AutofixAttempt>(`/api/tasks/${enc(id)}/autofix`, 'POST', failureId ? { failure_id: failureId } : {}, { 'Idempotency-Key': key }),
+ cancelAutofix: (id: string, aid: string) => call<AutofixAttempt>(`/api/tasks/${enc(id)}/autofix/${enc(aid)}/cancel`, 'POST', {}),
+ workflowChanges: (status: WorkflowChangeStatus = 'proposed') => call<WorkflowChange[]>(`/api/workflow-changes?status=${status}`),
+ decideChange: (id: string, approve: boolean) => call<WorkflowChange>(`/api/workflow-changes/${enc(id)}/${approve ? 'approve' : 'reject'}`, 'POST', {}),
/** One person action on a task. `run_checks` answers `{checks, task}`, the others the Task. */
act: async (id: string, action: TaskAction, reason?: string): Promise<Task> => {
const base = `/api/tasks/${enc(id)}`;
diff --git a/frontend/tests/missionAutofix.test.mjs b/frontend/tests/missionAutofix.test.mjs
new file mode 100644
index 00000000..987f0790
--- /dev/null
+++ b/frontend/tests/missionAutofix.test.mjs
@@ -0,0 +1,193 @@
+// Mission board, Phase B3 (docs/mission-control.md §12–§13): AutoFix explains a failure and retries it,
+// proposes workflow changes the person approves, and a restore holds the task until the person presses Run.
+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 { TaskCard, TaskDetailBody, InsightsStrip, RestorePreviewForm, RestoreSection, WorkflowChangeBox, FailureBox, HeldBox } from './src/components/MissionBoardView';
+ const r = (c, p) => renderToStaticMarkup(React.createElement(c, p));
+ export const card = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(TaskCard, p)));
+ export const detail = (p) => r(TaskDetailBody, p);
+ export const insights = (p) => r(InsightsStrip, p);
+ export const preview = (p) => r(RestorePreviewForm, p);
+ export const restore = (p) => r(RestoreSection, p);
+ export const change = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(WorkflowChangeBox, p)));
+ export const failure = (p) => r(FailureBox, p);
+ export const held = (p) => r(HeldBox, p);
+`);
+
+const NOW = Date.parse('2026-10-27T12:00:00Z');
+const noop = () => {};
+const names = { k_lin: 'Lin' };
+const none = { status: 'not_checked', passed: 0, failed: 0, needs_approval: 0, required_needs_approval: 0, total: 0 };
+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: 'failed', priority: 1, owner_kwant_id: 'k_lin', owner_name: 'Lin', suggested_kwant_id: null, budget_tokens: 40000, 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: null,
+ depends_on: [], waiting_on: [], claim: null, needs_you: [], checks_summary: none, forked_from: null, flags: [], ...over,
+});
+const attempt = (over = {}) => ({ id: 'af1', strategy: 'retry_with_diagnostics', status: 'suggested', not_before: null, reason: 'a check failed', tokens_spent: 0, retry_task_id: null, ...over });
+const lastFailure = { class: 'check_failed', summary: 'npm test: 2 tests failed', created_at: '2026-10-27T11:50:00Z' };
+const failed = (over = {}) => task({ last_failure: lastFailure, autofix: attempt(), recovery_spent_tokens: 3200, recovery_budget_tokens: 10000, ...over });
+const detailProps = (t, over = {}) => ({ detail: { task: t, checks: [], evidence: [], events: [] }, names, now: NOW, onAction: noop, onApproveCheck: noop, ...over });
+const ev = (kind, detail = {}, actor = 'kwant') => ({ id: kind, task_id: 'a', kind, actor, actor_name: null, from_state: null, to_state: null, detail, created_at: '2026-10-27T11:00:00Z' });
+
+test('failure classes and AutoFix attempts read as plain sentences', () => {
+ assert.equal(m.failureClassLabel('auth'), 'Signed out, or the key was rejected');
+ assert.equal(m.failureClassLabel('something_new'), 'Something new', 'an unknown class is humanized, not dropped');
+ assert.equal(m.autofixStatusText(attempt(), NOW), 'AutoFix suggests: try again with the check’s output. It waits for your OK.');
+ assert.match(m.autofixStatusText(attempt({ status: 'scheduled', strategy: 'wait_and_retry', not_before: '2026-10-27T12:05:00Z' }), NOW), /^AutoFix will wait, then try again in /);
+ assert.equal(m.autofixStatusText(attempt({ status: 'skipped', reason: 'over_recovery_budget: 9.8k of 10k' }), NOW), 'AutoFix didn’t retry: another try would go over its retry budget.');
+ assert.equal(m.autofixStatusText(attempt({ status: 'skipped', reason: 'no_attempts_left' }), NOW), 'AutoFix didn’t retry: no tries left.');
+ assert.equal(m.recoveryText(failed()), '3.2k of 10k tokens');
+ assert.equal(m.recoveryText(task()), null, 'an older server sends no recovery fields');
+});
+
+test('a failed task AutoFix is handling says so on its card and sits in Needs you when it waits for the person', () => {
+ const t = failed();
+ assert.equal(m.cardStatus(t, names, NOW), 'AutoFix suggests a retry');
+ assert.equal(m.columnOfTask(t), m.columnOf('failed'), 'without a needs_you item it stays where failed tasks go');
+ assert.equal(m.columnOfTask(failed({ needs_you: [{ kind: 'autofix_suggested', id: 'af1', text: 'Retry?' }] })), 'needs_you');
+ assert.equal(m.cardStatus(failed({ autofix: attempt({ status: 'running' }) }), names, NOW), 'AutoFix is retrying');
+ assert.equal(m.cardStatus(failed({ autofix: null }), names, NOW), 'A check failed (try 1 of 3)');
+ const c = ui.card({ task: failed({ autofix: attempt({ status: 'scheduled' }) }), names, now: NOW, onOpen: noop });
+ assert.match(c, /data-autofix-badge[^>]*><span[^>]*>AutoFix</);
+ assert.match(c, /text-violet-200[^>]*>AutoFix retries shortly/);
+ assert.doesNotMatch(ui.card({ task: failed({ autofix: null }), names, now: NOW, onOpen: noop }), /data-autofix-badge/);
+});
+
+test('the task panel shows the failure, the AutoFix plan, its tries and its spend', () => {
+ const failures = [
+ { id: 'fl0', attempt: 1, source: 'turn', class: 'transient', summary: 'the model timed out', excerpt: null, checkpoint_id: null, created_at: '2026-10-27T11:00:00Z', autofix: attempt({ id: 'af0', status: 'succeeded', strategy: 'wait_and_retry' }) },
+ { id: 'fl1', attempt: 2, source: 'check', class: 'check_failed', summary: 'npm test: 2 tests failed', excerpt: 'FAIL pricing.test.js', checkpoint_id: null, created_at: '2026-10-27T11:50:00Z', autofix: attempt() },
+ ];
+ const html = ui.detail(detailProps(failed({ needs_you: [{ kind: 'autofix_suggested', id: 'af1', text: 'Retry with the check output? npm test: 2 tests failed' }] }), { failures, onRetryAutofix: noop, onSkipAutofix: noop }));
+ assert.match(html, /data-failure-class="check_failed"[\s\S]*A check failed[\s\S]*npm test: 2 tests failed/);
+ assert.match(html, /data-autofix-status="suggested"/);
+ assert.match(html, /data-autofix-retry[^>]*>[\s\S]*Retry now/);
+ assert.match(html, /data-autofix-skip[^>]*>Don’t retry/);
+ assert.match(html, />AutoFix tries<\/dt><dd[^>]*>1</);
+ assert.match(html, />Spent on retries<\/dt><dd[^>]*>3\.2k of 10k tokens</);
+ assert.match(html, /Earlier failures \(1\)[\s\S]*Try 1:[\s\S]*the model timed out/);
+ assert.match(html, /FAIL pricing\.test\.js/, 'the redacted output is behind a disclosure');
+ assert.doesNotMatch(html, /data-needs-you/, 'the AutoFix item is not repeated under Waiting for you');
+ const fix = ui.detail(detailProps(task({ last_failure: { ...lastFailure, class: 'auth' }, autofix: null, needs_you: [{ kind: 'fix_needed', id: 'fl2', text: 'Sign in to GitHub again in Connections.' }] })));
+ assert.match(fix, /data-fix-needed[^>]*><span[^>]*>To fix: <\/span>Sign in to GitHub again in Connections\./);
+ assert.doesNotMatch(fix, /data-autofix-retry/, 'nothing to retry');
+ assert.doesNotMatch(ui.detail(detailProps(task())), /data-failure/, 'nothing without a failure');
+});
+
+test('AutoFix retries show as AutoFix in the activity, not as the person', () => {
+ assert.equal(m.eventText(ev('autofix', { strategy: 'retry_with_diagnostics' })), 'AutoFix sent it back to Ready: try again with the check’s output');
+ assert.match(m.eventText(ev('failure', { class: 'check_failed', summary: 'npm test failed' })), /^It failed: a check failed\. npm test failed/);
+ assert.equal(m.eventText(ev('released', {}, 'person')), 'You let it run again');
+ for (const k of ['autofix', 'autofix_scheduled', 'autofix_started', 'autofix_finished']) assert.doesNotMatch(m.eventText(ev(k, { strategy: 'retry_same', status: 'succeeded' })), /^You\b/, k);
+});
+
+test('a proposed workflow change shows before and after, and only Approve applies it', () => {
+ const c = {
+ id: 'wc1', task_id: 'a', routine_id: null, target: 'check_spec', reason: 'The check runs a script that does not exist',
+ before: { check_id: 'c1', kind: 'command', spec: { cmd: 'npm run tset' }, required: true },
+ after: { check_id: 'c1', kind: 'command', spec: { cmd: 'npm run tset' }, required: false },
+ proposed_by: 'kwant', proposed_by_name: null, status: 'proposed', decided_at: null, created_at: '2026-10-27T11:55:00Z',
+ };
+ const rows = m.changeRows(c.before, c.after);
+ assert.deepEqual(rows.map((r) => [r.label, r.before, r.after, r.changed]).slice(0, 1), [['Required', 'Yes', 'No', true]]);
+ assert.ok(!rows.some((r) => r.key === 'check_id'), 'ids are not shown');
+ assert.deepEqual(m.changeRows(3, 5).map((r) => [r.before, r.after]), [['3', '5']]);
+ const item = { kind: 'workflow_change', id: 'wc1', text: 'Allow this change to a check: …' };
+ const html = ui.change({ item, change: c, now: NOW, onDecide: noop });
+ assert.match(html, /Proposed change to a check: <\/span>The check runs a script that does not exist/);
+ assert.match(html, /AutoFix proposed it/);
+ assert.match(html, /data-change-row="required"[\s\S]*Now[\s\S]*Yes[\s\S]*After[\s\S]*No/);
+ assert.match(html, /Unchanged \(2\)/);
+ assert.match(html, /data-change-approve[^>]*>[\s\S]*Approve and apply/);
+ assert.match(html, /data-change-reject[^>]*>Reject/);
+ assert.match(html, /Nothing changes until you approve/);
+ const loading = ui.change({ item, change: null, onDecide: noop });
+ assert.match(loading, /<button[^>]*disabled=""[^>]*data-change-approve/, 'no approving before the details are in');
+ const panel = ui.detail(detailProps(task({ state: 'blocked', needs_you: [item] }), { changes: [c], onDecideChange: noop }));
+ assert.match(panel, /data-workflow-changes[\s\S]*Change to approve[\s\S]*data-workflow-change="wc1"/);
+ assert.equal(m.columnOfTask(task({ state: 'blocked', needs_you: [item] })), 'needs_you');
+});
+
+test('a held task says it waits for Run, on the card and in the panel (D10)', () => {
+ const t = task({ state: 'ready', held_at: '2026-10-27T11:58:00Z' });
+ assert.equal(m.cardStatus(t, names, NOW), 'On hold after restore. Press Run to start it');
+ assert.equal(m.cardStatus(task({ state: 'backlog', held_at: '2026-10-27T11:58:00Z' }), names, NOW), 'On hold after restore. Press Run to start it');
+ const c = ui.card({ task: t, names, now: NOW, onOpen: noop });
+ assert.match(c, /data-held-badge[^>]*><span[^>]*>On hold</);
+ assert.match(c, /text-amber-200[^>]*>On hold after restore/);
+ const html = ui.detail(detailProps(t, { onRunHeld: noop }));
+ assert.match(html, /data-held[\s\S]*On hold after restore[\s\S]*No bot picks it up until you press Run/);
+ assert.match(html, /data-run-held[^>]*>[\s\S]*Run</);
+ assert.doesNotMatch(ui.detail(detailProps(task({ state: 'ready' }))), /data-held/);
+ assert.equal(m.eventText(ev('held', { checkpoint_id: 'cp1' }, 'person')).length > 0, true);
+});
+
+test('restore errors and results read plainly', () => {
+ const err = (code, status = 409) => new m.MissionError('x', status, code);
+ assert.match(m.restoreErrorText(err('stale_preview')), /Files changed since this preview/);
+ assert.match(m.restoreErrorText(err('not_held')), /isn’t on hold any more/);
+ assert.match(m.restoreErrorText(err('unknown_force_path', 422)), /isn’t in the preview any more/);
+ assert.match(m.autofixErrorText(err('over_recovery_budget')), /retry budget/);
+ const r = { restored: ['a.md', 'b.md'], deleted: ['c.md'], failed: [], task: task({ state: 'ready', held_at: '2026-10-27T12:00:00Z' }) };
+ assert.equal(m.restoredText(r, false), 'Restored: 2 files put back, 1 file removed. It’s on hold until you press Run.');
+ assert.equal(m.restoredText({ ...r, task: task({ state: 'ready' }) }, true), 'Restored: 2 files put back, 1 file removed. It will run again.');
+});
+
+test('the restore preview offers Restore (hold) by default and Restore and run again; conflicts name no task without proof (D11)', () => {
+ const p = {
+ checkpoint_id: 'cp1', preview_sha256: 'abc', changes: [{ path: 'docs/pricing.md', action: 'overwrite' }, { path: 'docs/new.md', action: 'delete' }],
+ conflicts: [{ path: 'README.md', changed_by_task: null, why: 'changed outside this task' }, { path: 'docs/faq.md', changed_by_task: 'b' }],
+ skipped: [{ path: 'big.bin', why: 'too large' }], external_not_undone: [{ tool_name: 'http', summary: 'POST https://api.example.com/publish', at: '2026-10-27T11:30:00Z' }],
+ not_undone_note: 'kwant can’t undo these. Check them yourself.', effects_known: false, task_state_after: 'ready', refused: null,
+ };
+ assert.equal(m.conflictText(p.conflicts[0]), 'Changed outside this task');
+ assert.equal(m.conflictText(p.conflicts[1], (id) => (id === 'b' ? 'Write the FAQ' : undefined)), 'Changed by “Write the FAQ”');
+ assert.equal(m.conflictText(p.conflicts[1]), 'Changed by another task');
+ const html = ui.preview({ preview: p, titleOf: () => 'Write the FAQ', onRestore: noop, onCancel: noop });
+ assert.match(html, /Put back[\s\S]*docs\/pricing\.md/);
+ assert.match(html, /data-force="README\.md"[\s\S]*Changed outside this task/);
+ assert.match(html, /Changed by “Write the FAQ”/);
+ assert.match(html, /data-not-undone[\s\S]*kwant can’t undo these[\s\S]*POST https:\/\/api\.example\.com\/publish/);
+ assert.match(html, /data-effects-unknown[^>]*>Side effects unknown/);
+ assert.match(html, /data-restore[^-][^>]*>[\s\S]*Restore<\/button>/);
+ assert.match(html, /data-restore-rerun[^>]*>Restore and run again/);
+ assert.match(html, /stays on hold until you press Run/);
+ const refused = ui.preview({ preview: { ...p, refused: 'running' }, onRestore: noop });
+ assert.match(refused, /data-restore-refused="running"/);
+ assert.doesNotMatch(refused, /data-restore-rerun/);
+});
+
+test('the restore section shows only with checkpoints, and not on a verified task', () => {
+ assert.equal(ui.restore({ task: task({ checkpoint_count: 0 }) }), '');
+ assert.match(ui.restore({ task: task({ checkpoint_count: 3 }) }), /data-restore-open[^>]*>[\s\S]*Restore files from a checkpoint \(3\)/);
+ assert.match(ui.restore({ task: task({ state: 'verified', checkpoint_count: 3 }) }), /Use “Redo as a copy”/);
+ assert.match(ui.restore({ task: task({ state: 'working', checkpoint_count: 3 }) }), /restore once it stops/);
+});
+
+test('Insights count AutoFix fixes when the server sends them', () => {
+ const base = { verified_7d: 4, verified_by_check_7d: 3, verified_by_person_7d: 1, needs_you: 2, rework_rate_7d: 0.1, tokens_7d: 50000, tokens_per_verified_7d: 12500, open: 5 };
+ const old = ui.insights({ insights: base });
+ assert.doesNotMatch(old, /Fixed by AutoFix/);
+ const html = ui.insights({ insights: { ...base, autofix_7d: { attempts: 5, succeeded: 3, tokens: 8000 }, failures_by_class_7d: { transient: 3, check_failed: 2 } } });
+ assert.match(html, /Fixed by AutoFix[\s\S]*3 of 5[\s\S]*8k tokens on retries/);
+ assert.match(html, /A temporary error: 3, A check failed: 2/);
+ assert.match(html, /lg:grid-cols-6/);
+});
+
+test('AutoFix settings parse safely from GET /api/settings', () => {
+ assert.equal(m.parseAutofixSettings({}), null, 'an older server: no AutoFix setting shown');
+ assert.equal(m.parseAutofixSettings({ autofix: 'maybe' }), null);
+ assert.deepEqual(m.parseAutofixSettings({ autofix: 'off', recovery_budget_pct: 25 }), { autofix: 'off', recovery_budget_pct: 25 });
+ assert.deepEqual(m.parseAutofixSettings({ autofix: 'on', recovery_budget_pct: 140 }), { autofix: 'on', recovery_budget_pct: 100 });
+ assert.deepEqual(m.parseAutofixSettings({ autofix: 'suggest' }), { autofix: 'suggest', recovery_budget_pct: 25 });
+});