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.

26d: Details and the reply say which step failed or didn't run (#776)

Oleksandr Ivanchenkob1eb0611aca8
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 6a450dbc..e7b3b3c6 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,5 +1,6 @@
import React, { Suspense, lazy, useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { flushSync } from 'react-dom';
+import { recordRunWait } from './routineRow';
import { askOrder } from './askOrder';
import { refreshDictation } from './dictation';
import { DecidingMap, applyDecideEvent, decisionsApi, hydrateDeciding } from './decideFirst';
@@ -1573,6 +1574,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
case 'routine_run':
case 'RoutineRun':
+ recordRunWait(event.data);
emitContinuity({ type: 'routine_run', data: event.data });
break;
case 'notify':
@@ -3011,6 +3013,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
/** 0.9.5 F: a done item's Open in chat, and a routine run's History row: the chat, at the answer. */
+ // 26d: a waiting routine run's "Open the card" lands on its approval card in the routine's chat.
+ const openRunCard = (n: NotifiedChat) => {
+ if (spaceSettingsTab) closeSpaceSettings();
+ openPlace(n);
+ };
+
const openRunResult = (t: MessageTarget) => {
if (spaceSettingsTab) closeSpaceSettings();
if (t.thread_id) {
@@ -5038,6 +5046,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
routineFocus={routineFocus}
onOpenRunResult={openRunResult}
+ onOpenRunCard={openRunCard}
isPhone={isPhone}
onApprovalsChanged={refreshRoster}
onImported={reloadAfterImport}
diff --git a/frontend/src/activity.ts b/frontend/src/activity.ts
index 9cd264a6..638434d1 100644
--- a/frontend/src/activity.ts
+++ b/frontend/src/activity.ts
@@ -4,7 +4,9 @@
import { parseMetaObject } from './questions';
export type StepKind = 'thinking' | 'tool' | 'approval' | 'human_step' | 'note';
-export type StepStatus = 'running' | 'waiting' | 'ok' | 'failed' | 'done' | 'declined' | 'stopped';
+// 26b (#766): `unanswered` is a step whose approval card nobody answered in time, so it didn't run; `rehearsed`
+// is a dry run (Skill Foundry) that recorded the call instead of running it. Neither is "ok".
+export type StepStatus = 'running' | 'waiting' | 'ok' | 'failed' | 'done' | 'declined' | 'stopped' | 'unanswered' | 'rehearsed';
export interface ActivityStep {
id: string;
@@ -37,7 +39,7 @@ export interface LiveActivity {
}
const KINDS: StepKind[] = ['thinking', 'tool', 'approval', 'human_step', 'note'];
-const STATUSES: StepStatus[] = ['running', 'waiting', 'ok', 'failed', 'done', 'declined', 'stopped'];
+const STATUSES: StepStatus[] = ['running', 'waiting', 'ok', 'failed', 'done', 'declined', 'stopped', 'unanswered', 'rehearsed'];
const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined);
/** A step from the wire, or null when it isn't one. Unknown kinds draw as notes. */
@@ -173,7 +175,8 @@ export function formatClock(ms: number): string {
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`;
}
-/** "Worked 0:41 · 12 steps" (the strip's last time, same start), "1 step", plus "· 2 failed" when any failed. */
+/** "Worked 0:41 · 12 steps" (the strip's last time, same start), "1 step", plus "· 2 failed" when any failed and
+ * "· 1 didn't run" when an approval went unanswered (26d). */
export function activitySummary(a: SavedActivity): string {
const n = counted(a.steps).length + a.dropped;
const steps = `${n} ${n === 1 ? 'step' : 'steps'}`;
@@ -181,6 +184,8 @@ export function activitySummary(a: SavedActivity): string {
const parts = span !== null && span >= 1000 ? [`Worked ${formatClock(span)}`, steps] : [steps];
const failed = a.steps.filter((s) => s.status === 'failed').length;
if (failed) parts.push(`${failed} failed`);
+ const unanswered = a.steps.filter((s) => s.status === 'unanswered').length;
+ if (unanswered) parts.push(`${unanswered} didn’t run`);
return parts.join(' · ');
}
@@ -201,6 +206,10 @@ export function statusLabel(s: ActivityStep): string {
return s.kind === 'approval' ? 'Denied' : 'Skipped';
case 'stopped':
return 'Stopped';
+ case 'unanswered':
+ return 'Not approved in time';
+ case 'rehearsed':
+ return 'Dry run';
}
}
diff --git a/frontend/src/components/ActivityList.tsx b/frontend/src/components/ActivityList.tsx
index a751d149..841cb902 100644
--- a/frontend/src/components/ActivityList.tsx
+++ b/frontend/src/components/ActivityList.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
-import { Brain, Check, ChevronRight, CircleSlash, Hand, Info, ListTree, Loader2, ShieldQuestion, X } from 'lucide-react';
+import { Brain, Check, ChevronRight, CircleDashed, CircleSlash, Hand, Info, ListTree, Loader2, ShieldQuestion, TimerOff, X } from 'lucide-react';
import {
ActivityStep,
LiveActivity,
@@ -49,6 +49,10 @@ const StatusIcon: React.FC<{ step: ActivityStep }> = ({ step }) => {
return <CircleSlash size={13} className="text-zinc-400" />;
case 'stopped':
return <CircleSlash size={13} className="text-zinc-400" />;
+ case 'unanswered':
+ return <TimerOff size={13} className="text-amber-300" />;
+ case 'rehearsed':
+ return <CircleDashed size={13} className="text-zinc-400" />;
}
})();
return (
@@ -101,7 +105,12 @@ const ThinkingBox: React.FC<{ text: string; live: boolean; id: string }> = ({ te
);
};
-const StepRow: React.FC<{ step: ActivityStep; live?: LiveActivity; now: number; listId: string }> = ({ step, live, now, listId }) => {
+const STEP_MARK: Partial<Record<ActivityStep['status'], string>> = {
+ failed: 'text-rose-300 border-rose-500/30',
+ unanswered: 'text-amber-300 border-amber-500/30',
+};
+
+const StepRow: React.FC<{ step: ActivityStep; live?: LiveActivity; now: number; listId: string; opened?: boolean }> = ({ step, live, now, listId, opened = false }) => {
const time = stepTime(step, now);
const running = step.kind === 'thinking' && step.status === 'running';
const text = step.kind === 'thinking' ? thinkingText(step, live) : '';
@@ -120,12 +129,20 @@ const StepRow: React.FC<{ step: ActivityStep; live?: LiveActivity; now: number;
);
const waiting = step.status === 'waiting';
+ // 26d: a step that failed or wasn't approved in time says so in words, not only by its icon, even when a later
+ // step worked. The icon's label already names it for screen readers, so the mark is hidden from them.
+ const mark = STEP_MARK[step.status];
const head = (
<>
<StatusIcon step={step} />
<span className={`min-w-0 flex-1 break-words ${step.status === 'stopped' ? 'text-zinc-400' : waiting ? 'text-amber-100' : 'text-zinc-200'}`}>
{step.kind === 'thinking' ? (running ? 'Thinking…' : 'Thought') : <Title text={readableStepTitle(step.title)} />}
</span>
+ {mark && (
+ <span aria-hidden="true" data-step-mark={step.status} className={`flex-shrink-0 rounded border px-1 text-[10px] leading-4 font-medium ${mark}`}>
+ {statusLabel(step)}
+ </span>
+ )}
{time && <span className="flex-shrink-0 font-mono text-[10px] text-zinc-400 tabular-nums">{time}</span>}
</>
);
@@ -153,15 +170,20 @@ const StepRow: React.FC<{ step: ActivityStep; live?: LiveActivity; now: number;
}
return (
- <li className={`px-3 py-1.5 text-xs ${waiting ? 'bg-amber-500/[0.06]' : ''}`}>
+ <li
+ id={`${listId}-${step.id}`}
+ tabIndex={-1}
+ data-step-status={step.status}
+ className={`px-3 py-1.5 text-xs focus:outline-none focus-visible:bg-zinc-800/60 focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-400 ${waiting ? 'bg-amber-500/[0.06]' : ''}`}
+ >
{step.detail ? (
- <details className="group">
+ <details className="group" open={opened || undefined}>
<summary className="flex items-start gap-2 cursor-pointer list-none rounded [&::-webkit-details-marker]:hidden focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400">
{head}
<ChevronRight size={13} className="mt-px flex-shrink-0 text-zinc-400 transition-transform motion-reduce:transition-none group-open:rotate-90" aria-hidden="true" />
</summary>
<pre
- className={`mt-1 ml-5 font-mono text-[11px] whitespace-pre-wrap break-all rounded-md border px-2 py-1.5 max-h-40 overflow-y-auto ${
+ className={`mt-1 ml-5 font-mono text-[11px] whitespace-pre-wrap [overflow-wrap:anywhere] rounded-md border px-2 py-1.5 max-h-40 overflow-y-auto ${
step.status === 'failed' ? 'text-rose-200 bg-rose-950/30 border-rose-500/20' : 'text-zinc-300 bg-zinc-950/80 border-zinc-800'
}`}
>
@@ -175,12 +197,12 @@ const StepRow: React.FC<{ step: ActivityStep; live?: LiveActivity; now: number;
);
};
-const Steps: React.FC<{ steps: ActivityStep[]; live?: LiveActivity; dropped?: number; id: string }> = ({ steps, live, dropped = 0, id }) => {
+const Steps: React.FC<{ steps: ActivityStep[]; live?: LiveActivity; dropped?: number; id: string; openStep?: string | null }> = ({ steps, live, dropped = 0, id, openStep = null }) => {
const now = useNow(steps.some(isOpenStep));
return (
<ol id={id} aria-label="Steps" className="divide-y divide-zinc-700/40">
{steps.map((s) => (
- <StepRow key={s.id} step={s} live={live} now={now} listId={id} />
+ <StepRow key={s.id} step={s} live={live} now={now} listId={id} opened={s.id === openStep} />
))}
{dropped > 0 && (
<li className="px-3 py-1.5 text-xs text-zinc-400">
@@ -314,10 +336,32 @@ export const LiveActivityList: React.FC<{ live: LiveActivity; idBase: string; co
};
/** On a saved reply: "Worked 0:41 · 12 steps", opening to the list. `children` go under the steps. */
-export const SavedActivityList: React.FC<{ activity: SavedActivity; idBase: string; children?: React.ReactNode }> = ({ activity, idBase, children }) => {
- const [open, setOpen] = useState(false);
+export const SavedActivityList: React.FC<{
+ activity: SavedActivity;
+ idBase: string;
+ children?: React.ReactNode;
+ /** 26d: a nonce from the line under the reply; each new value opens the list at `focusStep` and focuses it. */
+ openRequest?: number;
+ focusStep?: string | null;
+ /** Start open (tests and shots). */
+ defaultOpen?: boolean;
+}> = ({ activity, idBase, children, openRequest, focusStep = null, defaultOpen = false }) => {
+ const [open, setOpen] = useState(defaultOpen);
+ const [asked, setAsked] = useState<string | null>(defaultOpen ? focusStep : null);
const listId = `${idBase}-steps`;
+ useEffect(() => {
+ if (!openRequest) return;
+ setOpen(true);
+ setAsked(focusStep);
+ }, [openRequest, focusStep]);
+ useEffect(() => {
+ if (!openRequest || !focusStep) return;
+ const el = document.getElementById(`${listId}-${focusStep}`);
+ el?.focus({ preventScroll: true });
+ el?.scrollIntoView({ block: 'nearest', behavior: window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
+ }, [openRequest, focusStep, listId, open]);
const failed = activity.steps.some((s) => s.status === 'failed');
+ const unanswered = activity.steps.some((s) => s.status === 'unanswered');
return (
<div className="mb-2 max-w-full">
<button
@@ -327,13 +371,13 @@ export const SavedActivityList: React.FC<{ activity: SavedActivity; idBase: stri
aria-controls={open ? listId : undefined}
className={STEPS_ROW_BUTTON}
>
- <ListTree size={13} className={failed ? 'text-rose-300' : 'text-sky-400/80'} aria-hidden="true" />
+ <ListTree size={13} className={unanswered ? 'text-amber-300' : failed ? 'text-rose-300' : 'text-sky-400/80'} aria-hidden="true" />
<span className="truncate min-w-0">{activitySummary(activity)}</span>
<ChevronRight size={13} className={`flex-shrink-0 text-zinc-400 transition-transform motion-reduce:transition-none ${open ? 'rotate-90' : ''}`} aria-hidden="true" />
</button>
{open && (
<div className={STEPS_ROW_LIST}>
- <Steps steps={activity.steps} dropped={activity.dropped} id={listId} />
+ <Steps steps={activity.steps} dropped={activity.dropped} id={listId} openStep={asked} />
{children}
</div>
)}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index cee520c6..a073e8a2 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -43,6 +43,8 @@ import { LiveActivity, foldLiveSteps, hasThinkingText, parseActivityMeta } from
import { LiveActivityList, SavedActivityList } from './ActivityList';
import { BrowsedChip } from './BrowsedChip';
import { pagesOfReply, type ReplyPage } from '../browserPages';
+import { ReplyCheckLine } from './ReplyCheckLine';
+import { replyOutcome } from '../replyOutcome';
import { FailoverNote, REPLY_NAME, REPLY_NAME_LINE_LIVE_HEIGHT, ReplyMeta, replyNameLine } from './ReplyMeta';
import { assignSwitchNotes, liveSwitchNote, type SwitchNote } from '../failoverNotes';
import { savedFailoverHandoff, savedFailoverNotice } from '../failover';
@@ -1267,6 +1269,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
return result ? result.ok : true;
};
+ // 26d: the line under a reply opens its Details at the step that failed or didn't run (a nonce per message).
+ const [detailsAsk, setDetailsAsk] = useState<Record<string, number>>({});
+ const askDetails = (id: string) => setDetailsAsk((m) => ({ ...m, [id]: (m[id] ?? 0) + 1 }));
const toggleThought = (id: string) => {
setOpenThoughts((prev) => ({ ...prev, [id]: !prev[id] }));
};
@@ -1767,6 +1772,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
const filesOnly = files.length > 0 && isSharedFileMessage(msg.meta);
const isThoughtOpen = !!openThoughts[msg.id];
const savedActivity = !isUser && msg.meta ? parseActivityMeta(msg.meta) : null;
+ const outcome = replyOutcome(savedActivity?.steps);
const ranOn = isUser ? null : ranOnLabel(msg.meta);
const account = isUser ? null : ranOnAccount(msg.meta);
const tokens = isUser ? null : replyTokens(msg.tokens_used, msg.meta);
@@ -1858,7 +1864,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
tokens={tokens}
cost={cost}
done={done}
- failed={!!savedActivity?.steps.some((s) => s.status === 'failed')}
+ outcome={outcome}
+ openRequest={detailsAsk[msg.id]}
note={savedFailoverNotice(msg.meta) ?? switchNoteFor.get(msg.id)}
handoff={savedFailoverHandoff(msg.meta)}
route={
@@ -1887,7 +1894,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
>
{/* What the reply did: "12 steps · 41s", opening to the steps (tool calls go inside) */}
{savedActivity && (
- <SavedActivityList activity={savedActivity} idBase={`act-${msg.id}`}>
+ <SavedActivityList activity={savedActivity} idBase={`act-${msg.id}`} openRequest={detailsAsk[msg.id]} focusStep={outcome?.stepId ?? null}>
{msg.tool_calls && (
<div className="border-t border-zinc-800/60 p-2">
<ToolCallsList raw={msg.tool_calls} />
@@ -1967,6 +1974,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
</div>
</div>
)}
+ {!isUser && !underReply && <ReplyCheckLine outcome={outcome} onDetails={() => askDetails(msg.id)} />}
{files.length > 0 && <FileTiles files={files} align={onYourSide ? 'end' : 'start'} sharedBy={filesOnly && !isUser ? displayName : undefined} at={msg.created_at ?? null} />}
{isUser && heldNotes?.[msg.id]}
{filesOnly && !isUser && files.length > 0 && shareInfo(msg.meta).auto && (
diff --git a/frontend/src/components/ReplyCheckLine.tsx b/frontend/src/components/ReplyCheckLine.tsx
new file mode 100644
index 00000000..192c611d
--- /dev/null
+++ b/frontend/src/components/ReplyCheckLine.tsx
@@ -0,0 +1,28 @@
+import React from 'react';
+import { CircleAlert } from 'lucide-react';
+import { checkLine, type ReplyOutcome } from '../replyOutcome';
+
+/**
+ * 26d: the quiet line under a reply whose step didn't run or failed for good, so a confident reply is never
+ * the last word. "Details" opens the reply's Details at that step. Nothing for "failed, then worked".
+ */
+export const ReplyCheckLine: React.FC<{ outcome: ReplyOutcome | null; onDetails: () => void }> = ({ outcome, onDetails }) => {
+ const text = checkLine(outcome);
+ if (!text) return null;
+ return (
+ <p data-reply-check={outcome!.kind} className="mt-1.5 flex max-w-full min-w-0 items-start gap-1.5 text-xs leading-5 text-zinc-400">
+ <CircleAlert size={13} aria-hidden="true" className={`mt-[3px] shrink-0 ${outcome!.kind === 'failed' ? 'text-rose-300' : 'text-amber-300'}`} />
+ <span className="min-w-0 break-words">
+ {text}{' '}
+ <button
+ type="button"
+ onClick={onDetails}
+ className="kw-focus kw-hit rounded font-semibold text-violet-300 hover:text-violet-200"
+ data-compact
+ >
+ Details
+ </button>
+ </span>
+ </p>
+ );
+};
diff --git a/frontend/src/components/ReplyMeta.tsx b/frontend/src/components/ReplyMeta.tsx
index 656d3ddc..c6ae5d35 100644
--- a/frontend/src/components/ReplyMeta.tsx
+++ b/frontend/src/components/ReplyMeta.tsx
@@ -1,4 +1,4 @@
-import React, { useId, useState } from 'react';
+import React, { useEffect, useId, useState } from 'react';
import { ChevronRight } from 'lucide-react';
import { localClock } from '../clock';
import { RouteInfo, useRouteChip } from './RouteChip';
@@ -7,6 +7,7 @@ import { SentToTelegram } from './TelegramMarks';
import { DoneMarker } from './DoneMarker';
import { ranOnWords } from '../modelUsage';
import type { ReplyDone } from '../replyDone';
+import { detailsLabel, type ReplyOutcome } from '../replyOutcome';
export interface ReplyFacts {
/** "Claude · Opus 5.5": the engine and model the reply ran on. */
@@ -23,8 +24,12 @@ export interface ReplyMetaProps extends ReplyFacts {
at?: string | null;
/** Drawn before the name on phones, where the avatar column is hidden. */
avatar?: React.ReactNode;
- /** Whether a step failed: the Details toggle says so while it's folded. */
+ /** Whether a step failed: the Details toggle says so while it's folded. Superseded by `outcome` when given. */
failed?: boolean;
+ /** 26d: what the steps add up to (replyOutcome); the folded toggle says which step failed or didn't run. */
+ outcome?: ReplyOutcome | null;
+ /** 26d: changes each time the line under the reply asks Details to open (a nonce; 0 or absent does nothing). */
+ openRequest?: number;
/** One muted line under the name, e.g. "Claude is out until 03:00 · answered on Codex (GPT-6.1)". */
note?: string | null;
/** Why this bot answered: Details' first row, in words, with "Wrong bot?" after it. */
@@ -51,7 +56,8 @@ const REPLY_NAME_LINE_TYPE = 'items-center gap-x-2 gap-y-1 text-xs text-zinc-400
// The Details button's height: min-h-6, and 44 px where modern.css makes every control a 44 px tap target
// (touch screens below 768 px), so the live line is as tall as the finished one there too.
export const REPLY_NAME_LINE_LIVE_HEIGHT = 'min-h-6 [@media(max-width:767px)_and_(pointer:coarse)]:min-h-11';
-export const replyNameLine = (extra: string): string => `${REPLY_NAME_LINE_BOX} ${extra} ${REPLY_NAME_LINE_TYPE}`;
+export const replyNameLine = (extra: string, wrap = false): string =>
+ `${wrap ? REPLY_NAME_LINE_BOX.replace('flex-nowrap', 'flex-wrap') : REPLY_NAME_LINE_BOX} ${extra} ${REPLY_NAME_LINE_TYPE}`;
export const FailoverNote: React.FC<{ text: string }> = ({ text }) => (
<p data-failover-note="" className="-mt-0.5 mb-1.5 max-w-full text-xs leading-snug text-zinc-500 break-words">
@@ -62,8 +68,14 @@ export const FailoverNote: React.FC<{ text: string }> = ({ text }) => (
const hasContent = (n: React.ReactNode) => React.Children.toArray(n).length > 0;
/** A bot reply's header: one line, "Name · [Done] · 3:42 PM · Details", and a Details toggle holding the rest in words. */
-export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, account, tokens, cost, failed = false, note, route, done, handoff, now, sentToTelegram = false, children }) => {
+export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, account, tokens, cost, failed = false, outcome, openRequest, note, route, done, handoff, now, sentToTelegram = false, children }) => {
const [open, setOpen] = useState(false);
+ useEffect(() => {
+ if (openRequest) setOpen(true);
+ }, [openRequest]);
+ const told: ReplyOutcome | null = outcome !== undefined ? outcome : failed ? { kind: 'failed', stepId: '' } : null;
+ // Rose for a step that didn't work for good, amber for one nobody answered, quiet for "failed, then worked".
+ const tone = !told || open ? 'text-zinc-400' : told.kind === 'failed' ? 'text-rose-300' : told.kind === 'unanswered' ? 'text-amber-300' : 'text-zinc-300';
const why = useRouteChip(route);
const panelId = useId();
const time = localClock(at, now);
@@ -90,7 +102,8 @@ export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, a
const hasDetails = facts.length > 0 || hasContent(children) || !!why.panel;
return (
<div className="w-full max-w-full min-w-0">
- <div className={replyNameLine('sm:flex-wrap')}>
+ {/* 26d: a Details label that names an outcome is long; on a phone it moves to its own row rather than clip. */}
+ <div className={replyNameLine('sm:flex-wrap', !!told)} data-name-line-wraps={told ? '' : undefined}>
{avatar && <span className="sm:hidden shrink-0 inline-flex">{avatar}</span>}
<span className={REPLY_NAME}>{name}</span>
{done && <DoneMarker done={done} />}
@@ -108,11 +121,10 @@ export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, a
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
- className={`shrink-0 inline-flex items-center gap-0.5 rounded-md px-1.5 min-h-6 text-xs hover:text-zinc-100 hover:bg-zinc-800 transition-colors motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 ${
- failed && !open ? 'text-rose-300' : 'text-zinc-400'
- }`}
+ className={`shrink-0 inline-flex items-center gap-0.5 whitespace-nowrap rounded-md px-1.5 min-h-6 text-xs hover:text-zinc-100 hover:bg-zinc-800 transition-colors motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 ${tone}`}
+ data-details-outcome={told && !open ? told.kind : undefined}
>
- {failed && !open ? 'Details · a step failed' : 'Details'}
+ {open ? 'Details' : detailsLabel(told)}
<ChevronRight size={12} className={`transition-transform motion-reduce:transition-none ${open ? 'rotate-90' : ''}`} aria-hidden="true" />
</button>
)}
diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsx
index 62e075e3..19bd4478 100644
--- a/frontend/src/components/RoutinesPanel.tsx
+++ b/frontend/src/components/RoutinesPanel.tsx
@@ -1,5 +1,7 @@
-import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
import { routineRunNote } from '../spendStop';
+import { liveWaitOf, runRowState, runWaitsNow, subscribeRunWaits, type RunTone, type RunWait } from '../routineRow';
+import type { NotifiedChat } from '../chatTarget';
import { useUndoableDelete } from '../undoDelete';
import { UndoNotice } from './UndoNotice';
import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Sparkles, Trash2 } from 'lucide-react';
@@ -7,7 +9,6 @@ import {
Routine,
RoutineInput,
RoutineRun,
- RunStatus,
ScheduleForm,
WEEKDAYS,
WORK_WEEK,
@@ -63,19 +64,25 @@ export interface RoutineFocus {
nonce: number;
}
-const STATUS: Record<RunStatus, { label: string; cls: string }> = {
- running: { label: 'Running', cls: 'bg-sky-500/10 text-sky-300 border-sky-500/20' },
- ok: { label: 'OK', cls: 'bg-emerald-500/10 text-emerald-300 border-emerald-500/20' },
- error: { label: 'Failed', cls: 'bg-rose-500/10 text-rose-300 border-rose-500/20' },
- skipped: { label: 'Skipped', cls: 'bg-zinc-700/30 text-zinc-400 border-zinc-700' },
+// 26d: `waiting` and `needs_you` take the amber the steps list already uses for an ask; no new colours.
+const TONE: Record<RunTone, string> = {
+ running: 'bg-sky-500/10 text-sky-300 border-sky-500/20',
+ ok: 'bg-emerald-500/10 text-emerald-300 border-emerald-500/20',
+ error: 'bg-rose-500/10 text-rose-300 border-rose-500/20',
+ skipped: 'bg-zinc-700/30 text-zinc-400 border-zinc-700',
+ waiting: 'bg-amber-500/10 text-amber-300 border-amber-500/20',
+ needs_you: 'bg-amber-500/10 text-amber-300 border-amber-500/20',
};
-const StatusBadge: React.FC<{ status: RunStatus }> = ({ status }) => (
- <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${STATUS[status]?.cls ?? STATUS.skipped.cls}`}>
- {status === 'running' && <Loader2 size={9} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
- {STATUS[status]?.label ?? status}
- </span>
-);
+const StatusBadge: React.FC<{ status: string; wait?: RunWait | null }> = ({ status, wait }) => {
+ const st = runRowState({ status }, wait);
+ return (
+ <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${TONE[st.tone]}`} data-run-badge={st.tone}>
+ {st.tone === 'running' && <Loader2 size={9} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {st.label}
+ </span>
+ );
+};
/** On a routine added from one kwant suggested (Automation Discovery). */
export const SuggestedBadge: React.FC = () => (
@@ -440,7 +447,70 @@ const lastRanDate = (iso: string | null | undefined): string | null => {
export const runResultTarget = (routine: Routine, run: RoutineRun): MessageTarget | null =>
run.message_id ? { message_id: run.message_id, channel_id: routine.channel_id, kwant_id: routine.kwant_id, thread_id: routine.thread_id ?? null } : null;
-const RunHistory: React.FC<{ routine: Routine; tick: number; onOpenRunResult?: (t: MessageTarget) => void }> = ({ routine, tick, onOpenRunResult }) => {
+/** 26d: a run's card, for "Open the card" on a run that waits (or waited) on it. */
+export const runCardTarget = (routine: Routine, cardId: string): NotifiedChat => ({
+ channel_id: routine.channel_id,
+ kwant_id: routine.kwant_id,
+ thread_id: routine.thread_id ?? null,
+ card_id: cardId,
+});
+
+/** One run in History: badge, when, how it started, Open the card (26d), Open result and the run's note. */
+export const RunRow: React.FC<{
+ routine: Routine;
+ run: RoutineRun;
+ wait?: RunWait | null;
+ onOpenRunResult?: (t: MessageTarget) => void;
+ onOpenRunCard?: (t: NotifiedChat) => void;
+}> = ({ routine, run: r, wait, onOpenRunResult, onOpenRunCard }) => {
+ const st = runRowState(r, wait);
+ const t = onOpenRunResult ? runResultTarget(routine, r) : null;
+ const card = onOpenRunCard && st.cardId ? st.cardId : null;
+ const note = routineRunNote(r);
+ const link = 'kw-focus kw-hit inline-flex items-center gap-0.5 rounded font-semibold text-violet-300 hover:text-violet-200';
+ return (
+ <li className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-zinc-400" data-run-row={r.id} data-run-state={st.tone}>
+ <StatusBadge status={r.status} wait={wait} />
+ <span>{formatWhen(r.started_at)}</span>
+ <span className="text-zinc-400">{r.trigger === 'manual' ? 'Run now' : 'Scheduled'}</span>
+ {/* Mira re-check 6: on a phone the links always sit on their own line under the badge. */}
+ {(t || card) && <span className="basis-full h-0 sm:hidden" aria-hidden="true" />}
+ {card && (
+ <button
+ type="button"
+ onClick={() => onOpenRunCard!(runCardTarget(routine, card))}
+ className={link}
+ aria-label={`Open the approval card the run on ${formatWhen(r.started_at)} ${st.tone === 'waiting' ? 'waits on' : 'waited on'}`}
+ data-compact
+ data-run-card={card}
+ >
+ Open the card <ChevronRight size={11} aria-hidden="true" />
+ </button>
+ )}
+ {t && (
+ <button
+ type="button"
+ onClick={() => onOpenRunResult!(t)}
+ className={link}
+ aria-label={`Open the result of the run on ${formatWhen(r.started_at)}`}
+ data-compact
+ data-run-result={r.id}
+ >
+ Open result <ChevronRight size={11} aria-hidden="true" />
+ </button>
+ )}
+ {note && <span className={`basis-full min-w-0 [overflow-wrap:anywhere] ${note.quiet ? 'text-zinc-400' : 'text-rose-300/90'}`}>{note.text}</span>}
+ </li>
+ );
+};
+
+const RunHistory: React.FC<{
+ routine: Routine;
+ tick: number;
+ waits: Record<string, RunWait>;
+ onOpenRunResult?: (t: MessageTarget) => void;
+ onOpenRunCard?: (t: NotifiedChat) => void;
+}> = ({ routine, tick, waits, onOpenRunResult, onOpenRunCard }) => {
const routineId = routine.id;
const [runs, setRuns] = useState<RoutineRun[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -460,41 +530,14 @@ const RunHistory: React.FC<{ routine: Routine; tick: number; onOpenRunResult?: (
return (
<ol className="space-y-1" aria-label="Run history">
{runs.map((r) => (
- <li key={r.id} className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-zinc-400">
- <StatusBadge status={r.status} />
- <span>{formatWhen(r.started_at)}</span>
- <span className="text-zinc-400">{r.trigger === 'manual' ? 'Run now' : 'Scheduled'}</span>
- {(() => {
- const t = onOpenRunResult ? runResultTarget(routine, r) : null;
- if (!t) return null;
- return (
- <>
- {/* Mira re-check 6: on a phone Open result always sits on its own line under the badge. */}
- <span className="basis-full h-0 sm:hidden" aria-hidden="true" />
- <button
- type="button"
- onClick={() => onOpenRunResult!(t)}
- className="kw-focus kw-hit inline-flex items-center gap-0.5 rounded font-semibold text-violet-300 hover:text-violet-200"
- aria-label={`Open the result of the run on ${formatWhen(r.started_at)}`}
- data-compact
- data-run-result={r.id}
- >
- Open result <ChevronRight size={11} aria-hidden="true" />
- </button>
- </>
- );
- })()}
- {(() => {
- const note = routineRunNote(r);
- if (!note) return null;
- return <span className={`basis-full min-w-0 [overflow-wrap:anywhere] ${note.quiet ? 'text-zinc-400' : 'text-rose-300/90'}`}>{note.text}</span>;
- })()}
- </li>
+ <RunRow key={r.id} routine={routine} run={r} wait={waits[r.id]} onOpenRunResult={onOpenRunResult} onOpenRunCard={onOpenRunCard} />
))}
</ol>
);
};
+const NO_WAITS: Record<string, RunWait> = {};
+
export const RoutineRow: React.FC<{
routine: Routine;
kwantName?: string;
@@ -505,10 +548,13 @@ export const RoutineRow: React.FC<{
onEdit: () => void;
/** 0.9.5 F: History rows link to each run's result message. */
onOpenRunResult?: (t: MessageTarget) => void;
+ /** 26d: live waits by run id, and where "Open the card" goes. */
+ waits?: Record<string, RunWait>;
+ onOpenRunCard?: (t: NotifiedChat) => void;
onChanged: () => void;
/** Tests: start in the Undo window. */
initialPending?: boolean;
-}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onOpenRunResult, onChanged, initialPending = false }) => {
+}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onOpenRunResult, waits = NO_WAITS, onOpenRunCard, onChanged, initialPending = false }) => {
const rowRef = useRef<HTMLLIElement>(null);
const switchRef = useRef<HTMLInputElement>(null);
const [highlight, setHighlight] = useState(false);
@@ -572,7 +618,7 @@ export const RoutineRow: React.FC<{
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className={`text-xs font-medium break-words ${routine.enabled ? 'text-zinc-100' : 'text-zinc-400'}`}>{routine.name}</span>
{routine.origin === 'discovery' && <SuggestedBadge />}
- {routine.last_status && <StatusBadge status={routine.last_status} />}
+ {routine.last_status && <StatusBadge status={routine.last_status} wait={liveWaitOf(waits, routine.id)} />}
</div>
{/* Routines setup F: what it does, then when it runs next, then the schedule, bot and place. */}
{what.line && (
@@ -625,7 +671,7 @@ export const RoutineRow: React.FC<{
{(error ?? removal.error) && <p className="pl-9 text-[11px] text-rose-400" role="alert">{error ?? `Couldn’t delete it: ${removal.error}`}</p>}
{open && (
<div id={historyId} className="pl-9 pt-1">
- <RunHistory routine={routine} tick={tick} onOpenRunResult={onOpenRunResult} />
+ <RunHistory routine={routine} tick={tick} waits={waits} onOpenRunResult={onOpenRunResult} onOpenRunCard={onOpenRunCard} />
</div>
)}
</li>
@@ -645,11 +691,16 @@ export const RoutinesPanel: React.FC<{
onOpenSettings?: () => void;
/** 0.9.5 F: a History row's Open result. */
onOpenRunResult?: (t: MessageTarget) => void;
-}> = ({ kwantId, kwants, channels, focus, onOpenSettings, onOpenRunResult }) => {
+ /** 26d: a waiting run's "Open the card": the routine's chat at its approval card. */
+ onOpenRunCard?: (t: NotifiedChat) => void;
+}> = ({ kwantId, kwants, channels, focus, onOpenSettings, onOpenRunResult, onOpenRunCard }) => {
const [routines, setRoutines] = useState<Routine[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [editing, setEditing] = useState<Routine | 'new' | null>(null);
const [tick, setTick] = useState(0);
+ // 26d: which runs wait on an approval card right now, by run id. App records the live `routine_run` events even
+ // while this panel is closed (routineRow.recordRunWait), so a wait that began earlier still shows.
+ const waits = useSyncExternalStore(subscribeRunWaits, runWaitsNow, runWaitsNow);
const reload = useCallback(async () => {
try {
@@ -785,6 +836,8 @@ export const RoutinesPanel: React.FC<{
focusPause={focus?.mode === 'pause' && focus.id === r.id ? focus.nonce : undefined}
onEdit={() => setEditing(r)}
onOpenRunResult={onOpenRunResult}
+ waits={waits}
+ onOpenRunCard={onOpenRunCard}
onChanged={reload}
/>
),
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index 5212a67c..826d1862 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -44,6 +44,7 @@ import { AppsAccounts } from './AppsAccounts';
import { PhoneAppCard } from './PhoneAppCard';
import { editorProps, useEscapeLayer } from '../escape';
import { devTeamRefs } from '../devMode';
+import type { NotifiedChat } from '../chatTarget';
export type { SettingsScope, SpaceSettingsTab };
@@ -96,6 +97,8 @@ interface Props {
routineFocus?: RoutineFocus | null;
/** 0.9.5 F: a routine run's History row opens its answer in the chat. */
onOpenRunResult?: (t: MessageTarget) => void;
+ /** 26d: a waiting routine run's "Open the card". */
+ onOpenRunCard?: (t: NotifiedChat) => void;
/** Phones get a full-screen dialog; desktop keeps the space rail beside Settings. */
isPhone?: boolean;
/** After an import or its undo: load bots, teams and chats again. */
@@ -262,7 +265,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {
{tab === 'teams' && <TeamsTab {...p} />}
{tab === 'docs' && <SpaceDocsTab key={space.id} spaceId={space.id} spaceName={space.name} isPhone={p.isPhone} />}
{tab === 'skills' && <SkillsTab {...p} />}
- {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={toApp} onOpenRunResult={p.onOpenRunResult} />}
+ {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={toApp} onOpenRunResult={p.onOpenRunResult} onOpenRunCard={p.onOpenRunCard} />}
{tab === 'import' && <ImportTab {...tp} />}
</>
)}
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index 990f5205..c5297271 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -63,7 +63,9 @@ export type Schedule =
export type MonthDay = number | 'last';
-export type RunStatus = 'running' | 'ok' | 'error' | 'skipped';
+// 26b (#766): `needs_you` is a run whose approval card nobody answered, so nothing ran; `incomplete` is a run
+// with a step that failed and never worked later (its `error` is that step's reason).
+export type RunStatus = 'running' | 'ok' | 'error' | 'skipped' | 'needs_you' | 'incomplete';
export interface Routine {
id: string;
@@ -621,7 +623,8 @@ export function notificationPermission(): NotificationPermission | 'unsupported'
export type ContinuityEvent =
| { type: 'memory_changed'; data: { kwant_id: string } }
- | { type: 'routine_run'; data: { routine_id: string; run_id: string; status: RunStatus } }
+ /** 26b: `waiting` is true while the run's turn waits on an approval card (`approval_id`); missing reads false. */
+ | { type: 'routine_run'; data: { routine_id: string; run_id: string; status: RunStatus; waiting?: boolean; approval_id?: string } }
| { type: 'skill_updated'; data: Skill | DeletedSkill }
/** Show it once: `skill_recording_updated` (api.md §5), a recording's state changed. It never carries steps. */
| { type: 'recording_updated'; data: Recording }
diff --git a/frontend/src/doneAway.ts b/frontend/src/doneAway.ts
index fcf41c7c..b012a860 100644
--- a/frontend/src/doneAway.ts
+++ b/frontend/src/doneAway.ts
@@ -383,7 +383,7 @@ export function findRun(runs: RoutineRun[], runId: string | null, at: string): R
if (Number.isNaN(t)) return null;
return (
runs
- .filter((r) => r.status === 'ok' || r.status === 'error')
+ .filter((r) => r.status === 'ok' || r.status === 'error' || r.status === 'needs_you' || r.status === 'incomplete')
.map((r) => ({
r,
d: Math.abs(Date.parse(r.ended_at ?? r.started_at) - t),
diff --git a/frontend/src/replyOutcome.ts b/frontend/src/replyOutcome.ts
new file mode 100644
index 00000000..e96bbf73
--- /dev/null
+++ b/frontend/src/replyOutcome.ts
@@ -0,0 +1,48 @@
+// 26d (autonomy/details-say-what-failed/brief.md): a saved reply's Details say which step failed or didn't run,
+// most specific first, and a quiet line under the reply asks the person to check it when a step didn't run or
+// failed for good. "Failed, then the same tool worked" is told in Details only: the reply is right.
+import type { ActivityStep } from './activity';
+
+export type ReplyOutcome =
+ /** A step's approval card went unanswered, so it didn't run (26b `unanswered`). */
+ | { kind: 'unanswered'; stepId: string }
+ /** A step failed and no later step of the same tool worked. */
+ | { kind: 'failed'; stepId: string }
+ /** Every failed step was followed by a step of the same tool that worked; `count` failed steps. */
+ | { kind: 'recovered'; count: number; stepId: string };
+
+// Only a tool step that worked is a retry that worked. An approval step names its tool too and settles ok/done
+// when the person says yes, but that is permission, not the call succeeding (Rigel's D1).
+const worked = (s: ActivityStep) => s.kind === 'tool' && (s.status === 'ok' || s.status === 'done');
+
+/**
+ * What the reply's steps add up to, or null when nothing failed or went unanswered. A failed step counts as
+ * recovered only when a later tool step names the same tool and worked (an approved approval card doesn't count);
+ * a step with no tool name never recovers.
+ * `stepId` is the step Details opens to: the first unanswered or failed-for-good step, else the first failed.
+ */
+export function replyOutcome(steps: readonly ActivityStep[] | null | undefined): ReplyOutcome | null {
+ if (!steps?.length) return null;
+ const unanswered = steps.find((s) => s.status === 'unanswered');
+ if (unanswered) return { kind: 'unanswered', stepId: unanswered.id };
+ const failed = steps.map((s, i) => [s, i] as const).filter(([s]) => s.status === 'failed');
+ if (!failed.length) return null;
+ const stuck = failed.find(([s, i]) => !s.tool || !steps.slice(i + 1).some((t) => t.tool === s.tool && worked(t)));
+ if (stuck) return { kind: 'failed', stepId: stuck[0].id };
+ return { kind: 'recovered', count: failed.length, stepId: failed[0][0].id };
+}
+
+/** The folded Details toggle's words. */
+export function detailsLabel(o: ReplyOutcome | null): string {
+ if (!o) return 'Details';
+ if (o.kind === 'unanswered') return 'Details · a step didn’t run (no answer)';
+ if (o.kind === 'failed') return 'Details · a step failed';
+ return `Details · ${o.count} ${o.count === 1 ? 'step' : 'steps'} failed, then worked`;
+}
+
+/** The quiet line under the reply: only when a step didn't run or failed without a later success. */
+export function checkLine(o: ReplyOutcome | null): string | null {
+ if (o?.kind === 'unanswered') return 'A step didn’t run, so check this before relying on it.';
+ if (o?.kind === 'failed') return 'A step failed, so check this before relying on it.';
+ return null;
+}
diff --git a/frontend/src/routineRow.ts b/frontend/src/routineRow.ts
index 1a66be55..74848ccb 100644
--- a/frontend/src/routineRow.ts
+++ b/frontend/src/routineRow.ts
@@ -23,3 +23,82 @@ export const routineLabel = (name: string): string => (name ? `Routine · ${name
/** The instructions on one line for the collapsed row: whitespace folded; CSS adds the ellipsis. */
export const routineLine = (text: string | null | undefined): string => (text ?? '').replace(/\s+/g, ' ').trim();
+
+// ---------------------------------------------------------------- 26d: a run's row in Routines › History
+
+/** What the live `routine_run` events said about a run that waits on an approval card (26b). */
+export interface RunWait {
+ routine_id: string | null;
+ waiting: boolean;
+ /** The card the run waits on (or last waited on, this session); null when no event named one. */
+ approval_id: string | null;
+}
+
+export type RunTone = 'running' | 'ok' | 'error' | 'skipped' | 'waiting' | 'needs_you';
+
+export interface RunRowState {
+ label: string;
+ tone: RunTone;
+ /** The approval card the row links to ("Open the card"), when there is one to open. */
+ cardId: string | null;
+}
+
+const RUN_LABEL: Record<string, { label: string; tone: RunTone }> = {
+ running: { label: 'Running', tone: 'running' },
+ ok: { label: 'OK', tone: 'ok' },
+ error: { label: 'Failed', tone: 'error' },
+ skipped: { label: 'Skipped', tone: 'skipped' },
+ needs_you: { label: 'Needed your approval, nothing ran', tone: 'needs_you' },
+ incomplete: { label: 'A step failed', tone: 'error' },
+};
+
+/**
+ * A run's badge in History. A running run that waits on a card reads "Waiting for you" and links to it; a
+ * `needs_you` run keeps that link when this session saw the card, since the card stays open after the wait.
+ * An unknown status reads as itself, in the skipped tone. `incomplete`'s reason shows under it (routineRunNote).
+ */
+export function runRowState(run: { status: string }, wait?: RunWait | null): RunRowState {
+ if (run.status === 'running' && wait?.waiting) return { label: 'Waiting for you', tone: 'waiting', cardId: wait.approval_id };
+ const known = RUN_LABEL[run.status];
+ const cardId = run.status === 'needs_you' ? wait?.approval_id ?? null : null;
+ return known ? { ...known, cardId } : { label: run.status, tone: 'skipped', cardId: null };
+}
+
+/** Folds a `routine_run` event into the waits by run id. The card id outlives the wait (needs_you links to it). */
+export function applyRunWait(
+ prev: Record<string, RunWait>,
+ data: { routine_id?: unknown; run_id?: unknown; waiting?: unknown; approval_id?: unknown } | null | undefined,
+): Record<string, RunWait> {
+ const id = typeof data?.run_id === 'string' ? data.run_id : '';
+ if (!id) return prev;
+ const waiting = data?.waiting === true;
+ const card = typeof data?.approval_id === 'string' && data.approval_id ? data.approval_id : null;
+ const had = prev[id];
+ if (!had && !waiting && !card) return prev;
+ const routine = typeof data?.routine_id === 'string' && data.routine_id ? data.routine_id : had?.routine_id ?? null;
+ const next: RunWait = { routine_id: routine, waiting, approval_id: card ?? had?.approval_id ?? null };
+ if (had && had.waiting === next.waiting && had.approval_id === next.approval_id && had.routine_id === next.routine_id) return prev;
+ return { ...prev, [id]: next };
+}
+
+/** The wait of a routine's run that waits right now, for the routine card's last-run badge; null when none. */
+export const liveWaitOf = (waits: Record<string, RunWait>, routineId: string): RunWait | null =>
+ Object.values(waits).find((w) => w.waiting && w.routine_id === routineId) ?? null;
+
+// 26d (Rigel's D2): live waits outlive the Routines panel. App records every `routine_run` event here, so opening
+// Routines after a run started waiting still shows "Waiting for you" and its card link.
+let runWaits: Record<string, RunWait> = {};
+const runWaitSubs = new Set<() => void>();
+export function recordRunWait(data: Parameters<typeof applyRunWait>[1]): void {
+ const next = applyRunWait(runWaits, data);
+ if (next === runWaits) return;
+ runWaits = next;
+ runWaitSubs.forEach((fn) => fn());
+}
+export function subscribeRunWaits(fn: () => void): () => void {
+ runWaitSubs.add(fn);
+ return () => {
+ runWaitSubs.delete(fn);
+ };
+}
+export const runWaitsNow = (): Record<string, RunWait> => runWaits;
diff --git a/frontend/src/spendStop.ts b/frontend/src/spendStop.ts
index 640c1a60..700c7359 100644
--- a/frontend/src/spendStop.ts
+++ b/frontend/src/spendStop.ts
@@ -230,6 +230,8 @@ export const ROUTINE_SKIPPED_TEXT = 'Skipped: today’s spending stop was on.';
/** A routine run's note: the stop's skip reads plainly, not as an error. */
export function routineRunNote(r: { status: string; error: string | null }): { text: string; quiet: boolean } | null {
if (!r.error) return null;
+ // 26d: the run row's badge already says a needs_you run waited on your approval and nothing ran.
+ if (r.status === 'needs_you') return null;
if (r.status === 'skipped' && isSpendStopReason(r.error)) return { text: ROUTINE_SKIPPED_TEXT, quiet: true };
return { text: r.error, quiet: false };
}
diff --git a/frontend/tests/detailsSayWhatFailed.test.mjs b/frontend/tests/detailsSayWhatFailed.test.mjs
new file mode 100644
index 00000000..2dd8ab45
--- /dev/null
+++ b/frontend/tests/detailsSayWhatFailed.test.mjs
@@ -0,0 +1,240 @@
+// 26d (autonomy/details-say-what-failed/brief.md): Details and the reply say which step failed or didn't run,
+// and a routine run's row says it waits on you, needed your approval, or had a step fail (26b's statuses).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+process.env.TZ = 'UTC';
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const o = await loadBundled(`
+ export * from './src/replyOutcome';
+ export { parseActivityMeta, activitySummary, statusLabel } from './src/activity';
+ export { runRowState, applyRunWait, liveWaitOf, recordRunWait, subscribeRunWaits, runWaitsNow } from './src/routineRow';
+ export { routineRunNote } from './src/spendStop';
+`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ReplyMeta } from './src/components/ReplyMeta';
+ import { ReplyCheckLine } from './src/components/ReplyCheckLine';
+ import { SavedActivityList } from './src/components/ActivityList';
+ import { ChatView } from './src/components/ChatView';
+ import { RunRow } from './src/components/RoutinesPanel';
+ const r = (C) => (props) => renderToStaticMarkup(React.createElement(C, props));
+ export const meta = r(ReplyMeta);
+ export const line = r(ReplyCheckLine);
+ export const steps = r(SavedActivityList);
+ export const chat = r(ChatView);
+ export const run = r(RunRow);
+`);
+
+const T0 = '2026-11-17T04:00:00Z';
+const step = (id, status, tool, extra = {}) => ({ id, kind: 'tool', status, title: `Calling ${tool}`, tool, started_at: T0, ...extra });
+const UNANSWERED_DETAIL = 'Waited 5 minutes for your answer; nothing ran';
+
+// The brief's fixtures
+const FAILED_THEN_OK = [step('s1', 'failed', 'ha_call_service', { detail: 'entity not found' }), step('s2', 'ok', 'ha_call_service')];
+const FAILED_ONLY = [step('s1', 'failed', 'ha_call_service', { detail: 'entity not found' })];
+const UNANSWERED_ONLY = [step('s1', 'unanswered', 'ha_get_states', { detail: UNANSWERED_DETAIL })];
+const UNANSWERED_PLUS_OK = [step('s1', 'unanswered', 'ha_get_states', { detail: UNANSWERED_DETAIL }), step('s2', 'ok', 'web_search')];
+
+test('replyOutcome: the four fixtures, most specific first', () => {
+ assert.deepEqual(o.replyOutcome(FAILED_THEN_OK), { kind: 'recovered', count: 1, stepId: 's1' });
+ assert.deepEqual(o.replyOutcome(FAILED_ONLY), { kind: 'failed', stepId: 's1' });
+ assert.deepEqual(o.replyOutcome(UNANSWERED_ONLY), { kind: 'unanswered', stepId: 's1' });
+ assert.deepEqual(o.replyOutcome(UNANSWERED_PLUS_OK), { kind: 'unanswered', stepId: 's1' }, 'an ok step of another tool does not clear it');
+ assert.equal(o.replyOutcome([step('s1', 'ok', 'a')]), null);
+ assert.equal(o.replyOutcome([]), null);
+ assert.equal(o.replyOutcome(null), null);
+});
+
+test('replyOutcome: recovery needs a later ok of the same tool', () => {
+ assert.equal(o.replyOutcome([step('s1', 'ok', 'a'), step('s2', 'failed', 'a')]).kind, 'failed', 'an ok before the failure does not count');
+ assert.equal(o.replyOutcome([step('s1', 'failed', 'a'), step('s2', 'ok', 'b')]).kind, 'failed', 'another tool does not count');
+ assert.equal(o.replyOutcome([step('s1', 'failed', undefined), step('s2', 'ok', undefined)]).kind, 'failed', 'no tool name never recovers');
+ assert.equal(o.replyOutcome([step('s1', 'failed', 'a'), step('s2', 'declined', 'a')]).kind, 'failed', 'declined is not a success');
+ // Rigel's D1: an approved approval card for the same tool is permission, not the retry working
+ const approved = { id: 's2', kind: 'approval', status: 'done', title: 'Allow Bash?', tool: 'Bash', started_at: T0 };
+ assert.equal(o.replyOutcome([step('s1', 'failed', 'Bash'), approved]).kind, 'failed', 'an approved card alone does not recover');
+ assert.equal(o.replyOutcome([step('s1', 'failed', 'Bash'), approved, step('s3', 'ok', 'Bash')]).kind, 'recovered', 'the approved retry that ran does');
+ const two = o.replyOutcome([step('s1', 'failed', 'a'), step('s2', 'failed', 'a'), step('s3', 'ok', 'a')]);
+ assert.deepEqual(two, { kind: 'recovered', count: 2, stepId: 's1' });
+ // One recovered and one stuck: the stuck one wins and Details opens at it
+ assert.deepEqual(o.replyOutcome([step('s1', 'failed', 'a'), step('s2', 'ok', 'a'), step('s3', 'failed', 'b')]), { kind: 'failed', stepId: 's3' });
+ // Unanswered beats a stuck failure
+ assert.equal(o.replyOutcome([step('s1', 'failed', 'a'), step('s2', 'unanswered', 'b')]).kind, 'unanswered');
+});
+
+test('detailsLabel and checkLine words', () => {
+ assert.equal(o.detailsLabel(null), 'Details');
+ assert.equal(o.detailsLabel({ kind: 'unanswered', stepId: 'x' }), 'Details · a step didn’t run (no answer)');
+ assert.equal(o.detailsLabel({ kind: 'failed', stepId: 'x' }), 'Details · a step failed');
+ assert.equal(o.detailsLabel({ kind: 'recovered', count: 1, stepId: 'x' }), 'Details · 1 step failed, then worked');
+ assert.equal(o.detailsLabel({ kind: 'recovered', count: 3, stepId: 'x' }), 'Details · 3 steps failed, then worked');
+ assert.equal(o.checkLine({ kind: 'unanswered', stepId: 'x' }), 'A step didn’t run, so check this before relying on it.');
+ assert.equal(o.checkLine({ kind: 'failed', stepId: 'x' }), 'A step failed, so check this before relying on it.');
+ assert.equal(o.checkLine({ kind: 'recovered', count: 1, stepId: 'x' }), null, 'not for "failed, then worked"');
+ assert.equal(o.checkLine(null), null);
+});
+
+test('activity: unanswered and rehearsed parse as their own statuses, never ok', () => {
+ const a = o.parseActivityMeta({ activity: { steps: [...UNANSWERED_PLUS_OK, step('s3', 'rehearsed', 'x')], dropped: 0 } });
+ assert.deepEqual(a.steps.map((s) => s.status), ['unanswered', 'ok', 'rehearsed']);
+ assert.equal(o.statusLabel(a.steps[0]), 'Not approved in time');
+ assert.equal(o.statusLabel(a.steps[2]), 'Dry run');
+ assert.equal(o.activitySummary(a), '3 steps · 1 didn’t run');
+ assert.equal(o.activitySummary({ steps: FAILED_THEN_OK, dropped: 0 }), '2 steps · 1 failed');
+});
+
+test('ReplyMeta: the folded toggle names the outcome; open, it reads Details', () => {
+ const html = (outcome) => ui.meta({ name: 'Ada', ranOn: 'Claude · Opus 5.5', outcome });
+ assert.match(html({ kind: 'unanswered', stepId: 's1' }), /data-details-outcome="unanswered"[^>]*>Details · a step didn’t run \(no answer\)/);
+ assert.match(html({ kind: 'unanswered', stepId: 's1' }), /text-amber-300/);
+ assert.match(html({ kind: 'failed', stepId: 's1' }), /data-details-outcome="failed"[^>]*>Details · a step failed/);
+ assert.match(html({ kind: 'failed', stepId: 's1' }), /text-rose-300/);
+ const rec = html({ kind: 'recovered', count: 1, stepId: 's1' });
+ assert.match(rec, />Details · 1 step failed, then worked/);
+ assert.doesNotMatch(rec, /text-rose-300|text-amber-300/, '"failed, then worked" stays quiet');
+ assert.match(html(null), />Details</);
+ assert.doesNotMatch(html(null), /data-details-outcome/);
+ // The old boolean still works for callers that pass it
+ assert.match(ui.meta({ name: 'Ada', ranOn: 'Codex', failed: true }), /Details · a step failed/);
+ // At 390 px the long label must not clip: the name line may wrap when it names an outcome, and the label stays whole
+ const recovered = html({ kind: 'recovered', count: 1, stepId: 's1' });
+ assert.match(recovered, /data-name-line-wraps=""/);
+ assert.match(recovered, /class="[^"]*\bflex-wrap\b[^"]*"[^>]*data-name-line-wraps/);
+ assert.doesNotMatch(recovered, /class="[^"]*flex-nowrap[^"]*"[^>]*data-name-line-wraps/);
+ assert.match(recovered, /whitespace-nowrap[^"]*"[^>]*data-details-outcome/);
+ assert.match(html(null), /flex-nowrap/, 'a plain Details keeps the one-row phone line');
+ assert.doesNotMatch(html(null), /data-name-line-wraps/);
+});
+
+test('ReplyCheckLine: only for a step that didn\'t run or failed for good, with a Details button', () => {
+ const un = ui.line({ outcome: { kind: 'unanswered', stepId: 's1' }, onDetails: () => {} });
+ assert.match(un, /data-reply-check="unanswered"/);
+ assert.match(un, /A step didn’t run, so check this before relying on it\. <button type="button"[^>]*>Details<\/button>/);
+ assert.match(un, /aria-hidden="true"/, 'the icon is decorative');
+ const failed = ui.line({ outcome: { kind: 'failed', stepId: 's1' }, onDetails: () => {} });
+ assert.match(failed, /A step failed, so check this before relying on it\./);
+ assert.equal(ui.line({ outcome: { kind: 'recovered', count: 1, stepId: 's1' }, onDetails: () => {} }), '');
+ assert.equal(ui.line({ outcome: null, onDetails: () => {} }), '');
+});
+
+test('Steps list: a failed step keeps "Failed" and an unanswered one says "Not approved in time", even after a success', () => {
+ const rec = ui.steps({ activity: { steps: FAILED_THEN_OK, dropped: 0 }, idBase: 'a', defaultOpen: true });
+ assert.match(rec, /data-step-mark="failed"[^>]*>Failed</);
+ assert.match(rec, /aria-label="Failed"/, 'the icon still names it for screen readers');
+ // Mira's design check: the step Details lands on shows a visible ring, and its detail never splits a word on a phone
+ assert.match(rec, /focus-visible:outline-sky-400[^"]*"[^>]*data-step-status|data-step-status="[^"]*"[^>]*class="[^"]*focus-visible:outline-sky-400/);
+ assert.match(rec, /\[overflow-wrap:anywhere\]/);
+ assert.doesNotMatch(rec, /break-all/);
+ const un = ui.steps({ activity: { steps: UNANSWERED_PLUS_OK, dropped: 0 }, idBase: 'a', defaultOpen: true, focusStep: 's1' });
+ assert.match(un, /data-step-mark="unanswered"[^>]*>Not approved in time</);
+ assert.match(un, /aria-label="Not approved in time"/);
+ assert.match(un, /<li id="a-steps-s1" tabindex="-1" data-step-status="unanswered"[^>]*><details class="group" open=""/, 'opens at the step with its detail shown');
+ assert.match(un, /Waited 5 minutes for your answer; nothing ran/);
+ assert.equal((un.match(/data-step-mark=/g) ?? []).length, 1, 'the ok step has no mark');
+});
+
+const chatProps = (messages) => ({
+ title: 'Ada', subtitle: '', messages, streamingText: '', streamingThinking: '', isStreaming: false,
+ pendingApprovals: [], onSendMessage: () => {}, onResolveApproval: () => {}, kwants: [], teams: [],
+});
+const reply = (id, text, steps) => ({ id, sender_role: 'kwant', sender_id: 'ada', text, created_at: T0, meta: JSON.stringify({ activity: { steps, dropped: 0 } }) });
+
+test('ChatView: label on the reply and the line under it, per fixture', () => {
+ const html = ui.chat(chatProps([
+ reply('m1', 'The living room lamp is now turned on.', FAILED_THEN_OK),
+ reply('m2', 'The lamp is on.', FAILED_ONLY),
+ reply('m3', 'I checked, no lights are on.', UNANSWERED_ONLY),
+ reply('m4', 'No lights are on, and the weather is fine.', UNANSWERED_PLUS_OK),
+ ]));
+ const part = (id) => html.split('data-message-id="').find((c) => c.startsWith(`${id}"`)) ?? '';
+ assert.match(part('m1'), /Details · 1 step failed, then worked/);
+ assert.doesNotMatch(part('m1'), /data-reply-check/, 'no line under a reply whose step failed, then worked');
+ assert.match(part('m2'), /Details · a step failed/);
+ assert.match(part('m2'), /data-reply-check="failed"/);
+ assert.match(part('m3'), /Details · a step didn’t run \(no answer\)/);
+ assert.match(part('m3'), /data-reply-check="unanswered"/);
+ assert.match(part('m4'), /data-reply-check="unanswered"/);
+ // The line sits under the reply's words, never above them
+ assert.ok(part('m3').indexOf('I checked, no lights are on.') < part('m3').indexOf('data-reply-check'));
+ // The reply text itself is untouched
+ assert.match(html, /The living room lamp is now turned on\./);
+});
+
+// ---------------------------------------------------------------- routine run row
+
+const routine = { id: 'rt1', kwant_id: 'k1', channel_id: null, thread_id: null, name: 'Lights check' };
+const runOf = (status, error = null, extra = {}) => ({ id: `run-${status}`, routine_id: 'rt1', trigger: 'schedule', started_at: T0, ended_at: null, status, error, message_id: null, ...extra });
+
+test('runRowState: each run status, plus waiting', () => {
+ assert.deepEqual(o.runRowState({ status: 'running' }, { routine_id: 'rt1', waiting: true, approval_id: 'ap1' }), { label: 'Waiting for you', tone: 'waiting', cardId: 'ap1' });
+ assert.deepEqual(o.runRowState({ status: 'running' }, { routine_id: 'rt1', waiting: false, approval_id: 'ap1' }), { label: 'Running', tone: 'running', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'running' }), { label: 'Running', tone: 'running', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'needs_you' }), { label: 'Needed your approval, nothing ran', tone: 'needs_you', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'needs_you' }, { routine_id: 'rt1', waiting: false, approval_id: 'ap1' }).cardId, 'ap1', 'the card stays open, so the link stays');
+ assert.deepEqual(o.runRowState({ status: 'incomplete' }), { label: 'A step failed', tone: 'error', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'ok' }), { label: 'OK', tone: 'ok', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'error' }), { label: 'Failed', tone: 'error', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'skipped' }), { label: 'Skipped', tone: 'skipped', cardId: null });
+ assert.deepEqual(o.runRowState({ status: 'ok' }, { routine_id: 'rt1', waiting: true, approval_id: 'ap1' }).tone, 'ok', 'a finished run never reads waiting');
+});
+
+test('applyRunWait: 26b\'s event order for an unanswered card', () => {
+ let w = {};
+ w = o.applyRunWait(w, { routine_id: 'rt1', run_id: 'r1', status: 'running', waiting: false });
+ assert.deepEqual(w, {}, 'a plain running event adds nothing');
+ w = o.applyRunWait(w, { routine_id: 'rt1', run_id: 'r1', status: 'running', waiting: true, approval_id: 'ap1' });
+ assert.deepEqual(w.r1, { routine_id: 'rt1', waiting: true, approval_id: 'ap1' });
+ assert.deepEqual(o.liveWaitOf(w, 'rt1'), w.r1);
+ w = o.applyRunWait(w, { routine_id: 'rt1', run_id: 'r1', status: 'running', waiting: false });
+ assert.deepEqual(w.r1, { routine_id: 'rt1', waiting: false, approval_id: 'ap1' }, 'the card id outlives the wait');
+ assert.equal(o.liveWaitOf(w, 'rt1'), null);
+ const same = o.applyRunWait(w, { routine_id: 'rt1', run_id: 'r1', status: 'needs_you' });
+ assert.equal(same, w, 'no change keeps the same object');
+ assert.equal(o.applyRunWait(w, null), w);
+ assert.equal(o.applyRunWait(w, { waiting: true }), w, 'no run id');
+});
+
+test('RunRow: waiting links to the card; needs_you and incomplete read in words', () => {
+ const card = () => {};
+ const waiting = ui.run({ routine, run: runOf('running'), wait: { routine_id: 'rt1', waiting: true, approval_id: 'ap1' }, onOpenRunCard: card });
+ assert.match(waiting, /data-run-state="waiting"/);
+ assert.match(waiting, />Waiting for you</);
+ assert.match(waiting, /<button type="button"[^>]*aria-label="Open the approval card the run on [^"]* waits on"[^>]*data-run-card="ap1">Open the card/);
+ assert.doesNotMatch(waiting, /animate-spin/, 'a wait does not spin');
+
+ const needs = ui.run({ routine, run: runOf('needs_you', 'A step is waiting for your approval, so it didn\'t run'), onOpenRunCard: card });
+ assert.match(needs, />Needed your approval, nothing ran</);
+ assert.doesNotMatch(needs, /A step is waiting for your approval/, 'the badge says it; no repeat');
+ assert.doesNotMatch(needs, /data-run-card/, 'no card id seen this session, so no link');
+
+ const inc = ui.run({ routine, run: runOf('incomplete', 'exit 7: the report server said 502') });
+ assert.match(inc, /data-run-badge="error"[^>]*>A step failed</);
+ assert.match(inc, /text-rose-300\/90">exit 7: the report server said 502</, 'the run\'s error line under it');
+
+ assert.match(ui.run({ routine, run: runOf('ok') }), />OK</);
+});
+
+test('routineRunNote: needs_you has no note; incomplete keeps its reason', () => {
+ assert.equal(o.routineRunNote({ status: 'needs_you', error: 'A step is waiting for your approval, so it didn\'t run' }), null);
+ assert.deepEqual(o.routineRunNote({ status: 'incomplete', error: 'Bash failed' }), { text: 'Bash failed', quiet: false });
+});
+
+test('run waits outlive the Routines panel (Rigel D2): App records them, the panel reads them when it opens', () => {
+ let calls = 0;
+ const off = o.subscribeRunWaits(() => calls++);
+ o.recordRunWait({ routine_id: 'r9', run_id: 'run9', status: 'running', waiting: true, approval_id: 'ap9' });
+ assert.equal(calls, 1);
+ assert.equal(o.liveWaitOf(o.runWaitsNow(), 'r9')?.approval_id, 'ap9');
+ const before = o.runWaitsNow();
+ o.recordRunWait({ routine_id: 'r9', run_id: 'run9', status: 'running', waiting: true, approval_id: 'ap9' });
+ assert.equal(o.runWaitsNow(), before, 'the same event changes nothing');
+ assert.equal(calls, 1);
+ off();
+ o.recordRunWait({ routine_id: 'r9', run_id: 'run9', status: 'needs_you', waiting: false });
+ assert.equal(calls, 1, 'unsubscribed');
+ assert.equal(o.runRowState({ status: 'needs_you' }, o.runWaitsNow().run9).cardId, 'ap9', 'the card id outlives the wait');
+});