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.

0.9.0 P1: watch a mission (UI) (#511)

Oleksandr Ivanchenko52a5610f5c60
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 46c13078..5ca84e57 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -49,6 +49,8 @@ import type { RoutineFocus } from './components/RoutinesPanel';
import { AwayPage } from './components/AwayView';
import { LooseEndsPage } from './components/LooseEndsView';
import { MissionBoardPage } from './components/MissionBoardView';
+import { WatchChatMessage } from './components/MissionWatch';
+import type { WatchMeta } from './missionWatch';
import { MISSION_BOARD_SETTING_EVENT, emitMission, parseMissionBoardSetting, sourceChat } from './missions';
import { type ChatTarget, type NotifiedChat, notifiedPlace, planOpenTarget } from './chatTarget';
import { ParallelPage } from './components/ParallelUniverseView';
@@ -474,6 +476,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const ideaJarCount = useIdeaJarBadge(space.id);
const jarWobble = useJarWobble();
const [pendingMissionId, setPendingMissionId] = useState<string | null>(null);
+ const [pendingWatchReport, setPendingWatchReport] = useState(false);
const [ideaToast, setIdeaToast] = useState<{ id: string; state: IdeaDropToastState } | null>(null);
const [jarAnnouncement, setJarAnnouncement] = useState('');
const [settingsFocusRow, setSettingsFocusRow] = useState<string | null>(null);
@@ -2128,6 +2131,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
/** Opens the thread, channel or direct chat an away item links to. */
const openAwayItem = (item: AwayItem) => {
+ // 0.9.0 P1: a watch item opens its mission's report on the board, where the needs-you line is.
+ if (item.kind === 'watch' && item.mission_id) {
+ setPendingMissionId(item.mission_id);
+ setPendingWatchReport(true);
+ showPage('board');
+ return;
+ }
const t = awayTarget(item);
// 0.8.1 F6: the same opener as a notification's tap, so a gone chat lands in the bot's 1:1 and
// an approval row shows its card
@@ -2511,6 +2521,27 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return decisionError(err, d === 'deny' ? 'say no' : d === 'undo' ? 'undo the hire' : 'hire it');
}
};
+ const renderWatchReport = (msg: ChatMessage, meta: WatchMeta, flash: boolean) => (
+ <WatchChatMessage
+ report={meta.report}
+ failed={meta.failed}
+ fallbackText={msg.text}
+ watcherName={kwantName(msg.sender_id) ?? chatTitle}
+ watcherId={msg.sender_id}
+ at={msg.created_at ?? null}
+ messageId={msg.id}
+ flash={flash}
+ onSeeClaims={
+ meta.missionId
+ ? () => {
+ setPendingMissionId(meta.missionId);
+ setPendingWatchReport(true);
+ showPage('board');
+ }
+ : undefined
+ }
+ />
+ );
const renderBotAction = (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => {
const owner = meta.kwant_id ?? undefined;
return (
@@ -3865,7 +3896,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
openTaskId={pendingTaskId}
onOpenedTaskId={() => setPendingTaskId(null)}
openMissionId={pendingMissionId}
- onOpenedMissionId={() => setPendingMissionId(null)}
+ openWatchReport={pendingWatchReport}
+ onOpenedMissionId={() => {
+ setPendingMissionId(null);
+ setPendingWatchReport(false);
+ }}
/>
);
const loose = (
@@ -4018,6 +4053,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
renderConnectionSuggestion={renderConnectionSuggestion}
renderBotAction={renderBotAction}
onOpenToolNote={openToolNote}
+ renderWatchReport={renderWatchReport}
renderHire={renderHire}
renderRouteChoice={renderRouteChoice}
rerouteTargets={openThreadId ? [] : rerouteTargetsFor(currentChannel, kwants)}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index fc216286..13f6e7c5 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -1,7 +1,7 @@
// "While you were away" (batch 3): what agents need from you, finished and failed since you last
// looked. Pure helpers, so the page and the node tests share them; the API calls are at the bottom.
-export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run';
+export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run' | 'watch';
export type AwaySection = 'waiting' | 'finished' | 'failed';
export type ApprovalDecision = 'allow_once' | 'always_allow' | 'deny';
@@ -28,6 +28,9 @@ export interface AwayItem {
details?: Record<string, unknown>;
/** Approvals only: set when the payment floor asked, also on servers that send no details. */
payment_reason?: string;
+ /** 0.9.0 P1, watch items only: the watched mission and the first task that needs the person. */
+ mission_id?: string | null;
+ task_id?: string | null;
}
export interface AwayCounts {
@@ -107,6 +110,8 @@ export function itemLabel(item: Pick<AwayItem, 'kind' | 'status'>): { label: str
case 'approval':
// Its turn stopped waiting, but the card is open and a late Allow resumes the work.
return item.status === 'waiting' ? { label: 'Still open', tone: 'sky' } : { label: 'Needs approval', tone: 'amber' };
+ case 'watch':
+ return { label: 'Watch', tone: 'amber' };
case 'routine_run':
return item.status === 'ok' ? { label: 'Routine ran', tone: 'emerald' } : { label: 'Routine failed', tone: 'rose' };
case 'delegation':
@@ -148,6 +153,28 @@ export function awayTarget(item: Pick<AwayItem, 'kwant_id' | 'link'>): AwayTarge
return { direct: l.direct_kwant_id || item.kwant_id };
}
+/**
+ * 0.9.0 P1: a watch item comes as {at, mission_id, task_id, thread_id} with no `timestamp` or `link`
+ * (p1-contract section 8). Give it the shape every card reads; other items pass through untouched.
+ */
+export function normalizeAwayItem(raw: AwayItem): AwayItem {
+ if (raw.kind !== 'watch') return raw;
+ const r = raw as AwayItem & { at?: unknown; thread_id?: unknown };
+ const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
+ return {
+ ...r,
+ timestamp: str(r.timestamp) ?? str(r.at) ?? '',
+ link: r.link ?? { thread_id: str(r.thread_id), channel_id: null, direct_kwant_id: str(r.kwant_id) },
+ mission_id: str(r.mission_id),
+ task_id: str(r.task_id),
+ };
+}
+
+export function normalizeAway(r: AwayResponse): AwayResponse {
+ const fix = (l: AwayItem[] | undefined) => (Array.isArray(l) ? l.map(normalizeAwayItem) : []);
+ return { ...r, waiting: fix(r.waiting), finished: fix(r.finished), failed: fix(r.failed) };
+}
+
/** Drops an acted-on item right away, before the refresh confirms it. */
export function withoutItem(r: AwayResponse, section: AwaySection, id: string): AwayResponse {
const list = r[section].filter((i) => i.id !== id);
@@ -208,7 +235,7 @@ async function call<T>(method: string, url: string, body?: unknown): Promise<T>
const enc = encodeURIComponent;
export const awayApi = {
- get: (since?: string) => call<AwayResponse>('GET', `/api/away${since ? `?since=${enc(since)}` : ''}`),
+ get: (since?: string) => call<AwayResponse>('GET', `/api/away${since ? `?since=${enc(since)}` : ''}`).then(normalizeAway),
seen: () => call<{ last_seen: string }>('POST', '/api/away/seen'),
answer: (id: string, choice: number) => call<unknown>('POST', `/api/questions/${enc(id)}/answer`, { choice }),
resolve: (id: string, decision: ApprovalDecision) => call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, { decision }),
diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsx
index 6f301241..35ae202c 100644
--- a/frontend/src/components/AwayView.tsx
+++ b/frontend/src/components/AwayView.tsx
@@ -68,12 +68,18 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice
const disabled = busy !== null;
const title = awayTitle(item);
return (
- <li key={`${item.kind}:${item.id}`} className="rounded-xl border border-zinc-800 bg-zinc-900/60 hover:border-zinc-700 transition-colors">
+ <li
+ key={`${item.kind}:${item.id}`}
+ data-away-kind={item.kind}
+ className={`rounded-xl border transition-colors ${
+ item.kind === 'watch' ? 'border-amber-400/30 bg-amber-400/[.06] hover:border-amber-400/50' : 'border-zinc-800 bg-zinc-900/60 hover:border-zinc-700'
+ }`}
+ >
<button
type="button"
onClick={() => onOpen(item)}
className="w-full flex items-start gap-3 p-3 text-left rounded-xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
- aria-label={`${title}, ${label}, from ${item.kwant_name}, ${when}. Open the chat.`}
+ aria-label={`${title}, ${label}, from ${item.kwant_name}, ${when}. ${item.kind === 'watch' && item.mission_id ? 'Open the mission.' : 'Open the chat.'}`}
>
<ModernAvatar role={item.kwant_name} name={item.kwant_name} size={30} kwantId={item.kwant_id} />
<div className="flex-1 min-w-0">
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 9219b3c1..ad9a3c30 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,4 +1,5 @@
import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from 'react';
+import { parseWatchMeta, type WatchMeta } from '../missionWatch';
import { flushSync } from 'react-dom';
import { queuedText } from '../claudeVm';
import { QueuedBeside } from './QueuedBeside';
@@ -294,6 +295,8 @@ export interface ChatViewProps {
renderBotAction?: (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => React.ReactNode;
/** 0.9.0 P5: a bot's tool-note line (meta kind "tool_note"); "See the note" opens it on Connections. */
onOpenToolNote?: (noteId: string) => void;
+ /** A mission watcher's check report (message meta kind "watch"). */
+ renderWatchReport?: (msg: ChatMessage, meta: WatchMeta, flash: boolean) => React.ReactNode;
/** A bot's proposal to hire a new bot (message meta kind "hire_proposal"). */
renderHire?: (msg: ChatMessage, meta: HireMeta, flash: boolean) => React.ReactNode;
/** Laya's "Who should answer this?" card (message meta kind "route_choice"); `question` is the
@@ -514,6 +517,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
renderConnectionSuggestion,
renderBotAction,
onOpenToolNote,
+ renderWatchReport,
renderHire,
renderRouteChoice,
rerouteTargets = [],
@@ -1290,6 +1294,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
const connection = msg.meta && renderConnectionSuggestion ? parseConnectionMeta(msg.meta) : null;
if (connection && renderConnectionSuggestion)
return <React.Fragment key={msg.id}>{renderConnectionSuggestion(msg, connection, flashId === msg.id)}</React.Fragment>;
+ const watch = msg.meta && renderWatchReport ? parseWatchMeta(msg.meta) : null;
+ if (watch && renderWatchReport) return <React.Fragment key={msg.id}>{renderWatchReport(msg, watch, flashId === msg.id)}</React.Fragment>;
const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;
if (botAction && renderBotAction) return <React.Fragment key={msg.id}>{renderBotAction(msg, botAction, flashId === msg.id)}</React.Fragment>;
const toolNote = msg.meta ? parseToolNoteMeta(msg.meta) : null;
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index ee9dea6a..63a74edb 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -168,6 +168,9 @@ import {
} from '../missions';
import { DEFAULT_CLASS, ENGINE_CANT_SANDBOX, TIER_HINTS, classLabel, engineCantSandboxText, showsTier, tierLabel, toClass, validClass } from '../flightSchool';
import { ScrollRow } from './ScrollRow';
+import { MissionWatchControls, WatchBoardContext, type WatchBoard } from './MissionWatch';
+import { watchApi, type WatchApi } from '../missionWatch';
+import { usePhoneLayout } from '../usePhoneLayout';
const TONES: Record<Tone, string> = {
emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',
@@ -590,6 +593,8 @@ export const MissionSummary: React.FC<{
.filter(([k]) => k !== 'cancelled')
.reduce((n, [, v]) => n + v, 0);
return (
+ <MissionWatchControls mission={m}>
+ {({ chip, report }) => (
<section className={`${card} p-3 sm:p-4 space-y-2`} data-mission={m.id} aria-label={`Mission: ${m.title}`}>
<div className="flex flex-wrap items-start gap-2">
<Target size={16} className="mt-0.5 shrink-0 text-sky-400" aria-hidden="true" />
@@ -604,6 +609,7 @@ export const MissionSummary: React.FC<{
</div>
<Badge tone={st.tone}>{st.label}</Badge>
{m.over_budget && <Badge tone="rose">Over its limit</Badge>}
+ {chip && <div className="basis-full sm:basis-auto min-w-0" data-watch-chip-slot>{chip}</div>}
</div>
<div className="space-y-1">
<div className="flex flex-wrap justify-between gap-x-3 text-[11px] text-zinc-400">
@@ -623,6 +629,7 @@ export const MissionSummary: React.FC<{
)}
</div>
{m.over_budget && <p className="text-[11px] text-rose-300">No new task starts until you raise or remove the mission’s token limit.</p>}
+ {report}
{m.status === 'draft' && (
<div className="flex flex-wrap items-center gap-2 pt-1">
<p className="text-xs text-amber-200 flex-1 min-w-[12rem]">{m.lead_name ?? 'A bot'} planned this. Nothing runs until you approve it.</p>
@@ -635,6 +642,8 @@ export const MissionSummary: React.FC<{
</div>
)}
</section>
+ )}
+ </MissionWatchControls>
);
};
@@ -3027,13 +3036,18 @@ export const MissionBoardPage: React.FC<{
onOpenedTaskId?: () => void;
/** A mission to select once the board has loaded (Open on board from an idea's take). */
openMissionId?: string | null;
+ /** 0.9.0 P1: with `openMissionId`, also open that mission's watch report ("See the claims"). */
+ openWatchReport?: boolean;
+ /** 0.9.0 P1: the watch API; tests and the shots pass a fake. */
+ watchApi?: WatchApi;
onOpenedMissionId?: () => void;
-}> = ({ spaceId, names, avatars, onBack, onOpenChat, turns, teams = NO_TEAMS, rooms, threadTitles, onOpenPlace, openTaskId = null, onOpenedTaskId, openMissionId = null, onOpenedMissionId }) => {
+}> = ({ spaceId, names, avatars, onBack, onOpenChat, turns, teams = NO_TEAMS, rooms, threadTitles, onOpenPlace, openTaskId = null, onOpenedTaskId, openMissionId = null, onOpenedMissionId, openWatchReport = false, watchApi: watchClient = watchApi }) => {
const [tasks, setTasks] = useState<Task[] | null>(null);
const [missions, setMissions] = useState<Mission[]>([]);
const [insights, setInsights] = useState<Insights | null>(null);
const [refreshCount, setRefreshCount] = useState(0);
const [missionId, setMissionId] = useState<string | null>(null);
+ const [watchReportFor, setWatchReportFor] = useState<string | null>(null);
const [column, setColumn] = useState<Column>('ready');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -3253,6 +3267,7 @@ export const MissionBoardPage: React.FC<{
useEffect(() => {
if (!openMissionId || tasks === null) return;
setMissionId(openMissionId);
+ setWatchReportFor(openWatchReport ? openMissionId : null);
onOpenedMissionId?.();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [openMissionId, tasks === null]);
@@ -3698,9 +3713,28 @@ export const MissionBoardPage: React.FC<{
const tasksById = useMemo(() => Object.fromEntries((tasks ?? []).map((t) => [t.id, t])), [tasks]);
const listed = openId ? tasksById[openId] : undefined;
+ const phone = usePhoneLayout();
+ const watchBoard = useMemo<WatchBoard>(
+ () => ({
+ api: watchClient,
+ phone,
+ onChanged: (id, w) => setMissions((list) => list.map((x) => (x.id === id ? ({ ...x, watch: w } as Mission) : x))),
+ onOpenChat: onOpenPlace
+ ? (m) => {
+ const kwantId = m.thread_id ? m.lead_kwant_id : m.channel_id ? null : m.direct_kwant_id ?? m.lead_kwant_id;
+ onOpenPlace({ channelId: m.thread_id ? null : m.channel_id, kwantId, threadId: m.thread_id });
+ }
+ : undefined,
+ onOpenTask: (id) => openTask(id),
+ openReportFor: watchReportFor,
+ }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [watchClient, phone, onOpenPlace, watchReportFor],
+ );
return (
<AvatarsContext.Provider value={avatars ?? NO_AVATARS}>
+ <WatchBoardContext.Provider value={watchBoard}>
<MissionBoardView
tasks={boardTasks}
missions={missions}
@@ -3837,6 +3871,7 @@ export const MissionBoardPage: React.FC<{
)}
</TaskPanel>
)}
+ </WatchBoardContext.Provider>
</AvatarsContext.Provider>
);
};
diff --git a/frontend/src/components/MissionWatch.tsx b/frontend/src/components/MissionWatch.tsx
new file mode 100644
index 00000000..e88da11a
--- /dev/null
+++ b/frontend/src/components/MissionWatch.tsx
@@ -0,0 +1,946 @@
+// 0.9.0 P1: watch a mission (design: release-090/designs/p1-watch-mission.md). The Watch chip on the
+// mission card, its setup popover (desktop) or sheet (phone), the report block under the card, the
+// watcher's chat message and the amber Inbox row. All copy is from the design; all numbers are the
+// report's own rows. Data that doesn't parse never reaches here (missionWatch.ts drops it).
+import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { AlertCircle, AlertTriangle, CheckCircle2, ChevronDown, ChevronUp, Eye, Hand, HelpCircle, Info, Loader2, MessageSquare, RotateCcw, ShieldCheck, XCircle, type LucideIcon } from 'lucide-react';
+import {
+ CHIP_TONES,
+ REPORT_SUB,
+ SETUP_BODY,
+ SETUP_BODY_PHONE,
+ VERDICT_TEXT,
+ chatParts,
+ chipView,
+ codeParts,
+ costText,
+ defaultCandidate,
+ finishedCheckId,
+ failedChatText,
+ firstNeedsYou,
+ footerText,
+ guardText,
+ hasReport,
+ hm,
+ orderClaims,
+ relationText,
+ reportOpensItself,
+ rowTint,
+ stickyText,
+ summaryChips,
+ taskTitle,
+ youText,
+ type ChipView,
+ type MissionWatch,
+ type NeedsYouAction,
+ type WatchAction,
+ type WatchApi,
+ type WatchCandidate,
+ type WatchClaim,
+ type WatchReport,
+ type WatchedMission,
+ type Verdict,
+} from '../missionWatch';
+import { inlineCodeClass } from './markdownInline';
+import { OwnerAvatar, UndoToast } from './MissionBoardView';
+
+const ring = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#9d8fff]';
+const ghostBtn = `inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3 rounded-lg border border-white/10 bg-white/[.03] text-[12.5px] font-medium text-zinc-100 hover:bg-white/[.07] disabled:opacity-50 ${ring}`;
+const primaryBtn = `inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3.5 rounded-lg bg-[#6f5ce6] text-[12.5px] font-semibold text-white hover:bg-[#7d6bf0] disabled:opacity-50 ${ring}`;
+const linkBtn = `text-[12.5px] font-medium text-[#b9adff] hover:text-[#d3ccff] underline-offset-2 hover:underline rounded ${ring}`;
+
+/** "Ran `npm test`" with the code in code spans; text nodes only. */
+const CodeText: React.FC<{ text: string }> = ({ text }) => (
+ <>
+ {codeParts(text).map((p, i) =>
+ p.code ? (
+ <code key={i} className={inlineCodeClass}>
+ {p.text}
+ </code>
+ ) : (
+ <React.Fragment key={i}>{p.text}</React.Fragment>
+ ),
+ )}
+ </>
+);
+
+// ---------- Chip ----------
+
+const ChipIcon: React.FC<{ v: ChipView; size: number }> = ({ v, size }) => {
+ if (v.icon === 'loader') return <Loader2 size={size} aria-hidden="true" className="shrink-0 motion-safe:animate-spin" data-watch-loader />;
+ if (v.icon === 'alert-triangle') return <AlertTriangle size={size} aria-hidden="true" className="shrink-0" />;
+ if (v.icon === 'alert-circle') return <AlertCircle size={size} aria-hidden="true" className="shrink-0" />;
+ return <Eye size={size} aria-hidden="true" className="shrink-0" />;
+};
+
+export const WatchChip = React.forwardRef<
+ HTMLButtonElement,
+ { view: ChipView; expanded: boolean; phone?: boolean; onClick: () => void; controls?: string }
+>(({ view: v, expanded, phone = false, onClick, controls }, ref) => {
+ const [lead, rest] = v.avatar ? ['Watching · ', v.avatar.name] : [v.text, null];
+ return (
+ <button
+ ref={ref}
+ type="button"
+ onClick={onClick}
+ disabled={v.disabled}
+ title={v.tooltip}
+ aria-expanded={v.click === 'retry' || v.click === 'none' ? undefined : expanded}
+ aria-controls={controls}
+ aria-label={v.label}
+ data-watch-chip={v.tone}
+ className={`shrink-0 inline-flex max-w-full items-center gap-1.5 rounded-full border ${phone ? 'h-9 px-3 text-[13px]' : 'h-7 px-[11px] text-[12.5px]'} font-medium transition-colors motion-reduce:transition-none motion-reduce:duration-0 disabled:cursor-not-allowed disabled:opacity-50 ${CHIP_TONES[v.tone]} ${ring}`}
+ >
+ <ChipIcon v={v} size={14} />
+ {/* The label is announced politely when a check finishes; the button keeps its own aria-label. */}
+ <span aria-live="polite" className="inline-flex min-w-0 items-center gap-1.5">
+ <span className="truncate">{lead}</span>
+ {v.avatar && (
+ <>
+ <OwnerAvatar kwantId={v.avatar.kwant_id} name={v.avatar.name} size={16} />
+ <span className="truncate">{rest}</span>
+ </>
+ )}
+ </span>
+ </button>
+ );
+});
+WatchChip.displayName = 'WatchChip';
+
+// ---------- Setup popover / sheet ----------
+
+type SetupMode = 'setup' | 'settings' | 'change';
+
+const CandidateRow: React.FC<{ c: WatchCandidate; picked: boolean; phone: boolean; name: string; onPick: () => void }> = ({ c, picked, phone, name, onPick }) => (
+ <label
+ data-watch-candidate={c.kwant_id}
+ className={`flex items-center gap-2.5 rounded-[10px] border px-2.5 ${phone ? 'min-h-[48px] text-[14px]' : 'min-h-[36px] text-[13px]'} ${
+ picked ? 'border-[#9d8fff] bg-[#8270f5]/12' : 'border-transparent'
+ } ${c.can_run ? 'cursor-pointer hover:bg-white/[.04]' : 'opacity-50 cursor-not-allowed'}`}
+ >
+ <input
+ type="radio"
+ name={name}
+ value={c.kwant_id}
+ checked={picked}
+ disabled={!c.can_run}
+ onChange={onPick}
+ className={`h-4 w-4 shrink-0 accent-[#8270f5] ${ring}`}
+ />
+ <OwnerAvatar kwantId={c.kwant_id} name={c.name} size={20} />
+ <span className="min-w-0 break-words">
+ <span className="font-semibold text-zinc-100">{c.name}</span> <span className="text-zinc-500">{relationText(c, phone)}</span>
+ </span>
+ </label>
+);
+
+export const WatchSetup: React.FC<{
+ mission: WatchedMission;
+ watch: MissionWatch | null;
+ candidates: WatchCandidate[] | null;
+ loadError?: string | null;
+ phone?: boolean;
+ busy?: boolean;
+ error?: string | null;
+ /** Start as "Change who checks" (from the can't-run chip's "Pick another bot"). */
+ startMode?: SetupMode;
+ timeZone?: string;
+ onWatch: (kwantId: string) => void;
+ onStop: () => void;
+ onCheckNow: () => void;
+ onClose: () => void;
+ id?: string;
+}> = ({ mission, watch, candidates, loadError = null, phone = false, busy = false, error = null, startMode, timeZone, onWatch, onStop, onCheckNow, onClose, id }) => {
+ const on = !!watch && !['off', 'no_tasks', 'finished'].includes(watch.state);
+ const [mode, setMode] = useState<SetupMode>(startMode ?? (on ? 'settings' : 'setup'));
+ const [confirmStop, setConfirmStop] = useState(false);
+ const cs = candidates ?? [];
+ const initial = (on && cs.find((c) => c.kwant_id === watch?.kwant_id && c.can_run)) || defaultCandidate(cs);
+ // The person's pick, else the current watcher or the default. Derived in render (not set in an
+ // effect) so the radio is checked on the same commit the candidates arrive, and the layout effect
+ // below can focus it.
+ const [chosen, setPick] = useState<string | null>(null);
+ const pick = chosen ?? initial?.kwant_id ?? null;
+ const picked = cs.find((c) => c.kwant_id === pick) ?? null;
+ const box = useRef<HTMLDivElement>(null);
+ const titleId = useId();
+ const radioName = useId();
+
+ // Focus the selected radio (or the first button) when the panel opens or changes mode.
+ useLayoutEffect(() => {
+ const el = box.current;
+ if (!el) return;
+ const target = el.querySelector<HTMLElement>('input[type=radio]:checked') ?? el.querySelector<HTMLElement>('button:not([disabled])');
+ target?.focus();
+ }, [mode, confirmStop, candidates === null]);
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ if (confirmStop) setConfirmStop(false);
+ else onClose();
+ return;
+ }
+ if (e.key !== 'Tab' || !box.current) return;
+ const f = [...box.current.querySelectorAll<HTMLElement>('button:not([disabled]), input:not([disabled])')].filter((x) => !(x instanceof HTMLInputElement && x.type === 'radio' && !x.checked));
+ if (!f.length) return;
+ const first = f[0];
+ const last = f[f.length - 1];
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+
+ const watcher = watch?.kwant_name ?? picked?.name ?? 'the watcher';
+ const shell = phone
+ ? 'fixed inset-x-0 bottom-0 z-50 max-h-[85vh] overflow-y-auto rounded-t-[18px] border-t border-white/10 bg-surface-overlay px-4 pt-2 pb-[max(1rem,env(safe-area-inset-bottom))] shadow-2xl'
+ : 'absolute right-0 top-full z-40 mt-2 w-[380px] max-w-[calc(100vw-2rem)] rounded-[14px] border border-white/10 bg-surface-overlay p-4 shadow-2xl';
+
+ let body: React.ReactNode;
+ if (confirmStop) {
+ body = (
+ <div className="space-y-3" data-watch-stop-confirm>
+ <p className="text-[14px] font-semibold text-zinc-100">Stop watching this mission?</p>
+ <p className="text-[13px] text-zinc-300">{watcher} won’t check claims any more. Past reports stay in the mission chat.</p>
+ {error && (
+ <p role="alert" className="text-[12.5px] text-rose-300" data-watch-stop-error>
+ {error}
+ </p>
+ )}
+ <div className="flex justify-end gap-2">
+ <button type="button" className={ghostBtn} onClick={() => setConfirmStop(false)}>
+ Cancel
+ </button>
+ <button type="button" className={primaryBtn} disabled={busy} onClick={onStop} data-watch-stop-yes>
+ Stop watching
+ </button>
+ </div>
+ </div>
+ );
+ } else if (mode === 'settings' && watch) {
+ const st = watch.state;
+ body = (
+ <div className="space-y-3" data-watch-settings={st}>
+ <div className="flex items-center gap-2 text-[13px] text-zinc-100">
+ <OwnerAvatar kwantId={watch.kwant_id} name={watcher} size={20} />
+ <span>
+ <span className="font-semibold">{watcher}</span> <span className="text-zinc-500">checks the claims</span>
+ </span>
+ </div>
+ {st === 'cant_run' ? (
+ <p className="rounded-[10px] border border-amber-300/30 bg-amber-300/8 px-3 py-2 text-[13px] text-amber-200" data-watch-cant-run>
+ {watcher} can’t run: {watch.reason?.text ?? 'it can’t run now'}. Pick another bot or fix {watcher}.
+ </p>
+ ) : st === 'checking' ? (
+ <p className="text-[12.5px] text-zinc-400">Checking since {hm(watch.last_check?.started_at, timeZone) || 'just now'}</p>
+ ) : st === 'over_limit' ? (
+ <p className="text-[12.5px] text-amber-200">The check didn’t start: this mission is over its limit. Raise or remove the limit first.</p>
+ ) : (
+ <p className="text-[12.5px] text-zinc-400" data-watch-last>
+ {watch.last_check?.finished_at ? `Last checked ${hm(watch.last_check.finished_at, timeZone)}` : 'Not checked yet'}
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="text-[12.5px] text-rose-300">
+ {error}
+ </p>
+ )}
+ <div className={`flex flex-wrap gap-2 ${phone ? '[&>button]:flex-1' : 'justify-end'}`}>
+ {watch.can_check_now && (
+ <button type="button" className={ghostBtn} disabled={busy} onClick={onCheckNow} data-watch-check-now>
+ {st === 'failed' ? 'Try again' : 'Check again now'}
+ </button>
+ )}
+ <button type="button" className={ghostBtn} disabled={busy} onClick={() => setMode('change')} data-watch-change>
+ {st === 'cant_run' ? 'Pick another bot' : 'Change who checks'}
+ </button>
+ <button type="button" className={ghostBtn} disabled={busy} onClick={() => (phone ? onStop() : setConfirmStop(true))} data-watch-stop>
+ Stop watching
+ </button>
+ </div>
+ </div>
+ );
+ } else {
+ const who = picked?.name ?? 'a bot';
+ body = (
+ <form
+ className="space-y-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (picked?.can_run && !busy) onWatch(picked.kwant_id);
+ }}
+ >
+ <p className={`${phone ? 'text-[14px]' : 'text-[13px]'} text-zinc-100`}>{phone ? SETUP_BODY_PHONE : SETUP_BODY}</p>
+ <fieldset className="space-y-1">
+ <legend className="mb-1 text-[12px] font-semibold text-zinc-300">Who checks</legend>
+ {candidates === null ? (
+ <p className="text-[12.5px] text-zinc-500" role="status">
+ {loadError ?? 'Loading…'}
+ </p>
+ ) : cs.length === 0 ? (
+ <p className="text-[12.5px] text-zinc-500">No bot in this space can check yet.</p>
+ ) : (
+ cs.map((c) => <CandidateRow key={c.kwant_id} c={c} picked={c.kwant_id === pick} phone={phone} name={radioName} onPick={() => setPick(c.kwant_id)} />)
+ )}
+ </fieldset>
+ <p className="flex gap-2 rounded-[10px] border border-white/[.06] bg-white/[.03] px-3 py-2 text-[12.5px] text-zinc-300">
+ <ShieldCheck size={14} aria-hidden="true" className="mt-0.5 shrink-0" />
+ <span>{guardText(who)}</span>
+ </p>
+ {!phone && <p className="text-[12px] text-zinc-500">{costText(who)}</p>}
+ {error && (
+ <p role="alert" className="text-[12.5px] text-rose-300">
+ {error}
+ </p>
+ )}
+ <div className={`flex gap-2 ${phone ? '[&>button]:flex-1' : 'justify-end'}`}>
+ <button type="button" className={ghostBtn} onClick={() => (mode === 'change' ? setMode('settings') : onClose())}>
+ Cancel
+ </button>
+ <button type="submit" className={primaryBtn} disabled={busy || !picked?.can_run} data-watch-confirm>
+ Watch with {who}
+ </button>
+ </div>
+ </form>
+ );
+ }
+
+ return (
+ <>
+ {phone && <div aria-hidden="true" className="fixed inset-0 z-40 bg-black/50" onClick={onClose} data-watch-backdrop />}
+ <div ref={box} id={id} role="dialog" aria-modal={phone ? true : undefined} aria-labelledby={titleId} onKeyDown={onKeyDown} className={shell} data-watch-setup={phone ? 'sheet' : 'popover'} data-mission-id={mission.id}>
+ {phone && <div aria-hidden="true" className="mx-auto mb-3 h-1 w-10 rounded-full bg-white/15" />}
+ <h4 id={titleId} className={`mb-2 flex items-center gap-2 font-[650] text-zinc-100 ${phone ? 'text-[17px]' : 'text-[14px]'}`}>
+ <Eye size={16} aria-hidden="true" />
+ Watch this mission
+ </h4>
+ {body}
+ </div>
+ </>
+ );
+};
+
+// ---------- Report ----------
+
+const VERDICT_LOOK: Record<Verdict, { icon: LucideIcon; cls: string }> = {
+ holds: { icon: CheckCircle2, cls: 'text-teal-300' },
+ doesnt_hold: { icon: XCircle, cls: 'text-rose-300' },
+ cant_tell: { icon: HelpCircle, cls: 'text-zinc-400' },
+};
+
+const VerdictText: React.FC<{ v: Verdict }> = ({ v }) => {
+ const L = VERDICT_LOOK[v];
+ const Icon = L.icon;
+ return (
+ <span className={`inline-flex items-center gap-1.5 font-semibold ${L.cls}`} data-verdict={v}>
+ <Icon size={14} aria-hidden="true" className="shrink-0" />
+ {VERDICT_TEXT[v]}
+ </span>
+ );
+};
+
+const CHIP_LOOK = {
+ rose: 'border-rose-300/40 bg-rose-300/8 text-rose-300',
+ amber: 'border-amber-300/40 bg-amber-300/8 text-amber-300',
+ zinc: 'border-white/10 bg-white/[.03] text-zinc-300',
+ teal: 'border-teal-400/35 bg-teal-400/8 text-teal-300',
+};
+const TINT = { rose: 'bg-rose-300/5', amber: 'bg-amber-400/5' };
+const CARD_TINT = { rose: 'border-rose-300/25 bg-rose-300/5', amber: 'border-amber-400/30 bg-amber-400/5' };
+
+const ClaimCard: React.FC<{ c: WatchClaim }> = ({ c }) => {
+ const t = rowTint(c);
+ return (
+ <li className={`rounded-xl border px-3 py-2.5 ${t ? CARD_TINT[t] : 'border-hairline'}`} data-claim={c.task_id} data-tint={t ?? ''}>
+ <div className="flex items-start gap-2">
+ {c.owner_name && <OwnerAvatar kwantId={c.owner_kwant_id} name={c.owner_name} size={18} />}
+ <p className="min-w-0 flex-1 break-words text-[14px] font-semibold text-zinc-100">{c.task_title}</p>
+ <span className="shrink-0 text-[13px]">
+ <VerdictText v={c.verdict} />
+ </span>
+ </div>
+ <p className="mt-1 break-words text-[13.5px] text-zinc-100">
+ {c.owner_name ? `${c.owner_name}: ` : ''}
+ {c.claimed}
+ </p>
+ <p className="mt-0.5 break-words text-[12.5px] text-zinc-400">
+ <CodeText text={c.checked} />
+ </p>
+ </li>
+ );
+};
+
+const ClaimRow: React.FC<{ c: WatchClaim }> = ({ c }) => {
+ const t = rowTint(c);
+ return (
+ <tr className={`border-t border-hairline align-top ${t ? TINT[t] : ''}`} data-claim={c.task_id} data-tint={t ?? ''}>
+ <th scope="row" className="px-3 py-2.5 text-left font-normal">
+ <span className="block break-words text-[12.5px] font-semibold text-zinc-100">{c.task_title}</span>
+ <span className="mt-0.5 block truncate font-mono text-[11px] text-zinc-500" title={c.task_id}>
+ {c.task_id}
+ </span>
+ </th>
+ <td className="px-3 py-2.5">
+ <span className="inline-flex min-w-0 items-center gap-1.5 text-[12.5px] text-zinc-200">
+ {c.owner_name && <OwnerAvatar kwantId={c.owner_kwant_id} name={c.owner_name} size={16} />}
+ <span className="break-words">{c.owner_name ?? 'No owner'}</span>
+ </span>
+ </td>
+ <td className="px-3 py-2.5 break-words text-[12.5px] text-zinc-200">{c.claimed}</td>
+ <td className="px-3 py-2.5 break-words text-[12.5px] text-zinc-300">
+ <CodeText text={c.checked} />
+ </td>
+ <td className="px-3 py-2.5 text-[12.5px] whitespace-nowrap">
+ <VerdictText v={c.verdict} />
+ </td>
+ </tr>
+ );
+};
+
+const noDot = (s: string) => s.replace(/[.\s]+$/, '');
+
+const ActionLine: React.FC<{ r: WatchReport; a: WatchAction; timeZone?: string; onOpenInbox?: (a: NeedsYouAction) => void }> = ({ r, a, timeZone, onOpenInbox }) => {
+ const icon = 'mt-[3px] shrink-0';
+ const task = (id: string) => <b className="font-semibold text-zinc-100">{taskTitle(r, id)}</b>;
+ switch (a.kind) {
+ case 'restart':
+ return (
+ <li className="flex gap-2" data-action="restart" data-applied={String(a.applied)}>
+ <RotateCcw size={13} aria-hidden="true" className={`${icon} text-zinc-400`} />
+ {a.applied ? (
+ <span>
+ Restarted {task(a.task_id)} with {a.bot_name}: “{a.reason}”
+ </span>
+ ) : (
+ <span>
+ Couldn’t restart {task(a.task_id)} with {a.bot_name}
+ {a.why ? `: ${noDot(a.why)}` : ''}.
+ </span>
+ )}
+ </li>
+ );
+ case 'ask':
+ return (
+ <li className="flex gap-2" data-action="ask" data-applied={String(a.applied)}>
+ <MessageSquare size={13} aria-hidden="true" className={`${icon} text-zinc-400`} />
+ <span>
+ {a.applied ? 'Asked' : 'Couldn’t ask'} {a.bot_name} for {noDot(a.what)} on {task(a.task_id)}
+ {!a.applied && a.why ? `: ${noDot(a.why)}` : ''}.
+ </span>
+ </li>
+ );
+ case 'needs_you':
+ return (
+ <li className="flex gap-2 text-amber-200" data-action="needs_you">
+ <Hand size={13} aria-hidden="true" className={`${icon} text-amber-300`} />
+ <span>
+ <b className="font-semibold text-amber-300">You:</b> {youText(r, a, timeZone)}{' '}
+ {onOpenInbox && (
+ <button type="button" className={linkBtn} onClick={() => onOpenInbox(a)} data-open-inbox>
+ Open it
+ </button>
+ )}
+ </span>
+ </li>
+ );
+ case 'refused':
+ return (
+ <li className="flex gap-2" data-action="refused">
+ <ShieldCheck size={13} aria-hidden="true" className={`${icon} text-rose-300`} />
+ <span>
+ {r.kwant_name} tried to {noDot(a.what)}. {a.why ? noDot(a.why) : 'Watchers can’t do that'}, so it was left for you.
+ </span>
+ </li>
+ );
+ }
+};
+
+export const WatchReportBlock: React.FC<{
+ report: WatchReport;
+ phone?: boolean;
+ /** Checking again: the last report greyed with "Checking again…" over it. */
+ checking?: boolean;
+ timeZone?: string;
+ onHide?: () => void;
+ onOpenChat?: () => void;
+ onOpenInbox?: (a: NeedsYouAction) => void;
+ id?: string;
+}> = ({ report: r, phone = false, checking = false, timeZone, onHide, onOpenChat, onOpenInbox, id }) => {
+ const [showHolds, setShowHolds] = useState(false);
+ const headingId = useId();
+ const k = r.counts;
+ if (!k) return null;
+ const { shown, folded } = orderClaims(r);
+ const rows = showHolds ? [...shown, ...folded] : shown;
+ const you = firstNeedsYou(r);
+ const watcher = r.kwant_name;
+ const holdsLink = folded.length > 0 && !showHolds && (
+ <button type="button" className={linkBtn} onClick={() => setShowHolds(true)} data-show-holds={folded.length}>
+ Show {folded.length} that hold
+ </button>
+ );
+ return (
+ <section
+ id={id}
+ aria-labelledby={headingId}
+ aria-busy={checking || undefined}
+ className={`relative ${phone ? '' : 'mt-3.5 border-t border-hairline pt-3.5'}`}
+ data-watch-report={r.id}
+ >
+ {checking && (
+ <p role="status" className="absolute inset-x-0 top-10 z-10 mx-auto w-fit rounded-full border border-white/10 bg-surface-overlay px-3 py-1 text-[12.5px] text-zinc-200 shadow" data-checking-again>
+ Checking again…
+ </p>
+ )}
+ <div className={checking ? 'opacity-60' : ''}>
+ <div className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5">
+ <OwnerAvatar kwantId={r.kwant_id} name={watcher} size={22} />
+ <h4 id={headingId} className={`font-[650] text-zinc-100 ${phone ? 'text-[16px]' : 'text-[14px]'}`}>
+ {watcher} checked {k.claims} claim{k.claims === 1 ? '' : 's'}
+ </h4>
+ <span className={`text-[12px] text-zinc-500 ${phone ? 'ml-auto' : ''}`}>
+ {phone ? hm(r.finished_at, timeZone) : `${hm(r.finished_at, timeZone)} · the mission stopped at ${hm(r.stopped_at, timeZone)}`}
+ </span>
+ {!phone && (onOpenChat || onHide) && (
+ <span className="ml-auto flex gap-2">
+ {onOpenChat && (
+ <button type="button" className={ghostBtn} onClick={onOpenChat} data-open-chat>
+ <MessageSquare size={14} aria-hidden="true" /> Open in the mission chat
+ </button>
+ )}
+ {onHide && (
+ <button type="button" className={ghostBtn} onClick={onHide} data-hide-report>
+ <ChevronDown size={14} aria-hidden="true" /> Hide
+ </button>
+ )}
+ </span>
+ )}
+ </div>
+ {!phone && <p className="mt-1.5 text-[12.5px] text-zinc-400">{REPORT_SUB}</p>}
+ <ul className="mt-2.5 flex flex-wrap gap-1.5" aria-label="Summary">
+ {summaryChips(k).map((c) => (
+ <li key={c.tone} className={`rounded-full border px-2.5 py-0.5 text-[12px] font-medium ${CHIP_LOOK[c.tone]}`} data-summary={c.tone}>
+ {c.text}
+ </li>
+ ))}
+ </ul>
+
+ {phone ? (
+ <ul className="mt-3 space-y-2.5" aria-label="Claims">
+ {rows.map((c) => (
+ <ClaimCard key={c.task_id} c={c} />
+ ))}
+ </ul>
+ ) : (
+ <div className="mt-3 overflow-x-auto rounded-xl border border-hairline">
+ <table className="w-full min-w-[720px] table-fixed border-collapse text-left">
+ <caption className="sr-only">Claimed vs checked</caption>
+ <colgroup>
+ <col className="w-[200px]" />
+ <col className="w-[96px]" />
+ <col className="w-[170px]" />
+ <col />
+ <col className="w-[124px]" />
+ </colgroup>
+ <thead>
+ <tr className="text-[11px] font-semibold uppercase tracking-[.04em] text-zinc-500">
+ <th scope="col" className="px-3 py-2">
+ Task
+ </th>
+ <th scope="col" className="px-3 py-2">
+ Who
+ </th>
+ <th scope="col" className="px-3 py-2">
+ Claimed
+ </th>
+ <th scope="col" className="px-3 py-2">
+ What {watcher} checked
+ </th>
+ <th scope="col" className="px-3 py-2">
+ Verdict
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((c) => (
+ <ClaimRow key={c.task_id} c={c} />
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ {holdsLink && <div className="mt-2.5">{holdsLink}</div>}
+
+ {r.actions.length > 0 && (
+ <div className="mt-3">
+ <h5 className="mb-1.5 text-[12px] font-semibold text-zinc-300">What {watcher} did</h5>
+ <ul className="space-y-1.5 text-[12.5px] text-zinc-200">
+ {r.actions.map((a, i) => (
+ <ActionLine key={i} r={r} a={a} timeZone={timeZone} onOpenInbox={onOpenInbox} />
+ ))}
+ </ul>
+ </div>
+ )}
+ <p className="mt-3 flex gap-1.5 text-[11.5px] text-zinc-500">
+ <Info size={13} aria-hidden="true" className="mt-px shrink-0" />
+ {footerText(watcher)}
+ </p>
+ {phone && onOpenChat && (
+ <button type="button" className={`${ghostBtn} mt-3 w-full`} onClick={onOpenChat} data-open-chat>
+ <MessageSquare size={14} aria-hidden="true" /> Open in the mission chat
+ </button>
+ )}
+ {phone && onHide && (
+ <button type="button" className={`${ghostBtn} mt-2 w-full`} onClick={onHide} data-hide-report>
+ <ChevronUp size={14} aria-hidden="true" /> Hide
+ </button>
+ )}
+ </div>
+ {phone && you && onOpenInbox && r.inbox?.open !== false && (
+ <div className="sticky bottom-0 z-10 mt-4 flex items-center gap-3 rounded-2xl border border-amber-400/30 bg-[#1d1710] px-3 py-2.5 shadow-lg" data-sticky-you>
+ <Hand size={18} aria-hidden="true" className="shrink-0 text-amber-300" />
+ <p className="min-w-0 flex-1 break-words text-[14px] text-amber-100">{stickyText(r, you)}</p>
+ <button type="button" onClick={() => onOpenInbox(you)} className={`min-h-[44px] shrink-0 rounded-xl bg-amber-400 px-4 text-[14px] font-semibold text-zinc-950 hover:bg-amber-300 ${ring}`}>
+ Open
+ </button>
+ </div>
+ )}
+ </section>
+ );
+};
+
+// ---------- On the mission card ----------
+
+/** What the board hands every mission card; without a provider the card has no Watch chip. */
+export interface WatchBoard {
+ api: WatchApi;
+ phone: boolean;
+ timeZone?: string;
+ /** The server's new watch for a mission, to put on the board's copy. */
+ onChanged: (missionId: string, w: MissionWatch) => void;
+ onOpenChat?: (m: WatchedMission) => void;
+ /** "Open it" on a needs-you line: the task it names. */
+ onOpenTask?: (taskId: string) => void;
+ /** The mission whose report should open (from "See the claims" in the chat). */
+ openReportFor?: string | null;
+}
+export const WatchBoardContext = React.createContext<WatchBoard | null>(null);
+
+/**
+ * The chip, its popover or sheet, and the report block, for one mission card. Who can check and
+ * the report itself are fetched only when they're opened; the chip comes from `mission.watch`.
+ */
+export const MissionWatchControls: React.FC<{
+ mission: WatchedMission;
+ /** Draws the parts where the card wants them: the chip in the header, the report under the meta line. */
+ children: (parts: { chip: React.ReactNode; report: React.ReactNode }) => React.ReactNode;
+}> = ({ mission: m, children }) => {
+ const board = React.useContext(WatchBoardContext);
+ if (!board) return <>{children({ chip: null, report: null })}</>;
+ return <Controls mission={m} board={board} children={children} />;
+};
+
+const Controls: React.FC<{
+ mission: WatchedMission;
+ board: WatchBoard;
+ children: (parts: { chip: React.ReactNode; report: React.ReactNode }) => React.ReactNode;
+}> = ({ mission: m, board, children }) => {
+ const { api, phone, timeZone } = board;
+ const w = m.watch ?? null;
+ const view = chipView(m, timeZone);
+ const finishedId = finishedCheckId(w);
+ const autoOpen = reportOpensItself(w);
+ const askedOpen = board.openReportFor === m.id;
+ const [reportOpen, setReportOpen] = useState<boolean>(autoOpen || askedOpen);
+ const [report, setReport] = useState<WatchReport | null>(null);
+ const [reportError, setReportError] = useState<string | null>(null);
+ /** Set when a check is running and no earlier check has finished: there is no report yet. */
+ const [noReport, setNoReport] = useState(false);
+ const [candidates, setCandidates] = useState<WatchCandidate[] | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [panel, setPanel] = useState<null | 'setup' | 'change'>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ /** A write from the chip itself failed (Try again, or the phone's Undo): shown under the chip. */
+ const [chipError, setChipError] = useState<string | null>(null);
+ const [undo, setUndo] = useState<{ kwant: string } | null>(null);
+ const chipRef = useRef<HTMLButtonElement>(null);
+ const wrap = useRef<HTMLDivElement>(null);
+ const panelId = useId();
+ const reportId = useId();
+
+ // A check that finishes opens the report when it has something to say. Keyed on the check
+ // reaching a finished status, not on its id: the server keeps one id from checking to done.
+ const seenFinished = useRef(finishedId);
+ useEffect(() => {
+ if (finishedId === seenFinished.current) return;
+ seenFinished.current = finishedId;
+ if (finishedId && autoOpen) setReportOpen(true);
+ }, [finishedId, autoOpen]);
+ useEffect(() => {
+ if (askedOpen) setReportOpen(true);
+ }, [askedOpen]);
+
+ // Fetch the report for the last finished check when it's open and we don't have that one.
+ const doneCheck = finishedId ?? report?.id ?? null;
+ const wantReport = reportOpen && hasReport(w);
+ // Opened while a check runs and no report is loaded: fetch the last finished one, if any.
+ const wantEarlier = wantReport && !doneCheck;
+ useEffect(() => {
+ if (!wantReport || !doneCheck || report?.id === doneCheck) return;
+ let live = true;
+ setReportError(null);
+ setNoReport(false);
+ api.get(m.id).then(
+ (x) => {
+ if (!live) return;
+ if (x.report && x.report.status !== 'checking') setReport(x.report);
+ else setReportError('The report couldn’t be read. Open the mission chat to see the message.');
+ if (x.candidates.length) setCandidates(x.candidates);
+ },
+ (e: Error) => live && setReportError(e.message),
+ );
+ return () => {
+ live = false;
+ };
+ }, [wantReport, doneCheck, m.id]);
+ useEffect(() => {
+ if (!wantEarlier) return;
+ let live = true;
+ setReportError(null);
+ setNoReport(false);
+ const earlier: Promise<WatchReport | null> = api.checks
+ ? api.checks(m.id, 5).then((xs) => xs.find((x) => x.status !== 'checking') ?? null)
+ : api.get(m.id).then((x) => (x.report && x.report.status !== 'checking' ? x.report : null));
+ earlier.then(
+ (r) => {
+ if (!live) return;
+ if (r) setReport(r);
+ else setNoReport(true);
+ },
+ (e: Error) => live && setReportError(e.message),
+ );
+ return () => {
+ live = false;
+ };
+ }, [wantEarlier, m.id]);
+
+ const close = () => {
+ setPanel(null);
+ setError(null);
+ requestAnimationFrame(() => chipRef.current?.focus());
+ };
+ const openPanel = (mode: 'setup' | 'change') => {
+ setChipError(null);
+ setPanel(mode);
+ setError(null);
+ setLoadError(null);
+ api.get(m.id).then(
+ (x) => setCandidates(x.candidates),
+ (e: Error) => setLoadError(e.message),
+ );
+ };
+ // Desktop popover: a click outside closes it.
+ useEffect(() => {
+ if (!panel || phone) return;
+ const onDown = (e: MouseEvent) => {
+ if (wrap.current && !wrap.current.contains(e.target as Node)) setPanel(null);
+ };
+ document.addEventListener('mousedown', onDown);
+ return () => document.removeEventListener('mousedown', onDown);
+ }, [panel, phone]);
+ // The phone's Undo for "Stop watching" lasts 5 s.
+ useEffect(() => {
+ if (!undo) return;
+ const t = window.setTimeout(() => setUndo(null), 5000);
+ return () => window.clearTimeout(t);
+ }, [undo]);
+
+ const run = async (f: () => Promise<MissionWatch | null>, after?: () => void, onChip?: (msg: string) => string) => {
+ setBusy(true);
+ setError(null);
+ setChipError(null);
+ try {
+ const next = await f();
+ if (next) board.onChanged(m.id, next);
+ after?.();
+ } catch (e) {
+ const msg = (e as Error).message;
+ if (onChip) setChipError(onChip(msg));
+ else setError(msg);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (!view) return <>{children({ chip: null, report: null })}</>;
+
+ const onChip = () => {
+ if (view.click === 'report') setReportOpen((o) => !o);
+ else if (view.click === 'retry') void run(() => api.checkNow(m.id), undefined, (msg) => msg);
+ else if (view.click === 'setup' || view.click === 'settings') {
+ if (panel) close();
+ else openPanel('setup');
+ }
+ };
+ const expanded = view.click === 'report' ? reportOpen : !!panel;
+ const prevKwant = w?.kwant_id ?? null;
+
+ const chip = (
+ <div ref={wrap} className="relative" data-watch-wrap>
+ <WatchChip ref={chipRef} view={view} expanded={expanded} phone={phone} onClick={onChip} controls={view.click === 'report' ? reportId : panel ? panelId : undefined} />
+ {chipError && !panel && (
+ <p role="alert" className="mt-1 max-w-[320px] break-words text-[12px] text-rose-300" data-watch-chip-error>
+ {chipError}
+ </p>
+ )}
+ {panel && (
+ <WatchSetup
+ id={panelId}
+ mission={m}
+ watch={w}
+ candidates={candidates}
+ loadError={loadError}
+ phone={phone}
+ busy={busy}
+ error={error}
+ startMode={panel === 'change' ? 'change' : undefined}
+ timeZone={timeZone}
+ onClose={close}
+ onWatch={(id) => void run(() => api.set(m.id, id), close)}
+ onCheckNow={() => void run(() => api.checkNow(m.id), close)}
+ onStop={() =>
+ void run(
+ () => api.stop(m.id),
+ () => {
+ close();
+ setReportOpen(false);
+ if (phone && prevKwant) setUndo({ kwant: prevKwant });
+ },
+ )
+ }
+ />
+ )}
+ {undo && (
+ <UndoToast
+ text="Stopped watching"
+ onUndo={() => {
+ const k = undo.kwant;
+ setUndo(null);
+ // The chip already shows the real state (off) from the stop; a failed Undo leaves it so.
+ void run(
+ () => api.set(m.id, k),
+ undefined,
+ (msg) => `Couldn’t turn the watch back on: ${msg.replace(/[.\s]+$/, '')}. The mission isn’t watched now.`,
+ );
+ }}
+ onClose={() => setUndo(null)}
+ />
+ )}
+ </div>
+ );
+
+ const shown = report;
+ let reportNode: React.ReactNode = null;
+ if (wantReport) {
+ reportNode = shown ? (
+ <WatchReportBlock
+ id={reportId}
+ report={shown}
+ phone={phone}
+ checking={w?.state === 'checking'}
+ timeZone={timeZone}
+ onHide={() => {
+ setReportOpen(false);
+ requestAnimationFrame(() => chipRef.current?.focus());
+ }}
+ onOpenChat={board.onOpenChat ? () => board.onOpenChat!(m) : undefined}
+ onOpenInbox={board.onOpenTask ? (a) => board.onOpenTask!(a.task_id) : undefined}
+ />
+ ) : (
+ <p
+ id={reportId}
+ role="status"
+ className={`text-[12.5px] ${reportError ? 'text-rose-300' : 'text-zinc-500'} ${phone ? '' : 'mt-3.5 border-t border-hairline pt-3.5'}`}
+ data-watch-report-loading={noReport ? undefined : ''}
+ data-watch-report-none={noReport ? '' : undefined}
+ >
+ {reportError ?? (noReport ? `No report yet. ${w?.kwant_name ?? 'The watcher'} is checking the claims, and the report shows here when it’s done.` : 'Loading the report…')}
+ </p>
+ );
+ }
+ return <>{children({ chip, report: reportNode })}</>;
+};
+
+// ---------- Chat message ----------
+
+/**
+ * The watcher's message in the mission chat. A report that doesn't parse shows the message text as
+ * the server wrote it.
+ */
+export const WatchChatMessage: React.FC<{
+ report: WatchReport | null;
+ failed?: string | null;
+ /** The message text as written, shown when the report doesn't parse. */
+ fallbackText: string;
+ watcherName: string;
+ watcherId?: string | null;
+ at?: string | null;
+ timeZone?: string;
+ onSeeClaims?: () => void;
+ messageId?: string;
+ flash?: boolean;
+}> = ({ report: r, failed = null, fallbackText, watcherName, watcherId = null, at = null, timeZone, onSeeClaims, messageId, flash = false }) => {
+ const name = r?.kwant_name ?? watcherName;
+ const parts = r ? chatParts(r, timeZone) : [];
+ const allHold = !!r?.counts && r.counts.dont_hold === 0 && r.counts.cant_tell === 0 && r.counts.needs_you === 0;
+ return (
+ <div
+ data-message-id={messageId}
+ data-watch-message={parts.length ? 'report' : failed ? 'failed' : 'text'}
+ className={`flex w-full max-w-3xl gap-3 rounded-2xl p-2 ${flash ? 'ring-2 ring-[#9d8fff]/50' : ''}`}
+ >
+ <OwnerAvatar kwantId={r?.kwant_id ?? watcherId} name={name} size={32} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2 text-[13px]">
+ <span className="font-semibold text-zinc-100">{name}</span>
+ <span className="inline-flex items-center gap-1 rounded-full border border-white/10 bg-white/[.03] px-2 py-px text-[11px] text-zinc-300" data-watch-tag>
+ <Eye size={11} aria-hidden="true" /> Watch
+ </span>
+ {at && <span className="text-[12px] text-zinc-500">{hm(at, timeZone)}</span>}
+ </div>
+ <div className="mt-1.5 rounded-2xl border border-white/[.08] bg-white/[.03] px-4 py-2.5 text-[13.5px] leading-relaxed text-zinc-100 break-words">
+ {parts.length ? (
+ <>
+ {parts.map((p, i) =>
+ p.bold ? (
+ <b key={i} className="font-semibold">
+ {p.text}
+ </b>
+ ) : (
+ <React.Fragment key={i}>{p.text}</React.Fragment>
+ ),
+ )}
+ {onSeeClaims && !allHold && (
+ <>
+ {' '}
+ <button type="button" className={linkBtn} onClick={onSeeClaims} data-see-claims>
+ See the claims
+ </button>
+ </>
+ )}
+ </>
+ ) : failed ? (
+ failedChatText(failed)
+ ) : (
+ <span className="whitespace-pre-wrap">{fallbackText}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/missionWatch.ts b/frontend/src/missionWatch.ts
new file mode 100644
index 00000000..c53d3a51
--- /dev/null
+++ b/frontend/src/missionWatch.ts
@@ -0,0 +1,613 @@
+// 0.9.0 P1: watch a mission. Design: release-090/designs/p1-watch-mission.md (Mira). Backend: Vega,
+// contract release-090/p1-contract.md. When every task in a mission has stopped, one bot (the watcher)
+// treats each status as a claim, checks it once, restarts what doesn't hold and names the person only
+// where a claim needs them. This file is the typed client and the pure logic the views draw from:
+// chip state and copy, the default watcher, report row order, the chat and Inbox lines.
+//
+// Nothing here works out a verdict or a count the server didn't send: counts are the server's, and a
+// report whose counts don't match its rows, or that doesn't parse, is dropped (the chat then shows the
+// message text as written).
+
+import { PersonCancelledError, personFetch } from './auth';
+import { parseMetaObject } from './questions';
+import type { Mission } from './missions';
+
+export type WatchState =
+ | 'off'
+ | 'no_tasks'
+ | 'finished'
+ | 'watching'
+ | 'checking'
+ | 'dont_hold'
+ | 'all_hold'
+ | 'cant_tell'
+ | 'same_stop'
+ | 'cant_run'
+ | 'over_limit'
+ | 'failed';
+export type Verdict = 'holds' | 'doesnt_hold' | 'cant_tell';
+export type CheckStatus = 'checking' | 'done' | 'failed' | 'cant_run' | 'over_limit';
+
+/** The server's counts (contract section 4). Shown as sent; never added up here. */
+export interface WatchCounts {
+ claims: number;
+ dont_hold: number;
+ needs_you: number;
+ cant_tell: number;
+ holds: number;
+}
+
+export interface WatchReason {
+ code: string;
+ text: string;
+}
+
+export interface WatchClaim {
+ task_id: string;
+ task_title: string;
+ owner_kwant_id: string | null;
+ owner_name: string | null;
+ /** The claim as the server words it: "In review", "Blocked: …", "Waiting for your OK". */
+ claimed: string;
+ /** What the watcher checked; may hold `code` spans. */
+ checked: string;
+ verdict: Verdict;
+ /** A needs-you action names this task. Not a verdict. */
+ needs_you: boolean;
+}
+
+export type WatchAction =
+ | { kind: 'restart'; task_id: string; bot_id: string | null; bot_name: string; reason: string; applied: boolean; why: string | null }
+ | { kind: 'ask'; task_id: string; bot_id: string | null; bot_name: string; what: string; applied: boolean; why: string | null }
+ | { kind: 'needs_you'; task_id: string; what: string; since: string | null }
+ | { kind: 'refused'; what: string; tool: string | null; why: string | null };
+export type NeedsYouAction = Extract<WatchAction, { kind: 'needs_you' }>;
+
+/** One check: the report (contract section 4). */
+export interface WatchReport {
+ id: string;
+ mission_id: string;
+ kwant_id: string | null;
+ kwant_name: string;
+ trigger: 'stop' | 'manual';
+ status: CheckStatus;
+ stopped_at: string | null;
+ started_at: string | null;
+ finished_at: string | null;
+ error: string | null;
+ reason: WatchReason | null;
+ counts: WatchCounts | null;
+ claims: WatchClaim[];
+ actions: WatchAction[];
+ inbox: { open: boolean; line: string } | null;
+ message_id: string | null;
+}
+
+/** The newest check as the mission payload carries it. */
+export interface WatchCheckSummary {
+ id: string;
+ status: CheckStatus;
+ trigger: 'stop' | 'manual';
+ started_at: string | null;
+ finished_at: string | null;
+ stopped_at: string | null;
+ counts: WatchCounts | null;
+ message_id: string | null;
+}
+
+/** `mission.watch` (contract section 1). The chip is drawn from this alone. */
+export interface MissionWatch {
+ state: WatchState;
+ kwant_id: string | null;
+ kwant_name: string | null;
+ set_at: string | null;
+ stopped: boolean;
+ stopped_at: string | null;
+ last_check: WatchCheckSummary | null;
+ reason: WatchReason | null;
+ can_check_now: boolean;
+}
+
+export type Relation = 'no_task' | 'lead' | 'has_task';
+export interface WatchCandidate {
+ kwant_id: string;
+ name: string;
+ title: string | null;
+ relation: Relation;
+ task_ids: string[];
+ can_run: boolean;
+ reason: WatchReason | null;
+ /** The server's default pick, or the current watcher when a watch is set. */
+ default: boolean;
+}
+
+/** A mission as the board has it, with the watch the server adds (absent on an older server). */
+export type WatchedMission = Mission & { watch?: MissionWatch | null };
+
+// ---------- Parsing (data from the server is checked, never trusted) ----------
+
+const STATES: WatchState[] = ['off', 'no_tasks', 'finished', 'watching', 'checking', 'dont_hold', 'all_hold', 'cant_tell', 'same_stop', 'cant_run', 'over_limit', 'failed'];
+const VERDICTS: Verdict[] = ['holds', 'doesnt_hold', 'cant_tell'];
+const STATUSES: CheckStatus[] = ['checking', 'done', 'failed', 'cant_run', 'over_limit'];
+const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v : null);
+const obj = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null);
+const okTime = (v: unknown): string | null => {
+ const s = str(v);
+ return s && Number.isFinite(Date.parse(s)) ? s : null;
+};
+const count = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : null);
+
+function parseCounts(raw: unknown): WatchCounts | null {
+ const c = obj(raw);
+ if (!c) return null;
+ const k = { claims: count(c.claims), dont_hold: count(c.dont_hold), needs_you: count(c.needs_you), cant_tell: count(c.cant_tell), holds: count(c.holds) };
+ return Object.values(k).every((n) => n !== null) ? (k as WatchCounts) : null;
+}
+
+function parseReason(raw: unknown): WatchReason | null {
+ const r = obj(raw);
+ const text = r && str(r.text);
+ return r && text ? { code: str(r.code) ?? 'unknown', text } : null;
+}
+
+function parseClaim(raw: unknown): WatchClaim | null {
+ const c = obj(raw);
+ if (!c) return null;
+ const task_id = str(c.task_id);
+ const task_title = str(c.task_title);
+ const claimed = str(c.claimed);
+ const checked = str(c.checked);
+ if (!task_id || !task_title || !claimed || !checked || !VERDICTS.includes(c.verdict as Verdict)) return null;
+ return { task_id, task_title, owner_kwant_id: str(c.owner_kwant_id), owner_name: str(c.owner_name), claimed, checked, verdict: c.verdict as Verdict, needs_you: c.needs_you === true };
+}
+
+function parseAction(raw: unknown): WatchAction | null {
+ const a = obj(raw);
+ if (!a) return null;
+ const task_id = str(a.task_id);
+ const applied = a.applied !== false;
+ const why = str(a.why);
+ switch (a.kind) {
+ case 'restart': {
+ const bot_name = str(a.bot_name);
+ const reason = str(a.reason);
+ return task_id && bot_name && reason ? { kind: 'restart', task_id, bot_id: str(a.bot_id), bot_name, reason, applied, why } : null;
+ }
+ case 'ask': {
+ const bot_name = str(a.bot_name);
+ const what = str(a.what);
+ return task_id && bot_name && what ? { kind: 'ask', task_id, bot_id: str(a.bot_id), bot_name, what, applied, why } : null;
+ }
+ case 'needs_you': {
+ const what = str(a.what);
+ return task_id && what ? { kind: 'needs_you', task_id, what, since: okTime(a.since) } : null;
+ }
+ case 'refused': {
+ const what = str(a.what);
+ return what ? { kind: 'refused', what, tool: str(a.tool), why } : null;
+ }
+ default:
+ return null;
+ }
+}
+
+/**
+ * The counts must say what the rows say, or the table and the chips would disagree. The contract
+ * reads two ways on whether `holds` includes the needs-you rows; both are accepted.
+ */
+function countsMatch(k: WatchCounts, claims: WatchClaim[]): boolean {
+ const n = (f: (c: WatchClaim) => boolean) => claims.filter(f).length;
+ const holds = n((c) => c.verdict === 'holds');
+ const holdsOnly = n((c) => c.verdict === 'holds' && !c.needs_you);
+ return (
+ k.claims === claims.length &&
+ k.dont_hold === n((c) => c.verdict === 'doesnt_hold') &&
+ k.cant_tell === n((c) => c.verdict === 'cant_tell') &&
+ k.needs_you === n((c) => c.needs_you) &&
+ (k.holds === holds || k.holds === holdsOnly)
+ );
+}
+
+/**
+ * A check we can draw as a report, or null: a finished (`done`) check needs its counts and every
+ * claim row to parse, and the counts to match the rows. A failed check parses with no claims.
+ * Unknown action kinds are skipped; they're notes about what the watcher did, not claims.
+ */
+export function parseReport(raw: unknown): WatchReport | null {
+ const r = obj(raw);
+ if (!r) return null;
+ const id = str(r.id);
+ const mission_id = str(r.mission_id);
+ const kwant_name = str(r.kwant_name);
+ const status = r.status as CheckStatus;
+ if (!id || !mission_id || !kwant_name || !STATUSES.includes(status)) return null;
+ const rawClaims = Array.isArray(r.claims) ? r.claims : [];
+ const claims = rawClaims.map(parseClaim);
+ if (claims.some((c) => c === null)) return null;
+ const counts = parseCounts(r.counts);
+ if (status === 'done' && (!counts || claims.length === 0 || !countsMatch(counts, claims as WatchClaim[]))) return null;
+ const inbox = obj(r.inbox);
+ return {
+ id,
+ mission_id,
+ kwant_id: str(r.kwant_id),
+ kwant_name,
+ trigger: r.trigger === 'manual' ? 'manual' : 'stop',
+ status,
+ stopped_at: okTime(r.stopped_at),
+ started_at: okTime(r.started_at),
+ finished_at: okTime(r.finished_at),
+ error: str(r.error),
+ reason: parseReason(r.reason),
+ counts,
+ claims: claims as WatchClaim[],
+ actions: Array.isArray(r.actions) ? r.actions.map(parseAction).filter((a): a is WatchAction => a !== null) : [],
+ inbox: inbox && str(inbox.line) ? { open: inbox.open === true, line: str(inbox.line)! } : null,
+ message_id: str(r.message_id),
+ };
+}
+
+/** Chat message meta `{kind: "watch", status, watch_report}`, or null for any other message. */
+export interface WatchMeta { report: WatchReport | null; failed: string | null; missionId: string | null; checkId: string | null }
+export function parseWatchMeta(raw: unknown): WatchMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'watch') return null;
+ const report = parseReport(m.watch_report);
+ const failed = m.status === 'failed' ? report?.reason?.text ?? report?.error ?? null : null;
+ return { report: m.status === 'failed' ? null : report, failed, missionId: str(m.mission_id), checkId: str(m.check_id) };
+}
+
+function parseCheckSummary(raw: unknown): WatchCheckSummary | null {
+ const c = obj(raw);
+ const id = c && str(c.id);
+ if (!c || !id || !STATUSES.includes(c.status as CheckStatus)) return null;
+ return {
+ id,
+ status: c.status as CheckStatus,
+ trigger: c.trigger === 'manual' ? 'manual' : 'stop',
+ started_at: okTime(c.started_at),
+ finished_at: okTime(c.finished_at),
+ stopped_at: okTime(c.stopped_at),
+ counts: parseCounts(c.counts),
+ message_id: str(c.message_id),
+ };
+}
+
+export function parseWatch(raw: unknown): MissionWatch | null {
+ const w = obj(raw);
+ if (!w || !STATES.includes(w.state as WatchState)) return null;
+ return {
+ state: w.state as WatchState,
+ kwant_id: str(w.kwant_id),
+ kwant_name: str(w.kwant_name),
+ set_at: okTime(w.set_at),
+ stopped: w.stopped === true,
+ stopped_at: okTime(w.stopped_at),
+ last_check: parseCheckSummary(w.last_check),
+ reason: parseReason(w.reason),
+ can_check_now: w.can_check_now === true,
+ };
+}
+
+export function parseCandidates(raw: unknown): WatchCandidate[] {
+ if (!Array.isArray(raw)) return [];
+ const out: WatchCandidate[] = [];
+ for (const x of raw) {
+ const c = obj(x);
+ const id = c && str(c.kwant_id);
+ const name = c && str(c.name);
+ if (!c || !id || !name || !['no_task', 'lead', 'has_task'].includes(c.relation as string)) continue;
+ out.push({
+ kwant_id: id,
+ name,
+ title: str(c.title),
+ relation: c.relation as Relation,
+ task_ids: Array.isArray(c.task_ids) ? c.task_ids.filter((t): t is string => typeof t === 'string') : [],
+ can_run: c.can_run !== false,
+ reason: parseReason(c.reason),
+ default: c.default === true,
+ });
+ }
+ return out;
+}
+
+// ---------- Times ----------
+
+/** 24-hour HH:MM in the person's zone (or the one given, for tests). */
+export function hm(at: string | null | undefined, timeZone?: string): string {
+ if (!at) return '';
+ const d = new Date(at);
+ if (!Number.isFinite(d.getTime())) return '';
+ return new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23', ...(timeZone ? { timeZone } : {}) }).format(d);
+}
+
+// ---------- Order and rows ----------
+
+/** Rank: doesn't hold, then needs you, then can't tell, then holds. */
+export function claimRank(c: WatchClaim): number {
+ if (c.verdict === 'doesnt_hold') return 0;
+ if (c.needs_you) return 1;
+ if (c.verdict === 'cant_tell') return 2;
+ return 3;
+}
+
+/**
+ * The rows in the design's order (the server sends them sorted; this keeps that order within a rank),
+ * split into what shows and what folds into "Show {n} that hold".
+ */
+export function orderClaims(r: WatchReport): { shown: WatchClaim[]; folded: WatchClaim[] } {
+ const sorted = r.claims.map((c, i) => [c, i] as const).sort((a, b) => claimRank(a[0]) - claimRank(b[0]) || a[1] - b[1]).map(([c]) => c);
+ return { shown: sorted.filter((c) => claimRank(c) < 3), folded: sorted.filter((c) => claimRank(c) === 3) };
+}
+
+export type RowTint = 'rose' | 'amber' | null;
+export const rowTint = (c: WatchClaim): RowTint => (c.verdict === 'doesnt_hold' ? 'rose' : c.needs_you ? 'amber' : null);
+
+/** Summary chips in the design's order, skipping zeros. Numbers are the server's counts. */
+export function summaryChips(k: WatchCounts): { tone: 'rose' | 'amber' | 'zinc' | 'teal'; text: string }[] {
+ return [
+ { tone: 'rose' as const, n: k.dont_hold, text: `${k.dont_hold} don’t hold` },
+ { tone: 'amber' as const, n: k.needs_you, text: `${k.needs_you} needs you` },
+ { tone: 'zinc' as const, n: k.cant_tell, text: `${k.cant_tell} can’t tell` },
+ { tone: 'teal' as const, n: k.holds, text: `${k.holds} hold` },
+ ]
+ .filter((c) => c.n > 0)
+ .map(({ tone, text }) => ({ tone, text }));
+}
+
+export const VERDICT_TEXT: Record<Verdict, string> = { holds: 'Holds', doesnt_hold: 'Doesn’t hold', cant_tell: 'Can’t tell' };
+
+/** A task's title in the report, by id; actions name tasks by id only. */
+export const taskTitle = (r: WatchReport, taskId: string): string => r.claims.find((c) => c.task_id === taskId)?.task_title ?? 'a task';
+
+/** Split "Ran `npm test` on `x`" into text and code parts. Text only: nothing becomes HTML. */
+export function codeParts(s: string): { code: boolean; text: string }[] {
+ const out: { code: boolean; text: string }[] = [];
+ const re = /`([^`\n]+)`/g;
+ let at = 0;
+ for (let m = re.exec(s); m; m = re.exec(s)) {
+ if (m.index > at) out.push({ code: false, text: s.slice(at, m.index) });
+ out.push({ code: true, text: m[1] });
+ at = m.index + m[0].length;
+ }
+ if (at < s.length) out.push({ code: false, text: s.slice(at) });
+ return out;
+}
+
+// ---------- The chip ----------
+
+export type ChipTone = 'ghost' | 'accent' | 'rose' | 'teal' | 'muted' | 'amber';
+export type ChipIcon = 'eye' | 'loader' | 'alert-triangle' | 'alert-circle';
+export interface ChipView {
+ /** What the person sees on it (the watcher's avatar sits after "Watching · "). */
+ text: string;
+ tone: ChipTone;
+ icon: ChipIcon;
+ /** Screen-reader label: the text, plus ", watch settings" where the click opens them. */
+ label: string;
+ /** What a click does. */
+ click: 'setup' | 'settings' | 'report' | 'retry' | 'none';
+ disabled?: boolean;
+ /** Disabled reason, shown as its tooltip. */
+ tooltip?: string;
+ /** Watching: show the avatar of this bot. */
+ avatar?: { kwant_id: string | null; name: string } | null;
+}
+
+const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
+
+/**
+ * The chip for a mission from `mission.watch.state`, or null when it hides (finished, or a draft
+ * that isn't running yet). An older server that sends no watch gets the plain Watch chip.
+ */
+export function chipView(m: WatchedMission, timeZone?: string): ChipView | null {
+ if (m.status === 'draft' || m.status === 'done' || m.status === 'cancelled') return null;
+ const w = m.watch ?? null;
+ const off: ChipView = { text: 'Watch', tone: 'ghost', icon: 'eye', label: 'Watch, watch settings', click: 'setup' };
+ if (!w) return off;
+ const name = w.kwant_name ?? 'The watcher';
+ const lc = w.last_check;
+ const at = hm(lc?.finished_at ?? lc?.started_at, timeZone);
+ const k = lc?.counts ?? null;
+ const settings = (text: string, tone: ChipTone, icon: ChipIcon = 'eye'): ChipView => ({ text, tone, icon, label: `${text}, watch settings`, click: 'settings' });
+ const watching: ChipView = { ...settings(`Watching · ${name}`, 'accent'), avatar: { kwant_id: w.kwant_id, name } };
+ switch (w.state) {
+ case 'finished':
+ return null;
+ case 'no_tasks': {
+ const tip = 'Add tasks first. There’s nothing to check yet.';
+ return { ...off, disabled: true, click: 'none', tooltip: tip, label: `Watch, watch settings. ${tip}` };
+ }
+ case 'off':
+ return off;
+ case 'watching':
+ return watching;
+ case 'checking': {
+ // Counts are null while checking, so the chip can't say how many.
+ const text = `${name} is checking the claims`;
+ return { text, tone: 'accent', icon: 'loader', label: `${text}, watch settings`, click: 'settings' };
+ }
+ case 'dont_hold': {
+ if (!k) return watching;
+ const text = `${k.dont_hold} ${plural(k.dont_hold, 'claim doesn’t hold', 'claims don’t hold')} · ${at}`;
+ return { text, tone: 'rose', icon: 'eye', label: text, click: 'report' };
+ }
+ case 'all_hold': {
+ if (!k) return watching;
+ const text = `All ${k.claims} ${plural(k.claims, 'claim holds', 'claims hold')} · ${at}`;
+ return { text, tone: 'teal', icon: 'eye', label: text, click: 'report' };
+ }
+ case 'cant_tell': {
+ // No row in the design; the contract's text, muted. Never "All hold" over a "Can't tell".
+ if (!k) return watching;
+ const text = `${k.claims} ${plural(k.claims, 'claim', 'claims')} checked · ${at}`;
+ return { text, tone: 'muted', icon: 'eye', label: text, click: 'report' };
+ }
+ case 'same_stop':
+ return settings(`No change since the ${at} check`, 'muted');
+ case 'cant_run':
+ return settings(`${name} can’t check: ${w.reason?.text ?? 'it can’t run'}`, 'amber', 'alert-triangle');
+ case 'over_limit':
+ return settings('Over the mission’s limit', 'amber', 'alert-triangle');
+ case 'failed':
+ return w.can_check_now
+ ? { text: 'The check failed · Try again', tone: 'rose', icon: 'alert-circle', label: 'The check failed. Try again', click: 'retry' }
+ : settings('The check failed', 'rose', 'alert-circle');
+ }
+}
+
+/** The report opens on its own after a check with a "doesn't hold" or a "needs you". */
+export const reportOpensItself = (w: MissionWatch | null): boolean =>
+ !!w && !!w.last_check?.counts && ['dont_hold', 'all_hold', 'cant_tell'].includes(w.state) && (w.last_check.counts.dont_hold > 0 || w.last_check.counts.needs_you > 0);
+
+/** States with a report to show (the last check, greyed while checking again). */
+export const hasReport = (w: MissionWatch | null): boolean => !!w?.last_check && w.state !== 'off' && w.state !== 'finished';
+
+export const CHIP_TONES: Record<ChipTone, string> = {
+ ghost: 'border-white/10 bg-white/[.03] text-zinc-200 hover:bg-white/[.06]',
+ accent: 'border-[#9d8fff]/40 bg-[#8270f5]/12 text-[#d3ccff] hover:bg-[#8270f5]/20',
+ rose: 'border-rose-300/40 bg-rose-300/8 text-rose-300 hover:bg-rose-300/15',
+ teal: 'border-teal-400/35 bg-teal-400/8 text-teal-300 hover:bg-teal-400/15',
+ muted: 'border-white/10 bg-white/[.03] text-zinc-400 hover:bg-white/[.06]',
+ amber: 'border-amber-300/40 bg-amber-300/8 text-amber-300 hover:bg-amber-300/15',
+};
+
+// ---------- Setup ----------
+
+export function relationText(c: WatchCandidate, phone = false): string {
+ if (!c.can_run) return `can’t run: ${c.reason?.text ?? 'it can’t run now'}`;
+ if (c.relation === 'lead') return phone ? 'leads it' : 'leads it, so it checks its own work';
+ if (c.relation === 'has_task') return 'has a task here';
+ return 'has no task in this mission';
+}
+
+/** The server marks the default (or the current watcher); else the first that can run, in its order. */
+export function defaultCandidate(cs: WatchCandidate[]): WatchCandidate | null {
+ const runs = cs.filter((c) => c.can_run);
+ return runs.find((c) => c.default) ?? runs.find((c) => c.relation === 'no_task') ?? runs.find((c) => c.relation === 'lead') ?? runs[0] ?? null;
+}
+
+export const SETUP_BODY =
+ 'When every task has stopped, one bot checks each claim once: is “done” really done, is “blocked” still blocked? Then it restarts what doesn’t hold or tells you who has to act.';
+export const SETUP_BODY_PHONE = 'When every task has stopped, one bot checks each claim once. Then it restarts what doesn’t hold or tells you who has to act.';
+export const guardText = (bot: string) => `${bot} can restart tasks and ask bots to act. It can’t approve, spend, add bots or do your steps.`;
+export const costText = (bot: string) => `Each check is one turn for ${bot} and counts toward this mission’s limit.`;
+export const footerText = (bot: string) => `${bot} checks again only when the mission stops in a different state. It can’t approve, spend, add bots or do your steps.`;
+export const REPORT_SUB = 'Every task had stopped: nothing running, waiting in line or due to retry. Each “done”, “blocked” and “waiting” is a claim, checked against what’s really there.';
+
+// ---------- Chat message, the needs-you lines ----------
+
+/** The watcher's message, as parts so "{n} don't hold" can be bold, with local times. Text only. */
+export function chatParts(r: WatchReport, timeZone?: string): { bold?: boolean; text: string }[] {
+ const k = r.counts;
+ if (!k) return [];
+ const head = `Checked ${k.claims} ${plural(k.claims, 'claim', 'claims')} after the mission stopped at ${hm(r.stopped_at, timeZone)}. `;
+ if (k.dont_hold === 0 && k.cant_tell === 0 && k.needs_you === 0) return [{ text: `${head}All hold.` }];
+ const parts: { bold?: boolean; text: string }[] = [{ text: head }];
+ if (k.dont_hold) parts.push({ bold: true, text: `${k.dont_hold} don’t hold` });
+ const rest = [k.needs_you && `${k.needs_you} needs you`, k.cant_tell && `${k.cant_tell} can’t tell`, k.holds && `${k.holds} hold`].filter(Boolean) as string[];
+ if (rest.length) parts.push({ text: `${k.dont_hold ? ', ' : ''}${rest.join(', ')}` });
+ parts.push({ text: '.' });
+ const restarts = r.actions.filter((a): a is Extract<WatchAction, { kind: 'restart' }> => a.kind === 'restart' && a.applied);
+ if (restarts.length) {
+ const list = restarts.map((a) => `${taskTitle(r, a.task_id)} with ${a.bot_name}`);
+ const joined = list.length === 1 ? list[0] : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;
+ parts.push({ text: ` I restarted ${joined}.` });
+ }
+ return parts;
+}
+
+export const chatText = (r: WatchReport, timeZone?: string) =>
+ chatParts(r, timeZone)
+ .map((p) => p.text)
+ .join('');
+
+export const failedChatText = (reason: string) => `The check failed: ${reason}. Nothing was restarted.`;
+
+/** "Deploy the site waits for your OK to deploy since 13:55." (`what` is the watcher's phrase.) */
+export const youText = (r: WatchReport, a: NeedsYouAction, timeZone?: string) => `${taskTitle(r, a.task_id)} ${a.what}${a.since ? ` since ${hm(a.since, timeZone)}` : ''}.`;
+
+/** The phone's sticky bar. */
+export const stickyText = (r: WatchReport, a: NeedsYouAction) => `${taskTitle(r, a.task_id)} ${a.what}`;
+
+export const firstNeedsYou = (r: WatchReport): NeedsYouAction | null => r.actions.find((a): a is NeedsYouAction => a.kind === 'needs_you') ?? null;
+
+// ---------- API ----------
+
+export class WatchError extends Error {
+ constructor(message: string, readonly status: number, readonly code: string | null = null) {
+ super(message);
+ }
+}
+
+async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+ let res: Response;
+ try {
+ res = await personFetch(url, {
+ method,
+ cache: 'no-store',
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new WatchError(e.message, 401);
+ throw new WatchError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const answer = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ if (res.ok) return answer as T;
+ const err = answer && typeof answer.error === 'string' ? answer.error : null;
+ const code = answer && typeof answer.code === 'string' ? answer.code : null;
+ if (res.status === 403) throw new WatchError('Only you can change a mission’s watch.', 403, code);
+ if (res.status === 404 && !err) throw new WatchError('This server can’t watch missions yet. Update the app and try again.', 404, code);
+ throw new WatchError((code && WATCH_ERRORS[code]) || err || `Something went wrong (HTTP ${res.status}).`, res.status, code);
+}
+
+const enc = encodeURIComponent;
+
+export interface WatchApi {
+ /** The watch, the last check and who could check, in the server's order. */
+ get: (missionId: string) => Promise<{ watch: MissionWatch | null; report: WatchReport | null; candidates: WatchCandidate[] }>;
+ /** Turn the watch on, or change who checks. */
+ set: (missionId: string, kwantId: string) => Promise<MissionWatch | null>;
+ stop: (missionId: string) => Promise<MissionWatch | null>;
+ /** "Check again now" and "Try again": one new check, ignoring the last fingerprint. */
+ checkNow: (missionId: string) => Promise<MissionWatch | null>;
+ /** One check by id ("See the claims" in the chat). */
+ check: (checkId: string) => Promise<WatchReport | null>;
+ /** The mission's checks, newest first (for the last finished report while a new one runs). */
+ checks?: (missionId: string, limit?: number) => Promise<WatchReport[]>;
+}
+
+const watchOf = (r: { watch?: unknown } | null) => parseWatch(r?.watch);
+
+export const watchApi: WatchApi = {
+ get: (id) =>
+ call<{ watch?: unknown; report?: unknown; candidates?: unknown }>(`/api/missions/${enc(id)}/watch`).then((r) => ({
+ watch: watchOf(r),
+ report: parseReport(r?.report),
+ candidates: parseCandidates(r?.candidates),
+ })),
+ set: (id, kwant_id) => call<{ watch?: unknown }>(`/api/missions/${enc(id)}/watch`, 'PUT', { kwant_id }).then(watchOf),
+ stop: (id) => call<{ watch?: unknown }>(`/api/missions/${enc(id)}/watch`, 'DELETE').then(watchOf),
+ checkNow: (id) => call<{ watch?: unknown }>(`/api/missions/${enc(id)}/watch/check`, 'POST', {}).then(watchOf),
+ check: (checkId) => call<unknown>(`/api/watch-checks/${enc(checkId)}`).then(parseReport),
+ checks: (id, limit = 10) =>
+ call<{ checks?: unknown }>(`/api/missions/${enc(id)}/watch/checks?limit=${limit}`).then((r) =>
+ (Array.isArray(r?.checks) ? r.checks : []).map(parseReport).filter((x): x is WatchReport => !!x),
+ ),
+};
+
+/** The id of the newest check that has finished, or null while the newest one is still checking. */
+export const finishedCheckId = (w: MissionWatch | null): string | null => (w?.last_check && w.last_check.status !== 'checking' ? w.last_check.id : null);
+
+/** The mission's watch from the board payload, parsed; null when the server sends none. */
+export const missionWatch = (m: Mission): MissionWatch | null => parseWatch((m as { watch?: unknown }).watch);
+
+/** Error codes from the write routes, in the person's words where the server's text is terse. */
+export const WATCH_ERRORS: Record<string, string> = {
+ not_stopped: 'Tasks are still moving. The check starts when every task has stopped.',
+ checking: 'A check is already running.',
+ over_limit: 'This mission is over its limit. Raise or remove the limit first.',
+ finished: 'This mission is finished. There’s nothing left to watch.',
+ no_tasks: 'Add tasks first. There’s nothing to check yet.',
+};
diff --git a/frontend/tests/missionWatch.test.mjs b/frontend/tests/missionWatch.test.mjs
new file mode 100644
index 00000000..d5d47bc4
--- /dev/null
+++ b/frontend/tests/missionWatch.test.mjs
@@ -0,0 +1,198 @@
+// 0.9.0 P1 "watch a mission": parsing, the chip for every state, the report's rows and text,
+// the chat message and the Inbox item (p1-contract.md, designs/p1-watch-mission.md).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const w = await loadBundled(`export * from './src/missionWatch'; export * from './src/away';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { WatchChip, WatchReportBlock, WatchChatMessage } from './src/components/MissionWatch';
+ export const chip = (props) => renderToStaticMarkup(React.createElement(WatchChip, props));
+ export const report = (props) => renderToStaticMarkup(React.createElement(WatchReportBlock, props));
+ export const chat = (props) => renderToStaticMarkup(React.createElement(WatchChatMessage, props));
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const TZ = 'UTC';
+
+const claim = (over = {}) => ({
+ task_id: 't-1', task_title: 'Write the tests', owner_kwant_id: 'k-lin', owner_name: 'Lin', state: 'done',
+ claimed: 'Done: tests pass', checked: 'Ran `npm test`: 3 fail', verdict: 'doesnt_hold', needs_you: false, ...over,
+});
+const rawReport = (over = {}) => ({
+ id: 'wc-1', mission_id: 'm-1', kwant_id: 'k-rigel', kwant_name: 'Rigel', trigger: 'stop', status: 'done',
+ stopped_at: '2026-11-10T18:10:00Z', started_at: '2026-11-10T18:11:00Z', finished_at: '2026-11-10T18:14:00Z',
+ counts: { claims: 3, dont_hold: 1, needs_you: 1, cant_tell: 0, holds: 2 },
+ claims: [
+ claim({ task_id: 't-3', task_title: 'Ship the docs', verdict: 'holds', claimed: 'Done', checked: 'The page is live' }),
+ claim({ task_id: 't-5', task_title: 'Deploy the site', verdict: 'holds', needs_you: true, state: 'waiting', claimed: 'Waiting for your OK', checked: 'The request is open' }),
+ claim(),
+ ],
+ actions: [
+ { kind: 'restart', task_id: 't-1', bot_id: 'k-lin', bot_name: 'Lin', reason: '3 tests fail', applied: true },
+ { kind: 'needs_you', task_id: 't-5', what: 'waits for your OK to deploy', since: '2026-11-10T18:12:00Z' },
+ { kind: 'refused', what: 'approve the deploy', tool: 'approve', why: 'Only you can approve' },
+ { kind: 'something_new', what: 'x' },
+ ],
+ inbox: { open: true, line: 'Rigel: t-5 has waited for your OK to deploy since 18:12.' },
+ message_id: 'msg-1', tokens: 1200, ...over,
+});
+const watch = (over = {}) => ({
+ state: 'watching', kwant_id: 'k-rigel', kwant_name: 'Rigel', set_at: '2026-11-10T17:00:00Z', stopped: false, stopped_at: null,
+ last_check: null, reason: null, can_check_now: false, ...over,
+});
+const lastCheck = (counts) => ({ id: 'wc-1', status: 'done', trigger: 'stop', started_at: '2026-11-10T18:11:00Z', finished_at: '2026-11-10T18:14:00Z', counts });
+const mission = (wv) => ({ id: 'm-1', title: 'Launch', status: 'active', watch: wv === undefined ? undefined : w.parseWatch(wv) });
+
+test('parseReport: a done check with matching counts parses; unknown actions are skipped', () => {
+ const r = w.parseReport(rawReport());
+ assert.ok(r);
+ assert.equal(r.claims.length, 3);
+ assert.deepEqual(r.actions.map((a) => a.kind), ['restart', 'needs_you', 'refused']);
+ assert.equal(r.inbox.open, true);
+});
+
+test('parseReport: holds may count the needs-you rows or not (both contract readings)', () => {
+ assert.ok(w.parseReport(rawReport({ counts: { claims: 3, dont_hold: 1, needs_you: 1, cant_tell: 0, holds: 1 } })));
+ assert.ok(w.parseReport(rawReport({ counts: { claims: 3, dont_hold: 1, needs_you: 1, cant_tell: 0, holds: 2 } })));
+});
+
+test('parseReport: invalid data falls back (null) instead of drawing wrong numbers', () => {
+ assert.equal(w.parseReport(rawReport({ counts: { claims: 4, dont_hold: 1, needs_you: 1, cant_tell: 0, holds: 2 } })), null);
+ assert.equal(w.parseReport(rawReport({ counts: { claims: 3, dont_hold: 2, needs_you: 1, cant_tell: 0, holds: 2 } })), null);
+ assert.equal(w.parseReport(rawReport({ counts: null })), null);
+ assert.equal(w.parseReport(rawReport({ counts: { claims: 3, dont_hold: -1, needs_you: 1, cant_tell: 0, holds: 2 } })), null);
+ assert.equal(w.parseReport(rawReport({ claims: [claim({ verdict: 'maybe' })], counts: { claims: 1, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 0 } })), null);
+ assert.equal(w.parseReport(rawReport({ claims: [], counts: { claims: 0, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 0 } })), null);
+ assert.equal(w.parseReport(rawReport({ status: 'weird' })), null);
+ assert.equal(w.parseReport('nope'), null);
+ // A failed check has no claims and still parses.
+ const f = w.parseReport(rawReport({ status: 'failed', counts: null, claims: [], error: 'timed out' }));
+ assert.equal(f.status, 'failed');
+});
+
+test('parseWatchMeta: only kind "watch"; a failed check carries its reason', () => {
+ assert.equal(w.parseWatchMeta(JSON.stringify({ kind: 'bot_action' })), null);
+ const ok = w.parseWatchMeta(JSON.stringify({ kind: 'watch', mission_id: 'm-1', check_id: 'wc-1', status: 'done', watch_report: rawReport() }));
+ assert.equal(ok.missionId, 'm-1');
+ assert.ok(ok.report);
+ const failed = w.parseWatchMeta({ kind: 'watch', mission_id: 'm-1', status: 'failed', watch_report: rawReport({ status: 'failed', claims: [], counts: null, reason: { code: 'timeout', text: 'the turn timed out' } }) });
+ assert.equal(failed.report, null);
+ assert.equal(failed.failed, 'the turn timed out');
+});
+
+test('parseWatch and parseCandidates drop what they cannot read', () => {
+ assert.equal(w.parseWatch({ state: 'sleeping' }), null);
+ assert.equal(w.parseWatch(watch()).state, 'watching');
+ const cs = w.parseCandidates([
+ { kwant_id: 'k1', name: 'Rigel', relation: 'no_task', can_run: true, default: true },
+ { kwant_id: 'k2', name: 'Lin', relation: 'lead', can_run: false, reason: { code: 'no_model', text: 'it has no model' } },
+ { kwant_id: 'k3', relation: 'lead' },
+ { kwant_id: 'k4', name: 'X', relation: 'boss' },
+ ]);
+ assert.deepEqual(cs.map((c) => c.kwant_id), ['k1', 'k2']);
+ assert.equal(w.defaultCandidate(cs).kwant_id, 'k1');
+ assert.equal(w.relationText(cs[1]), "can’t run: it has no model");
+});
+
+test('chipView: every state', () => {
+ const v = (wv, status = 'active') => w.chipView({ ...mission(wv), status }, TZ);
+ assert.equal(v(undefined).text, 'Watch');
+ assert.equal(v(watch(), 'done'), null);
+ assert.equal(v(watch({ state: 'off' })).click, 'setup');
+ const nt = v(watch({ state: 'no_tasks' }));
+ assert.equal(nt.disabled, true);
+ assert.equal(nt.tooltip, 'Add tasks first. There’s nothing to check yet.');
+ assert.equal(v(watch({ state: 'finished' })), null);
+ assert.equal(v(watch()).text, 'Watching · Rigel');
+ const ck = v(watch({ state: 'checking' }));
+ assert.equal(ck.icon, 'loader');
+ assert.equal(ck.text, 'Rigel is checking the claims');
+ const dh = v(watch({ state: 'dont_hold', last_check: lastCheck({ claims: 3, dont_hold: 1, needs_you: 1, cant_tell: 0, holds: 1 }) }));
+ assert.deepEqual([dh.text, dh.tone, dh.click], ['1 claim doesn’t hold · 18:14', 'rose', 'report']);
+ assert.equal(v(watch({ state: 'dont_hold', last_check: lastCheck({ claims: 3, dont_hold: 2, needs_you: 0, cant_tell: 0, holds: 1 }) })).text, '2 claims don’t hold · 18:14');
+ const ah = v(watch({ state: 'all_hold', last_check: lastCheck({ claims: 4, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 4 }) }));
+ assert.deepEqual([ah.text, ah.tone], ['All 4 claims hold · 18:14', 'teal']);
+ const ct = v(watch({ state: 'cant_tell', last_check: lastCheck({ claims: 4, dont_hold: 0, needs_you: 0, cant_tell: 1, holds: 3 }) }));
+ assert.deepEqual([ct.text, ct.tone], ['4 claims checked · 18:14', 'muted']);
+ assert.equal(v(watch({ state: 'same_stop', last_check: lastCheck({ claims: 1, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 1 }) })).text, 'No change since the 18:14 check');
+ const cr = v(watch({ state: 'cant_run', reason: { code: 'no_model', text: 'it has no model' } }));
+ assert.deepEqual([cr.text, cr.tone], ['Rigel can’t check: it has no model', 'amber']);
+ assert.equal(v(watch({ state: 'over_limit' })).tone, 'amber');
+ assert.equal(v(watch({ state: 'failed', can_check_now: true })).click, 'retry');
+ assert.equal(v(watch({ state: 'failed', can_check_now: false })).click, 'settings');
+});
+
+test('reportOpensItself only for a "doesn’t hold" or a "needs you"', () => {
+ const p = (state, counts) => w.reportOpensItself(w.parseWatch(watch({ state, last_check: lastCheck(counts) })));
+ assert.equal(p('dont_hold', { claims: 2, dont_hold: 1, needs_you: 0, cant_tell: 0, holds: 1 }), true);
+ assert.equal(p('all_hold', { claims: 2, dont_hold: 0, needs_you: 1, cant_tell: 0, holds: 2 }), true);
+ assert.equal(p('all_hold', { claims: 2, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 2 }), false);
+});
+
+test('orderClaims, tints and summary chips follow the design and the server counts', () => {
+ const r = w.parseReport(rawReport());
+ const { shown, folded } = w.orderClaims(r);
+ assert.deepEqual(shown.map((c) => c.task_id), ['t-1', 't-5']);
+ assert.deepEqual(folded.map((c) => c.task_id), ['t-3']);
+ assert.deepEqual(shown.map(w.rowTint), ['rose', 'amber']);
+ assert.deepEqual(w.summaryChips(r.counts).map((c) => c.text), ['1 don’t hold', '1 needs you', '2 hold']);
+});
+
+test('chat text, needs-you lines and code parts', () => {
+ const r = w.parseReport(rawReport());
+ assert.equal(w.chatText(r, TZ), 'Checked 3 claims after the mission stopped at 18:10. 1 don’t hold, 1 needs you, 2 hold. I restarted Write the tests with Lin.');
+ const all = w.parseReport(rawReport({ counts: { claims: 1, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 1 }, claims: [claim({ verdict: 'holds' })], actions: [] }));
+ assert.equal(w.chatText(all, TZ), 'Checked 1 claim after the mission stopped at 18:10. All hold.');
+ const a = w.firstNeedsYou(r);
+ assert.equal(w.youText(r, a, TZ), 'Deploy the site waits for your OK to deploy since 18:12.');
+ assert.deepEqual(w.codeParts('Ran `npm test` now'), [{ code: false, text: 'Ran ' }, { code: true, text: 'npm test' }, { code: false, text: ' now' }]);
+ assert.equal(w.failedChatText('the turn timed out'), 'The check failed: the turn timed out. Nothing was restarted.');
+});
+
+test('the chip is a labelled button with a polite live label', () => {
+ const view = w.chipView(mission(watch()), TZ);
+ const html = ui.chip({ view, expanded: false, controls: 'p', onClick: () => {} });
+ assert.match(html, /<button/);
+ assert.match(html, /aria-label="Watching · Rigel, watch settings"/);
+ assert.match(html, /aria-expanded="false"/);
+ assert.match(html, /aria-live="polite"/);
+});
+
+test('the report: a real table with headers, rows in order, nothing rendered as HTML', () => {
+ const evil = rawReport({ claims: rawReport().claims.map((c, i) => (i === 2 ? { ...c, checked: '<img src=x onerror=alert(1)>' } : c)) });
+ const html = ui.report({ report: w.parseReport(evil), phone: false, timeZone: TZ, id: 'r' });
+ assert.match(html, /<table/);
+ assert.match(html, /<caption/);
+ assert.equal((html.match(/<th[^>]*scope="col"/g) || []).length >= 3, true);
+ assert.doesNotMatch(html, /<img/);
+ const t = text(html);
+ assert.ok(t.indexOf('Write the tests') < t.indexOf('Deploy the site'));
+ assert.match(t, /Show 1 that hold/);
+ assert.match(t, /What Rigel did/);
+ assert.match(t, /Rigel tried to approve the deploy\. Only you can approve, so it was left for you\./);
+});
+
+test('the chat message falls back to the message text when the report is invalid', () => {
+ const html = ui.chat({ report: null, fallbackText: 'Checked 3 claims.', watcherName: 'Rigel', timeZone: TZ });
+ assert.match(text(html), /Checked 3 claims\./);
+ const ok = ui.chat({ report: w.parseReport(rawReport()), fallbackText: 'x', watcherName: 'Rigel', timeZone: TZ, onSeeClaims: () => {} });
+ assert.match(text(ok), /See the claims/);
+ const all = w.parseReport(rawReport({ counts: { claims: 1, dont_hold: 0, needs_you: 0, cant_tell: 0, holds: 1 }, claims: [claim({ verdict: 'holds' })], actions: [], inbox: null }));
+ assert.doesNotMatch(text(ui.chat({ report: all, fallbackText: 'x', watcherName: 'Rigel', timeZone: TZ, onSeeClaims: () => {} })), /See the claims/);
+});
+
+test('Inbox: a watch item gets the card shape, an amber Watch label, and others pass through', () => {
+ const raw = { kind: 'watch', id: 'wc-1', kwant_id: 'k-rigel', kwant_name: 'Rigel', title: 'Launch', summary: 'Rigel: …', status: 'open', at: '2026-11-10T18:14:00Z', mission_id: 'm-1', task_id: 't-5', thread_id: 'th-1' };
+ const n = w.normalizeAwayItem(raw);
+ assert.equal(n.timestamp, '2026-11-10T18:14:00Z');
+ assert.deepEqual(n.link, { thread_id: 'th-1', channel_id: null, direct_kwant_id: 'k-rigel' });
+ assert.equal(n.mission_id, 'm-1');
+ assert.deepEqual(w.itemLabel(n), { label: 'Watch', tone: 'amber' });
+ const q = { kind: 'question', id: 'q', timestamp: 't', link: { thread_id: null, channel_id: null, direct_kwant_id: 'k' } };
+ assert.equal(w.normalizeAwayItem(q), q);
+});
diff --git a/frontend/tests/missionWatchFix511.test.mjs b/frontend/tests/missionWatchFix511.test.mjs
new file mode 100644
index 00000000..4ba8db57
--- /dev/null
+++ b/frontend/tests/missionWatchFix511.test.mjs
@@ -0,0 +1,228 @@
+// 0.9.0 P1 #511 QA fixes (qa-p1-ui.md, Nov 11): the live MissionWatchControls in jsdom.
+// F-A report opens itself when the same check id goes checking -> done; F-B no endless
+// "Loading the report…" while a check runs; F-C setup focus; F-D failed stop on desktop;
+// F-E failed Undo on the phone; N-1 no colour transition in reduced motion.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/s1/board', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'localStorage', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle']) {
+ if (k in dom.window) Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+globalThis.IS_REACT_ACT_ENVIRONMENT = false;
+
+const ui = await loadBundled(`
+ import React from 'react';
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ import { MissionWatchControls, WatchBoardContext } from './src/components/MissionWatch';
+ export { parseWatch, parseReport, parseCandidates } from './src/missionWatch';
+ /** A board with one mission card; window.__setWatch plays the SSE update. */
+ export const Harness = ({ mission, api, phone, openReportFor }) => {
+ const [m, setM] = React.useState(mission);
+ window.__setWatch = (w) => setM((x) => ({ ...x, watch: w }));
+ const board = { api, phone, timeZone: 'UTC', openReportFor, onChanged: (_id, w) => setM((x) => ({ ...x, watch: w })) };
+ return React.createElement(WatchBoardContext.Provider, { value: board },
+ React.createElement(MissionWatchControls, { mission: m }, ({ chip, report }) => React.createElement('div', null, chip, report)));
+ };
+`);
+const h = ui.React.createElement;
+const settle = async (ms = 40) => {
+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
+ await new Promise((r) => setTimeout(r, ms));
+};
+
+const counts = (dont_hold, needs_you = 0) => ({ claims: 2, dont_hold, needs_you, cant_tell: 0, holds: 2 - dont_hold });
+const claimRows = (dont) => [
+ { task_id: 't-1', task_title: 'Write the tests', owner_kwant_id: 'k-lin', owner_name: 'Lin', state: 'done', claimed: 'Done', checked: 'Ran `npm test`', verdict: dont ? 'doesnt_hold' : 'holds', needs_you: false },
+ { task_id: 't-2', task_title: 'Ship the docs', owner_kwant_id: 'k-lin', owner_name: 'Lin', state: 'done', claimed: 'Done', checked: 'The page is live', verdict: 'holds', needs_you: false },
+];
+const rawReport = (id, dont = 1) => ({
+ id, mission_id: 'm-1', kwant_id: 'k-vega', kwant_name: 'Vega', trigger: 'stop', status: 'done',
+ stopped_at: '2026-11-11T03:00:00Z', started_at: '2026-11-11T03:01:00Z', finished_at: '2026-11-11T03:04:00Z',
+ error: null, reason: null, counts: counts(dont), claims: claimRows(dont), actions: [], inbox: null, message_id: 'msg-' + id,
+});
+const rawWatch = (state, last_check = null) =>
+ ui.parseWatch({ state, kwant_id: 'k-vega', kwant_name: 'Vega', set_at: '2026-11-11T02:00:00Z', stopped: false, stopped_at: null, last_check, reason: null, can_check_now: false });
+const check = (id, status, c = null) => ({ id, status, trigger: 'stop', started_at: '2026-11-11T03:01:00Z', finished_at: status === 'checking' ? null : '2026-11-11T03:04:00Z', stopped_at: null, counts: c, message_id: null });
+const cands = () =>
+ ui.parseCandidates([
+ { kwant_id: 'k-old', name: 'Old', relation: 'no_task', task_ids: [], can_run: false, reason: { code: 'x', text: 'paused' }, default: false },
+ { kwant_id: 'k-vega', name: 'Vega', relation: 'no_task', task_ids: [], can_run: true, reason: null, default: true },
+ { kwant_id: 'k-ada', name: 'Ada', relation: 'lead', task_ids: [], can_run: true, reason: null, default: false },
+ ]);
+
+function fakeApi(over = {}) {
+ const calls = [];
+ const api = {
+ get: async (id) => (calls.push(`get ${id}`), { watch: null, report: ui.parseReport(rawReport('wc-2')), candidates: cands() }),
+ set: async (id, k) => (calls.push(`set ${id} ${k}`), rawWatch('watching')),
+ stop: async (id) => (calls.push(`stop ${id}`), rawWatch('off')),
+ checkNow: async () => rawWatch('checking', check('wc-3', 'checking')),
+ check: async () => null,
+ checks: async (id) => (calls.push(`checks ${id}`), []),
+ ...over,
+ };
+ return { api, calls };
+}
+const mount = (props) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = ui.createRoot(host);
+ root.render(h(ui.Harness, { phone: false, ...props }));
+ return { host, root, done: () => (root.unmount(), host.remove()) };
+};
+const mission = (w) => ({ id: 'm-1', title: 'Launch', status: 'active', watch: w });
+const chip = (host) => host.querySelector('[data-watch-chip]');
+const click = (el) => el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+
+test('F-A: the same check id going checking -> done with a doesn’t-hold opens the report by itself', async () => {
+ const { api, calls } = fakeApi();
+ const t = mount({ mission: mission(rawWatch('checking', check('wc-2', 'checking'))), api });
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report]').length, 0, 'closed while checking');
+ window.__setWatch(rawWatch('dont_hold', check('wc-2', 'done', counts(1))));
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report="wc-2"]').length, 1, 'report wc-2 opened itself');
+ assert.ok(calls.includes('get m-1'));
+ t.done();
+});
+
+test('F-A: a needs-you result opens it too; an all-hold result does not; a later SSE echo does not reopen', async () => {
+ const { api } = fakeApi();
+ let t = mount({ mission: mission(rawWatch('checking', check('wc-2', 'checking'))), api });
+ await settle();
+ window.__setWatch(rawWatch('all_hold', check('wc-2', 'done', counts(0, 1))));
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report]').length, 1, 'needs-you opens');
+ t.done();
+
+ t = mount({ mission: mission(rawWatch('checking', check('wc-2', 'checking'))), api });
+ await settle();
+ window.__setWatch(rawWatch('all_hold', check('wc-2', 'done', counts(0, 0))));
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report]').length, 0, 'all-hold stays closed');
+ t.done();
+
+ // Opened, hidden by the person, then the same finished check arrives again: stays hidden.
+ t = mount({ mission: mission(rawWatch('checking', check('wc-2', 'checking'))), api });
+ await settle();
+ window.__setWatch(rawWatch('dont_hold', check('wc-2', 'done', counts(1))));
+ await settle();
+ click(chip(t.host));
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report]').length, 0, 'hidden from the chip');
+ window.__setWatch(rawWatch('dont_hold', check('wc-2', 'done', counts(1))));
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report]').length, 0, 'an echo of the same check does not reopen');
+ t.done();
+});
+
+test('F-B: report opened while the first check runs says there is no report yet (not "Loading" forever)', async () => {
+ const { api, calls } = fakeApi();
+ const t = mount({ mission: mission(rawWatch('checking', check('wc-2', 'checking'))), api, openReportFor: 'm-1' });
+ await settle();
+ assert.ok(calls.includes('checks m-1'), 'asks for earlier checks');
+ const none = t.host.querySelector('[data-watch-report-none]');
+ assert.ok(none, 'plain "no report yet" line');
+ assert.match(none.textContent, /^No report yet\. Vega is checking the claims/);
+ assert.equal(t.host.querySelector('[data-watch-report-loading]'), null);
+ // When the check finishes, its report replaces the line.
+ window.__setWatch(rawWatch('dont_hold', check('wc-2', 'done', counts(1))));
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report="wc-2"]').length, 1);
+ t.done();
+});
+
+test('F-B: report opened while a re-check runs shows the last finished report', async () => {
+ const { api } = fakeApi({ checks: async () => [ui.parseReport(rawReport('wc-1'))] });
+ const t = mount({ mission: mission(rawWatch('checking', check('wc-2', 'checking'))), api, openReportFor: 'm-1' });
+ await settle();
+ assert.equal(t.host.querySelectorAll('[data-watch-report="wc-1"]').length, 1, 'last finished report wc-1');
+ assert.equal(t.host.querySelector('[data-watch-report-loading]'), null);
+ t.done();
+});
+
+test('F-C: first open focuses the selected radio once candidates load; save and Esc return focus to the chip', async () => {
+ let release;
+ const gate = new Promise((r) => (release = r));
+ const { api } = fakeApi({ get: async () => (await gate, { watch: null, report: null, candidates: cands() }) });
+ const t = mount({ mission: mission(rawWatch('off')), api });
+ await settle();
+ click(chip(t.host));
+ await settle();
+ release();
+ await settle();
+ const a = document.activeElement;
+ assert.equal(a.tagName, 'INPUT', `focus is on ${a.tagName} "${a.textContent}"`);
+ assert.equal(a.type, 'radio');
+ assert.equal(a.checked, true);
+ assert.equal(a.value, 'k-vega', 'the default pick');
+ // Save: the submit goes through the form.
+ t.host.querySelector('[data-watch-setup] form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.equal(t.host.querySelector('[role=dialog]'), null, 'closed after save');
+ assert.equal(document.activeElement, chip(t.host), 'focus back on the chip after save');
+ // Esc from a reopened panel.
+ click(chip(t.host));
+ await settle();
+ assert.ok(t.host.querySelector('[role=dialog]'));
+ t.host.querySelector('[role=dialog]').dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.equal(t.host.querySelector('[role=dialog]'), null);
+ assert.equal(document.activeElement, chip(t.host), 'focus back on the chip after Esc');
+ t.done();
+});
+
+test('F-D: a failed stop on desktop shows the error in the confirm and keeps the watcher', async () => {
+ const { api } = fakeApi({ stop: async () => { throw new Error('nope'); } });
+ const t = mount({ mission: mission(rawWatch('watching')), api });
+ await settle();
+ click(chip(t.host));
+ await settle();
+ click(t.host.querySelector('[data-watch-stop]'));
+ await settle();
+ click(t.host.querySelector('[data-watch-stop-yes]'));
+ await settle();
+ const al = [...t.host.querySelectorAll('[role=dialog] [role=alert]')];
+ assert.equal(al.length, 1);
+ assert.equal(al[0].textContent, 'nope');
+ assert.ok(t.host.querySelector('[data-watch-stop-confirm]'), 'confirm stays open');
+ assert.match(chip(t.host).textContent, /Watching/);
+ t.done();
+});
+
+test('F-E: a failed Undo on the phone shows an alert and the chip stays at the real state (off)', async () => {
+ const { api, calls } = fakeApi({ set: async (id, k) => { calls.push(`set ${id} ${k}`); throw new Error('Server down.'); } });
+ const t = mount({ mission: mission(rawWatch('watching')), api, phone: true });
+ await settle();
+ click(chip(t.host));
+ await settle();
+ click(t.host.querySelector('[data-watch-stop]'));
+ await settle();
+ assert.equal(chip(t.host).textContent, 'Watch');
+ click(t.host.querySelector('[data-undo]'));
+ await settle();
+ assert.ok(calls.includes('set m-1 k-vega'), 'Undo is PUT with the old watcher');
+ const al = t.host.querySelector('[data-watch-chip-error][role=alert]');
+ assert.ok(al, 'alert under the chip');
+ assert.equal(al.textContent, 'Couldn’t turn the watch back on: Server down. The mission isn’t watched now.');
+ assert.equal(chip(t.host).textContent, 'Watch');
+ // Opening the setup clears the stale alert.
+ click(chip(t.host));
+ await settle();
+ assert.equal(t.host.querySelector('[data-watch-chip-error]'), null);
+ t.done();
+});
+
+test('N-1: the chip has no colour transition in reduced motion', async () => {
+ const { api } = fakeApi();
+ const t = mount({ mission: mission(rawWatch('watching')), api });
+ await settle();
+ const cls = chip(t.host).className.split(/\s+/);
+ assert.ok(cls.includes('motion-reduce:transition-none'));
+ assert.ok(cls.includes('motion-reduce:duration-0'));
+ t.done();
+});