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.5 F: Inbox "Done while you were away" (#539)

Oleksandr Ivanchenkof0dd2ebc3c2e
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 71d377ed..e50557eb 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -3,6 +3,7 @@ import { DecidingMap, applyDecideEvent, decisionsApi, hydrateDeciding } from './
import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';
import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';
import { InboxPage } from './components/InboxPage';
+import type { MessageTarget } from './components/DoneDetail';
import { AppsSection, InboxTab, SettingsScope, SpaceView, viewSegment } from './nav';
import { PHONE_QUERY } from './layout';
import { useSettingsCover } from './settingsFocus';
@@ -2763,6 +2764,17 @@ 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. */
+ const openRunResult = (t: MessageTarget) => {
+ if (spaceSettingsTab) closeSpaceSettings();
+ if (t.thread_id) {
+ openThread(t.kwant_id, t.thread_id);
+ return;
+ }
+ setPage('chat');
+ void handleJump({ message_id: t.message_id, channel_id: t.channel_id, channel_name: null, kwant_id: t.kwant_id, author: '', snippet: '', created_at: null });
+ };
+
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') {
@@ -3984,6 +3996,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onApprovalResolved={dropApproval}
onOpenConnections={openConnections}
onCrumb={(c) => showPage(c === 'board' ? 'board' : 'dev')}
+ onOpenMessage={openRunResult}
+ onEditRoutine={(id) => handleOpenRoutine(id, 'edit')}
+ placeName={(id) => {
+ const c = id ? channels.find((x) => x.id === id) : null;
+ return c ? channelLabel(c.name) : null;
+ }}
top={
<>
<PrepushNeedsYou cards={prepush.cards} names={kwantNames} onOpen={openPrepush} />
@@ -4559,6 +4577,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
</Suspense>
}
routineFocus={routineFocus}
+ onOpenRunResult={openRunResult}
isPhone={isPhone}
onApprovalsChanged={refreshRoster}
onImported={reloadAfterImport}
diff --git a/frontend/src/api/inbox.ts b/frontend/src/api/inbox.ts
index 5128e0fa..6085af16 100644
--- a/frontend/src/api/inbox.ts
+++ b/frontend/src/api/inbox.ts
@@ -6,7 +6,7 @@
import { PersonCancelledError, personFetch } from '../auth';
import type { AwayItem, AwayKind } from '../away';
-export type InboxKind = AwayKind | 'review';
+export type InboxKind = AwayKind | 'review' | 'team_job';
export type InboxGroup = 'waiting_on_you' | 'failed_or_stuck' | 'to_review' | 'finished';
export type VerdictResult = 'pass' | 'fail' | 'needs_you' | 'none';
@@ -132,6 +132,58 @@ export interface ReviewFields {
one_tap: boolean;
batchable: boolean;
rollback_ok: boolean;
+ /**
+ * 0.9.5 B (Vega): whether the work changed anything (files, messages sent, settings). false draws
+ * "Read only · changed nothing" and hides Roll back. Missing reads as unknown.
+ */
+ changed?: boolean | null;
+}
+
+/** 0.9.5 part B (Vega #543): one step of what the bot did, saved on its result message. */
+export interface DoneTrailStep {
+ at: string;
+ kind: 'page' | 'message' | 'write' | 'tool';
+ label: string;
+ detail: string | null;
+ status: 'ok' | 'error' | 'skipped';
+ /** Set only on a team job's member steps: the member's name. */
+ by: string | null;
+}
+
+export type DoneSource =
+ | { kind: 'routine'; routine_id: string; run_id: string; trigger: string; task_id?: string }
+ | { kind: 'task'; task_id: string }
+ | { kind: 'delegation'; delegation_id: string }
+ | { kind: 'team_job'; delegation_id: string | null };
+
+/** A bot named in a team job. */
+export interface TeamMember {
+ kwant_id: string;
+ kwant_name: string;
+}
+
+/**
+ * 0.9.5 part B (Vega #543, impl-b.md "Iris's part F"): the done fields on finished, failed and review items
+ * and on team jobs, plus `unread` on every item. All optional: an older server sends none, and the UI keeps
+ * its own fallbacks (the routine's run and message).
+ */
+export interface DoneFields {
+ unread?: boolean;
+ result_message_id?: string | null;
+ result_conversation_id?: string | null;
+ result_thread_id?: string | null;
+ result_link?: { thread_id: string | null; channel_id: string | null; direct_kwant_id: string | null } | null;
+ answer_excerpt?: string | null;
+ trail?: DoneTrailStep[];
+ trail_dropped?: number;
+ why?: string | null;
+ why_kind?: 'routine' | 'task' | 'ask' | 'request' | null;
+ /** When the person asked (optional; 0.9.6). Without it, Why carries no date. */
+ why_at?: string | null;
+ source?: DoneSource | null;
+ /** Team jobs only: who led it and whom it handed work to. */
+ lead?: TeamMember;
+ members?: TeamMember[];
}
// `task_id` is a review's task (ReviewFields) or a watch item's (P1, null when none), so it takes both.
@@ -140,7 +192,8 @@ export type InboxItem = Omit<AwayItem, 'kind' | 'task_id'> & {
group: InboxGroup;
sort_key: (string | number)[];
task_id?: string | null;
-} & Partial<Omit<ReviewFields, 'task_id'>>;
+} & Partial<Omit<ReviewFields, 'task_id'>> &
+ DoneFields;
/** A review item, with every review field present. */
export type ReviewItem = Omit<InboxItem, keyof ReviewFields> & ReviewFields & { kind: 'review' };
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index ab34814b..123a1631 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -28,6 +28,11 @@ export interface AwayItem {
details?: Record<string, unknown>;
/** Approvals only: set when the payment floor asked, also on servers that send no details. */
payment_reason?: string;
+ /**
+ * 0.9.5 part B, approvals only: the card's own question built from what the call names, e.g.
+ * `Approve “Spring sale: 15% off”?`. Absent when the call names nothing; `title` is always sent.
+ */
+ question?: string;
/** 0.9.0 P1, watch items only: the watched mission and the first task that needs the person. */
mission_id?: string | null;
task_id?: string | null;
diff --git a/frontend/src/components/DoneDetail.tsx b/frontend/src/components/DoneDetail.tsx
new file mode 100644
index 00000000..516c906c
--- /dev/null
+++ b/frontend/src/components/DoneDetail.tsx
@@ -0,0 +1,363 @@
+// 0.9.5 F: a done item's pane (mockup ux-audit-090/mockups/2-while-you-were-away.html). In order: the meta line
+// (what ran, when, why), the chips, the answer inline with Open in chat, "What <bot> did", "Why", then the
+// actions. A routine's review task draws these inside ReviewItemView (which keeps Looks good, Ask to redo and
+// Roll back); a finished item with no review task draws DoneItemView. Text from the server is text only.
+
+import React, { useEffect, useId, useState } from 'react';
+import { AlertTriangle, ChevronRight, CornerUpLeft, Eye, Loader2 } from 'lucide-react';
+import type { InboxItem } from '../api/inbox';
+import { type Routine, type RoutineRun, continuityApi } from '../continuity';
+import {
+ type DoneMessage,
+ answerHeading,
+ answerText,
+ changedState,
+ doneTitle,
+ findRoutine,
+ findRun,
+ isRoutineItem,
+ isTeamJob,
+ metaLine,
+ monthDay,
+ noChecksSet,
+ redoInChatLabel,
+ servedDropped,
+ teamLead,
+ trailDropped,
+ trailFrom,
+ trailFromServed,
+ trailHeading,
+ whyLead,
+} from '../doneAway';
+import { MarkdownRenderer } from './MarkdownRenderer';
+import { ModernAvatar } from './ModernAvatar';
+
+/** Where an answer lives, for Open in chat. */
+export interface MessageTarget {
+ message_id: string;
+ channel_id: string | null;
+ kwant_id: string;
+ thread_id: string | null;
+}
+
+export interface DoneApi {
+ routines: () => Promise<Routine[]>;
+ runs: (routineId: string) => Promise<RoutineRun[]>;
+ /** The result message, or null when it is gone. */
+ message: (t: MessageTarget) => Promise<DoneMessage | null>;
+}
+
+async function getJson<T>(url: string): Promise<T | null> {
+ const r = await fetch(url);
+ if (r.status === 404) return null;
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return (await r.json()) as T;
+}
+
+export const defaultDoneApi: DoneApi = {
+ routines: () => continuityApi.routines(),
+ runs: (id) => continuityApi.routineRuns(id, 50),
+ async message(t) {
+ const enc = encodeURIComponent;
+ const url = t.thread_id
+ ? `/api/threads/${enc(t.thread_id)}/messages`
+ : `/api/channels/${enc(t.channel_id ?? t.kwant_id)}/messages?around=${enc(t.message_id)}&limit=1`;
+ const list = await getJson<DoneMessage[]>(url);
+ return (Array.isArray(list) ? list : []).find((m) => m && m.id === t.message_id) ?? null;
+ },
+};
+
+export interface DoneDetailData {
+ loading: boolean;
+ error: string | null;
+ routine: Routine | null;
+ run: RoutineRun | null;
+ message: DoneMessage | null;
+ target: MessageTarget | null;
+}
+
+const EMPTY: DoneDetailData = {
+ loading: false,
+ error: null,
+ routine: null,
+ run: null,
+ message: null,
+ target: null,
+};
+
+/**
+ * Loads what today's API has for a done item: its routine (by bot and name), the run (by id for a run row,
+ * else the one that ended closest), and the run's result message (finish_routine_run saves its id).
+ */
+export function useDoneDetail(item: InboxItem, runItem: InboxItem | null, api: DoneApi = defaultDoneApi, initial?: DoneDetailData): DoneDetailData {
+ const routineLike = isRoutineItem(item);
+ const [d, setD] = useState<DoneDetailData>(initial ?? (routineLike ? { ...EMPTY, loading: true } : EMPTY));
+ const runId = item.kind === 'routine_run' ? item.id : (runItem?.id ?? null);
+ useEffect(() => {
+ if (initial || !routineLike) return;
+ let cancelled = false;
+ setD({ ...EMPTY, loading: true });
+ (async () => {
+ const routine = findRoutine(await api.routines(), item);
+ if (!routine) return { ...EMPTY };
+ const run = findRun(await api.runs(routine.id), runId, runItem?.timestamp ?? item.timestamp);
+ const target: 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 message = target ? await api.message(target).catch(() => null) : null;
+ return { loading: false, error: null, routine, run, message, target };
+ })().then(
+ (v) => !cancelled && setD(v),
+ (e) =>
+ !cancelled &&
+ setD({
+ ...EMPTY,
+ error: e instanceof Error ? e.message : 'Something went wrong.',
+ }),
+ );
+ return () => {
+ cancelled = true;
+ };
+ // item.id and runId name the item; the rest is read once per item.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [item.id, runId, routineLike, initial]);
+ return d;
+}
+
+const label = 'text-[11px] font-semibold uppercase tracking-[0.06em] text-zinc-400';
+// F1: data-compact keeps the coarse-pointer 44 px min-height off these inline links; kw-hit's ::before keeps the
+// 44×44 tap area, so the chip and the Why line keep their own height.
+const linkBtn = 'kw-focus kw-hit inline-flex items-center gap-0.5 rounded text-meta font-semibold text-violet-300 hover:text-violet-200';
+
+/** "Read only · changed nothing" and "No checks set · Add one". */
+export const DoneChips: React.FC<{
+ item: InboxItem;
+ d: DoneDetailData;
+ onAddCheck?: () => void;
+}> = ({ item, d, onAddCheck }) => {
+ const changed = changedState(item, d.message);
+ const noChecks = noChecksSet(item);
+ if (changed !== false && !noChecks) return null;
+ return (
+ <div className="flex flex-wrap items-center gap-1.5" data-done-chips>
+ {changed === false && (
+ <span className="kw-chip !py-0 border-teal-300/30 bg-teal-300/[0.08] text-teal-200" data-chip="read-only">
+ <Eye size={12} aria-hidden="true" /> Read only · changed nothing
+ </span>
+ )}
+ {noChecks && (
+ <span className="kw-chip !py-0" data-chip="no-checks">
+ No checks set
+ {onAddCheck && (
+ <>
+ {' · '}
+ <button
+ type="button"
+ onClick={onAddCheck}
+ className="kw-focus kw-hit rounded font-semibold text-violet-300 hover:text-violet-200"
+ data-compact
+ data-add-check
+ >
+ Add one
+ </button>
+ </>
+ )}
+ </span>
+ )}
+ </div>
+ );
+};
+
+/** The answer, "What <bot> did" and "Why", in the mockup's order. */
+export const DoneSections: React.FC<{
+ item: InboxItem;
+ d: DoneDetailData;
+ place: string | null;
+ onOpenChat?: () => void;
+ onEditRoutine?: (id: string) => void;
+}> = ({ item, d, place, onOpenChat, onEditRoutine }) => {
+ const uid = useId();
+ const bot = item.kwant_name;
+ const excerpt = typeof item.answer_excerpt === 'string' && item.answer_excerpt.trim() ? item.answer_excerpt : null;
+ const text = answerText(d.message) ?? excerpt ?? (item.summary?.trim() ? item.summary : null);
+ const fromMessage = !!answerText(d.message);
+ // Part B serves the trail on the item (with skipped steps and a team member's name); else the loaded message.
+ const served = trailFromServed(item, place);
+ const trail = served ?? trailFrom(d.message, place);
+ const dropped = served ? (servedDropped(item) ?? 0) : trailDropped(d.message);
+ const routine = d.routine;
+ const routineLike = isRoutineItem(item);
+ const why = typeof item.why === 'string' ? item.why.trim() : '';
+ const lead = whyLead(item);
+ return (
+ <>
+ <section aria-labelledby={`${uid}-ans`} className="rounded-2xl border border-hairline bg-surface-raised p-4 space-y-2 min-w-0" data-done-answer>
+ <h3 id={`${uid}-ans`} className={label}>
+ {answerHeading(item)}
+ </h3>
+ {d.loading && !text ? (
+ <p className="flex items-center gap-1.5 text-meta text-zinc-400" role="status">
+ <Loader2 size={13} className="motion-safe:animate-spin" aria-hidden="true" /> Loading the answer…
+ </p>
+ ) : text ? (
+ fromMessage ? (
+ // F5: on a phone the answer's table keeps each cell on one line and scrolls sideways as a whole;
+ // the scroller is a focusable, named region so a keyboard can reach it.
+ <div
+ tabIndex={0}
+ role="region"
+ aria-label={`${bot}’s answer`}
+ className="kw-focus rounded min-w-0 overflow-x-auto [&_.markdown-content]:text-body max-sm:[&_th]:whitespace-nowrap max-sm:[&_td]:whitespace-nowrap"
+ data-answer-text
+ >
+ <MarkdownRenderer content={text} />
+ </div>
+ ) : (
+ <p className="text-body text-zinc-100 whitespace-pre-wrap break-words" data-answer-text>
+ {text}
+ </p>
+ )
+ ) : (
+ <p className="text-meta text-zinc-400">The answer isn’t here any more. Open the chat to see what is.</p>
+ )}
+ {onOpenChat && (
+ <button type="button" onClick={onOpenChat} className={linkBtn} data-compact data-open-in-chat>
+ Open in chat <ChevronRight size={14} aria-hidden="true" />
+ </button>
+ )}
+ </section>
+
+ {(routineLike || served !== null) && (
+ <section aria-labelledby={`${uid}-did`} className="space-y-2 min-w-0" data-done-trail>
+ <h3 id={`${uid}-did`} className={label}>
+ {trailHeading(item)}
+ </h3>
+ {trail.length ? (
+ <ol className="space-y-1.5">
+ {dropped > 0 && (
+ <li className="grid grid-cols-[64px_minmax(0,1fr)] gap-x-2 text-meta text-zinc-400" data-trail-dropped>
+ <span aria-hidden="true" />
+ <span>
+ {dropped} more {dropped === 1 ? 'step' : 'steps'} before these
+ </span>
+ </li>
+ )}
+ {trail.map((r, i) => (
+ <li key={i} className="grid grid-cols-[64px_minmax(0,1fr)] gap-x-2 text-body" data-trail-row data-status={r.failed ? 'error' : r.skipped ? 'skipped' : 'ok'}>
+ <time className="tabular-nums text-meta text-zinc-400 pt-px">{r.at}</time>
+ <span className={`min-w-0 break-words ${r.failed ? 'text-rose-200' : r.skipped ? 'text-zinc-400' : 'text-zinc-100'}`}>
+ {r.by && (
+ <>
+ <span className="font-semibold text-zinc-100" data-trail-by>
+ {r.by}
+ </span>
+ {' · '}
+ </>
+ )}
+ {r.failed && <AlertTriangle size={13} className="inline -mt-0.5 mr-1" aria-label="Failed" />}
+ {r.what}
+ {r.failed && ' · failed'}
+ {r.skipped && ' · skipped'}
+ {r.detail && <span className="text-zinc-400"> · {r.detail}</span>}
+ </span>
+ </li>
+ ))}
+ </ol>
+ ) : (
+ <p className="text-meta text-zinc-400" data-trail-empty>
+ {d.loading ? 'Loading…' : 'This run kept no steps. Open the chat to see the whole reply.'}
+ </p>
+ )}
+ </section>
+ )}
+
+ {routine ? (
+ <section aria-labelledby={`${uid}-why`} className="space-y-2 min-w-0" data-done-why>
+ <h3 id={`${uid}-why`} className={label}>
+ Why
+ </h3>
+ <p className="text-body text-zinc-300 break-words">
+ You set up this routine
+ {monthDay(routine.created_at) ? ` on ${monthDay(routine.created_at)}` : ''}:{' '}
+ <q className="text-zinc-100 [quotes:'“'_'”']" data-why-quote>
+ {routine.instructions}
+ </q>{' '}
+ {onEditRoutine && (
+ <button type="button" onClick={() => onEditRoutine(routine.id)} className={linkBtn} data-compact data-edit-routine>
+ Edit routine
+ </button>
+ )}
+ </p>
+ </section>
+ ) : (
+ why &&
+ (lead || (routineLike && item.why_kind === 'routine')) && (
+ <section aria-labelledby={`${uid}-why`} className="space-y-2 min-w-0" data-done-why={item.why_kind ?? ''}>
+ <h3 id={`${uid}-why`} className={label}>
+ Why
+ </h3>
+ <p className="text-body text-zinc-300 break-words">
+ {lead ?? 'You set up this routine:'}{' '}
+ <q className="text-zinc-100 [quotes:'“'_'”']" data-why-quote>
+ {why}
+ </q>
+ </p>
+ </section>
+ )
+ )}
+ {d.error && (
+ <p className="text-meta text-zinc-400" role="status" title={d.error} data-done-error>
+ Couldn’t load the routine just now, so some details are missing.
+ </p>
+ )}
+ </>
+ );
+};
+
+/** A done item with no review task: what ran and the answer; Ask to redo opens the chat. */
+export const DoneItemView: React.FC<{
+ item: InboxItem;
+ d: DoneDetailData;
+ place: string | null;
+ hideTitle?: boolean;
+ phone?: boolean;
+ onOpenChat?: () => void;
+ onEditRoutine?: (id: string) => void;
+}> = ({ item, d, place, hideTitle = false, phone = false, onOpenChat, onEditRoutine }) => {
+ const uid = useId();
+ const title = doneTitle(item);
+ return (
+ <section role="region" aria-labelledby={`${uid}-t`} className="space-y-4 min-w-0" data-done-item={item.id}>
+ <header className="flex items-start gap-3 min-w-0">
+ {!hideTitle && <ModernAvatar role={item.kwant_name} name={item.kwant_name} size={34} kwantId={item.kwant_id} />}
+ <div className="min-w-0 flex-1 space-y-1">
+ <h2 id={`${uid}-t`} className={hideTitle ? 'sr-only' : 'text-[16px] leading-snug font-[650] text-zinc-50 break-words'}>
+ {title}
+ </h2>
+ <p className="text-meta text-zinc-400 break-words" data-done-meta>
+ {metaLine(item, d.routine, d.run)}
+ </p>
+ </div>
+ </header>
+ <DoneChips item={item} d={d} onAddCheck={d.routine && onEditRoutine ? () => onEditRoutine(d.routine!.id) : undefined} />
+ <DoneSections item={item} d={d} place={place} onOpenChat={onOpenChat} onEditRoutine={onEditRoutine} />
+ {onOpenChat && (
+ <div className={phone ? 'grid gap-2' : 'flex flex-wrap gap-2'} data-actions>
+ <button
+ type="button"
+ onClick={onOpenChat}
+ className="kw-focus inline-flex items-center justify-center gap-1.5 rounded-xl px-3.5 min-h-[36px] max-md:min-h-[44px] text-meta font-semibold border border-hairline-strong bg-white/[0.03] text-zinc-200 hover:bg-white/[0.08]"
+ data-redo
+ >
+ <CornerUpLeft size={14} aria-hidden="true" /> {redoInChatLabel(isTeamJob(item) ? teamLead(item).kwant_name : item.kwant_name)}
+ </button>
+ </div>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsx
index df1b0011..adf746db 100644
--- a/frontend/src/components/InboxNew.tsx
+++ b/frontend/src/components/InboxNew.tsx
@@ -26,9 +26,12 @@ import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard } from './ModernApprovalCard';
import { ReviewDone, VERDICT_STYLE } from './ReviewItemStub';
import { ReviewItemView } from './ReviewItemView';
+import { type DoneApi, type DoneDetailData, type MessageTarget, DoneChips, DoneItemView, DoneSections, defaultDoneApi, useDoneDetail } from './DoneDetail';
+import { DONE_EMPTY, DONE_FOOTER, changedState, doneTitle, isDoneGroup, isRoutineItem, isUnread, metaLine, rowKicker, sectionItems, teamSize, unreadLine } from '../doneAway';
+import { usePhoneLayout } from '../usePhoneLayout';
import { approvalFromAway, awayTitle, lateAnswerText } from '../approvals';
import { ApprovalDecision, AwayError, AwayItem, actionFailureNotice, awayApi, awaySummary, itemLabel, windowLabel } from '../away';
-import { INBOX_GROUPS, InboxGroup, InboxItem, ReviewItem, groupItems, isBeingChecked, isReview, pendingHeld, reviewWord } from '../api/inbox';
+import { InboxGroup, InboxItem, ReviewItem, isBeingChecked, isReview, pendingHeld, reviewWord } from '../api/inbox';
import {
BatchRow,
Crumb,
@@ -68,6 +71,33 @@ export function useWide(): boolean {
const CRUMB_LABEL: Record<'board' | 'dev', string> = { board: 'Mission board', dev: 'Dev desk' };
+/** 0.9.5 F: the queue's two sections (Mira's mockup 2). Rows keep their own group's tint. */
+const SECTION: Record<
+ 'needs' | 'done',
+ {
+ label: string;
+ short: string;
+ head: string;
+ icon: React.ReactNode;
+ empty: string;
+ }
+> = {
+ needs: {
+ label: 'Needs you',
+ short: 'Needs you',
+ head: 'text-amber-300',
+ icon: <Hand size={13} aria-hidden="true" />,
+ empty: 'Nothing needs you right now.',
+ },
+ done: {
+ label: 'Done while you were away',
+ short: 'Done',
+ head: 'text-teal-300',
+ icon: <CheckCircle2 size={13} aria-hidden="true" />,
+ empty: DONE_EMPTY,
+ },
+};
+
const GROUP_STYLE: Record<InboxGroup, { head: string; icon: React.ReactNode; row: string }> = {
waiting_on_you: { head: 'text-amber-300', icon: <Hand size={13} aria-hidden="true" />, row: 'border-amber-500/30 bg-amber-950/20' },
failed_or_stuck: { head: 'text-rose-300', icon: <AlertTriangle size={13} aria-hidden="true" />, row: 'border-rose-500/25 bg-rose-950/20' },
@@ -88,12 +118,22 @@ export function clock(ts: string): string {
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}
-/** A row's title: an approve that came back says so. */
+/**
+ * A row's title: an approve that came back says so. An approval shows its own question when the
+ * server sent one (0.9.5 part B), else the card's action in words; `title` is always present, so
+ * it is never the test.
+ */
export function rowTitle(i: InboxItem): string {
if (isReview(i) && (i.stale || i.approve_error)) return `Couldn’t approve: ${i.title}`;
+ if (isDoneGroup(i.group) && isRoutineItem(i)) return doneTitle(i);
+ if (i.kind === 'approval' && typeof i.question === 'string' && i.question.trim()) return i.question;
return isReview(i) ? i.title : awayTitle(i as AwayItem);
}
+/** 0.9.5 F: a finished item that opens in the pane (what ran, the answer, the trail) instead of its chat. */
+export const opensInPane = (i: InboxItem | null | undefined): boolean =>
+ !!i && (isReview(i) || i.kind === 'team_job' || (i.group === 'finished' && (i.kind === 'routine_run' || i.kind === 'delegation')));
+
export function staleLine(paths: string[]): string {
if (!paths.length) return 'Its files changed after its check';
return `${paths[0]}${paths.length > 1 ? ` and ${paths.length - 1} more` : ''} changed after its check`;
@@ -147,10 +187,18 @@ const AwaySubline: React.FC<{ item: InboxItem }> = ({ item }) => {
const toneText = tone === 'amber' ? 'text-amber-300' : tone === 'rose' ? 'text-rose-300' : tone === 'emerald' ? 'text-teal-300' : tone === 'sky' ? 'text-sky-300' : 'text-zinc-400';
const sum = awaySummary(item as AwayItem);
const showSum = sum && item.kind !== 'approval' && !(item.kind === 'question' && item.choices?.length);
+ // F6: an approval titled with its own question still says what the bot wants to use: "Needs approval · use gmail".
+ const asked = item.kind === 'approval' && typeof item.question === 'string' && !!item.question.trim();
+ const use = asked ? awayTitle(item as AwayItem) : '';
return (
<span className="flex items-center gap-1.5 min-w-0">
<span className={`shrink-0 font-semibold ${toneText}`}>{label}</span>
{showSum && <span className="min-w-0 truncate text-zinc-400">{sum}</span>}
+ {use && (
+ <span className="min-w-0 truncate text-zinc-400" data-approval-use>
+ · {use.charAt(0).toLowerCase() + use.slice(1)}
+ </span>
+ )}
</span>
);
};
@@ -164,11 +212,15 @@ interface RowProps {
onPick: (i: InboxItem) => void;
onAnswer: (i: InboxItem, choice: number) => void;
onResolve: (i: InboxItem, d: ApprovalDecision) => void;
+ /** A routine's review task in Done: its run's first line, as the run's own row would show it. */
+ doneSummary?: string | null;
+ /** The conversation it happened in ("@Spring launch"), said before the bot's name like the mockup. */
+ place?: string | null;
/** 0.9.5: a connection row's Reconnect opens Settings › Connections. */
onOpenConnections?: () => void;
}
-const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve, onOpenConnections }) => {
+const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve, doneSummary, place, onOpenConnections }) => {
const review = isReview(item) ? item : null;
const title = rowTitle(item);
// The server decides one_tap; an item with no verdict (Not checked yet, Being checked) never gets inline Approve.
@@ -176,6 +228,11 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o
const stale = !!review?.stale;
const disabled = busy !== null;
const tint = selected ? 'border-violet-400/70 bg-violet-500/10' : GROUP_STYLE[item.group].row;
+ const kicker = (isDoneGroup(item.group) ? rowKicker(item) : null) ?? place ?? null;
+ // A team job names the team's size where a row names its bot: "@Spring launch · 3 bots" (Needs B 2).
+ const who = (item.kind === 'team_job' ? teamSize(item) : null) ?? item.kwant_name;
+ const unread = isUnread(item);
+ const doneRow = !review && isDoneGroup(item.group) && opensInPane(item);
return (
<li role="presentation" className={`relative rounded-xl border transition-colors ${tint}`} data-row={item.id} data-group={item.group}>
<div
@@ -185,6 +242,7 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o
tabIndex={focusable ? 0 : -1}
data-option={item.id}
data-review={review ? '' : undefined}
+ data-done={doneRow ? '' : undefined}
onClick={() => onPick(item)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -197,13 +255,40 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o
<ModernAvatar role={item.kwant_name} name={item.kwant_name} size={30} kwantId={item.kwant_id} />
<span className="flex-1 min-w-0">
<span className="flex items-center gap-2 text-[11px]">
- <span className="font-semibold text-zinc-300 truncate">{item.kwant_name}</span>
- <time dateTime={item.timestamp} className="ml-auto shrink-0 tabular-nums text-zinc-400">
+ <span className="font-semibold text-zinc-300 truncate">
+ {kicker && (
+ <span className="font-normal text-zinc-400" data-kicker>
+ {kicker} ·{' '}
+ </span>
+ )}
+ {who}
+ </span>
+ {unread && (
+ <span className="ml-auto shrink-0 inline-flex items-center" data-unread>
+ <span className="block w-2 h-2 rounded-full bg-violet-400" aria-hidden="true" />
+ <span className="sr-only">New</span>
+ </span>
+ )}
+ <time dateTime={item.timestamp} className={`${unread ? '' : 'ml-auto '}shrink-0 tabular-nums text-zinc-400`}>
{clock(item.timestamp)}
</time>
</span>
<span className="block mt-0.5 text-sm font-semibold text-zinc-100 break-words max-md:line-clamp-3 md:truncate">{title}</span>
- <span className="block mt-1 text-xs">{review ? <ReviewSubline item={review} /> : <AwaySubline item={item} />}</span>
+ <span className="block mt-1 text-xs">
+ {review && doneSummary ? (
+ <span className="block text-zinc-400 max-md:line-clamp-2 md:truncate" data-done-summary>
+ {doneSummary}
+ </span>
+ ) : review ? (
+ <ReviewSubline item={review} />
+ ) : doneRow && item.summary ? (
+ <span className="block text-zinc-400 max-md:line-clamp-2 md:truncate" data-done-summary>
+ {item.summary}
+ </span>
+ ) : (
+ <AwaySubline item={item} />
+ )}
+ </span>
</span>
</div>
@@ -494,6 +579,68 @@ const Skeleton: React.FC = () => (
</ul>
);
+// ---------- The item pane ----------
+
+/**
+ * A review opens in ReviewItemView. A routine's review task in Done gets the done layout inside it (meta line,
+ * chips, answer, trail, Why above Looks good and Ask to redo); a finished item with no review task opens in
+ * DoneItemView.
+ */
+const ItemPane: React.FC<{
+ item: InboxItem;
+ runItem: InboxItem | null;
+ entry: Exclude<Crumb, null> | 'inbox';
+ onDone: (r: ReviewDone) => void;
+ onHeldResolved: (approvalId: string, status: 'allowed' | 'denied' | 'expired') => void;
+ onOpenItemChat: (i: InboxItem) => void;
+ onOpenMessage?: (t: MessageTarget) => void;
+ onEditRoutine?: (routineId: string) => void;
+ placeName?: (channelId: string | null) => string | null;
+ api?: DoneApi;
+ initial?: DoneDetailData;
+}> = ({ item, runItem, entry, onDone, onHeldResolved, onOpenItemChat, onOpenMessage, onEditRoutine, placeName, api, initial }) => {
+ const phone = usePhoneLayout();
+ const d = useDoneDetail(item, runItem, api ?? defaultDoneApi, initial);
+ const doneLayout = isDoneGroup(item.group) && (!isReview(item) || isRoutineItem(item));
+ if (isReview(item) && !doneLayout) return <ReviewItemView item={item} entry={entry} onDone={onDone} onHeldResolved={onHeldResolved} />;
+ const target = d.target ?? servedTarget(item);
+ const openChat = () => (target && onOpenMessage ? onOpenMessage(target) : onOpenItemChat(runItem ?? item));
+ // Part B's result_link names where the answer is when the routine isn't loaded (and for team jobs).
+ const placeId = d.routine?.channel_id ?? item.result_link?.channel_id ?? null;
+ const place = placeId ? (placeName?.(placeId) ?? null) : null;
+ const routineId = d.routine?.id;
+ const edit = onEditRoutine && routineId ? () => onEditRoutine(routineId) : undefined;
+ if (!isReview(item)) return <DoneItemView item={item} d={d} place={place} phone={phone} onOpenChat={openChat} onEditRoutine={onEditRoutine} />;
+ return (
+ <ReviewItemView
+ item={item}
+ entry={entry}
+ onDone={onDone}
+ onHeldResolved={onHeldResolved}
+ done={{
+ title: doneTitle(item),
+ meta: metaLine(item, d.routine, d.run),
+ chips: <DoneChips item={item} d={d} onAddCheck={edit} />,
+ body: <DoneSections item={item} d={d} place={place} onOpenChat={openChat} onEditRoutine={onEditRoutine} />,
+ changed: changedState(item, d.message),
+ }}
+ />
+ );
+};
+
+/** Part B: where the answer is, from the item's own result fields, when the pane loaded no routine run. */
+export function servedTarget(item: InboxItem): MessageTarget | null {
+ const id = item.result_message_id;
+ if (typeof id !== 'string' || !id) return null;
+ const l = item.result_link;
+ return {
+ message_id: id,
+ channel_id: l?.channel_id ?? null,
+ kwant_id: l?.direct_kwant_id ?? item.kwant_id,
+ thread_id: l?.thread_id ?? item.result_thread_id ?? null,
+ };
+}
+
// ---------- Page ----------
export interface InboxNewProps {
@@ -514,6 +661,16 @@ export interface InboxNewProps {
noLoad?: boolean;
/** Tests: force the layout. */
wide?: boolean;
+ /** 0.9.5 F: Open in chat at the answer itself; without it, the item's chat opens. */
+ onOpenMessage?: (t: MessageTarget) => void;
+ /** Edit routine / Add one: open the routine in Routines. */
+ onEditRoutine?: (routineId: string) => void;
+ /** A channel's name for "Wrote the answer in …" (null: the bot's direct chat). */
+ placeName?: (channelId: string | null) => string | null;
+ /** Tests: where a done item's routine, run and answer come from. */
+ doneApi?: DoneApi;
+ /** Tests and screenshots: a done item's details by item id, instead of loading them. */
+ doneDetails?: Record<string, DoneDetailData>;
}
/** Writes `?item=` for the open item; the Shell sets the path first, so this waits a tick. */
@@ -529,7 +686,23 @@ function writeItemParam(id: string | null) {
}, 0);
}
-export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApprovalResolved, onBack, onOpenConnections, onCrumb, top, now = Date.now(), noLoad = false, wide: forceWide }) => {
+export const InboxNew: React.FC<InboxNewProps> = ({
+ onOpen,
+ onCounts,
+ onApprovalResolved,
+ onBack,
+ onOpenConnections,
+ onCrumb,
+ top,
+ now = Date.now(),
+ noLoad = false,
+ wide: forceWide,
+ onOpenMessage,
+ onEditRoutine,
+ placeName,
+ doneApi,
+ doneDetails,
+}) => {
const st = useInbox();
const mqWide = useWide();
const wide = forceWide ?? mqWide;
@@ -564,19 +737,25 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
if (st.pendingKey && data) resolvePending();
}, [st.pendingKey, data]);
- const groups = data ? groupItems(data) : null;
+ const sections = data ? sectionItems(data) : null;
const bItems = batchItems(data);
const showBatch = !!data?.batch && (bItems.length >= 2 || !!st.batch?.running);
- const selectable = data ? [...data.items.filter(isReview).map((i) => i.id), ...(showBatch ? ['batch'] : [])] : [];
- const selItem = selectedId && selectedId !== 'batch' ? data?.items.find((i) => i.id === selectedId) ?? bItems.find((i) => i.id === selectedId) ?? null : null;
- const selValid = selectedId === 'batch' ? showBatch || !!st.batch : !!selItem && isReview(selItem);
+ const folded = new Set(Object.values(sections?.runFor ?? {}).map((r) => r.id));
+ const selectable = data ? [...data.items.filter((i) => opensInPane(i) && !folded.has(i.id)).map((i) => i.id), ...(showBatch ? ['batch'] : [])] : [];
+ const selItem =
+ selectedId && selectedId !== 'batch' ? (data?.items.find((i) => i.id === selectedId) ?? bItems.find((i) => i.id === selectedId) ?? null) : null;
+ const selValid = selectedId === 'batch' ? showBatch || !!st.batch : !!selItem && opensInPane(selItem);
// Desktop: something is always open. The first item (in queue order) on load, the next one after.
useEffect(() => {
if (!wide || !data || st.pendingKey) return;
if (selValid) return;
- const first = data.items.find(isReview)?.id ?? (showBatch ? 'batch' : null);
+ // Needs you first, then Done: the first item that opens here, in the order the queue draws them.
+ const order = sections ? [...sections.needs, ...sections.done] : data.items;
+ const first = order.find((i) => opensInPane(i) && !folded.has(i.id))?.id ?? (showBatch ? 'batch' : null);
if (first !== selectedId) select(first);
+ // sections and folded come from data
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [wide, data, selValid, selectedId, showBatch, st.pendingKey]);
// The address carries the open item, so a reload or a shared link opens it again.
@@ -586,7 +765,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
const pick = useCallback(
(i: InboxItem) => {
- if (isReview(i)) {
+ if (opensInPane(i)) {
select(i.id);
setCrumb(null);
return;
@@ -645,7 +824,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
if (!next) return;
next.focus();
const id = next.dataset.option!;
- if (wide && (id === 'batch' || next.dataset.review !== undefined)) select(id);
+ if (wide && (id === 'batch' || next.dataset.review !== undefined || next.dataset.done !== undefined)) select(id);
};
const onDone = (r: ReviewDone) => {
@@ -662,7 +841,8 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
void loadInbox();
};
- const firstFocusable = selectable.includes(selectedId ?? '') ? selectedId : data?.items[0]?.id ?? (showBatch ? 'batch' : null);
+ const firstRow = sections ? [...sections.needs, ...sections.done][0]?.id : undefined;
+ const firstFocusable = selectable.includes(selectedId ?? '') ? selectedId : (firstRow ?? (showBatch ? 'batch' : null));
const empty = !!data && data.items.length === 0 && !showBatch;
const header = (
<div className={`h-14 shrink-0 border-b border-zinc-800/80 ${onBack && !wide ? 'px-2' : 'px-4'} flex items-center justify-between gap-3 select-none`}>
@@ -673,7 +853,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
)}
<div className="min-w-0 flex-1">
<h2 className="text-sm font-semibold text-zinc-100 truncate">Inbox</h2>
- <p className="text-[11px] text-zinc-400 truncate mt-0.5">{data ? windowLabel(data.since, now) : 'What your bots need, finished and failed'}</p>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">{data ? (unreadLine(data, now) ?? windowLabel(data.since, now)) : 'What your bots need, finished and failed'}</p>
</div>
<button
type="button"
@@ -716,45 +896,67 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
{status}
{!data && loading && <Skeleton />}
{empty && <EmptyQueue />}
- {data && !empty && groups && (
- <div ref={listRef} role="listbox" aria-label="Inbox" aria-activedescendant={undefined} onKeyDown={onListKey} className={`space-y-5 ${error ? 'opacity-50' : ''}`}>
- {INBOX_GROUPS.map(({ key, label, hint, empty: none }) => {
- const rows = groups[key];
- const withBatch = key === 'to_review' && showBatch;
+ {data && !empty && sections && (
+ <div
+ ref={listRef}
+ role="listbox"
+ aria-label="Inbox"
+ aria-activedescendant={undefined}
+ onKeyDown={onListKey}
+ className={`space-y-5 ${error ? 'opacity-50' : ''}`}
+ >
+ {(['needs', 'done'] as const).map((key) => {
+ const rows = sections[key];
+ const reviewsEnd = key === 'done' ? rows.filter((i) => i.group === 'to_review').length : 0;
+ const withBatch = key === 'done' && showBatch;
const count = rows.length;
- const g = GROUP_STYLE[key];
+ const sec = SECTION[key];
+ const row = (i: InboxItem) => (
+ <QueueRow
+ key={`${i.kind}:${i.id}`}
+ item={i}
+ selected={selectedId === i.id && opensInPane(i)}
+ focusable={firstFocusable === i.id}
+ wide={wide}
+ busy={busy}
+ onPick={pick}
+ onAnswer={onAnswer}
+ onResolve={onResolve}
+ doneSummary={sections.runFor[i.id]?.summary || null}
+ place={i.link?.channel_id ? (placeName?.(i.link.channel_id) ?? null) : null}
+ onOpenConnections={onOpenConnections}
+ />
+ );
return (
<div key={key} role="group" aria-labelledby={`inbox-${key}`} data-section={key}>
<h3 id={`inbox-${key}`} className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider">
- <span className={`inline-flex items-center gap-1.5 ${g.head}`}>
- {g.icon}
- {label}
- </span>
- <span className="normal-case tracking-normal font-normal text-zinc-400">
- {count}
- {wide && count > 1 && <span data-inbox-hint={key}> · {hint}</span>}
- </span>
+ <span className={`inline-flex items-center gap-1.5 ${sec.head}`}>
+ {sec.icon}
+ {sec.label}
+ </span>{' '}
+ <span className="normal-case tracking-normal font-normal text-zinc-400">· {count}</span>
</h3>
{count > 0 || withBatch ? (
<ul role="presentation" className="space-y-2">
- {rows.map((i) => (
- <QueueRow
- key={`${i.kind}:${i.id}`}
- item={i}
- selected={selectedId === i.id && isReview(i)}
- focusable={firstFocusable === i.id}
+ {rows.slice(0, key === 'done' ? reviewsEnd : rows.length).map(row)}
+ {withBatch && (
+ <BatchCard
+ items={bItems}
+ selected={wide && selectedId === 'batch'}
+ focusable={firstFocusable === 'batch'}
wide={wide}
- busy={busy}
- onPick={pick}
- onAnswer={onAnswer}
- onResolve={onResolve}
- onOpenConnections={onOpenConnections}
+ onPick={() => select('batch')}
/>
- ))}
- {withBatch && <BatchCard items={bItems} selected={wide && selectedId === 'batch'} focusable={firstFocusable === 'batch'} wide={wide} onPick={() => select('batch')} />}
+ )}
+ {key === 'done' && rows.slice(reviewsEnd).map(row)}
</ul>
) : (
- <p className="px-1 text-xs text-zinc-400">{none}</p>
+ <p className="px-1 text-xs text-zinc-400">{sec.empty}</p>
+ )}
+ {key === 'done' && count > 0 && (
+ <p className="mt-3 px-1 text-xs text-zinc-400" data-done-footer>
+ {DONE_FOOTER}
+ </p>
)}
</div>
);
@@ -787,8 +989,21 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
const paneBody =
selectedId === 'batch' && selValid ? (
<BatchPane wide={wide} onOpenItem={openFromBatch} />
- ) : selItem && isReview(selItem) ? (
- <ReviewItemView item={selItem} entry={crumb ?? 'inbox'} onDone={onDone} onHeldResolved={(approvalId, status) => markHeld(selItem.id, approvalId, status)} />
+ ) : selItem && opensInPane(selItem) ? (
+ <ItemPane
+ key={selItem.id}
+ item={selItem}
+ runItem={sections?.runFor[selItem.id] ?? null}
+ entry={crumb ?? 'inbox'}
+ onDone={onDone}
+ onHeldResolved={(approvalId, status) => markHeld(selItem.id, approvalId, status)}
+ onOpenItemChat={(i) => onOpen(i as AwayItem)}
+ onOpenMessage={onOpenMessage}
+ onEditRoutine={onEditRoutine}
+ placeName={placeName}
+ api={doneApi}
+ initial={doneDetails?.[selItem.id]}
+ />
) : empty ? (
<div className="h-full grid place-items-center text-center" data-pane-empty>
<div className="space-y-1.5">
@@ -820,6 +1035,15 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
// Phone and narrow windows: the queue, or the open item as a full page.
const open = selValid && selectedId && (selectedId === 'batch' || selItem);
+ const position = (() => {
+ if (!sections || !selItem || crumb) return null;
+ for (const key of ['needs', 'done'] as const) {
+ const rows = sections[key].filter((i) => opensInPane(i));
+ const at = rows.findIndex((i) => i.id === selItem.id);
+ if (at >= 0) return `${SECTION[key].short} · ${at + 1} of ${rows.length}`;
+ }
+ return null;
+ })();
if (open) {
const back = () => {
if (crumb) {
@@ -834,6 +1058,11 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
<button type="button" onClick={back} className="kw-focus inline-flex items-center gap-1 min-h-[44px] px-2 rounded-lg text-sm text-zinc-200 hover:bg-zinc-800" data-item-back>
<ChevronLeft size={18} aria-hidden="true" /> {crumb ? CRUMB_LABEL[crumb] : 'Inbox'}
</button>
+ {position && (
+ <span className="ml-auto pr-2 text-xs text-zinc-400 tabular-nums" data-item-position>
+ {position}
+ </span>
+ )}
</div>
<div role="region" aria-label={paneLabel} className="flex-1 overflow-y-auto px-4 pt-4 flex flex-col" data-item-pane>
<div className="flex-1 flex flex-col pb-4">
diff --git a/frontend/src/components/ReviewItemView.tsx b/frontend/src/components/ReviewItemView.tsx
index edf9a9ca..8e8e5c03 100644
--- a/frontend/src/components/ReviewItemView.tsx
+++ b/frontend/src/components/ReviewItemView.tsx
@@ -33,6 +33,7 @@ import {
} from 'lucide-react';
import { type InboxItem, type ReviewItem, type HeldAction, type HeldStatus, type InboxCriterion, BEING_CHECKED_LINE, InboxError, approveState, inboxApi, isBeingChecked, reviewWord } from '../api/inbox';
import { AwayError } from '../away';
+import { LOOKS_GOOD, noChecksSet, redoLabel, redoTitle, rollbackShown as rollbackFor } from '../doneAway';
import { type Checkpoint, type RestorePreview, MissionError, RESTORE_ACTION_LABELS, conflictText, missionsApi, newIdempotencyKey, restoreErrorText } from '../missions';
import { usePhoneLayout } from '../usePhoneLayout';
import { ImageViewer } from './Attachments';
@@ -103,6 +104,17 @@ export interface ReviewItemViewProps {
onHeldResolved?: (approvalId: string, status: Exclude<HeldStatus, 'pending'>) => void;
/** The phone page draws its own top bar with the title; the view then starts at the chips. */
hideTitle?: boolean;
+ /**
+ * 0.9.5 F, a done item in the Inbox (a routine's review task): its own title and meta line, the chips, and
+ * the answer, trail and Why above the actions. The verdict box then shows only when there is a verdict.
+ */
+ done?: {
+ title: string;
+ meta: string;
+ chips: React.ReactNode;
+ body: React.ReactNode;
+ changed: boolean | null;
+ };
}
const BACK_LABEL: Record<ReviewEntry, string | null> = { inbox: null, board: 'Back to Mission board', dev: 'Back to Dev desk' };
@@ -174,12 +186,14 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
onOpenTask,
onHeldResolved,
hideTitle = false,
+ done: doneView,
}) => {
const phone = usePhoneLayout();
const uid = useId();
const titleId = `${uid}-title`;
const [held, setHeld] = useState<Record<string, HeldState>>(() => Object.fromEntries(item.held_actions.map((h) => [h.approval_id, heldFrom(h)])));
const openHeld = item.held_actions.filter((h) => held[h.approval_id]?.state === 'open');
+ const noChecks = !!doneView && noChecksSet(item);
const blocked = openHeld.length > 0 ? approveState({ held_actions: openHeld }).blocked : null;
const [busy, setBusy] = useState<null | 'approve' | 'send' | 'check'>(null);
const [notice, setNotice] = useState<{ text: string; tone: 'ok' | 'bad' | 'info'; undo?: string | null; copy?: string | null } | null>(null);
@@ -258,14 +272,22 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
setNotice(null);
try {
await api.verify(item.task_id, item.verdict.id);
- finish({ kind: 'approved', text: `Approved: “${item.title}”.`, task_id: item.task_id }, 'ok');
+ // 0.9.5 F3: the done layout says what its button said, with the routine's own name.
+ const okText = doneView ? `Looks good: “${doneView.title}”.` : `Approved: “${item.title}”.`;
+ finish({ kind: 'approved', text: okText, task_id: item.task_id }, 'ok');
} catch (e) {
if (e instanceof InboxError && e.stale) {
// The paths go in the stale box and the list row, not in this text (the Inbox status line), V1-4.
- finish({ kind: 'stale', text: `Couldn’t approve “${item.title}”. It’s back in Failed or stuck, and nothing was approved.`, task_id: item.task_id, paths: e.paths }, 'bad');
+ const text = doneView
+ ? `Couldn’t save “${doneView.title}”. It’s back in Failed or stuck, and nothing was saved.`
+ : `Couldn’t approve “${item.title}”. It’s back in Failed or stuck, and nothing was approved.`;
+ finish({ kind: 'stale', text, task_id: item.task_id, paths: e.paths }, 'bad');
} else {
const why = e instanceof Error ? e.message.replace(/\.$/, '') : 'Something went wrong';
- setNotice({ text: `Couldn’t approve “${item.title}”. ${why}. Nothing was approved.`, tone: 'bad' });
+ setNotice({
+ text: doneView ? `Couldn’t save “${doneView.title}”. ${why}. Nothing was saved.` : `Couldn’t approve “${item.title}”. ${why}. Nothing was approved.`,
+ tone: 'bad',
+ });
}
} finally {
inFlight.current = false;
@@ -362,7 +384,14 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
const since = clock(item.in_review_since);
const back = BACK_LABEL[entry];
const lockAll = done || busy !== null;
- const rollbackShown = item.rollback_ok;
+ const changed = doneView ? doneView.changed : typeof item.changed === 'boolean' ? item.changed : null;
+ const rollbackShown = rollbackFor(item, changed);
+ const showVerdict = !doneView || checking || v.result !== 'none';
+ // The done layout (0.9.5 F) leaves out what has nothing to say: a low risk chip, no criteria, no evidence.
+ const showRisk = !!item.risk.level && !(doneView && item.risk.level === 'low');
+ const showCriteria = !doneView || item.criteria.length > 0;
+ const ev = item.evidence;
+ const showEvidence = !doneView || ev.checks.length > 0 || ev.screenshots.length > 0 || !!ev.pr;
return (
<section role="region" aria-labelledby={titleId} className="space-y-4 min-w-0" data-review-item={item.id} data-entry={entry}>
@@ -376,20 +405,25 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
{!hideTitle && <ModernAvatar role={item.kwant_name} name={item.kwant_name} size={34} kwantId={item.kwant_id} />}
<div className="min-w-0 flex-1 space-y-1">
<h2 id={titleId} className={hideTitle ? 'sr-only' : 'text-[16px] leading-snug font-[650] text-zinc-50 break-words'}>
- {item.title}
+ {doneView ? doneView.title : item.title}
</h2>
- <div className="flex flex-wrap items-center gap-1.5 text-meta text-zinc-400">
+ {doneView && (
+ <p className="text-meta text-zinc-400 break-words" data-done-meta>
+ {doneView.meta}
+ </p>
+ )}
+ <div className={doneView && item.round.n <= 1 && !showRisk ? 'hidden' : 'flex flex-wrap items-center gap-1.5 text-meta text-zinc-400'}>
{item.round.n > 1 && (
<span className="kw-chip border-violet-400/40 bg-violet-500/15 text-violet-200 !py-0" data-round-chip>
Round {item.round.n}
</span>
)}
- {item.risk.level && (
+ {showRisk && item.risk.level && (
<span className={`kw-chip !py-0 ${item.risk.level === 'high' ? 'kw-chip-warn' : ''}`} data-risk={item.risk.level}>
{RISK_WORD[item.risk.level]}
</span>
)}
- <span className="min-w-0 break-words">
+ <span className={doneView ? 'hidden' : 'min-w-0 break-words'}>
{[item.project, since ? `in Review since ${since}` : null, `round ${item.round.n} of ${item.round.max}`].filter(Boolean).join(' · ')}
</span>
</div>
@@ -410,21 +444,28 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
)}
</header>
+ {doneView?.chips}
+ {doneView?.body}
+
{/* Verdict */}
- <div className={`rounded-2xl border px-4 py-3 space-y-1 ${tone.box}`} data-verdict={checking ? 'being_checked' : v.result}>
- <p className="text-[15px] font-semibold flex flex-wrap items-center gap-x-1.5">
- <VIcon size={17} className={tone.text} aria-hidden="true" />
- <span className={tone.text}>{reviewWord(item)}</span>
- {conf && <span className="font-normal text-zinc-400">· {conf}</span>}
- </p>
- <p className="text-body text-zinc-100 break-words" data-verdict-line>{checking ? BEING_CHECKED_LINE : v.line}</p>
- {meta && (
- <p className="flex items-start gap-1.5 text-meta text-zinc-400" data-checker-meta>
- <Eye size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
- <span className="min-w-0">{meta}</span>
+ {showVerdict && (
+ <div className={`rounded-2xl border px-4 py-3 space-y-1 ${tone.box}`} data-verdict={checking ? 'being_checked' : v.result}>
+ <p className="text-[15px] font-semibold flex flex-wrap items-center gap-x-1.5">
+ <VIcon size={17} className={tone.text} aria-hidden="true" />
+ <span className={tone.text}>{reviewWord(item)}</span>
+ {conf && <span className="font-normal text-zinc-400">· {conf}</span>}
</p>
- )}
- </div>
+ <p className="text-body text-zinc-100 break-words" data-verdict-line>
+ {checking ? BEING_CHECKED_LINE : v.line}
+ </p>
+ {meta && (
+ <p className="flex items-start gap-1.5 text-meta text-zinc-400" data-checker-meta>
+ <Eye size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span className="min-w-0">{meta}</span>
+ </p>
+ )}
+ </div>
+ )}
{/* Stale and approve_error, from the server */}
{stalePaths && (
@@ -476,7 +517,7 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
data-approve
>
{busy === 'approve' ? <Loader2 size={14} className={spin} aria-hidden="true" /> : <Check size={14} aria-hidden="true" />}
- {busy === 'approve' ? 'Approving…' : 'Approve'}
+ {busy === 'approve' ? 'Saving…' : LOOKS_GOOD}
</button>
{phone && blocked && <BlockedLine id={`${uid}-blocked`} text={blocked} className="col-span-2" />}
<button
@@ -486,10 +527,10 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
disabled={lockAll}
aria-expanded={sendOpen}
aria-keyshortcuts={phone ? undefined : 'S'}
- className={btnQuiet}
+ className={`${btnQuiet} ${phone && !rollbackShown ? 'col-span-2' : ''}`}
data-send-back
>
- <CornerUpLeft size={14} aria-hidden="true" /> Send back
+ <CornerUpLeft size={14} aria-hidden="true" /> {redoLabel(item.kwant_name)}
</button>
{rollbackShown && (
<button ref={rollBtnRef} type="button" onClick={() => setRollOpen({})} disabled={lockAll} aria-haspopup="dialog" className={btnRose} data-roll-back>
@@ -501,15 +542,6 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
Last round. Sending back again asks you how to go on.
</span>
)}
- {!phone && (
- <span className="ml-auto hidden lg:flex items-center gap-1" aria-hidden="true">
- {['A', 'S', 'J', 'K'].map((k) => (
- <kbd key={k} className="rounded border border-hairline-strong px-1 text-[10px] leading-4 text-zinc-400">
- {k}
- </kbd>
- ))}
- </span>
- )}
</div>
{!phone && blocked && <BlockedLine id={`${uid}-blocked`} text={blocked} />}
{phone && lastRound(item.round) && item.round.n > 1 && <p className="text-meta text-zinc-400">Last round. Sending back again asks you how to go on.</p>}
@@ -549,15 +581,26 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
{/* Send back: inline panel on desktop, sheet on phone */}
{sendOpen &&
(phone ? (
- <Sheet title={`Send back to ${item.kwant_name}`} onClose={closeSend}>
- <SendBackForm item={item} note={note} setNote={setNote} err={sendErr} busy={busy === 'send'} openHeld={openHeld.length} onSend={() => void sendBack()} onCancel={closeSend} phone />
+ <Sheet title={redoTitle(item.kwant_name)} onClose={closeSend}>
+ <SendBackForm
+ item={item}
+ note={note}
+ setNote={setNote}
+ err={sendErr}
+ busy={busy === 'send'}
+ openHeld={openHeld.length}
+ noChecks={noChecks}
+ onSend={() => void sendBack()}
+ onCancel={closeSend}
+ phone
+ />
</Sheet>
) : (
<div className="rounded-2xl border border-violet-400/40 bg-surface-raised p-4 space-y-3 kw-fade-in" data-send-panel>
<h3 className="flex items-center gap-2 text-body font-semibold text-zinc-100">
- <CornerUpLeft size={15} aria-hidden="true" /> Send back to {item.kwant_name}
+ <CornerUpLeft size={15} aria-hidden="true" /> {redoTitle(item.kwant_name)}
</h3>
- <SendBackForm item={item} note={note} setNote={setNote} err={sendErr} busy={busy === 'send'} openHeld={openHeld.length} onSend={() => void sendBack()} onCancel={closeSend} />
+ <SendBackForm item={item} note={note} setNote={setNote} err={sendErr} busy={busy === 'send'} openHeld={openHeld.length} noChecks={noChecks} onSend={() => void sendBack()} onCancel={closeSend} />
</div>
))}
@@ -603,28 +646,39 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
</ul>
</Fold>
)}
- <Fold
- id={`${uid}-crit`}
- icon={ListChecks}
- label="What done looks like"
- summary={criteriaSummaryText(item.criteria_summary)}
- summaryBad={item.criteria_summary.not_met > 0}
- open={folds.criteria}
- onToggle={() => toggleFold('criteria')}
- >
- {item.criteria.length ? (
- <ul className="rounded-xl border border-hairline divide-y divide-hairline">
- {item.criteria.map((c) => (
- <CriterionRow key={c.index} c={c} />
- ))}
- </ul>
- ) : (
- <p className="text-meta text-zinc-400">No criteria were set for this task.</p>
- )}
- </Fold>
- <Fold id={`${uid}-ev`} icon={Terminal} label="Evidence" summary={evidenceSummaryText(item.evidence)} open={folds.evidence} onToggle={() => toggleFold('evidence')}>
- <Evidence item={item} />
- </Fold>
+ {showCriteria && (
+ <Fold
+ id={`${uid}-crit`}
+ icon={ListChecks}
+ label="What done looks like"
+ summary={criteriaSummaryText(item.criteria_summary)}
+ summaryBad={item.criteria_summary.not_met > 0}
+ open={folds.criteria}
+ onToggle={() => toggleFold('criteria')}
+ >
+ {item.criteria.length ? (
+ <ul className="rounded-xl border border-hairline divide-y divide-hairline">
+ {item.criteria.map((c) => (
+ <CriterionRow key={c.index} c={c} />
+ ))}
+ </ul>
+ ) : (
+ <p className="text-meta text-zinc-400">No criteria were set for this task.</p>
+ )}
+ </Fold>
+ )}
+ {showEvidence && (
+ <Fold
+ id={`${uid}-ev`}
+ icon={Terminal}
+ label="Evidence"
+ summary={evidenceSummaryText(item.evidence)}
+ open={folds.evidence}
+ onToggle={() => toggleFold('evidence')}
+ >
+ <Evidence item={item} />
+ </Fold>
+ )}
</div>
{rollOpen && (
@@ -735,10 +789,12 @@ const SendBackForm: React.FC<{
err: string | null;
busy: boolean;
openHeld: number;
+ /** Mira re-check 4: a finished run with no checks has no checker to promise. */
+ noChecks: boolean;
onSend: () => void;
onCancel: () => void;
phone?: boolean;
-}> = ({ item, note, setNote, err, busy, openHeld, onSend, onCancel, phone = false }) => {
+}> = ({ item, note, setNote, err, busy, openHeld, noChecks, onSend, onCancel, phone = false }) => {
const ta = useRef<HTMLTextAreaElement>(null);
const id = useId();
useEffect(() => {
@@ -782,7 +838,7 @@ const SendBackForm: React.FC<{
</div>
)}
<ul className="list-disc pl-5 space-y-0.5 text-meta text-zinc-400">
- {sendBackSteps(item, openHeld).map((s) => (
+ {sendBackSteps(item, openHeld, noChecks).map((s) => (
<li key={s}>{s}</li>
))}
</ul>
diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsx
index 0003e35e..19002780 100644
--- a/frontend/src/components/RoutinesPanel.tsx
+++ b/frontend/src/components/RoutinesPanel.tsx
@@ -26,6 +26,7 @@ import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
import { SuggestedRoutines } from './SuggestedRoutines';
import { editorProps } from '../escape';
+import type { MessageTarget } from './DoneDetail';
const smallBtn =
'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
@@ -372,7 +373,12 @@ export const RoutineForm: React.FC<{
);
};
-const RunHistory: React.FC<{ routineId: string; tick: number }> = ({ routineId, tick }) => {
+/** 0.9.5 F: where a run's result message lives, for its History row's link. */
+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 }) => {
+ const routineId = routine.id;
const [runs, setRuns] = useState<RoutineRun[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -394,7 +400,27 @@ const RunHistory: React.FC<{ routineId: string; tick: number }> = ({ routineId,
<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-600">{r.trigger === 'manual' ? 'Run now' : 'Scheduled'}</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;
@@ -414,10 +440,12 @@ export const RoutineRow: React.FC<{
/** Opened from a card's Pause: scrolls here, focuses the switch and says how to pause. */
focusPause?: number;
onEdit: () => void;
+ /** 0.9.5 F: History rows link to each run's result message. */
+ onOpenRunResult?: (t: MessageTarget) => void;
onChanged: () => void;
/** Tests: start in the Undo window. */
initialPending?: boolean;
-}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onChanged, initialPending = false }) => {
+}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onOpenRunResult, onChanged, initialPending = false }) => {
const rowRef = useRef<HTMLLIElement>(null);
const switchRef = useRef<HTMLInputElement>(null);
const [highlight, setHighlight] = useState(false);
@@ -516,7 +544,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 routineId={routine.id} tick={tick} />
+ <RunHistory routine={routine} tick={tick} onOpenRunResult={onOpenRunResult} />
</div>
)}
</li>
@@ -534,7 +562,9 @@ export const RoutinesPanel: React.FC<{
focus?: RoutineFocus | null;
/** Opens app Settings, where suggestions are turned on. */
onOpenSettings?: () => void;
-}> = ({ kwantId, kwants, channels, focus, onOpenSettings }) => {
+ /** 0.9.5 F: a History row's Open result. */
+ onOpenRunResult?: (t: MessageTarget) => void;
+}> = ({ kwantId, kwants, channels, focus, onOpenSettings, onOpenRunResult }) => {
const [routines, setRoutines] = useState<Routine[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [editing, setEditing] = useState<Routine | 'new' | null>(null);
@@ -656,6 +686,7 @@ export const RoutinesPanel: React.FC<{
tick={tick}
focusPause={focus?.mode === 'pause' && focus.id === r.id ? focus.nonce : undefined}
onEdit={() => setEditing(r)}
+ onOpenRunResult={onOpenRunResult}
onChanged={reload}
/>
),
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index 6b00a5df..2afeb36c 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -27,6 +27,7 @@ import type { Profile } from '../profiles';
import { EnginesPanel } from './EnginesPanel';
import { ApiKeysPanel } from './ApiKeysPanel';
import { RoutinesPanel, type RoutineFocus } from './RoutinesPanel';
+import type { MessageTarget } from './DoneDetail';
import { HirePolicyPanel } from './HirePolicyPanel';
import { ModernAvatar } from './ModernAvatar';
import { SpaceTile } from './Spaces';
@@ -90,6 +91,8 @@ interface Props {
onOpenTools: () => void;
/** Set by a routine card's Edit or Pause: opens that routine in Routines. */
routineFocus?: RoutineFocus | null;
+ /** 0.9.5 F: a routine run's History row opens its answer in the chat. */
+ onOpenRunResult?: (t: MessageTarget) => 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. */
@@ -248,7 +251,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {
{tab === 'bots' && <BotsTab {...tp} />}
{tab === 'teams' && <TeamsTab {...p} />}
{tab === 'skills' && <SkillsTab {...p} />}
- {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={toApp} />}
+ {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={toApp} onOpenRunResult={p.onOpenRunResult} />}
{tab === 'import' && <ImportTab {...tp} />}
</>
)}
diff --git a/frontend/src/doneAway.ts b/frontend/src/doneAway.ts
new file mode 100644
index 00000000..ace80408
--- /dev/null
+++ b/frontend/src/doneAway.ts
@@ -0,0 +1,404 @@
+// 0.9.5 F: Inbox "Done while you were away" (release-095/inbox-away/brief.md, Mira's ux-audit-090 §1 and
+// mockup 2). The queue splits into Needs you and Done while you were away; a done item's pane says what ran,
+// when and why, shows the answer inline, what the bot did, and the routine's own words. Everything here is
+// read from today's API (inbox items, /api/routines, a routine's runs, the result message). Fields the API
+// lacks are listed in release-095/inbox-away/impl.md for Vega's part B; nothing here invents a number.
+
+import { parseActivityMeta, plainTitle } from './activity';
+import type { DoneTrailStep, InboxGroup, InboxItem, InboxResponse, ReviewItem, TeamMember } from './api/inbox';
+import { isReview } from './api/inbox';
+import { type Routine, type RoutineRun, type Schedule, WEEKDAYS, monthDaysText } from './continuity';
+import { parseMetaObject } from './questions';
+import { relativeTime } from './away';
+
+export const NEEDS_GROUPS: InboxGroup[] = ['waiting_on_you', 'failed_or_stuck'];
+export const DONE_GROUPS: InboxGroup[] = ['to_review', 'finished'];
+
+/** How long done items stay (part B keeps them 7 days, seen or not); the footer says so. */
+export const DONE_DAYS = 7;
+export const DONE_FOOTER = `Done items stay here for ${DONE_DAYS} days.`;
+export const DONE_EMPTY = `Nothing finished in the last ${DONE_DAYS} days.`;
+
+/** Part B's `unread`: true only when the server says so. */
+export const isUnread = (i: Pick<InboxItem, 'unread'>): boolean => i.unread === true;
+
+/**
+ * The header's subtitle (Mira's Needs B 1). Once the list holds 7 days, "Since you last looked" no longer
+ * describes it, so it counts what is new: "3 new since you last looked, 2 h ago", or "Nothing new since …".
+ * Null when the server is older than part B (no item carries `unread` and the window starts at the last
+ * visit); the caller keeps today's window line then.
+ */
+export function unreadLine(r: Pick<InboxResponse, 'items' | 'since' | 'last_seen'>, now: number = Date.now()): string | null {
+ const flagged = r.items.some((i) => typeof i.unread === 'boolean');
+ const since = Date.parse(r.since);
+ const seen = Date.parse(r.last_seen ?? '');
+ const widened = Number.isFinite(since) && Number.isFinite(seen) && since < seen - 60_000;
+ if (!flagged && !widened) return null;
+ // Rows, not items: a routine run folded into its review is one row, so it counts once.
+ const { needs, done } = sectionItems(r);
+ const n = [...needs, ...done].filter(isUnread).length;
+ const ago = r.last_seen ? relativeTime(r.last_seen, now) : '';
+ const head = n ? `${n} new` : 'Nothing new';
+ return ago ? `${head} since you last looked, ${ago}` : head;
+}
+
+export const isDoneGroup = (g: InboxGroup | undefined): boolean => !!g && DONE_GROUPS.includes(g);
+
+const ROUTINE_PREFIX = /^Routine:\s*/;
+
+/** A routine run's own row, or the review task a routine run made (`Routine: <name>`). */
+export const isRoutineItem = (i: InboxItem): boolean => i.kind === 'routine_run' || (isReview(i) && ROUTINE_PREFIX.test(i.title));
+
+/** The routine's name: a review task's title without its `Routine: ` prefix. */
+export const routineName = (i: InboxItem): string => (isReview(i) ? i.title.replace(ROUTINE_PREFIX, '') : i.title);
+
+/** How close a routine run's end and its review task's time must be to read as the same run. */
+const SAME_RUN_MS = 15 * 60_000;
+
+export interface Sections {
+ needs: InboxItem[];
+ done: InboxItem[];
+ /**
+ * A routine's review task and its finished run are one thing done: the run's row is folded into the review
+ * (same bot, same routine name, ended within 15 minutes). Keyed by the review item's id.
+ */
+ runFor: Record<string, InboxItem>;
+}
+
+/** Needs you (waiting, then failed or stuck) and Done (to review, then finished), in the server's order. */
+export function sectionItems(r: Pick<InboxResponse, 'items'>): Sections {
+ const by: Record<InboxGroup, InboxItem[]> = {
+ waiting_on_you: [],
+ failed_or_stuck: [],
+ to_review: [],
+ finished: [],
+ };
+ for (const i of r.items) (by[i.group] ?? by.finished).push(i);
+ const runFor: Record<string, InboxItem> = {};
+ const folded = new Set<string>();
+ const runs = r.items.filter((i) => i.kind === 'routine_run' && isDoneGroup(i.group));
+ for (const rev of r.items) {
+ if (!isReview(rev) || !ROUTINE_PREFIX.test(rev.title) || !isDoneGroup(rev.group)) continue;
+ const name = routineName(rev);
+ const at = Date.parse(rev.timestamp);
+ const run = runs
+ .filter((x) => !folded.has(x.id) && x.kwant_id === rev.kwant_id && x.title === name)
+ .map((x) => ({ x, d: Math.abs(Date.parse(x.timestamp) - at) }))
+ .filter(({ d }) => Number.isFinite(d) && d <= SAME_RUN_MS)
+ .sort((a, b) => a.d - b.d)[0]?.x;
+ if (run) {
+ runFor[rev.id] = run;
+ folded.add(run.id);
+ }
+ }
+ const keep = (i: InboxItem) => !folded.has(i.id);
+ return {
+ needs: [...by.waiting_on_you, ...by.failed_or_stuck],
+ done: [...by.to_review, ...by.finished].filter(keep),
+ runFor,
+ };
+}
+
+/** The row's first line before the bot's name: "Routine" for a routine's work, else nothing. */
+export const rowKicker = (i: InboxItem): string | null => (isRoutineItem(i) ? 'Routine' : null);
+
+// ---------- Team jobs (part B) ----------
+
+export const isTeamJob = (i: InboxItem | null | undefined): boolean => !!i && i.kind === 'team_job';
+
+/** The bot that led a team job: `lead`, else the item's own bot (the server sends the lead there too). */
+export const teamLead = (i: InboxItem): TeamMember => i.lead ?? { kwant_id: i.kwant_id, kwant_name: i.kwant_name };
+
+/** The bots it handed work to, without the lead. */
+export const teamMembers = (i: InboxItem): TeamMember[] => {
+ const lead = teamLead(i).kwant_id;
+ return (Array.isArray(i.members) ? i.members : []).filter((m) => m && m.kwant_id !== lead);
+};
+
+/** "3 bots": the members and the lead. Null when the server named no members. */
+export function teamSize(i: InboxItem): string | null {
+ if (!Array.isArray(i.members)) return null;
+ const n = teamMembers(i).length + 1;
+ return `${n} ${n === 1 ? 'bot' : 'bots'}`;
+}
+
+/** "Ann led Ben and Cody", "Ann led Ben, Cody and 2 more"; just "Ann" when nobody was handed work. */
+export function ledLine(i: InboxItem): string {
+ const lead = teamLead(i).kwant_name;
+ const m = teamMembers(i).map((x) => x.kwant_name);
+ if (!m.length) return lead;
+ if (m.length === 1) return `${lead} led ${m[0]}`;
+ if (m.length === 2) return `${lead} led ${m[0]} and ${m[1]}`;
+ return `${lead} led ${m[0]}, ${m[1]} and ${m.length - 2} more`;
+}
+
+/** The row's title: a routine's own name, without the `Routine: ` its review task carries. */
+export const doneTitle = (i: InboxItem): string => (isRoutineItem(i) ? routineName(i) : i.title);
+
+// ---------- Times ----------
+
+const pad = (n: number) => String(n).padStart(2, '0');
+
+/** "22:51", local time; '' for a bad stamp. */
+export function hm(ts: string | null | undefined): string {
+ const t = Date.parse(ts ?? '');
+ if (Number.isNaN(t)) return '';
+ const d = new Date(t);
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+/** "22:51:02", local time; '' for a bad stamp. */
+export function hms(ts: string | null | undefined): string {
+ const t = Date.parse(ts ?? '');
+ if (Number.isNaN(t)) return '';
+ const d = new Date(t);
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+}
+
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+/** "Nov 11", local date; '' for a bad stamp. */
+export function monthDay(ts: string | null | undefined): string {
+ const t = Date.parse(ts ?? '');
+ if (Number.isNaN(t)) return '';
+ const d = new Date(t);
+ return `${MONTHS[d.getMonth()]} ${d.getDate()}`;
+}
+
+// ---------- Meta line ----------
+
+/** The schedule as the meta line says it: "every Mon 09:00", "every day 08:30", "every 2 h". */
+export function scheduleShort(s: Schedule | null | undefined): string {
+ if (!s || typeof s !== 'object') return '';
+ switch (s.type) {
+ case 'once':
+ return 'once';
+ case 'daily':
+ return `every day ${s.time}`;
+ case 'weekly': {
+ const days = s.weekdays.length === 7 ? 'day' : s.weekdays.map((d) => WEEKDAYS.find((w) => w.id === d)?.label ?? d).join(', ');
+ return `every ${days} ${s.time}`;
+ }
+ case 'interval':
+ return s.every_minutes % 60 === 0 ? `every ${s.every_minutes / 60} h` : `every ${s.every_minutes} min`;
+ case 'monthly':
+ return `monthly on ${monthDaysText(s.days)} ${s.time}`;
+ case 'cron':
+ return 'on a custom rule';
+ default:
+ return '';
+ }
+}
+
+/**
+ * "Ben · routine, every Mon 09:00 · ran 22:51 because you pressed Run now". Without the routine it says what
+ * the item says ("Ben · finished 22:45"); without the run it leaves the why out rather than guess it.
+ */
+export function metaLine(item: InboxItem, routine: Routine | null, run: RoutineRun | null): string {
+ const bot = isTeamJob(item) ? ledLine(item) : item.kwant_name;
+ if (!isRoutineItem(item)) {
+ const at = hm(item.timestamp);
+ return at ? `${bot} · finished ${at}` : bot;
+ }
+ const sched = routine ? scheduleShort(routine.schedule) : '';
+ const parts = [bot, sched ? `routine, ${sched}` : 'routine'];
+ const ranAt = hm(run?.started_at ?? null) || hm(item.timestamp);
+ if (ranAt) parts.push(`ran ${ranAt}${triggerWords(run?.trigger ?? servedTrigger(item))}`);
+ return parts.join(' · ');
+}
+
+/** The run's trigger as part B sends it on `source`, when the routine's run isn't loaded. */
+const servedTrigger = (item: InboxItem): string | null => (item.source?.kind === 'routine' ? item.source.trigger : null);
+
+/** " because you pressed Run now", " on an app event", " on schedule"; '' when unknown, rather than guess. */
+export function triggerWords(trigger: string | null | undefined): string {
+ if (!trigger) return '';
+ if (trigger === 'manual') return ' because you pressed Run now';
+ if (trigger === 'event') return ' on an app event';
+ return ' on schedule';
+}
+
+// ---------- The result message ----------
+
+/** The fields of a chat message this pane reads (GET /api/channels/:id/messages). */
+export interface DoneMessage {
+ id: string;
+ text: string;
+ created_at: string;
+ meta?: unknown;
+ sender_id?: string | null;
+}
+
+export interface TrailRow {
+ at: string;
+ /** Plain text: a step's title without its markdown backticks. */
+ what: string;
+ detail: string | null;
+ failed: boolean;
+ /** Declined, stopped, or still waiting when saved (part B `status: 'skipped'`). */
+ skipped?: boolean;
+ /** A team job's member who did it. */
+ by?: string | null;
+}
+
+/**
+ * Part B's served trail, when the item has one (Vega reads the same `meta.activity` steps on the server,
+ * keeps the last 30 and adds `by` on team jobs), then the answer itself. Null when the server sent none,
+ * so the caller falls back to the loaded message.
+ */
+export function trailFromServed(item: InboxItem, place: string | null): TrailRow[] | null {
+ if (!Array.isArray(item.trail)) return null;
+ const rows: TrailRow[] = item.trail
+ .filter((s): s is DoneTrailStep => !!s && typeof s.label === 'string')
+ .map((s) => ({
+ at: hms(s.at),
+ what: plainTitle(s.label),
+ detail: s.detail ? plainTitle(s.detail) : null,
+ failed: s.status === 'error',
+ skipped: s.status === 'skipped',
+ by: typeof s.by === 'string' && s.by ? s.by : null,
+ }));
+ if (!rows.length) return [];
+ rows.push({
+ at: hms(item.timestamp),
+ what: place ? `Wrote the answer in ${place}` : 'Wrote the answer',
+ detail: null,
+ failed: false,
+ });
+ return rows;
+}
+
+/** Part B's `trail_dropped`: a non-negative whole count, else null (unknown). */
+export function servedDropped(item: InboxItem): number | null {
+ const n = item.trail_dropped;
+ return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.floor(n) : null;
+}
+
+/** The trail's heading: "What the team did" for a team job, else "What Ben did". */
+export const trailHeading = (item: InboxItem): string => (isTeamJob(item) ? 'What the team did' : `What ${item.kwant_name} did`);
+
+/** "Ann’s answer": a team job's answer is its lead's. */
+export const answerHeading = (item: InboxItem): string => `${isTeamJob(item) ? teamLead(item).kwant_name : item.kwant_name}’s answer`;
+
+/**
+ * Why, from part B's `why` and `why_kind` (Mira's Needs B 2 and 3). The routine case keeps today's copy,
+ * drawn from the routine itself. Null when there is nothing to quote.
+ */
+export function whyLead(item: InboxItem): string | null {
+ const why = typeof item.why === 'string' ? item.why.trim() : '';
+ if (!why) return null;
+ switch (item.why_kind) {
+ case 'task':
+ return 'The task said:';
+ case 'ask':
+ return `You asked ${item.kwant_name}:`;
+ case 'request': {
+ // The finish time can be a day after the ask, so the date comes only from the ask's own time.
+ const day = monthDay(item.why_at);
+ return day ? `You asked on ${day}:` : 'You asked:';
+ }
+ default:
+ return null;
+ }
+}
+
+/**
+ * "What <bot> did": the steps the reply saved in `meta.activity` (tools, approvals, human steps; thinking and
+ * notes left out), each at the time it started, then the answer itself. Empty when the message saved none.
+ */
+export function trailFrom(msg: DoneMessage | null, place: string | null): TrailRow[] {
+ if (!msg) return [];
+ const a = parseActivityMeta(msg.meta);
+ const rows: TrailRow[] = (a?.steps ?? [])
+ .filter((s) => s.kind !== 'thinking' && s.kind !== 'note')
+ .map((s) => ({
+ at: hms(s.started_at),
+ what: plainTitle(s.title),
+ detail: s.detail ? plainTitle(s.detail) : null,
+ failed: s.status === 'failed',
+ }));
+ if (!rows.length) return [];
+ rows.push({
+ at: hms(msg.created_at),
+ what: place ? `Wrote the answer in ${place}` : 'Wrote the answer',
+ detail: null,
+ failed: false,
+ });
+ return rows;
+}
+
+/** Steps the saved activity left out (it keeps the last ones), so the trail can say so. */
+export const trailDropped = (msg: DoneMessage | null): number => parseActivityMeta(msg?.meta)?.dropped ?? 0;
+
+/** A message's own text, or null when there is none to show. */
+export const answerText = (msg: DoneMessage | null): string | null => (msg && typeof msg.text === 'string' && msg.text.trim() ? msg.text : null);
+
+/** `meta.changed` on a result message, when a server sends it (Vega B); else unknown. */
+export function changedFromMeta(msg: DoneMessage | null): boolean | null {
+ const v = parseMetaObject(msg?.meta)?.changed;
+ return typeof v === 'boolean' ? v : null;
+}
+
+// ---------- Chips and actions ----------
+
+/**
+ * Whether the work changed anything: the item's `changed` when the server sends it (Vega B), else the
+ * message's `meta.changed`. For a review, `rollback_ok` true means there is something to roll back.
+ * Null means unknown, and then no "Read only" chip is drawn.
+ */
+export function changedState(item: InboxItem, msg: DoneMessage | null): boolean | null {
+ const own = (item as { changed?: unknown }).changed;
+ if (typeof own === 'boolean') return own;
+ const m = changedFromMeta(msg);
+ if (m !== null) return m;
+ if (isReview(item) && item.rollback_ok) return true;
+ return null;
+}
+
+/** Roll back shows only when something changed and the server says it can be rolled back. */
+export const rollbackShown = (item: ReviewItem, changed: boolean | null): boolean => !!item.rollback_ok && changed !== false;
+
+/** "No checks set": a review with no checks and no criteria. Unknown for other items (no chip). */
+export function noChecksSet(item: InboxItem): boolean {
+ if (!isReview(item)) return false;
+ return item.evidence.checks.length === 0 && item.criteria.length === 0 && item.verdict.result === 'none';
+}
+
+/** The send-back button and its panel's title. */
+export const redoLabel = (bot: string): string => `Ask ${bot} to redo…`;
+export const redoTitle = (bot: string): string => `Ask ${bot} to redo`;
+/** F7: a finished item with no review task; the button opens the chat, so it says so and has no ellipsis. */
+export const redoInChatLabel = (bot: string): string => `Ask ${bot} to redo in chat`;
+export const LOOKS_GOOD = 'Looks good';
+
+// ---------- Finding the routine and its run ----------
+
+/** The routine an item came from: same bot and name. Null when it was renamed or deleted. */
+export function findRoutine(routines: Routine[], item: InboxItem): Routine | null {
+ if (!isRoutineItem(item)) return null;
+ const name = routineName(item);
+ return routines.find((r) => r.kwant_id === item.kwant_id && r.name === name) ?? null;
+}
+
+/** The run: by id for a routine-run row, else the finished run that ended closest to the item's time. */
+export function findRun(runs: RoutineRun[], runId: string | null, at: string): RoutineRun | null {
+ if (runId) {
+ const own = runs.find((r) => r.id === runId);
+ if (own) return own;
+ }
+ const t = Date.parse(at);
+ if (Number.isNaN(t)) return null;
+ return (
+ runs
+ .filter((r) => r.status === 'ok' || r.status === 'error')
+ .map((r) => ({
+ r,
+ d: Math.abs(Date.parse(r.ended_at ?? r.started_at) - t),
+ }))
+ .filter(({ d }) => Number.isFinite(d) && d <= SAME_RUN_MS)
+ .sort((a, b) => a.d - b.d)[0]?.r ?? null
+ );
+}
+
+/** Where the answer was written, for the trail's last line: the routine's channel, else the direct chat. */
+export const placeLabel = (channelName: string | null | undefined): string | null => (channelName ? channelName : null);
diff --git a/frontend/src/doneAwayFixture.ts b/frontend/src/doneAwayFixture.ts
new file mode 100644
index 00000000..fd9242c5
--- /dev/null
+++ b/frontend/src/doneAwayFixture.ts
@@ -0,0 +1,268 @@
+// 0.9.5 F demo data: mockup 2 ("While you were away") as the API sends it with Vega's part B (#543: unread,
+// 7 days kept, the done fields, a team_job item), for tests and the screenshots. Not imported by the app.
+// Names, shops and prices are the mockup's made-up ones.
+
+import type { InboxItem, InboxResponse, ReviewItem } from './api/inbox';
+import type { Routine, RoutineRun } from './continuity';
+import type { DoneApi, DoneDetailData, MessageTarget } from './components/DoneDetail';
+import type { DoneMessage } from './doneAway';
+
+/** UTC; the tests and shots run in UTC so the clock reads like the mockup. */
+const at = (hms: string, day = '2026-11-11') => `${day}T${hms}Z`;
+const NOW = at('00:50:00', '2026-11-12');
+
+export const AWAY_CHANNEL = { id: 'c-spring', name: 'team-Spring launch' };
+
+const approval: InboxItem = {
+ kind: 'approval',
+ id: 'ap-1',
+ kwant_id: 'k-ann',
+ kwant_name: 'Ann',
+ title: 'Approve “Spring sale: 15% off”?',
+ question: 'Approve “Spring sale: 15% off”?',
+ summary: 'needs your OK',
+ status: 'pending',
+ timestamp: at('22:58:00'),
+ link: { thread_id: null, channel_id: AWAY_CHANNEL.id, direct_kwant_id: null },
+ tool_name: 'gmail',
+ details: { to: '[email protected]', subject: 'Spring sale: 15% off' },
+ group: 'waiting_on_you',
+ sort_key: [1, 0, 0, 'Ann', 'ap-1'],
+ unread: true,
+};
+
+/** The review task the routine's run made (`Routine: <name>`); nothing to check, nothing changed. */
+export const AWAY_ROUTINE_REVIEW: ReviewItem = {
+ kind: 'review',
+ id: 'r-prices',
+ kwant_id: 'k-ben',
+ kwant_name: 'Ben',
+ title: 'Routine: Competitor prices',
+ summary: 'No change since last week. Beanline still cheapest.',
+ status: 'review',
+ timestamp: at('22:51:10'),
+ link: { thread_id: null, channel_id: AWAY_CHANNEL.id, direct_kwant_id: null },
+ group: 'to_review',
+ sort_key: [3, 0, 0, 'Ben', 'r-prices'],
+ task_id: 't-prices',
+ mission_id: null,
+ project: null,
+ in_review_since: at('22:51:10'),
+ round: { n: 1, max: 2 },
+ verdict: {
+ id: null,
+ result: 'none',
+ confidence: null,
+ line: '',
+ checker: null,
+ checked_at: null,
+ steps_run: 0,
+ steps_total: 0,
+ },
+ risk: { level: 'low', reasons: [] },
+ criteria: [],
+ criteria_summary: { met: 0, total: 0, not_met: 0, not_checked: 0 },
+ couldnt_verify: [],
+ decisions: { total: 0, top: [] },
+ evidence: { checks: [], screenshots: [], pr: null },
+ held_actions: [],
+ previous_round: null,
+ stale: null,
+ approve_error: null,
+ one_tap: false,
+ batchable: false,
+ rollback_ok: true,
+ changed: false,
+ unread: true,
+ result_message_id: 'm-prices',
+ result_conversation_id: AWAY_CHANNEL.id,
+ result_thread_id: null,
+ result_link: { thread_id: null, channel_id: AWAY_CHANNEL.id, direct_kwant_id: null },
+ answer_excerpt: 'No change since last week. Beanline is still the cheapest at $24.00 per kg.',
+ trail: [
+ { at: at('22:51:02'), kind: 'page', label: 'Opened beanline.example.com', detail: 'found House Blend 1 kg $24.00, 15% off until Mar 31', status: 'ok', by: null },
+ { at: at('22:51:05'), kind: 'page', label: 'Opened roastco.example.com', detail: 'found 1 kg $27.00, free shipping over $40', status: 'ok', by: null },
+ { at: at('22:51:09'), kind: 'tool', label: 'Compared with last Monday’s run', detail: 'nothing changed', status: 'ok', by: null },
+ ],
+ trail_dropped: 0,
+ why: 'Check Beanline and RoastCo prices and tell me what changed since last week.',
+ why_kind: 'routine',
+ source: { kind: 'routine', routine_id: 'rt-prices', run_id: 'run-1', trigger: 'manual', task_id: 't-prices' },
+} as unknown as ReviewItem;
+
+/** The run's own row (folded into the review above). */
+const runRow: InboxItem = {
+ kind: 'routine_run',
+ id: 'run-1',
+ kwant_id: 'k-ben',
+ kwant_name: 'Ben',
+ title: 'Competitor prices',
+ summary: 'No change since last week. Beanline still cheapest.',
+ status: 'ok',
+ timestamp: at('22:51:10'),
+ link: { thread_id: null, channel_id: null, direct_kwant_id: 'k-ben' },
+ group: 'finished',
+ sort_key: [4, 0, 0, 'Ben', 'run-1'],
+ unread: true,
+};
+
+/** A lead's `Done:` reply after a team job (part B `team_job`): Ann led Ben and Cody. */
+export const AWAY_TEAM_JOB: InboxItem = {
+ kind: 'team_job',
+ id: 'tj-spring',
+ kwant_id: 'k-ann',
+ kwant_name: 'Ann',
+ lead: { kwant_id: 'k-ann', kwant_name: 'Ann' },
+ members: [
+ { kwant_id: 'k-ben', kwant_name: 'Ben' },
+ { kwant_id: 'k-cody', kwant_name: 'Cody' },
+ ],
+ title: 'Spring sale plan',
+ summary: 'Ben checked 2 shops, Cody drafted the email, you picked 15%',
+ status: 'completed',
+ timestamp: at('22:45:00'),
+ link: { thread_id: null, channel_id: AWAY_CHANNEL.id, direct_kwant_id: null },
+ group: 'finished',
+ sort_key: [4, 0, 1, 'Ann', 'tj-spring'],
+ unread: false,
+ changed: true,
+ result_message_id: 'm-spring',
+ result_conversation_id: AWAY_CHANNEL.id,
+ result_thread_id: null,
+ result_link: { thread_id: null, channel_id: AWAY_CHANNEL.id, direct_kwant_id: null },
+ answer_excerpt: 'Done: Ben checked 2 shops, Cody drafted the sale email, and you picked 15% off. The draft is in the channel.',
+ trail: [
+ { at: at('22:31:04'), kind: 'page', label: 'Opened beanline.example.com', detail: 'House Blend 1 kg $24.00', status: 'ok', by: 'Ben' },
+ { at: at('22:33:40'), kind: 'page', label: 'Opened roastco.example.com', detail: null, status: 'error', by: 'Ben' },
+ { at: at('22:38:12'), kind: 'write', label: 'Drafted the sale email', detail: 'Spring sale: 15% off', status: 'ok', by: 'Cody' },
+ { at: at('22:41:30'), kind: 'message', label: 'Sent the draft to the list', detail: null, status: 'skipped', by: 'Cody' },
+ ],
+ trail_dropped: 3,
+ why: 'Plan a spring sale for the house blend and draft the email.',
+ why_kind: 'request',
+ source: { kind: 'team_job', delegation_id: 'dl-1' },
+};
+
+export const AWAY_INBOX: InboxResponse = {
+ now: NOW,
+ since: at('00:50:00', '2026-11-05'),
+ last_seen: at('22:50:00'),
+ counts: {
+ waiting_on_you: 1,
+ failed_or_stuck: 0,
+ to_review: 1,
+ finished: 2,
+ badge: 2,
+ },
+ items: [approval, AWAY_ROUTINE_REVIEW, runRow, AWAY_TEAM_JOB],
+ batch: null,
+} as InboxResponse;
+
+export const AWAY_ROUTINE: Routine = {
+ id: 'rt-prices',
+ kwant_id: 'k-ben',
+ channel_id: AWAY_CHANNEL.id,
+ name: 'Competitor prices',
+ instructions: 'Check Beanline and RoastCo prices and tell me what changed since last week.',
+ schedule: { type: 'weekly', weekdays: ['mon'], time: '09:00', tz: 'UTC' },
+ enabled: true,
+ next_run_at: at('09:00:00', '2026-11-16'),
+ last_run_at: at('22:51:00'),
+ last_status: 'ok',
+ created_at: at('10:12:00'),
+ thread_id: null,
+};
+
+export const AWAY_RUN: RoutineRun = {
+ id: 'run-1',
+ routine_id: 'rt-prices',
+ trigger: 'manual',
+ started_at: at('22:51:00'),
+ ended_at: at('22:51:10'),
+ status: 'ok',
+ error: null,
+ message_id: 'm-prices',
+};
+
+/** A finished hand-off with no review task and none of part B's fields (an older server). */
+export const AWAY_HANDOFF: InboxItem = {
+ kind: 'delegation',
+ id: 'd-spring',
+ kwant_id: 'k-cody',
+ kwant_name: 'Cody',
+ title: 'Spring sale email',
+ summary: 'Drafted the sale email for the list.',
+ status: 'completed',
+ timestamp: at('22:45:00'),
+ link: { thread_id: null, channel_id: AWAY_CHANNEL.id, direct_kwant_id: null },
+ group: 'finished',
+ sort_key: [4, 0, 2, 'Cody', 'd-spring'],
+};
+
+const step = (id: string, t: string, title: string, detail: string, kind = 'tool') => ({
+ id,
+ kind,
+ status: 'ok',
+ title,
+ detail,
+ started_at: at(t),
+ ended_at: at(t),
+});
+
+export const AWAY_MESSAGE: DoneMessage = {
+ id: 'm-prices',
+ created_at: at('22:51:10'),
+ text: [
+ 'No change since last week. Beanline is still the cheapest at $24.00 per kg.',
+ '',
+ '| Shop | 1 kg house blend | 250 g | Offer | vs last week |',
+ '|---|---|---|---|---|',
+ '| Beanline | $24.00 | $13.50 | 15% off until Mar 31 | no change |',
+ '| RoastCo | $27.00 | $15.00 | Free shipping over $40 | no change |',
+ ].join('\n'),
+ meta: {
+ activity: {
+ steps: [
+ {
+ id: 's0',
+ kind: 'thinking',
+ status: 'done',
+ title: 'Thinking',
+ started_at: at('22:51:01'),
+ },
+ step('s1', '22:51:02', 'Opened beanline.example.com', 'found House Blend 1 kg $24.00, 15% off until Mar 31'),
+ step('s2', '22:51:05', 'Opened roastco.example.com', 'found 1 kg $27.00, free shipping over $40'),
+ step('s3', '22:51:09', 'Compared with last Monday’s run', 'nothing changed'),
+ ],
+ dropped: 0,
+ },
+ },
+};
+
+export const AWAY_TARGET: MessageTarget = {
+ message_id: 'm-prices',
+ channel_id: AWAY_CHANNEL.id,
+ kwant_id: 'k-ben',
+ thread_id: null,
+};
+
+/** What the pane loads for the routine review, already loaded. */
+export const AWAY_DETAIL: DoneDetailData = {
+ loading: false,
+ error: null,
+ routine: AWAY_ROUTINE,
+ run: AWAY_RUN,
+ message: AWAY_MESSAGE,
+ target: AWAY_TARGET,
+};
+
+/** A DoneApi over the data above, recording its calls. */
+export function awayDoneApi(calls: string[] = []): DoneApi {
+ return {
+ routines: async () => (calls.push('routines'), [AWAY_ROUTINE]),
+ runs: async (id) => (calls.push(`runs:${id}`), [AWAY_RUN]),
+ message: async (t) => (calls.push(`message:${t.message_id}`), t.message_id === AWAY_MESSAGE.id ? AWAY_MESSAGE : null),
+ };
+}
+
+export const awayPlaceName = (id: string | null): string | null => (id === AWAY_CHANNEL.id ? '@Spring launch' : null);
diff --git a/frontend/src/reviewItem.ts b/frontend/src/reviewItem.ts
index d31dcdfb..7fea3595 100644
--- a/frontend/src/reviewItem.ts
+++ b/frontend/src/reviewItem.ts
@@ -119,11 +119,16 @@ export const changePrefill = (question: string): string => `Change: ${question}
export const lastRound = (r: ReviewItem['round']): boolean => r.n >= r.max;
/** The Send back panel's "what happens" list (Mira §6), in order. */
-export function sendBackSteps(i: Pick<ReviewItem, 'kwant_name' | 'round' | 'held_actions' | 'evidence'>, openHeld: number): string[] {
+export function sendBackSteps(i: Pick<ReviewItem, 'kwant_name' | 'round' | 'held_actions' | 'evidence'>, openHeld: number, noChecks = false): string[] {
const out: string[] = [];
if (openHeld > 0) out.push(heldDeniedFirst(i, openHeld));
- out.push(`${i.kwant_name} starts round ${i.round.n + 1} with your note, the checker’s findings and the work so far.`);
- out.push('The checker then checks everything again, including what passed.');
+ if (noChecks) {
+ // A run with no checks has no checker: the note and the work so far are all the next round gets.
+ out.push(`${i.kwant_name} starts round ${i.round.n + 1} with your note and the work so far.`);
+ } else {
+ out.push(`${i.kwant_name} starts round ${i.round.n + 1} with your note, the checker’s findings and the work so far.`);
+ out.push('The checker then checks everything again, including what passed.');
+ }
out.push(`This is round ${i.round.n} of ${i.round.max}. After round ${i.round.max} it comes back to you, whatever the verdict.`);
return out;
}
diff --git a/frontend/tests/inboxAway095.test.mjs b/frontend/tests/inboxAway095.test.mjs
new file mode 100644
index 00000000..fc2230be
--- /dev/null
+++ b/frontend/tests/inboxAway095.test.mjs
@@ -0,0 +1,350 @@
+// 0.9.5 F (release-095/inbox-away/brief.md): Inbox "Done while you were away". Sections, the done pane's
+// order and copy (mockup 2), Looks good / Ask to redo, Roll back only when something changed, the 7-day
+// footer, and the routine History link to a run's result.
+process.env.TZ = 'UTC';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/inbox', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'HTMLTextAreaElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'DOMParser', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.IS_REACT_ACT_ENVIRONMENT = false;
+const fetched = [];
+const notFound = async (url) => (fetched.push(String(url)), { ok: false, status: 404, json: async () => ({}) });
+g.fetch = notFound;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export * as away from './src/doneAway';
+ export * as fx from './src/doneAwayFixture';
+ export * as store from './src/inboxStore';
+ export { InboxNew } from './src/components/InboxNew';
+ export { DoneItemView, useDoneDetail } from './src/components/DoneDetail';
+ export { RoutinesPanel, runResultTarget } from './src/components/RoutinesPanel';
+`);
+const { React, createRoot, away: a, fx, store: s } = m;
+const h = React.createElement;
+const settle = async (n = 12) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const clone = (x) => JSON.parse(JSON.stringify(x));
+const click = async (b) => {
+ b.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+
+async function mountInbox(props = {}, data = clone(fx.AWAY_INBOX)) {
+ document.body.innerHTML = '';
+ sessionStorage.clear();
+ window.history.replaceState(null, '', '/inbox');
+ s.inboxStore.reset();
+ s.inboxSource.get = async () => data;
+ s.inboxStore.patch({ data });
+ const el = document.createElement('div');
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ root.render(h(m.InboxNew, { onOpen: () => {}, noLoad: true, wide: true, now: Date.parse(data.now), placeName: fx.awayPlaceName, ...props }));
+ await settle();
+ return { el, root, q: (x) => el.querySelector(x), qa: (x) => [...el.querySelectorAll(x)] };
+}
+
+test('sections: Needs you holds waiting and failed, Done holds to review and finished; a routine run folds into its review', () => {
+ const r = a.sectionItems(fx.AWAY_INBOX);
+ assert.deepEqual(r.needs.map((i) => i.id), ['ap-1']);
+ assert.deepEqual(r.done.map((i) => i.id), ['r-prices', 'tj-spring'], 'the run row is folded, the team job stays');
+ assert.equal(r.runFor['r-prices'].id, 'run-1');
+ // A run of another routine, or one far from the review's time, is not folded.
+ const far = clone(fx.AWAY_INBOX);
+ far.items.find((i) => i.id === 'run-1').timestamp = '2026-11-11T20:00:00Z';
+ assert.deepEqual(a.sectionItems(far).done.map((i) => i.id), ['r-prices', 'run-1', 'tj-spring']);
+ assert.equal(a.rowKicker(fx.AWAY_ROUTINE_REVIEW), 'Routine');
+ assert.equal(a.doneTitle(fx.AWAY_ROUTINE_REVIEW), 'Competitor prices');
+});
+
+test('meta line: what ran, when, and why; without the run it leaves the why out', () => {
+ const it = fx.AWAY_ROUTINE_REVIEW;
+ assert.equal(a.metaLine(it, fx.AWAY_ROUTINE, fx.AWAY_RUN), 'Ben · routine, every Mon 09:00 · ran 22:51 because you pressed Run now');
+ assert.equal(a.metaLine(it, fx.AWAY_ROUTINE, { ...fx.AWAY_RUN, trigger: 'schedule' }), 'Ben · routine, every Mon 09:00 · ran 22:51 on schedule');
+ assert.equal(a.metaLine({ ...it, source: undefined }, null, null), 'Ben · routine · ran 22:51');
+ // Part B's source.trigger, when the run isn't loaded; an app event says so (Needs B 5).
+ assert.equal(a.metaLine(it, null, null), 'Ben · routine · ran 22:51 because you pressed Run now');
+ assert.equal(a.metaLine({ ...it, source: { ...it.source, trigger: 'event' } }, null, null), 'Ben · routine · ran 22:51 on an app event');
+ assert.equal(a.metaLine(it, fx.AWAY_ROUTINE, { ...fx.AWAY_RUN, trigger: 'event' }), 'Ben · routine, every Mon 09:00 · ran 22:51 on an app event');
+ assert.equal(a.scheduleShort({ type: 'daily', time: '08:30', tz: 'UTC' }), 'every day 08:30');
+ assert.equal(a.scheduleShort({ type: 'interval', every_minutes: 120 }), 'every 2 h');
+ assert.equal(a.scheduleShort(null), '');
+});
+
+test('trail: tool steps at their own time, thinking left out, then where the answer was written', () => {
+ const rows = a.trailFrom(fx.AWAY_MESSAGE, '@Spring launch');
+ assert.deepEqual(rows.map((r) => `${r.at} ${r.what}${r.detail ? ' · ' + r.detail : ''}`), [
+ '22:51:02 Opened beanline.example.com · found House Blend 1 kg $24.00, 15% off until Mar 31',
+ '22:51:05 Opened roastco.example.com · found 1 kg $27.00, free shipping over $40',
+ '22:51:09 Compared with last Monday’s run · nothing changed',
+ '22:51:10 Wrote the answer in @Spring launch',
+ ]);
+ assert.deepEqual(a.trailFrom({ ...fx.AWAY_MESSAGE, meta: null }, 'x'), [], 'no saved steps: no made-up trail');
+ assert.deepEqual(a.trailFrom(null, 'x'), []);
+});
+
+test('changed: the item field wins, then meta.changed, then rollback_ok; Roll back hides when nothing changed', () => {
+ const it = fx.AWAY_ROUTINE_REVIEW;
+ assert.equal(a.changedState(it, null), false);
+ const noField = { ...it, changed: undefined };
+ assert.equal(a.changedState(noField, { ...fx.AWAY_MESSAGE, meta: { changed: false } }), false);
+ assert.equal(a.changedState(noField, null), true, 'rollback_ok means there is something to roll back');
+ assert.equal(a.changedState({ ...noField, rollback_ok: false }, null), null);
+ assert.equal(a.rollbackShown(it, false), false);
+ assert.equal(a.rollbackShown(it, null), true);
+ assert.equal(a.rollbackShown({ ...it, rollback_ok: false }, true), false);
+ assert.equal(a.noChecksSet(it), true);
+});
+
+test('queue: Needs you · 1 then Done while you were away · 2, kicker and place, unread dots, the 7-day footer', async () => {
+ const { q, qa, root } = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL } });
+ assert.deepEqual(qa('[data-section]').map((x) => x.getAttribute('data-section')), ['needs', 'done']);
+ const heads = qa('[data-section] > h3').map((x) => x.textContent.replace(/\s+/g, ' ').trim());
+ assert.match(heads[0], /Needs you · 1/);
+ assert.match(heads[1], /Done while you were away · 2/);
+ assert.equal(q('[data-row="ap-1"]').textContent.includes('@Spring launch · Ann'), true);
+ assert.equal(q('[data-row="r-prices"] [data-kicker]').textContent, 'Routine · ');
+ assert.equal(q('[data-row="r-prices"] [data-done-summary]').textContent, 'No change since last week. Beanline still cheapest.');
+ assert.equal(q('[data-row="run-1"]'), null, 'the run is folded into its review');
+ assert.equal(q('[data-row="tj-spring"] [data-done-summary]').textContent, 'Ben checked 2 shops, Cody drafted the email, you picked 15%');
+ // Needs B 2: a team job names the team's size where a row names its bot.
+ assert.equal(q('[data-row="tj-spring"]').textContent.includes('@Spring launch · 3 bots'), true);
+ // Needs B 1: the header counts what is new, unread rows get a dot with "New" for screen readers.
+ assert.equal(q('[data-inbox-new] h2 + p').textContent, '2 new since you last looked, 2 h ago');
+ assert.equal(q('[data-row="r-prices"] [data-unread]').textContent, 'New');
+ assert.ok(q('[data-row="ap-1"] [data-unread]'));
+ assert.equal(q('[data-row="tj-spring"] [data-unread]'), null, 'a read row has no dot');
+ assert.equal(q('[data-done-footer]').textContent, 'Done items stay here for 7 days.');
+ assert.equal(q('[data-earlier]'), null, 'Earlier this week is gone: the list already holds 7 days');
+ root.unmount();
+});
+
+test('approval row: its own question when sent, else the card action; title alone is never used', async () => {
+ const data = clone(fx.AWAY_INBOX);
+ let r = await mountInbox({}, data);
+ const title = (q) => q('[data-row="ap-1"]').textContent;
+ assert.match(title(r.q), /Approve “Spring sale: 15% off”\?/);
+ // F6: the subline still says what the bot wants to use.
+ assert.equal(r.q('[data-row="ap-1"] [data-approval-use]').textContent, '· use gmail');
+ r.root.unmount();
+ const bare = clone(fx.AWAY_INBOX);
+ const ap = bare.items.find((x) => x.id === 'ap-1');
+ delete ap.question;
+ ap.title = 'Use gmail (mail)';
+ r = await mountInbox({}, bare);
+ assert.equal(title(r.q).includes('Use gmail (mail)'), false, 'no raw server title');
+ assert.equal(title(r.q).includes('Approve “Spring sale'), false);
+ assert.equal(r.q('[data-row="ap-1"] [data-approval-use]'), null, 'no question: the title already names the tool');
+ r.root.unmount();
+});
+
+test('pane order: meta, chips, answer with Open in chat, What Ben did, Why, then Looks good and Ask Ben to redo…', async () => {
+ const opened = [];
+ const edits = [];
+ const { q, qa, root } = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL }, onOpenMessage: (t) => opened.push(t), onEditRoutine: (id) => edits.push(id) });
+ await click(q('[data-option="r-prices"]'));
+ const pane = q('[data-done-answer]').closest('section[role="region"], [data-review-item], div');
+ assert.ok(pane);
+ const order = ['[data-done-meta]', '[data-done-chips]', '[data-done-answer]', '[data-done-trail]', '[data-done-why]', '[data-approve]'];
+ const els = order.map((x) => q(x));
+ els.forEach((e, i) => assert.ok(e, `${order[i]} is drawn`));
+ for (let i = 1; i < els.length; i++) {
+ assert.ok(els[i - 1].compareDocumentPosition(els[i]) & Node.DOCUMENT_POSITION_FOLLOWING, `${order[i - 1]} comes before ${order[i]}`);
+ }
+ assert.equal(q('[data-done-meta]').textContent, 'Ben · routine, every Mon 09:00 · ran 22:51 because you pressed Run now');
+ assert.match(q('[data-chip="read-only"]').textContent, /Read only · changed nothing/);
+ assert.match(q('[data-chip="no-checks"]').textContent, /No checks set · Add one/);
+ // F2: a neutral chip, not amber; F1: the inline links stay compact and keep the 44 px tap area.
+ assert.equal(/amber/.test(q('[data-chip="no-checks"]').className), false);
+ for (const x of ['[data-add-check]', '[data-open-in-chat]', '[data-edit-routine]']) {
+ assert.ok(q(x).hasAttribute('data-compact'), `${x} is compact`);
+ assert.match(q(x).className, /kw-hit/);
+ }
+ // F5: the answer's scroller is a focusable, named region; on a phone its cells don't wrap.
+ const ans = q('[data-answer-text]');
+ assert.equal(ans.getAttribute('tabindex'), '0');
+ assert.equal(ans.getAttribute('role'), 'region');
+ assert.equal(ans.getAttribute('aria-label'), 'Ben’s answer');
+ assert.match(ans.className, /max-sm:\[&_td\]:whitespace-nowrap/);
+ assert.match(q('[data-done-answer] h3').textContent, /Ben’s answer/);
+ assert.ok(q('[data-done-answer] table'), 'the answer is the message, table and all');
+ assert.equal(q('[data-done-answer]').innerHTML.includes('<script'), false);
+ assert.match(q('[data-done-trail] h3').textContent, /What Ben did/);
+ assert.equal(qa('[data-trail-row]').length, 4);
+ assert.match(q('[data-why-quote]').textContent, /^Check Beanline and RoastCo prices/);
+ assert.match(q('[data-done-why]').textContent, /You set up this routine on Nov 11:/);
+ assert.equal(q('[data-approve]').textContent.trim(), 'Looks good');
+ assert.equal(q('[data-send-back]').textContent.trim(), 'Ask Ben to redo…');
+ assert.equal(qa('kbd').length, 0, 'no letter hints on the buttons');
+ assert.equal(q('[data-approve]').getAttribute('aria-keyshortcuts'), 'A', 'the shortcut stays');
+ assert.equal(q('[data-roll-back]'), null, 'nothing changed: no Roll back');
+ assert.equal(q('[data-verdict]'), null, 'no checks: no verdict box');
+ await click(q('[data-open-in-chat]'));
+ assert.deepEqual(opened, [fx.AWAY_TARGET]);
+ await click(q('[data-edit-routine]'));
+ await click(q('[data-add-check]'));
+ assert.deepEqual(edits, ['rt-prices', 'rt-prices']);
+ // Re-check 4: with no checks set, Ask Ben to redo promises no checker.
+ await click(q('[data-send-back]'));
+ const steps = q('[data-send-panel] ul').textContent;
+ assert.match(steps, /Ben starts round \d+ with your note and the work so far\./);
+ assert.equal(/checker/.test(steps), false);
+ root.unmount();
+});
+
+test('a review that changed something keeps Roll back; a non-routine review keeps its old layout', async () => {
+ const data = clone(fx.AWAY_INBOX);
+ data.items.find((i) => i.id === 'r-prices').changed = true;
+ const { q, root } = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL } }, data);
+ await click(q('[data-option="r-prices"]'));
+ assert.ok(q('[data-roll-back]'), 'Roll back shows when something changed');
+ assert.equal(q('[data-chip="read-only"]'), null);
+ root.unmount();
+});
+
+test('a team job opens in the pane: led-by meta, the lead’s answer, the team’s trail with who, skipped and dropped steps, Why', async () => {
+ const opened = [];
+ const { q, qa, root } = await mountInbox({ onOpenMessage: (t) => opened.push(t) });
+ await click(q('[data-option="tj-spring"]'));
+ assert.equal(q('[data-done-meta]').textContent, 'Ann led Ben and Cody · finished 22:45');
+ assert.equal(q('[data-done-answer] h3').textContent, 'Ann’s answer');
+ assert.match(q('[data-answer-text]').textContent, /^Done: Ben checked 2 shops/, 'the served excerpt, as text');
+ assert.equal(q('[data-done-trail] h3').textContent, 'What the team did');
+ assert.equal(q('[data-trail-dropped]').textContent.trim(), '3 more steps before these');
+ const rows = qa('[data-trail-row]');
+ assert.equal(rows.length, 5, 'four steps, then the answer');
+ assert.equal(rows[0].querySelector('[data-trail-by]').textContent, 'Ben');
+ assert.match(rows[0].textContent, /Ben · Opened beanline\.example\.com · House Blend/);
+ assert.equal(rows[1].getAttribute('data-status'), 'error');
+ assert.ok(rows[1].querySelector('[aria-label="Failed"]'));
+ // Re-check 1: the bot's name leads, then the icon, then what happened and the word "failed".
+ assert.equal(rows[1].querySelector('span').firstElementChild.hasAttribute('data-trail-by'), true, 'the name comes first');
+ assert.match(rows[1].textContent, / · failed( · |$)/);
+ assert.ok(rows[1].querySelector('[data-trail-by]').compareDocumentPosition(rows[1].querySelector('[aria-label="Failed"]')) & Node.DOCUMENT_POSITION_FOLLOWING);
+ assert.equal(rows[3].getAttribute('data-status'), 'skipped');
+ assert.match(rows[3].textContent, /Cody · Sent the draft to the list · skipped/);
+ assert.equal(rows[3].querySelector('[aria-label="Failed"]'), null, 'skipped: no icon');
+ assert.match(rows[3].lastElementChild.className, /text-zinc-400/);
+ assert.match(rows[4].textContent, /Wrote the answer in @Spring launch/);
+ assert.match(q('[data-done-why]').textContent.replace(/\s+/g, ' '), /You asked: Plan a spring sale for the house blend and draft the email\.$/);
+ assert.equal(q('[data-done-why]').getAttribute('data-done-why'), 'request');
+ assert.equal(q('[data-why-quote]').textContent, 'Plan a spring sale for the house blend and draft the email.');
+ assert.equal(q('[data-redo]').textContent.trim(), 'Ask Ann to redo in chat');
+ await click(q('[data-redo]'));
+ assert.deepEqual(opened, [{ message_id: 'm-spring', channel_id: 'c-spring', kwant_id: 'k-ann', thread_id: null }], 'opens the lead’s answer');
+ root.unmount();
+});
+
+test('F7: a finished hand-off with no review and no part B fields: summary answer, Ask Cody to redo in chat opens its chat', async () => {
+ const data = clone(fx.AWAY_INBOX);
+ data.items.push(clone(fx.AWAY_HANDOFF));
+ const chats = [];
+ const { q, root } = await mountInbox({ onOpen: (i) => chats.push(i.id) }, data);
+ await click(q('[data-option="d-spring"]'));
+ assert.equal(q('[data-done-meta]').textContent, 'Cody · finished 22:45');
+ assert.match(q('[data-answer-text]').textContent, /Drafted the sale email/);
+ assert.equal(q('[data-done-trail]'), null, 'no trail for a job the API has no steps for');
+ assert.equal(q('[data-redo]').textContent.trim(), 'Ask Cody to redo in chat');
+ await click(q('[data-redo]'));
+ assert.deepEqual(chats, ['d-spring']);
+ root.unmount();
+});
+
+test('Why for a task and a hand-off (Needs B 3)', () => {
+ const base = { ...fx.AWAY_HANDOFF, why: 'Check the RoastCo price' };
+ assert.equal(a.whyLead({ ...base, why_kind: 'task' }), 'The task said:');
+ assert.equal(a.whyLead({ ...base, why_kind: 'ask' }), 'You asked Cody:');
+ // Re-check 7: no date from the finish time; a date only from the ask's own time.
+ assert.equal(a.whyLead({ ...base, why_kind: 'request' }), 'You asked:');
+ assert.equal(a.whyLead({ ...base, why_kind: 'request', why_at: '2026-11-10T21:00:00Z' }), 'You asked on Nov 10:');
+ assert.equal(a.whyLead({ ...base, why_kind: 'routine' }), null, 'routines keep their own copy');
+ assert.equal(a.whyLead({ ...base, why: ' ', why_kind: 'task' }), null);
+ assert.equal(a.ledLine({ ...fx.AWAY_TEAM_JOB, members: [1, 2, 3, 4].map((n) => ({ kwant_id: `k${n}`, kwant_name: `B${n}` })) }), 'Ann led B1, B2 and 2 more');
+ assert.equal(a.teamSize({ ...fx.AWAY_TEAM_JOB, members: [] }), '1 bot');
+ assert.equal(a.teamSize({ ...fx.AWAY_TEAM_JOB, members: undefined }), null, 'no members field: no count');
+});
+
+test('the pane loads routine, run and message itself through the done api', async () => {
+ const calls = [];
+ const { q, root } = await mountInbox({ doneApi: fx.awayDoneApi(calls) });
+ await click(q('[data-option="r-prices"]'));
+ await settle(20);
+ assert.deepEqual(calls, ['routines', 'runs:rt-prices', 'message:m-prices']);
+ assert.equal(q('[data-done-meta]').textContent, 'Ben · routine, every Mon 09:00 · ran 22:51 because you pressed Run now');
+ assert.equal(q('[data-chip="read-only"]') !== null, true);
+ root.unmount();
+});
+
+test('header: n new, nothing new, and today’s window line on a server older than part B; Done’s empty line', async () => {
+ const now = Date.parse(fx.AWAY_INBOX.now);
+ assert.equal(a.unreadLine(fx.AWAY_INBOX, now), '2 new since you last looked, 2 h ago');
+ const none = clone(fx.AWAY_INBOX);
+ none.items.forEach((i) => (i.unread = false));
+ assert.equal(a.unreadLine(none, now), 'Nothing new since you last looked, 2 h ago');
+ const old = clone(fx.AWAY_INBOX);
+ old.items.forEach((i) => delete i.unread);
+ old.since = old.last_seen;
+ assert.equal(a.unreadLine(old, now), null);
+ const empty = { ...clone(fx.AWAY_INBOX), items: [] };
+ assert.equal(a.unreadLine(empty, now), 'Nothing new since you last looked, 2 h ago', 'a 7-day window with nothing in it');
+ const doneless = clone(fx.AWAY_INBOX);
+ doneless.items = doneless.items.filter((i) => i.group === 'waiting_on_you');
+ const { q, root } = await mountInbox({}, doneless);
+ assert.equal(q('[data-section="done"] p').textContent, 'Nothing finished in the last 7 days.');
+ assert.equal(q('[data-done-footer]'), null, 'Re-check 5: no footer under an empty Done');
+ assert.match(q('[data-section="done"] h3').textContent, /· 0/);
+ root.unmount();
+});
+
+test('F3: after Looks good the notice uses the button’s words and the routine’s name; a failure says nothing was saved', async () => {
+ g.fetch = async (url) => (fetched.push(String(url)), { ok: true, status: 200, json: async () => ({}) });
+ let r = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL } });
+ await click(r.q('[data-option="r-prices"]'));
+ await click(r.q('[data-approve]'));
+ await settle(20);
+ assert.equal(r.q('[data-inbox-status]').textContent, 'Looks good: “Competitor prices”.');
+ r.root.unmount();
+ g.fetch = async (url) => (fetched.push(String(url)), { ok: false, status: 500, json: async () => ({ error: 'Disk full.' }) });
+ r = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL } });
+ await click(r.q('[data-option="r-prices"]'));
+ await click(r.q('[data-approve]'));
+ await settle(20);
+ assert.equal(r.q('[data-review-status]').textContent, 'Couldn’t save “Competitor prices”. Disk full. Nothing was saved.');
+ r.root.unmount();
+ g.fetch = notFound;
+});
+
+test('F4: on a phone, Ask Ben to redo… spans the row when there is no Roll back', async () => {
+ const mm = window.matchMedia;
+ window.matchMedia = (query) => ({ matches: /max-width/.test(query), media: query, addEventListener() {}, removeEventListener() {} });
+ try {
+ let r = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL } });
+ await click(r.q('[data-option="r-prices"]'));
+ assert.match(r.q('[data-send-back]').className, /col-span-2/);
+ r.root.unmount();
+ const data = clone(fx.AWAY_INBOX);
+ data.items.find((i) => i.id === 'r-prices').changed = true;
+ r = await mountInbox({ doneDetails: { 'r-prices': fx.AWAY_DETAIL } }, data);
+ await click(r.q('[data-option="r-prices"]'));
+ assert.ok(r.q('[data-roll-back]'));
+ assert.equal(/col-span-2/.test(r.q('[data-send-back]').className), false, 'with Roll back, the two share the row');
+ r.root.unmount();
+ } finally {
+ window.matchMedia = mm;
+ }
+});
+
+test('routine History: a run with a result message links to it', () => {
+ assert.deepEqual(m.runResultTarget(fx.AWAY_ROUTINE, fx.AWAY_RUN), fx.AWAY_TARGET);
+ assert.equal(m.runResultTarget(fx.AWAY_ROUTINE, { ...fx.AWAY_RUN, message_id: null }), null);
+});
diff --git a/frontend/tests/inboxV1.test.mjs b/frontend/tests/inboxV1.test.mjs
index 3f86dafa..76addd03 100644
--- a/frontend/tests/inboxV1.test.mjs
+++ b/frontend/tests/inboxV1.test.mjs
@@ -107,7 +107,11 @@ test('Inbox › New, wide: 392px queue, item pane with the first review selected
s.select(null);
const d = doc(html(React.createElement(m.InboxNew, { noLoad: true, wide: true, now: Date.parse(m.INBOX_FIXTURE.now) })));
assert.ok(d.querySelector('[data-inbox-new="wide"] .w-\\[392px\\]'));
- assert.deepEqual([...d.querySelectorAll('[data-section]')].map((n) => n.getAttribute('data-section')), ['waiting_on_you', 'failed_or_stuck', 'to_review', 'finished']);
+ // 0.9.5 F: two sections; rows keep the server's group order inside them.
+ assert.deepEqual([...d.querySelectorAll('[data-section]')].map((n) => n.getAttribute('data-section')), ['needs', 'done']);
+ const groupsIn = (k) => [...new Set([...d.querySelectorAll(`[data-section="${k}"] [data-group]`)].map((n) => n.getAttribute('data-group')))];
+ assert.deepEqual(groupsIn('needs'), ['waiting_on_you', 'failed_or_stuck']);
+ assert.deepEqual(groupsIn('done'), ['to_review', 'finished']);
const card = d.querySelector('[data-batch-card]');
assert.ok(card);
assert.match(d.querySelector('[data-approve-all]').textContent, /Approve all 5/);
diff --git a/frontend/tests/reviewItemView.test.mjs b/frontend/tests/reviewItemView.test.mjs
index 8ca9f7b4..6e6ec9ac 100644
--- a/frontend/tests/reviewItemView.test.mjs
+++ b/frontend/tests/reviewItemView.test.mjs
@@ -98,6 +98,12 @@ test('helpers: summaries come from the server numbers, tail keeps 12 lines', ()
assert.equal(m.notUndoneTitle({ effects_known: true, external_not_undone: [] }), null);
assert.equal(m.sendBackSteps(FX.needsYou, 1)[0], 'The held merge of #512 is denied first, so nothing runs.');
assert.equal(m.sendBackSteps(FX.heldDenied, 0).some((s) => /denied first/.test(s)), false);
+ const withChecks = m.sendBackSteps(FX.heldDenied, 0);
+ const noChecks = m.sendBackSteps(FX.heldDenied, 0, true);
+ assert.equal(noChecks.length, withChecks.length - 1, 'no-checks drops the checker line');
+ assert.equal(noChecks.some((s) => /checker/.test(s)), false);
+ assert.match(noChecks[0], /starts round \d+ with your note and the work so far\.$/);
+ assert.equal(noChecks.at(-1), withChecks.at(-1), 'the round line stays');
});
test('invalid data falls back to the plain card with the title and summary as text', async () => {