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.8: a waiting check shows as one line on the task card and in the detail (#575)

Oleksandr Ivanchenko51a4491ea864
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 55336559..4a0e0494 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -127,6 +127,7 @@ import {
cardStatus,
checkKindLabel,
checksText,
+ stoppedWaiting,
optionalChecksNote,
approvalHolds,
columnOfTask,
@@ -175,6 +176,8 @@ import { ScrollRow } from './ScrollRow';
import { MissionWatchControls, WatchBoardContext, type WatchBoard } from './MissionWatch';
import { watchApi, type WatchApi } from '../missionWatch';
import { usePhoneLayout } from '../usePhoneLayout';
+import { CardWaitingChecks, WaitingCheckLine } from './WaitingCheckLine';
+import { waitLine } from '../waitingChecks';
const TONES: Record<Tone, string> = {
emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',
@@ -673,7 +676,7 @@ export const TaskCard: React.FC<{
onDismissMany?: (ts: Task[]) => void;
}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen, onRemoveLimit, busy = false, openRisks = 0, older = [], onQuick, onDismissMany }) => {
const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
- const checks = checksText(t.checks_summary);
+ const checks = checksText(t.checks_summary, stoppedWaiting(t));
const optionalNote = optionalChecksNote(t.checks_summary);
const status = cardStatus(t, names, now);
const flags = openFlags(t);
@@ -755,7 +758,7 @@ export const TaskCard: React.FC<{
</span>
)}
{status && (
- <span className={`block text-[11px] break-words line-clamp-2 ${t.state === 'needs_you' || t.held_at || (t.state === 'review' && approvalHolds(t.checks_summary)) ? 'text-amber-200' : autofixLive ? 'text-violet-200' : t.state === 'blocked' || t.state === 'failed' ? 'text-rose-300' : 'text-zinc-400'}`}>
+ <span className={`block text-[11px] break-words line-clamp-2 ${t.state === 'needs_you' || t.held_at || (t.state === 'review' && (approvalHolds(t.checks_summary) || stoppedWaiting(t) > 0)) ? 'text-amber-200' : autofixLive ? 'text-violet-200' : t.state === 'blocked' || t.state === 'failed' ? 'text-rose-300' : 'text-zinc-400'}`}>
{status}
</span>
)}
@@ -768,6 +771,7 @@ export const TaskCard: React.FC<{
</span>
</span>
)}
+ <CardWaitingChecks task={t} now={now} />
{t.forked_from && <span className="block text-[11px] text-zinc-500" data-forked-from>A copy, made to redo an earlier task</span>}
<span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-zinc-400">
{owner ? (
@@ -1386,6 +1390,11 @@ export const EvidenceReceipt: React.FC<{
{!l.check.required && <span className="text-[10px] text-zinc-500">Optional</span>}
</p>
{l.target && <code className="block mt-1 text-[11px] text-zinc-300 break-all whitespace-pre-wrap">{l.target}</code>}
+ {waitLine(l.check) && (
+ <span className="block mt-1">
+ <WaitingCheckLine line={waitLine(l.check)!} />
+ </span>
+ )}
<p className="mt-1 text-[10px] text-zinc-500">
{[l.by ? `Checked by ${l.by}` : null, l.check.finished_at ? ago(l.check.finished_at) : null].filter(Boolean).join(' · ') || 'Hasn’t run yet'}
</p>
@@ -2049,6 +2058,8 @@ export const TaskDetailBody: React.FC<{
notice?: TaskNotice | null;
onAction: (a: TaskAction, reason?: string) => void;
onApproveCheck: (c: Check) => void;
+ /** A check that stopped waiting: wait longer (POST /api/checks/:id/wait-more). */
+ onWaitMore?: (checkId: string) => void;
onOpenChat?: (t: Task, place?: ChatPlace | null) => void;
onOpenTask?: (id: string) => void;
onResolveFlag?: (f: OpenFlag, choice: ResolveChoice) => void;
@@ -2092,6 +2103,7 @@ export const TaskDetailBody: React.FC<{
notice,
onAction,
onApproveCheck,
+ onWaitMore,
onOpenChat,
onOpenTask,
onResolveFlag,
@@ -2442,7 +2454,9 @@ export const TaskDetailBody: React.FC<{
? 'Check to allow'
: n.kind === ENGINE_CANT_SANDBOX
? 'Engine can’t be sandboxed'
- : 'Question'}
+ : n.kind === 'check_timed_out'
+ ? 'Stopped waiting'
+ : 'Question'}
:{' '}
</span>
{n.kind === ENGINE_CANT_SANDBOX ? <span data-engine-cant-sandbox>{engineCantSandboxText(owner ?? null)}</span> : n.text}
@@ -2458,6 +2472,19 @@ export const TaskDetailBody: React.FC<{
</button>
) : null;
})()
+ ) : n.kind === 'check_timed_out' ? (
+ onWaitMore &&
+ n.actions?.includes('wait_more') && (
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => onWaitMore(n.id)}
+ className="px-2 py-1 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[44px] sm:min-h-[32px] disabled:opacity-50"
+ data-wait-more
+ >
+ Wait {n.wait_more_hours ?? 24} h more
+ </button>
+ )
) : onOpenChat && answerChat(t, n) && (
<button type="button" onClick={() => onOpenChat(t, answerChat(t, n))} className="px-2 py-1 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[32px]" data-answer-in-chat>
Answer in chat
@@ -3469,6 +3496,21 @@ export const MissionBoardPage: React.FC<{
}
};
+ const waitMore = async (checkId: string) => {
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ await missionsApi.waitMore(checkId);
+ if (!alive.current) return;
+ setDetailNotice({ text: 'It waits longer now. It looks again soon.', error: false });
+ if (openId) await loadDetail(openId);
+ } catch (e) {
+ if (alive.current) setDetailNotice({ text: failMsg(e), error: true });
+ } finally {
+ if (alive.current) setBusy(false);
+ }
+ };
+
const afterChange = async (changed: Task[], openNext: string | null) => {
setTasks((list) => (list ? changed.reduce((l, x) => upsertTask(l, x), list) : list));
if (graphMission.current) loadGraph(graphMission.current);
@@ -3874,6 +3916,7 @@ export const MissionBoardPage: React.FC<{
notice={detailNotice}
onAction={act}
onApproveCheck={approveCheck}
+ onWaitMore={waitMore}
onResolveFlag={resolveFlag}
onFork={forkTask}
inGoalMission={!!missionGoalLink(missions.find((m) => m.id === detail.task.mission_id) ?? {})}
diff --git a/frontend/src/components/WaitingCheckLine.tsx b/frontend/src/components/WaitingCheckLine.tsx
new file mode 100644
index 00000000..942365af
--- /dev/null
+++ b/frontend/src/components/WaitingCheckLine.tsx
@@ -0,0 +1,116 @@
+import React, { useEffect, useState } from 'react';
+import { AlertTriangle, Hourglass } from 'lucide-react';
+import { missionsApi, type Check, type Task } from '../missions';
+import { cardWaits, detailLineText, isWaiting, nextRefresh, shortLabel, waitLine, waitLineText, waitingFallback, type WaitLine } from '../waitingChecks';
+
+/**
+ * One waiting check as a line: "Waiting on <label> since 09:12 · next look 09:27", and under it
+ * the last line the script printed. Spans only, so it can sit inside the card's button.
+ * `compact` (the card) shortens the label; the detail shows it whole and adds the deadline.
+ */
+export const WaitingCheckLine: React.FC<{ line: WaitLine; compact?: boolean }> = ({ line, compact = false }) => {
+ const label = compact ? shortLabel(line.label) : line.label;
+ const tone = line.timedOut ? 'text-amber-200' : 'text-sky-200';
+ // The detail's stopped row already has the amber hand: no second warning icon there.
+ const Icon = line.timedOut ? (compact ? AlertTriangle : null) : Hourglass;
+ const indent = Icon ? 'pl-4' : '';
+ // The detail row prints the label just above, so the detail line leaves it out.
+ const detailText = compact ? null : detailLineText(line);
+ return (
+ <span className={`block text-[11px] ${tone}`} data-waiting-line={line.timedOut ? 'timed-out' : 'waiting'}>
+ <span className="flex items-start gap-1 min-w-0">
+ {Icon && <Icon size={11} className="mt-0.5 shrink-0" aria-hidden="true" />}
+ {detailText !== null ? (
+ <span className="min-w-0 break-words" data-waiting-detail>
+ <span className="sr-only">{detailText.replace(' · ', ', ')}</span>
+ <span aria-hidden="true">{detailText}</span>
+ </span>
+ ) : (
+ <span className="min-w-0 break-words">
+ <span className="sr-only">{waitLineText(line)}</span>
+ <span aria-hidden="true">
+ {!line.timedOut && 'Waiting on '}
+ <span className="font-mono break-all text-zinc-200" title={line.label}>
+ {label}
+ </span>
+ {line.rest ? ` ${line.rest}` : ''}
+ </span>
+ </span>
+ )}
+ </span>
+ {line.last && (
+ <span className={`mt-0.5 flex min-w-0 ${indent} text-zinc-400`} data-waiting-last>
+ <span className="sr-only">It last printed: </span>
+ <span className={`min-w-0 font-mono ${compact ? 'truncate' : 'break-all whitespace-pre-wrap'}`} title={line.last}>
+ {line.last}
+ </span>
+ </span>
+ )}
+ {!compact && line.deadline && (
+ <span className={`mt-0.5 block ${indent} text-zinc-400`} data-waiting-deadline>
+ {line.deadline}
+ </span>
+ )}
+ </span>
+ );
+};
+
+/**
+ * A task card's waiting checks. The task list carries only the count (`checks_summary.waiting`),
+ * so a card that has some looks its checks up once, again when the task changes, and again a
+ * minute after the earliest next look. Until then it says "Waiting on an outside service".
+ */
+export function useWaitingChecks(t: Task): Check[] | null {
+ const waits = cardWaits(t);
+ const [checks, setChecks] = useState<Check[] | null>(null);
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ if (!waits) {
+ setChecks(null);
+ return;
+ }
+ let live = true;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ missionsApi.task(t.id).then(
+ (d) => {
+ if (!live) return;
+ const list = d.checks.filter(isWaiting);
+ setChecks(list);
+ const ms = nextRefresh(list);
+ if (ms !== null) timer = setTimeout(() => setTick((n) => n + 1), ms);
+ },
+ () => live && setChecks(null),
+ );
+ return () => {
+ live = false;
+ if (timer) clearTimeout(timer);
+ };
+ }, [waits, t.id, t.updated_at, t.checks_summary.waiting, tick]);
+ return waits ? checks : null;
+}
+
+/** The card's lines: one per waiting check (at most two, then "+N more"), or the fallback. */
+export const CardWaitingChecks: React.FC<{ task: Task; now?: number }> = ({ task, now = Date.now() }) => {
+ const checks = useWaitingChecks(task);
+ if (!cardWaits(task)) return null;
+ const lines = (checks ?? []).flatMap((c) => {
+ const l = waitLine(c, now);
+ return l ? [{ id: c.id, l }] : [];
+ });
+ if (!lines.length) {
+ return (
+ <span className="flex items-start gap-1 text-[11px] text-sky-200" data-waiting-line="summary">
+ <Hourglass size={11} className="mt-0.5 shrink-0" aria-hidden="true" />
+ {waitingFallback(task.checks_summary.waiting ?? 1)}
+ </span>
+ );
+ }
+ return (
+ <span className="block space-y-1" data-waiting-checks>
+ {lines.slice(0, 2).map(({ id, l }) => (
+ <WaitingCheckLine key={id} line={l} compact />
+ ))}
+ {lines.length > 2 && <span className="block pl-4 text-[11px] text-zinc-400">+{lines.length - 2} more waiting</span>}
+ </span>
+ );
+};
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 6dd8f260..72575a3e 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -15,7 +15,7 @@ export type TaskState = 'backlog' | 'ready' | 'working' | 'needs_you' | 'review'
export type MissionStatus = 'draft' | 'active' | 'done' | 'cancelled';
export type SourceKind = 'mission' | 'person' | 'delegation' | 'routine' | 'zombie' | 'work_ahead' | 'chat';
export type CheckKind = 'command' | 'http' | 'file_exists' | 'file_contains' | 'file_sha256' | 'peer_review' | 'person';
-export type CheckStatus = 'pending' | 'needs_approval' | 'running' | 'passed' | 'failed' | 'error';
+export type CheckStatus = 'pending' | 'needs_approval' | 'running' | 'waiting' | 'passed' | 'failed' | 'error';
export type ChecksStatus = 'not_checked' | 'pending' | 'passed' | 'failed';
export type StateCounts = Record<TaskState, number>;
@@ -63,6 +63,7 @@ export interface NeedsYouItem {
| 'approval'
| 'human_step'
| 'check_approval'
+ | 'check_timed_out'
| 'may_be_invalid'
| 'autofix_suggested'
| 'fix_needed'
@@ -72,6 +73,9 @@ export interface NeedsYouItem {
| 'rests_on_disputed_fact';
id: string;
text: string;
+ /** check_timed_out: what the person can do ("wait_more", "verify") and how long Wait adds. */
+ actions?: string[];
+ wait_more_hours?: number;
/** fact_changed, rests_on_disputed_fact: the fact (id = fact_id), its status now and what replaced it. */
fact_id?: string;
status?: string;
@@ -95,6 +99,8 @@ export interface ChecksSummary {
needs_approval?: number;
/** How many of `needs_approval` are required, so hold the task (older servers leave it out). */
required_needs_approval?: number;
+ /** Checks that count and wait on an outside service, or waited too long (older servers leave it out). */
+ waiting?: number;
total: number;
}
@@ -385,6 +391,14 @@ export interface Check {
created_at: string;
started_at: string | null;
finished_at: string | null;
+ /** A check waiting on an outside service (exit 75): the round's first "not yet", its next run and
+ * its deadline. `timed_out_at` is set when it stopped at the deadline (status `error`). Older
+ * servers leave them out. */
+ waiting_since?: string | null;
+ next_run_at?: string | null;
+ wait_until?: string | null;
+ runs?: number;
+ timed_out_at?: string | null;
}
export type EvidenceKind = 'file' | 'url' | 'note' | 'screenshot' | 'check_output';
@@ -528,8 +542,11 @@ export function columnOfTask(t: Pick<Task, 'state' | 'flags' | 'needs_you'>): Co
return c && (openFlags(t).length || (t.needs_you ?? []).some((n) => PERSON_ITEMS.has(n.kind))) ? 'needs_you' : c;
}
+/** How many of the task's checks stopped waiting on an outside service (Needs-you `check_timed_out`). */
+export const stoppedWaiting = (t: Pick<Task, 'needs_you'>): number => (t.needs_you ?? []).filter((n) => n.kind === 'check_timed_out').length;
+
/** Items that wait for the person whatever the task's state, so its card sits in Needs you. */
-const PERSON_ITEMS = new Set<NeedsYouItem['kind']>(['autofix_suggested', 'fix_needed', 'workflow_change', 'check_approval', ENGINE_CANT_SANDBOX]);
+const PERSON_ITEMS = new Set<NeedsYouItem['kind']>(['autofix_suggested', 'fix_needed', 'workflow_change', 'check_approval', 'check_timed_out', ENGINE_CANT_SANDBOX]);
/**
* The lane a phone opens on: Needs you when something waits on the person, else Working, else Ready.
@@ -827,11 +844,15 @@ function optionalWaitingCount(s: ChecksSummary): number {
* `total`: an optional check waiting for you isn't a check that didn't pass. A task that has never
* been checked says so, plainly.
*/
-export function checksText(s: ChecksSummary): { text: string; tone: Tone } {
+export function checksText(s: ChecksSummary, stopped = 0): { text: string; tone: Tone } {
const n = (k: number, one: string, many: string) => (k === 1 ? one : many.replace('#', String(k)));
if (approvalHolds(s)) return { text: n(s.required_needs_approval ?? 0, '1 check needs your OK', '# checks need your OK'), tone: 'amber' };
if (s.status === 'not_checked') return { text: 'Not checked', tone: 'zinc' };
if (s.status === 'failed') return { text: n(s.failed, '1 check failed', '# checks failed'), tone: 'rose' };
+ // #564 counts a check that stopped waiting in `waiting` too; the person has to act on those.
+ if (s.status === 'pending' && stopped > 0) return { text: n(stopped, '1 check stopped waiting', '# checks stopped waiting'), tone: 'amber' };
+ const waiting = (s.waiting ?? 0) - stopped;
+ if (s.status === 'pending' && waiting > 0) return { text: n(waiting, '1 check waiting', '# checks waiting'), tone: 'zinc' };
if (s.status === 'pending') return { text: s.passed > 0 ? n(s.passed, '1 check passed, still checking', '# checks passed, still checking') : 'Checking', tone: 'zinc' };
return { text: s.passed > 1 ? `${s.passed} checks passed` : 'Check passed', tone: 'emerald' };
}
@@ -892,6 +913,9 @@ export function cardStatus(t: Task, names: Record<string, string> = {}, now: num
if (t.checks_summary.status === 'not_checked') {
return t.reviewer?.name ? `Waiting for ${t.reviewer.name} to review` : 'Bot says done. Not checked yet';
}
+ if (stoppedWaiting(t) > 0) return 'Waiting for you: wait longer, or verify by hand';
+ // Between looks nothing is checking: the waiting line says what it waits on.
+ if (t.checks_summary.status === 'pending' && (t.checks_summary.waiting ?? 0) > 0) return 'Bot says done';
// While a required check runs the card reads as checking; the grey note covers optional ones.
if (t.checks_summary.status === 'pending') return 'Bot says done. Checking';
return optionalWaitingText(optionalWaitingCount(t.checks_summary)) ?? 'Bot says done. Checking';
@@ -1395,6 +1419,7 @@ export const CHECK_STATUS: Record<CheckStatus, { label: string; tone: Tone }> =
failed: { label: 'Failed', tone: 'rose' },
error: { label: 'Couldn’t run', tone: 'rose' },
running: { label: 'Running', tone: 'violet' },
+ waiting: { label: 'Waiting', tone: 'sky' },
pending: { label: 'Not run yet', tone: 'zinc' },
needs_approval: { label: 'Needs your OK', tone: 'amber' },
};
@@ -1439,7 +1464,7 @@ export function buildReceipt(d: Pick<TaskDetail, 'task' | 'checks' | 'evidence'>
.sort((a, b) => Date.parse(b.finished_at ?? b.created_at) - Date.parse(a.finished_at ?? a.created_at))
.map<ReceiptLine>((c) => ({
check: c,
- status: checkStatusLabel(c.status),
+ status: c.status === 'error' && c.timed_out_at ? { label: 'Stopped waiting', tone: 'amber' } : checkStatusLabel(c.status),
target: checkTarget(c),
by: c.checked_by ? actorName(c.checked_by, c.checked_by_name, names) : null,
output: c.evidence_id ? byId.get(c.evidence_id) ?? null : null,
@@ -1529,6 +1554,8 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
case 'check_started':
return 'A check started';
case 'check_result':
+ if (str(d.status) === 'waiting') return 'A check is still waiting';
+ if (str(d.status) === 'error' && d.timed_out) return 'A check stopped waiting';
return `A check ${str(d.status) === 'passed' ? 'passed' : str(d.status) === 'error' ? 'couldn’t run' : 'failed'}`;
case 'review':
return `${Who} reviewed it: ${str(d.verdict) === 'pass' ? 'pass' : 'fail'}${note ? `. ${note}` : ''}`;
@@ -1824,6 +1851,8 @@ export const missionsApi = {
tasks: () => call<{ tasks: Task[] }>('/api/tasks?limit=500').then((r) => r.tasks),
task: (id: string) => call<TaskDetail>(`/api/tasks/${enc(id)}`),
approveCheck: (id: string) => call<Check>(`/api/checks/${enc(id)}/approve`, 'POST', {}),
+ /** A check that stopped waiting on an outside service: wait `wait_more_hours` longer (person only). */
+ waitMore: (id: string) => call<Check>(`/api/checks/${enc(id)}/wait-more`, 'POST', {}),
graph: (missionId: string) => call<WorkGraph>(`/api/missions/${enc(missionId)}/graph`),
scan: (missionId: string) => call<GraphScanResult>(`/api/missions/${enc(missionId)}/graph/scan`, 'POST', {}),
/** Settle a flag. The key rides along on `redo` too, since a verified task's redo makes a copy. */
diff --git a/frontend/src/waitingChecks.ts b/frontend/src/waitingChecks.ts
new file mode 100644
index 00000000..a21b0c6b
--- /dev/null
+++ b/frontend/src/waitingChecks.ts
@@ -0,0 +1,122 @@
+/**
+ * Waiting checks (0.9.7, #564): a Mission Control check whose command exited 75, or whose http
+ * reply said "not ready yet", waits on an outside service. The task card and the task detail show
+ * it as one line, "Waiting on <label> since 09:12 · next look 09:27", plus the last line the
+ * script printed. Past its deadline it stops and tells you once in Needs you.
+ *
+ * Everything here reads the server's fields as they are: no new numbers, only clock times and the
+ * hours between the server's own `waiting_since` and `wait_until`.
+ */
+import type { Check, Task } from './missions';
+import { clockTime } from './failover';
+
+type WaitFields = Pick<Check, 'kind' | 'spec' | 'status' | 'output_excerpt' | 'waiting_since' | 'next_run_at' | 'wait_until' | 'timed_out_at'>;
+
+/** Whether the check waits on an outside service now, or stopped waiting at its deadline. */
+export const isWaiting = (c: Pick<Check, 'status' | 'timed_out_at'>): boolean => c.status === 'waiting' || (c.status === 'error' && !!c.timed_out_at);
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v.trim() : null);
+
+/**
+ * What the check waits on, as the server names it in Needs you (`check_label`): the command, the
+ * address, or the file. The spec in task JSON is already masked by the server.
+ */
+export function waitLabel(c: Pick<Check, 'kind' | 'spec'>): string {
+ const s = c.spec ?? {};
+ const what = c.kind === 'command' ? str(s.command) : c.kind === 'http' ? str(s.url) : str(s.path);
+ return what ?? c.kind;
+}
+
+/** A label cut to `max` characters with an ellipsis, so the line never runs off a phone card. */
+export function shortLabel(label: string, max = 48): string {
+ const chars = [...label];
+ return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : label;
+}
+
+/**
+ * The last line the script printed. The server stores a waiting run's output as
+ * "run N: not ready yet\n<output>", so that first line is kwant's, not the script's.
+ */
+export function lastPrinted(excerpt: string | null | undefined): string | null {
+ if (!excerpt) return null;
+ const lines = excerpt.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
+ if (lines.length && /^run \d+: not ready yet$/.test(lines[0])) lines.shift();
+ return lines.length ? lines[lines.length - 1] : null;
+}
+
+const at = (iso: string | null | undefined): Date | null => {
+ if (!iso) return null;
+ const t = Date.parse(iso);
+ return Number.isNaN(t) ? null : new Date(t);
+};
+
+export interface WaitLine {
+ /** Full label, for the title and screen readers. */
+ label: string;
+ /** "since 09:12 · next look 09:27" (waiting), or "didn't answer in 72 h." (stopped). */
+ rest: string;
+ /** Stopped: the hours between the server's `waiting_since` and `wait_until`, or null. */
+ hours: number | null;
+ /** Waiting: "If it isn't ready by Sun 09:12, it stops and tells you." Stopped: null. */
+ deadline: string | null;
+ /** The last line the script printed, or null. */
+ last: string | null;
+ timedOut: boolean;
+}
+
+/** The one line for a waiting check, or null when it isn't waiting. */
+export function waitLine(c: WaitFields, now: number = Date.now()): WaitLine | null {
+ if (!isWaiting(c)) return null;
+ const label = waitLabel(c);
+ const last = lastPrinted(c.output_excerpt);
+ const since = at(c.waiting_since);
+ const until = at(c.wait_until);
+ if (c.status === 'error') {
+ const hours = since && until ? Math.max(1, Math.round((until.getTime() - since.getTime()) / 3_600_000)) : null;
+ return { label, rest: `${hours ? `didn’t answer in ${hours} h` : 'didn’t answer in time'}.`, hours, deadline: null, last, timedOut: true };
+ }
+ const next = at(c.next_run_at);
+ const parts = [since ? `since ${clockTime(since, now)}` : null, next ? `next look ${next.getTime() <= now ? 'soon' : clockTime(next, now)}` : null].filter(Boolean);
+ return {
+ label,
+ rest: parts.join(' · '),
+ hours: null,
+ deadline: until ? `If it isn’t ready by ${clockTime(until, now)}, it stops and tells you.` : null,
+ last,
+ timedOut: false,
+ };
+}
+
+/** The whole line as one sentence, for screen readers and tests. */
+export function waitLineText(w: WaitLine): string {
+ if (w.timedOut) return `${w.label} ${w.rest}`;
+ return `Waiting on ${w.label}${w.rest ? ` ${w.rest}` : ''}`;
+}
+
+/**
+ * The detail's line, where the receipt row already shows the label above it:
+ * "Waiting since 10:08 · next look 10:38", or "No answer in 72 h.".
+ */
+export function detailLineText(w: WaitLine): string {
+ if (w.timedOut) return w.hours ? `No answer in ${w.hours} h.` : 'No answer in time.';
+ return w.rest ? `Waiting ${w.rest}` : 'Waiting';
+}
+
+/** Whether the card should look up its waiting checks: it is in review and the summary counts some. */
+export const cardWaits = (t: Pick<Task, 'state' | 'checks_summary'>): boolean => t.state === 'review' && (t.checks_summary.waiting ?? 0) > 0;
+
+/** Before the card has its checks: "Waiting on an outside service" (or "on 2 outside services"). */
+export function waitingFallback(n: number): string {
+ return n > 1 ? `Waiting on ${n} outside services` : 'Waiting on an outside service';
+}
+
+/** When to look the card's checks up again: shortly after the earliest next look, or null. */
+export function nextRefresh(checks: Pick<Check, 'status' | 'next_run_at'>[], now: number = Date.now()): number | null {
+ const due = checks
+ .filter((c) => c.status === 'waiting')
+ .map((c) => Date.parse(c.next_run_at ?? ''))
+ .filter((t) => !Number.isNaN(t));
+ if (!due.length) return null;
+ // A minute after the run is due (the missions tick runs it then), and never sooner than 30 s.
+ return Math.max(30_000, Math.min(...due) + 60_000 - now);
+}
diff --git a/frontend/tests/waitingChecks.test.mjs b/frontend/tests/waitingChecks.test.mjs
new file mode 100644
index 00000000..ec59dc3f
--- /dev/null
+++ b/frontend/tests/waitingChecks.test.mjs
@@ -0,0 +1,189 @@
+// Waiting checks (0.9.7, #564): a check that waits on an outside service shows as one line on the
+// task card and in the task detail, "Waiting on <label> since 09:12 · next look 09:27", plus the
+// last line the script printed. Past its deadline the card moves to Needs you with a Wait N h more button.
+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/waitingChecks'; export { checksText, buildReceipt, checkStatusLabel, cardStatus, columnOfTask, stoppedWaiting, missionsApi, eventText } from './src/missions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { TaskCard, EvidenceReceipt, TaskDetailBody } from './src/components/MissionBoardView';
+ import { WaitingCheckLine } from './src/components/WaitingCheckLine';
+ import { buildReceipt } from './src/missions';
+ export const card = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(TaskCard, p)));
+ export const line = (p) => renderToStaticMarkup(React.createElement(WaitingCheckLine, p));
+ export const detail = (p) => renderToStaticMarkup(React.createElement(TaskDetailBody, p));
+ export const receipt = (d) => renderToStaticMarkup(React.createElement(EvidenceReceipt, { receipt: buildReceipt(d, {}), names: {} }));
+`);
+
+// Local times (no zone), so the clock reads the same in any time zone.
+const NOW = Date.parse('2026-11-13T09:20:00');
+const iso = (s) => new Date(Date.parse(s)).toISOString();
+const check = (over = {}) => ({
+ id: 'ch1', task_id: 't1', kind: 'command', spec: { command: './gate.sh', recheck_mins: 15, wait_hours: 72 }, required: true, approved: true,
+ status: 'waiting', output_excerpt: 'run 2: not ready yet\nasking the store\njob 42: in_review (run 2)', checked_by: 'kwant', checked_by_name: null,
+ requested_by: 'person', evidence_id: null, created_at: iso('2026-11-13T09:00:00'), started_at: iso('2026-11-13T09:12:00'),
+ finished_at: iso('2026-11-13T09:12:05'), waiting_since: iso('2026-11-13T09:12:00'), next_run_at: iso('2026-11-13T09:27:00'),
+ wait_until: iso('2026-11-16T09:12:00'), runs: 2, timed_out_at: null, ...over,
+});
+const task = (over = {}) => ({
+ id: 't1', space_id: 's1', mission_id: 'm1', mission_title: 'Ship 1.2', title: 'Submit the app for review', acceptance: 'The store approves 1.2.',
+ state: 'review', priority: 1, owner_kwant_id: 'k_lin', owner_name: 'Lin', suggested_kwant_id: null, budget_tokens: 50000, spent_tokens: 1200,
+ attempts: 0, max_attempts: 3, blocked_reason: null, source_kind: 'mission', source_id: 'm1', channel_id: 'c1', direct_kwant_id: null,
+ thread_id: null, created_by: 'person', created_at: iso('2026-11-13T09:00:00'), updated_at: iso('2026-11-13T09:12:05'), finished_at: null,
+ depends_on: [], waiting_on: [], claim: null, needs_you: [],
+ checks_summary: { status: 'pending', passed: 0, failed: 0, waiting: 1, needs_approval: 0, required_needs_approval: 0, total: 1 },
+ ...over,
+});
+
+test('a waiting check reads as one line with its clock times, the deadline and the last printed line', () => {
+ const l = w.waitLine(check(), NOW);
+ assert.equal(w.waitLineText(l), 'Waiting on ./gate.sh since 09:12 · next look 09:27');
+ assert.equal(l.last, 'job 42: in_review (run 2)', "the script's last line, not kwant's run header");
+ assert.match(l.deadline, /^If it isn’t ready by \S+ 09:12, it stops and tells you\.$/, 'tells you, as in the 0.9.7 copy');
+ assert.equal(l.timedOut, false);
+});
+
+test('a next look that is already due says soon; an http check waits on its address', () => {
+ const l = w.waitLine(check({ next_run_at: iso('2026-11-13T09:15:00') }), NOW);
+ assert.equal(w.waitLineText(l), 'Waiting on ./gate.sh since 09:12 · next look soon');
+ const h = w.waitLine(check({ kind: 'http', spec: { url: 'https://status.example/jobs/42', waiting_status: 202 } }), NOW);
+ assert.match(w.waitLineText(h), /^Waiting on https:\/\/status\.example\/jobs\/42 since/);
+});
+
+test('the last printed line skips the run header and is null when the script printed nothing', () => {
+ assert.equal(w.lastPrinted('run 1: not ready yet\n'), null);
+ assert.equal(w.lastPrinted('run 3: not ready yet\nfirst\n\nsecond \n'), 'second');
+ assert.equal(w.lastPrinted(null), null);
+ assert.equal(w.waitLine(check({ output_excerpt: 'run 1: not ready yet' }), NOW).last, null);
+});
+
+test('past its deadline the card line says it did not answer, and the detail says No answer', () => {
+ const l = w.waitLine(check({ status: 'error', next_run_at: null, timed_out_at: iso('2026-11-16T09:12:00') }), NOW);
+ assert.equal(w.waitLineText(l), './gate.sh didn’t answer in 72 h.');
+ assert.equal(l.hours, 72);
+ assert.equal(w.detailLineText(l), 'No answer in 72 h.');
+ assert.equal(w.detailLineText({ ...l, hours: null }), 'No answer in time.');
+ assert.equal(w.detailLineText(w.waitLine(check(), NOW)), 'Waiting since 09:12 · next look 09:27');
+ const det = ui.line({ line: l });
+ assert.ok(!det.includes('./gate.sh'), 'the detail row already shows the label');
+ assert.ok(!det.includes('<svg'), 'no second warning icon in the detail');
+ assert.ok(!det.includes('pl-4'), 'the last printed line lines up under the text');
+ const card = ui.line({ line: l, compact: true });
+ assert.ok(card.includes('<svg'), 'the card keeps its triangle');
+ assert.ok(!card.includes('Verify the task by hand'));
+ assert.equal(l.deadline, null);
+ assert.equal(l.timedOut, true);
+ assert.equal(w.waitLine(check({ status: 'error', timed_out_at: null }), NOW), null, 'an ordinary error is not a wait');
+ assert.equal(w.waitLine(check({ status: 'passed' }), NOW), null);
+});
+
+test('long labels are cut on the card only', () => {
+ const long = './scripts/' + 'a'.repeat(80) + '.sh';
+ assert.equal([...w.shortLabel(long)].length, 48);
+ assert.ok(w.shortLabel(long).endsWith('…'));
+ const compact = ui.line({ line: w.waitLine(check({ spec: { command: long } }), NOW), compact: true });
+ assert.ok(compact.includes(`title="${long}"`), 'the full label stays in the title');
+ assert.ok(compact.includes(`Waiting on ${long} since`), 'and in the screen-reader sentence');
+});
+
+test('the line is labelled for screen readers and never renders HTML from the script', () => {
+ const html = ui.line({ line: w.waitLine(check({ output_excerpt: 'run 1: not ready yet\n<img src=x onerror=alert(1)>' }), NOW) });
+ assert.ok(!html.includes('<img'), 'output is text');
+ assert.ok(html.includes('&lt;img'));
+ assert.ok(html.includes('class="sr-only">Waiting since 09:12, next look 09:27<'));
+ assert.ok(html.includes('>Waiting since 09:12 · next look 09:27<'));
+ assert.ok(!html.includes('text-zinc-500'), 'small grey text meets AA');
+ assert.ok(ui.line({ line: w.waitLine(check(), NOW), compact: true }).includes('class="sr-only">Waiting on ./gate.sh since 09:12 · next look 09:27<'));
+ assert.ok(html.includes('It last printed: '));
+ assert.ok(html.includes('data-waiting-deadline'));
+ assert.ok(html.includes('aria-hidden="true"'));
+});
+
+test('the card says it waits before its checks load, and the chip counts waiting checks', () => {
+ const html = ui.card({ task: task(), names: {}, now: NOW, onOpen: () => {} });
+ assert.ok(html.includes('data-waiting-line="summary"'));
+ assert.ok(html.includes('Waiting on an outside service'));
+ assert.ok(html.includes('1 check waiting'));
+ assert.equal(w.checksText(task().checks_summary).text, '1 check waiting');
+ assert.equal(w.waitingFallback(2), 'Waiting on 2 outside services');
+ const plain = ui.card({ task: task({ checks_summary: { status: 'pending', passed: 0, failed: 0, total: 1 } }), names: {}, now: NOW, onOpen: () => {} });
+ assert.ok(!plain.includes('data-waiting-line'), 'an older server without the count shows nothing new');
+ assert.ok(!ui.card({ task: task({ state: 'verified' }), names: {}, now: NOW, onOpen: () => {} }).includes('data-waiting-line'));
+});
+
+test('the detail receipt shows the waiting line in the check row, and a timed-out check as Stopped waiting', () => {
+ const d = { task: task(), checks: [check()], evidence: [] };
+ const html = ui.receipt(d);
+ assert.ok(html.includes('data-check-status="waiting"'));
+ assert.ok(html.includes('>Waiting<'), 'the status badge');
+ assert.ok(html.includes('data-waiting-line="waiting"'));
+ assert.ok(html.includes('job 42: in_review (run 2)'));
+ const out = ui.receipt({ ...d, checks: [check({ status: 'error', timed_out_at: iso('2026-11-16T09:12:00') })] });
+ assert.ok(out.includes('Stopped waiting'));
+ assert.ok(!out.includes('Couldn’t run'));
+ assert.ok(out.includes('data-waiting-line="timed-out"'));
+});
+
+test('the card looks again a minute after the earliest next look, never sooner than 30 s', () => {
+ assert.equal(w.nextRefresh([check()], NOW), 8 * 60_000);
+ assert.equal(w.nextRefresh([check({ next_run_at: iso('2026-11-13T09:00:00') })], NOW), 30_000);
+ assert.equal(w.nextRefresh([check({ status: 'error' })], NOW), null);
+});
+
+const stopped = (over = {}) => task({
+ needs_you: [{ id: 'ch1', kind: 'check_timed_out', text: './gate.sh didn’t answer in 72 h. Wait longer, or verify by hand.', check_label: './gate.sh', actions: ['wait_more', 'verify'], wait_more_hours: 24 }],
+ ...over,
+});
+
+test('a waiting card says Bot says done; a stopped one moves to Needs you, amber, with its own chip', () => {
+ assert.equal(w.cardStatus(task(), {}, NOW), 'Bot says done');
+ assert.equal(w.columnOfTask(task()), 'review');
+ const t = stopped();
+ assert.equal(w.stoppedWaiting(t), 1);
+ assert.equal(w.columnOfTask(t), 'needs_you');
+ assert.equal(w.cardStatus(t, {}, NOW), 'Waiting for you: wait longer, or verify by hand');
+ assert.deepEqual(w.checksText(t.checks_summary, 1), { text: '1 check stopped waiting', tone: 'amber' });
+ assert.deepEqual(w.checksText({ ...t.checks_summary, waiting: 3 }, 2), { text: '2 checks stopped waiting', tone: 'amber' });
+ const html = ui.card({ task: t, names: {}, now: NOW, onOpen: () => {} });
+ assert.ok(/text-amber-200[^>]*>Waiting for you: wait longer/.test(html));
+ assert.ok(html.includes('1 check stopped waiting'));
+ assert.ok(!html.includes('1 check waiting'), 'the waiting count leaves the stopped one out');
+});
+
+test('the detail offers Wait 24 h more for a stopped check, 44 px on phones, labelled Stopped waiting', () => {
+ let asked = null;
+ const t = stopped();
+ const p = { detail: { task: t, checks: [check({ status: 'error', timed_out_at: iso('2026-11-16T09:12:00') })], evidence: [], events: [] }, names: {}, now: NOW, onAction() {}, onApproveCheck() {}, onWaitMore: (id) => (asked = id) };
+ const html = ui.detail(p);
+ const btn = html.match(/<button[^>]*data-wait-more[^>]*>([\s\S]*?)<\/button>/);
+ assert.ok(btn, 'the button');
+ assert.ok(btn[0].includes('min-h-[44px] sm:min-h-[32px]'), '44 px on phones');
+ assert.equal(btn[1].replace(/<!-- -->/g, ''), 'Wait 24 h more');
+ const flat = html.replace(/<!-- -->/g, '');
+ assert.ok(flat.includes('>Stopped waiting: <'), 'the row label');
+ assert.ok(!flat.includes('Question: '));
+ const six = ui.detail({ ...p, detail: { ...p.detail, task: stopped({ needs_you: [{ ...t.needs_you[0], wait_more_hours: 6 }] }) } });
+ assert.ok(six.replace(/<!-- -->/g, '').includes('>Wait 6 h more<'));
+ const noAction = ui.detail({ ...p, detail: { ...p.detail, task: stopped({ needs_you: [{ ...t.needs_you[0], actions: ['verify'] }] }) } });
+ assert.ok(!noAction.includes('data-wait-more'), 'no button when the server does not offer it');
+ assert.equal(typeof w.missionsApi.waitMore, 'function');
+ assert.equal(asked, null);
+});
+
+// Round 3 (Rigel QA): the Activity trail must not say "A check failed" for each waiting poll, nor
+// "A check couldn't run" when the check stops waiting. passed / failed / plain error read as before.
+test('activity trail: waiting polls and the stop read as waiting, other results unchanged', () => {
+ const ev = (detail) => ({ id: 1, task_id: 't1', mission_id: null, kind: 'check_result', actor: 'kwant', actor_name: null,
+ from_state: null, to_state: null, detail, created_at: iso('2026-11-13T09:12:05') });
+ assert.equal(w.eventText(ev({ status: 'waiting' })), 'A check is still waiting');
+ assert.equal(w.eventText(ev({ status: 'error', timed_out: true })), 'A check stopped waiting');
+ assert.equal(w.eventText(ev({ status: 'passed' })), 'A check passed');
+ assert.equal(w.eventText(ev({ status: 'failed' })), 'A check failed');
+ assert.equal(w.eventText(ev({ status: 'error' })), 'A check couldn’t run');
+ assert.equal(w.eventText(ev({ status: 'error', timed_out: false })), 'A check couldn’t run');
+});