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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.9 V1: Review inbox shell and Approve all (#506)
Oleksandr Ivanchenko9e943d15afdd
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 5ca84e57..86a0ce33 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -46,7 +46,9 @@ import { HireCard, type HireDecision } from './components/HireCard';import { RouteChoiceCard } from './components/RouteChoiceCard';import { RouteChoiceMeta, applyRouteChoice, correctRoute, isAskingReply, rerouteTargetsFor, resolveRouteChoice } from './routeChoice';import type { RoutineFocus } from './components/RoutinesPanel';-import { AwayPage } from './components/AwayView';+import { InboxNew } from './components/InboxNew';+import { inboxBadge, isReview, type InboxItem } from './api/inbox';+import { batchItems, inboxNav, loadInbox, openItem, useInbox } from './inboxStore';import { LooseEndsPage } from './components/LooseEndsView';import { MissionBoardPage } from './components/MissionBoardView';import { WatchChatMessage } from './components/MissionWatch';@@ -526,6 +528,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({// A task to open on the board once it shows (from a lesson on a bot's Memory tab).const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);const [awayCount, setAwayCount] = useState(0);+ // 0.9.0 V1: the Inbox store (GET /api/inbox, or /api/away before the server has it).+ const inboxState = useInbox();+ const inboxCount = inboxBadge(inboxState.data, { unseen: { total: awayCount } }, prepushWaiting);+ const reviewItems: InboxItem[] = inboxState.data ? [...inboxState.data.items, ...batchItems(inboxState.data)].filter(isReview) : [];// "Needs you" nudges (attention.ts): what waits on the person, the pill, and the "Show nudges" setting.const [awayWaiting, setAwayWaiting] = useState(0);/** What waits on you right now (approvals, questions), for the phone Chats tab's Needs you. */@@ -555,11 +561,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setOpenedAt((prev) => ({ ...prev, [readChat]: Date.now() }));return () => setOpenedAt((prev) => ({ ...prev, [readChat]: Date.now() }));}, [readChat]);- const awaySinceRef = useRef<string | null>(null);const awayTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);const refreshAwayCount = (delay = 0) => {clearTimeout(awayTimerRef.current);awayTimerRef.current = setTimeout(() => {+ void loadInbox();awayApi.get().then((r) => {setAwayCount(r.unseen.total);setAwayWaiting(r.unseen.waiting);@@ -3733,6 +3739,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({finished: awayDone.finished,busy: busyKwants,status: botStatus,+ reviews: reviewItems,openedAt: page === 'chat' && !isChannel && selectedId ? { ...openedAt, [selectedId]: Date.now() } : openedAt,}): undefined;@@ -3800,7 +3807,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setIsNewChannelOpen(true);playSfx('click');}}- inboxCount={awayCount + prepushWaiting}+ inboxCount={inboxCount}+ onOpenReview={(i: InboxItem) => {+ openItem(i.id, null);+ showPage('inbox', 'new');+ }}inboxActive={page === 'inbox'}onOpenInbox={() => {showPage('inbox');@@ -3838,7 +3849,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({);const away = (- <AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount} onApprovalResolved={dropApproval}+ <InboxNew+ onOpen={openAwayItem}+ onCounts={setAwayCount}+ onApprovalResolved={dropApproval}+ onCrumb={(c) => showPage(c === 'board' ? 'board' : 'dev')}top={<><PrepushNeedsYou cards={prepush.cards} names={kwantNames} onOpen={openPrepush} />@@ -3847,6 +3862,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}/>);+ // The board card, drawer and Dev desk open review items here (crumb set by the caller).+ inboxNav.go = () => showPage('inbox', 'new');const backToList = isPhone ? () => { setPage('chat'); setPhoneView('list'); } : undefined;const parallel = <ParallelPage onBack={backToList} />;const connectionsPage = (@@ -3910,7 +3927,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({addImap={looseAddImap > 0}/>);- const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={awayCount + prepushWaiting} onBack={backToList} newPage={away} loosePage={loose} />;+ const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={inboxCount} onBack={backToList} newPage={away} loosePage={loose} />;const chat = (<ChatViewdropOff={!!spaceSettingsTab}@@ -4150,7 +4167,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({badgeTone: 'violet',badgeNoun: ideaJarCount === 1 ? 'take ready' : 'takes ready',},- { id: 'inbox', label: 'Inbox', icon: <Inbox size={20} aria-hidden="true" />, badge: awayCount + prepushWaiting },+ { id: 'inbox', label: 'Inbox', icon: <Inbox size={20} aria-hidden="true" />, badge: inboxCount },{ id: 'space', label: 'Space', icon: <Settings size={20} aria-hidden="true" /> },];const showPhoneList = isPhone && phoneView === 'list' && !needsSetup;diff --git a/frontend/src/api/inbox.ts b/frontend/src/api/inbox.tsnew file mode 100644index 00000000..a89b1704--- /dev/null+++ b/frontend/src/api/inbox.ts@@ -0,0 +1,478 @@+// 0.9.0 V1 Review inbox: the GET /api/inbox shape (Mira's ENG in release-090/designs/v1-review-inbox.md,+// with Ada's decisions D1-D5), its fetch, a few pure helpers, and a fixture that covers every state on+// v1-states-board. Iris's ReviewItemView imports the types and the fixture; the Inbox store and queue use+// the rest. Nothing here decides what is safe to approve: `one_tap` and `batchable` come from the server.++import { PersonCancelledError, personFetch } from '../auth';+import type { AwayItem, AwayKind } from '../away';++export type InboxKind = AwayKind | 'review';+export type InboxGroup = 'waiting_on_you' | 'failed_or_stuck' | 'to_review' | 'finished';++export type VerdictResult = 'pass' | 'fail' | 'needs_you' | 'none';+export type Confidence = 'high' | 'medium' | 'low';+export type RiskLevel = 'low' | 'medium' | 'high';+export type CriterionStatus = 'met' | 'not_met' | 'not_checked' | 'claim_only';+export type CriterionSource = 'task' | 'person_note' | 'must_not_change';++export interface InboxVerdict {+ /**+ * The verdict record's id (task_verdicts.id), sent back as `verdict_id` on verify so a stale approve+ * gets 409 `stale` (D2). Null when there is no verdict yet ('none').+ */+ id: string | null;+ result: VerdictResult;+ confidence: Confidence | null;+ /** One sentence on why. A Not met criterion's text is in it (Mira §3.6). */+ line: string;+ checker: { engine: string; model: string; tier_note: 'different_tier' | null } | null;+ checked_at: string | null;+ steps_run: number | null;+ steps_total: number | null;+}++export interface InboxCriterion {+ index: number;+ text: string;+ status: CriterionStatus;+ source: CriterionSource;+ evidence: { kind: string; ref: string; label: string } | null;+ note: string | null;+ round_added: number;+}++export interface InboxDecision {+ index: number;+ question: string;+ picked: string;+ why: string;+ /** Always null in 0.9 (D3). */+ cost: 'costly' | 'cheap' | null;+}++export interface InboxCheck {+ name: string;+ command: string;+ result: 'pass' | 'fail';+ summary: string;+ ran_by: 'checker' | 'author';+ output_tail: string;+}++export interface InboxPr {+ repo: string;+ number: number;+ url: string;+ add: number;+ del: number;+ files: number;+ ci: string;+}++export type HeldStatus = 'pending' | 'allowed' | 'denied' | 'expired';++/**+ * One of today's approvals held for this task (D3). Approve never runs it: it has its own Deny /+ * Allow once, resolved with POST /api/approvals/:approval_id/resolve (`allow_once` or `deny` only).+ */+export interface HeldAction {+ approval_id: string;+ tool_name: string;+ summary: string;+ /** The tool and its arguments as they will run, redacted like the approval card. */+ args_display: string;+ gate: 'merge' | 'payment' | 'approval';+ status: HeldStatus;+ resolved_at: string | null;+ /** After it was resolved: what happened ("Merged #512 into main."), else null. */+ result_line: string | null;+}++/** The decisions the item view may send; no `always_allow` from here (D3). */+export type HeldDecision = 'allow_once' | 'deny';++export interface PreviousRound {+ sent_back_at: string;+ note: string;+ flips: { index: number; from: CriterionStatus; to: CriterionStatus }[];+ diff: { files: number; add: number; del: number };+ bot_summary: string;+}++/** Review-only fields; present when `kind === 'review'`. */+export interface ReviewFields {+ task_id: string;+ mission_id?: string | null;+ project?: string | null;+ in_review_since: string;+ round: { n: number; max: number };+ verdict: InboxVerdict;+ risk: { level: RiskLevel | null; reasons: string[] };+ criteria: InboxCriterion[];+ criteria_summary: { met: number; total: number; not_met: number; not_checked: number };+ couldnt_verify: { what: string; why: string }[];+ decisions: { total: number; top: InboxDecision[] };+ evidence: { checks: InboxCheck[]; screenshots: { url: string; caption: string }[]; pr: InboxPr | null };+ /**+ * Today's approvals for this task, shown exactly as they will run with their own Deny / Allow once.+ * Approve stays disabled while any is `pending` (D3); resolved ones stay listed with their result.+ */+ held_actions: HeldAction[];+ previous_round: PreviousRound | null;+ /** Set when an approve failed its freshness check; the item is then in failed_or_stuck. */+ stale: { paths: string[]; at: string } | null;+ /** Only server errors on verify; never from held actions (D3). */+ approve_error: { code: string; message: string } | null;+ /** Both false whenever any held action is pending (server-computed). */+ one_tap: boolean;+ batchable: boolean;+ rollback_ok: boolean;+}++// `task_id` is a review's task (ReviewFields) or a watch item's (P1, null when none), so it takes both.+export type InboxItem = Omit<AwayItem, 'kind' | 'task_id'> & {+ kind: InboxKind;+ group: InboxGroup;+ sort_key: (string | number)[];+ task_id?: string | null;+} & Partial<Omit<ReviewFields, 'task_id'>>;++/** A review item, with every review field present. */+export type ReviewItem = Omit<InboxItem, keyof ReviewFields> & ReviewFields & { kind: 'review' };++export interface InboxCounts {+ waiting_on_you: number;+ failed_or_stuck: number;+ to_review: number;+ finished: number;+ /** Today's unseen.total + open review items; the Low-risk card counts 1. Absent on older servers. */+ badge?: number;+}++export interface InboxResponse {+ now: string;+ since: string;+ last_seen: string | null;+ counts: InboxCounts;+ /** Already sorted by sort_key. Items in `batch.ids` are left out; the client draws the card. */+ items: InboxItem[];+ /** The Low-risk card; null when fewer than 2 qualify. */+ batch: { ids: string[]; count: number } | null;+ /** The batch's items, so the card can list them. Optional: older shapes send only ids. */+ batch_items?: InboxItem[];+}++export const INBOX_GROUPS: { key: InboxGroup; label: string; hint: string; empty: string }[] = [+ { key: 'waiting_on_you', label: 'Waiting on you', hint: 'oldest first', empty: 'No questions or approvals waiting.' },+ { key: 'failed_or_stuck', label: 'Failed or stuck', hint: 'oldest first', empty: 'Nothing failed or stuck.' },+ { key: 'to_review', label: 'To review', hint: 'highest risk first', empty: 'Nothing to review.' },+ { key: 'finished', label: 'Finished', hint: 'not read first, then newest', empty: 'Nothing finished since you last looked.' },+];++export const isReview = (i: InboxItem | null | undefined): i is ReviewItem => !!i && i.kind === 'review' && !!i.task_id;++/** Items per group, in the server's order. */+export function groupItems(r: Pick<InboxResponse, 'items'>): Record<InboxGroup, InboxItem[]> {+ const out: Record<InboxGroup, InboxItem[]> = { waiting_on_you: [], failed_or_stuck: [], to_review: [], finished: [] };+ for (const i of r.items) (out[i.group] ?? out.finished).push(i);+ return out;+}++/**+ * The one Inbox badge: `counts.badge` when the server sends it, else today's sum+ * (`unseen.total + prepushWaiting`).+ */+export function inboxBadge(inbox: Pick<InboxResponse, 'counts'> | null | undefined, away: { unseen: { total: number } } | null | undefined, prepushWaiting = 0): number {+ const b = inbox?.counts?.badge;+ if (typeof b === 'number' && Number.isFinite(b)) return Math.max(0, b);+ return (away?.unseen.total ?? 0) + prepushWaiting;+}++/** The held actions still waiting for Deny / Allow once. */+export const pendingHeld = (item: Pick<ReviewFields, 'held_actions'>): HeldAction[] => item.held_actions.filter((a) => a.status === 'pending');++/**+ * Approve's label. In 0.9 Approve never runs a held action (D3), so it is always "Approve"; while any+ * held action is pending it is disabled and `blocked` says why (and `A` focuses Deny instead).+ */+export function approveState(item: Pick<ReviewFields, 'held_actions'>): { label: string; blocked: string | null } {+ return { label: 'Approve', blocked: pendingHeld(item).length ? 'Allow or deny the held action first' : null };+}++/**+ * Send back and Roll back deny every pending held action first (D3), one at a time. Stops at the+ * first failure and throws it, so the caller shows the error and does not reject or restore.+ */+export async function denyPendingHeld(item: Pick<ReviewFields, 'held_actions'>): Promise<void> {+ for (const a of pendingHeld(item)) await inboxApi.resolveHeld(a.approval_id, 'deny');+}++/** The verdict word Mira's spec shows. */+export const VERDICT_WORD: Record<VerdictResult, string> = { pass: 'Pass', fail: 'Fail', needs_you: 'Needs you', none: 'Not checked yet' };++/** "Pass · high" for the board card, or null with no verdict. */+export function verdictShort(v: Pick<InboxVerdict, 'result' | 'confidence'> | null | undefined): string | null {+ if (!v || v.result === 'none') return null;+ return v.confidence ? `${VERDICT_WORD[v.result]} · ${v.confidence}` : VERDICT_WORD[v.result];+}++// ---- API ----++export class InboxError extends Error {+ constructor(public status: number, message: string, public code: string | null = null, public paths: string[] = []) {+ super(message);+ }+ /** A 409 from verify: the work changed after its check, nothing was approved. */+ get stale(): boolean {+ return this.status === 409 && this.code === 'stale';+ }+}++async function call<T>(method: string, url: string, body?: unknown): Promise<T> {+ let res: Response;+ try {+ res = await personFetch(url, {+ method,+ cache: 'no-store',+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ } catch (e) {+ if (e instanceof PersonCancelledError) throw new InboxError(401, e.message);+ throw new InboxError(0, 'the server didn’t answer');+ }+ const data = await res.json().catch(() => null);+ if (res.ok) return data as T;+ const d = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};+ const msg = typeof d.error === 'string' && d.error ? d.error : `HTTP ${res.status}`;+ const code = typeof d.code === 'string' ? d.code : null;+ const paths = Array.isArray(d.paths) ? d.paths.filter((p): p is string => typeof p === 'string') : [];+ throw new InboxError(res.status, msg, code, paths);+}++const enc = encodeURIComponent;++export const inboxApi = {+ get: (since?: string) => call<InboxResponse>('GET', `/api/inbox${since ? `?since=${enc(since)}` : ''}`),+ /** Approve. Approve all always sends verdict_id; a 409 `stale` throws InboxError with `.stale` and `.paths`. */+ verify: (taskId: string, verdictId?: string | null) =>+ call<unknown>('POST', `/api/tasks/${enc(taskId)}/verify`, verdictId ? { verdict_id: verdictId } : {}),+ reject: (taskId: string, reason: string) => call<unknown>('POST', `/api/tasks/${enc(taskId)}/reject`, { reason }),+ /** Deny / Allow once on a held action (today's approvals endpoint). */+ resolveHeld: (approvalId: string, decision: HeldDecision) =>+ call<unknown>('POST', `/api/approvals/${enc(approvalId)}/resolve`, { decision }),+ /** "Check again" on a stale item. */+ runChecks: (taskId: string) => call<unknown>('POST', `/api/tasks/${enc(taskId)}/checks/run`, {}),+};++// ---- Fixture: every state on v1-states-board ----++const T0 = '2026-11-10T15:20:00Z';+const ago = (min: number) => new Date(Date.parse(T0) - min * 60_000).toISOString();+const link = (kwant: string) => ({ thread_id: null, channel_id: null, direct_kwant_id: kwant });++function review(over: Partial<ReviewItem> & Pick<ReviewItem, 'id' | 'kwant_id' | 'kwant_name' | 'title' | 'group'>): ReviewItem {+ const base: ReviewItem = {+ kind: 'review',+ summary: '',+ status: 'review',+ timestamp: ago(30),+ link: link(over.kwant_id),+ sort_key: [],+ task_id: `t-${over.id}`,+ mission_id: 'm-auth',+ project: 'shop',+ in_review_since: ago(30),+ round: { n: 1, max: 2 },+ verdict: {+ id: `v-${over.id}`,+ result: 'pass',+ confidence: 'high',+ line: 'All 4 criteria are met and every check re-ran clean.',+ checker: { engine: 'Codex', model: 'gpt-5.5-codex', tier_note: null },+ checked_at: ago(25),+ steps_run: 2,+ steps_total: 2,+ },+ risk: { level: 'low', reasons: [] },+ criteria: [+ { index: 1, text: 'Typo fixed in README', status: 'met', source: 'task', evidence: { kind: 'check', ref: 'test.py', label: 'test.py · 4 passed' }, note: null, round_added: 1 },+ ],+ criteria_summary: { met: 1, total: 1, 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,+ ...over,+ } as ReviewItem;+ return base;+}++const CRITERIA_ALL_STATES: InboxCriterion[] = [+ { index: 1, text: 'Met, with evidence', status: 'met', source: 'task', evidence: { kind: 'check', ref: 'test.py', label: 'test.py · 4 passed' }, note: null, round_added: 1 },+ { index: 2, text: 'The table keeps its last row', status: 'not_met', source: 'task', evidence: null, note: 'Checker: “drops the last row at 101 rows”', round_added: 1 },+ { index: 3, text: 'Works on Safari', status: 'not_checked', source: 'task', evidence: null, note: 'No evidence. See “Couldn’t check”.', round_added: 1 },+ { index: 4, text: 'Rate limit is per IP', status: 'claim_only', source: 'task', evidence: null, note: 'Lin says it works; nothing backs it.', round_added: 1 },+ { index: 5, text: 'Show the error under the field, not in a toast', status: 'met', source: 'person_note', evidence: { kind: 'screenshot', ref: 'shot-1', label: 'login-error.png' }, note: null, round_added: 2 },+ { index: 6, text: 'Don’t change the public login URL', status: 'met', source: 'must_not_change', evidence: null, note: null, round_added: 1 },+];++/** Needs you · medium, round 1, high risk: Waiting on you. */+const needsYou = review({+ id: 'r-needs', kwant_id: 'k-lin', kwant_name: 'Lin', title: 'Limit sign-in attempts', group: 'waiting_on_you', sort_key: [1, 0, 1, 'Lin', 'r-needs'],+ timestamp: ago(48), in_review_since: ago(48),+ verdict: { id: 'v-needs', result: 'needs_you', confidence: 'medium', line: 'The checks pass, but Lin assumed per-IP counting.', checker: { engine: 'Codex', model: 'gpt-5.5-codex', tier_note: null }, checked_at: ago(40), steps_run: 6, steps_total: 6 },+ risk: { level: 'high', reasons: ['touches auth', 'priority high'] },+ criteria: CRITERIA_ALL_STATES.slice(0, 4),+ criteria_summary: { met: 1, total: 4, not_met: 1, not_checked: 2 },+ couldnt_verify: [{ what: 'Safari login', why: 'no Safari in the clean copy' }],+ decisions: { total: 4, top: [+ { index: 1, question: 'Count failed sign-ins per IP or per account?', picked: 'Per IP', why: '“Per account lets an attacker lock anyone out.”', cost: null },+ { index: 2, question: 'Lockout length?', picked: '15 minutes', why: '“Matches the old session timeout.”', cost: null },+ ] },+ evidence: {+ checks: [{ name: 'unit', command: 'cargo test auth', result: 'pass', summary: '42 passed', ran_by: 'checker', output_tail: 'test auth::limit::per_ip ... ok\ntest result: ok. 42 passed; 0 failed' }],+ screenshots: [{ url: '/api/files/shot-1', caption: 'login-error.png' }],+ pr: { repo: 'shop', number: 512, url: 'https://github.com/example/shop/pull/512', add: 84, del: 12, files: 3, ci: 'passed' },+ },+ held_actions: [{ approval_id: 'a-merge', tool_name: 'github', summary: 'merge pull request', args_display: 'github · merge pull request\nrepo shop · #512 → main · squash', gate: 'merge', status: 'pending', resolved_at: null, result_line: null }],+});++/** Fail at the round limit (round 2 of 2), on a different tier: Waiting on you, with round 2 data. */+const failRoundLimit = review({+ id: 'r-fail2', kwant_id: 'k-iris', kwant_name: 'Iris', title: 'Legend under the plot', group: 'waiting_on_you', sort_key: [1, 0, 2, 'Iris', 'r-fail2'],+ timestamp: ago(35), in_review_since: ago(35), round: { n: 2, max: 2 },+ verdict: { id: 'v-fail2', result: 'fail', confidence: 'high', line: 'Criterion 2 is still not met: the table drops the last row. Repro: rows=101.', checker: { engine: 'Claude', model: 'claude-sonnet-5-5', tier_note: 'different_tier' }, checked_at: ago(30), steps_run: 2, steps_total: 2 },+ risk: { level: 'medium', reasons: [] },+ criteria: CRITERIA_ALL_STATES,+ criteria_summary: { met: 3, total: 6, not_met: 1, not_checked: 2 },+ previous_round: {+ sent_back_at: ago(90), note: 'Show the error under the field, not in a toast',+ flips: [{ index: 2, from: 'not_met', to: 'met' }],+ diff: { files: 2, add: 14, del: 6 },+ bot_summary: '“Moved the error under the field and fixed the legend overlap.”',+ },+});++/** Not checked yet (no checker): To review, medium (null) risk; never one-tap, never batched. */+const notChecked = review({+ id: 'r-none', kwant_id: 'k-juno', kwant_name: 'Juno', title: 'Nightly export to CSV', group: 'to_review', sort_key: [3, 1, 3, 'Juno', 'r-none'],+ verdict: { id: null, result: 'none', confidence: null, line: '3 of 3 required checks passed. The checker hasn’t looked at this one.', checker: null, checked_at: null, steps_run: null, steps_total: null },+ risk: { level: null, reasons: [] },+ criteria: [{ index: 1, text: 'Export runs at 02:00', status: 'not_checked', source: 'task', evidence: null, note: null, round_added: 1 }],+ criteria_summary: { met: 0, total: 1, not_met: 0, not_checked: 1 },+ round: { n: 1, max: 2 },+});++/** Pass · high, high risk, held refund still pending: To review, Approve disabled, not one-tap. */+const passHeld = review({+ id: 'r-refund', kwant_id: 'k-vega', kwant_name: 'Vega', title: 'Refund the double charge', group: 'to_review', sort_key: [3, 0, 1, 'Vega', 'r-refund'],+ risk: { level: 'high', reasons: ['payment'] },+ held_actions: [{ approval_id: 'a-refund', tool_name: 'stripe', summary: 'create refund', args_display: 'stripe · create refund\ncustomer cus_4f2… · 49.00 EUR', gate: 'payment', status: 'pending', resolved_at: null, result_line: null }],+});++/** The same kind of item after Allow once: the held action shows its result and Approve is enabled. */+const heldAllowed = review({+ id: 'r-allowed', kwant_id: 'k-vega', kwant_name: 'Vega', title: 'Merge the pricing fix', group: 'to_review', sort_key: [3, 0, 2, 'Vega', 'r-allowed'],+ risk: { level: 'high', reasons: ['merges to main'] },+ held_actions: [{ approval_id: 'a-merge-ok', tool_name: 'github', summary: 'merge pull request', args_display: 'github · merge pull request\nrepo shop · #509 → main · squash', gate: 'merge', status: 'allowed', resolved_at: ago(4), result_line: 'Merged #509 into main.' }],+});++/** After Deny (e.g. by Send back) and an expired one: nothing pending, so Approve is enabled. */+const heldDenied = review({+ id: 'r-denied', kwant_id: 'k-juno', kwant_name: 'Juno', title: 'Email the beta list', group: 'to_review', sort_key: [3, 1, 5, 'Juno', 'r-denied'],+ risk: { level: 'medium', reasons: [] },+ held_actions: [+ { approval_id: 'a-mail', tool_name: 'gmail', summary: 'send email', args_display: 'gmail · send email\nto beta@… · “0.9 is out”', gate: 'approval', status: 'denied', resolved_at: ago(6), result_line: 'Denied. Nothing was sent.' },+ { approval_id: 'a-post', tool_name: 'x', summary: 'post', args_display: 'x · post\n“0.9 is out”', gate: 'approval', status: 'expired', resolved_at: ago(2), result_line: 'Expired before anyone answered. Nothing ran.' },+ ],+});++/** Pass · high, medium risk, nothing held: one-tap, but alone (not in the batch). */+const oneTap = review({+ id: 'r-onetap', kwant_id: 'k-mira', kwant_name: 'Mira', title: 'Empty state copy', group: 'to_review', sort_key: [3, 1, 2, 'Mira', 'r-onetap'],+ risk: { level: 'medium', reasons: [] }, one_tap: true,+});++/** Freshness fail: Failed or stuck, with Check again. */+const stale = review({+ id: 'r-stale', kwant_id: 'k-rigel', kwant_name: 'Rigel', title: 'Fix typo in README', group: 'failed_or_stuck', sort_key: [2, 0, 1, 'Rigel', 'r-stale'],+ stale: { paths: ['README.md'], at: '2026-11-10T15:09:00Z' },+});++/** Server error on verify (states board "Couldn't approve …"); never from a held action (D3). */+const approveError = review({+ id: 'r-err', kwant_id: 'k-lin', kwant_name: 'Lin', title: 'Rotate the API key', group: 'failed_or_stuck', sort_key: [2, 0, 2, 'Lin', 'r-err'],+ approve_error: { code: 'server_error', message: 'The server couldn’t save the approval. Nothing was approved; try again.' },+});++/** Roll back not possible (verified elsewhere, no checkpoint). */+const noRollback = review({+ id: 'r-norb', kwant_id: 'k-ada', kwant_name: 'Ada', title: 'Release notes for 0.9', group: 'to_review', sort_key: [3, 1, 4, 'Ada', 'r-norb'],+ risk: { level: 'medium', reasons: [] }, rollback_ok: false,+});++const BATCH_NAMES: [string, string, string][] = [+ ['k-iris', 'Iris', 'Tooltip delay'],+ ['k-mira', 'Mira', 'Icon spacing in the drawer'],+ ['k-juno', 'Juno', 'Log line for retries'],+ ['k-lin', 'Lin', 'Bump serde'],+ ['k-vega', 'Vega', 'Fix a flaky test name'],+];+/** The Low-risk card's 5 items: pass · high · low risk · nothing held · nothing couldn't-check. */+export const FIXTURE_BATCH: ReviewItem[] = BATCH_NAMES.map(([kid, name, title], i) =>+ review({ id: `r-b${i + 1}`, kwant_id: kid, kwant_name: name, title, group: 'to_review', sort_key: [3, 2, i, name, `r-b${i + 1}`], one_tap: true, batchable: true }),+);++const question: InboxItem = {+ kind: 'question', id: 'q1', kwant_id: 'k-scout', kwant_name: 'Scout', title: 'Ship tonight?', summary: 'Choices: Yes · No', status: 'open',+ timestamp: ago(60), link: { thread_id: null, channel_id: 'c1', direct_kwant_id: null }, choices: ['Yes', 'No'], group: 'waiting_on_you', sort_key: [1, 0, 0, 'Scout', 'q1'],+};+const finished: InboxItem = {+ kind: 'delegation', id: 'd1', kwant_id: 'k-dev', kwant_name: 'Dev', title: 'Write the brief', summary: 'Brief is in the shared folder.', status: 'completed',+ timestamp: ago(10), link: { thread_id: 't1', channel_id: null, direct_kwant_id: null }, group: 'finished', sort_key: [4, 0, 0, 'Dev', 'd1'],+};++/** Every review state, one item each (for ReviewItemView stories and tests). */+export const FIXTURE_REVIEW_ITEMS: Record<string, ReviewItem> = {+ needsYou, failRoundLimit, notChecked, passHeld, heldAllowed, heldDenied, oneTap, stale, approveError, noRollback, batchFirst: FIXTURE_BATCH[0],+};++/** A full GET /api/inbox answer in H5 + V1 order, with the Low-risk card. */+export const INBOX_FIXTURE: InboxResponse = {+ now: T0,+ since: ago(7 * 24 * 60),+ last_seen: ago(120),+ counts: { waiting_on_you: 3, failed_or_stuck: 2, to_review: 11, finished: 1, badge: 3 + 2 + 6 + 1 + 1 },+ items: [question, needsYou, failRoundLimit, stale, approveError, passHeld, heldAllowed, heldDenied, notChecked, oneTap, noRollback, finished].sort(cmpSortKey),+ batch: { ids: FIXTURE_BATCH.map((i) => i.id), count: FIXTURE_BATCH.length },+ batch_items: FIXTURE_BATCH,+};++/** All clear. */+export const INBOX_FIXTURE_EMPTY: InboxResponse = {+ now: T0, since: ago(7 * 24 * 60), last_seen: ago(5),+ counts: { waiting_on_you: 0, failed_or_stuck: 0, to_review: 0, finished: 0, badge: 0 },+ items: [], batch: null,+};++/** Compares two sort keys element by element (numbers numerically, strings A→Z). */+export function cmpSortKey(a: Pick<InboxItem, 'sort_key'>, b: Pick<InboxItem, 'sort_key'>): number {+ const n = Math.max(a.sort_key.length, b.sort_key.length);+ for (let i = 0; i < n; i++) {+ const x = a.sort_key[i];+ const y = b.sort_key[i];+ if (x === y) continue;+ if (x === undefined) return -1;+ if (y === undefined) return 1;+ if (typeof x === 'number' && typeof y === 'number') return x - y;+ return String(x).localeCompare(String(y));+ }+ return 0;+}diff --git a/frontend/src/chatsTab.ts b/frontend/src/chatsTab.tsindex 10435b1e..656364e9 100644--- a/frontend/src/chatsTab.ts+++ b/frontend/src/chatsTab.ts@@ -1,6 +1,7 @@// The phone's Chats tab lists everything you talk to: who needs you first, then who is working,// then channels, team chats and every other bot's direct chat (spec 0.6.13 B1).import type { AwayItem } from './away';+import type { InboxItem } from './api/inbox';/** One bot waiting on you: the newest approval or question it asked, or an open browser step. */export interface NeedsYouRow {@@ -64,18 +65,23 @@ export const directIds = <K extends { id: string; name: string }>(kwants: K[], s// ---- H5: the one attention order, used by the sidebar block, the phone sections and the Inbox ----/**- * 1 Needs you · 2 Stuck or failed · 3 Finished, not read · 4 Working · 5 Waiting in line · 6 everyone else.- * A bot sits in the highest group it qualifies for.+ * 1 Needs you · 2 Stuck or failed · 3 To review (0.9 V1) · 4 Finished, not read · 5 Working · 6 Waiting in+ * line · 7 everyone else. A bot sits in the highest group it qualifies for.*/-export type AttentionRank = 1 | 2 | 3 | 4 | 5 | 6;+export type AttentionRank = 1 | 2 | 3 | 4 | 5 | 6 | 7;++/** The ranks pinned in "Needs attention" on desktop, and given a dot on team rollups. */+export const PINNED_RANK = 4;export interface AttentionRow<K> {kwant: K;rank: AttentionRank;- /** The status line for ranks 1–3 ("Asked you a question", "Stuck: …", "Finished: …"). */+ /** The status line for ranks 1–4 ("Asked you a question", "Stuck: …", "To review: …", "Finished: …"). */line?: string;- /** Ranks 1–3: the ask or Inbox item it comes from (none for a browser step). */+ /** Ranks 1–4: the ask or Inbox item it comes from (none for a browser step). */item?: AwayItem;+ /** Set when the row comes from a review item: clicking it opens that item in the Inbox. */+ review?: InboxItem;needs?: NeedsYouRow;/** When it asked, failed or finished, for the order inside the group. */at?: number;@@ -89,6 +95,8 @@ export interface AttentionInput<K> {failed?: AwayItem[];/** Inbox `finished` items not seen yet. */finished?: AwayItem[];+ /** 0.9 V1: the Inbox's review items (any group), including the Low-risk card's. */+ reviews?: InboxItem[];/** Live turns per bot (`busyLines`), and each bot's dot status (queued vs working). */busy?: Record<string, string>;status?: Record<string, string>;@@ -108,34 +116,45 @@ export const stuckLine = (i: AwayItem): string => {export const finishedLine = (i: AwayItem): string => (i.title ? `Finished: ${i.title}` : 'Finished');+/** A review item's rank and line, from the Inbox group it sits in. */+export function reviewRank(i: InboxItem): { rank: 1 | 2 | 3; line: string } {+ if (i.group === 'waiting_on_you') {+ const yourCall = i.verdict?.result === 'fail' && !!i.round && i.round.n >= i.round.max;+ return { rank: 1, line: `${yourCall ? 'Your call' : 'Needs you'}: ${i.title}` };+ }+ if (i.group === 'failed_or_stuck') return { rank: 2, line: `Couldn’t approve: ${i.title}` };+ return { rank: 3, line: `To review: ${i.title}` };+}+/** One rank for one bot (the rules; `attentionRows` applies them to everyone). */-export function attentionRank(bot: { needs?: boolean; failed?: boolean; finished?: boolean; working?: boolean; queued?: boolean }): AttentionRank {+export function attentionRank(bot: { needs?: boolean; failed?: boolean; review?: boolean; finished?: boolean; working?: boolean; queued?: boolean }): AttentionRank {if (bot.needs) return 1;if (bot.failed) return 2;- if (bot.finished) return 3;- if (bot.working) return 4;- if (bot.queued) return 5;- return 6;+ if (bot.review) return 3;+ if (bot.finished) return 4;+ if (bot.working) return 5;+ if (bot.queued) return 6;+ return 7;}/**- * The order inside and across groups: rank first; then oldest first for 1 and 2, newest first for 3;- * 4 and 5 by name (the sidebar has no turn start times); ties by name A→Z. Rank 6 keeps its input order.+ * The order inside and across groups: rank first; then oldest first for 1–3, newest first for 4;+ * 5 and 6 by name (the sidebar has no turn start times); ties by name A→Z. Rank 7 keeps its input order.*/export function attentionSort<K extends { name: string }>(rows: AttentionRow<K>[]): AttentionRow<K>[] {const pos = new Map(rows.map((r, i) => [r, i]));return [...rows].sort((a, b) => {if (a.rank !== b.rank) return a.rank - b.rank;- if (a.rank === 6) return pos.get(a)! - pos.get(b)!;- if (a.rank <= 2 && a.at !== b.at) return (a.at ?? 0) - (b.at ?? 0);- if (a.rank === 3 && a.at !== b.at) return (b.at ?? 0) - (a.at ?? 0);+ if (a.rank === 7) return pos.get(a)! - pos.get(b)!;+ if (a.rank <= 3 && a.at !== b.at) return (a.at ?? 0) - (b.at ?? 0);+ if (a.rank === 4 && a.at !== b.at) return (b.at ?? 0) - (a.at ?? 0);return a.kwant.name.localeCompare(b.kwant.name);});}/** Every bot with its rank and line, in the one order. */export function attentionRows<K extends { id: string; name: string }>(input: AttentionInput<K>): AttentionRow<K>[] {- const { kwants, needs, failed = [], finished = [], busy = {}, status = {}, openedAt = {}, now = Date.now() } = input;+ const { kwants, needs, failed = [], finished = [], reviews = [], busy = {}, status = {}, openedAt = {}, now = Date.now() } = input;const needsBy = new Map(needs.map((r, i) => [r.kwant_id, { r, i }]));// Oldest failure per bot from the last 24 h; newest finished item per bot not read since.const failedBy = new Map<string, AwayItem>();@@ -152,28 +171,49 @@ export function attentionRows<K extends { id: string; name: string }>(input: Attconst had = finishedBy.get(i.kwant_id);if (!had || t > ts(had)) finishedBy.set(i.kwant_id, i);}+ // Review items: each bot's highest-ranked one, oldest first inside a rank.+ const reviewBy = new Map<string, { i: InboxItem; rank: 1 | 2 | 3; line: string }>();+ for (const i of reviews) {+ if (i.kind !== 'review') continue;+ const r = reviewRank(i);+ const had = reviewBy.get(i.kwant_id);+ if (!had || r.rank < had.rank || (r.rank === had.rank && ts(i as AwayItem) < ts(had.i as AwayItem))) reviewBy.set(i.kwant_id, { i, ...r });+ }const rows = kwants.map((k): AttentionRow<K> => {const n = needsBy.get(k.id);const f = failedBy.get(k.id);const d = finishedBy.get(k.id);+ const v = reviewBy.get(k.id);const queued = status[k.id] === 'queued';- const rank = attentionRank({ needs: !!n, failed: !!f, finished: !!d, working: !!busy[k.id] && !queued, queued: !!busy[k.id] && queued });- if (rank === 1) return { kwant: k, rank, line: n!.r.line, item: n!.r.item, needs: n!.r, at: n!.r.item ? ts(n!.r.item) : n!.i };- if (rank === 2) return { kwant: k, rank, line: stuckLine(f!), item: f, at: ts(f) };- if (rank === 3) return { kwant: k, rank, line: finishedLine(d!), item: d, at: ts(d) };+ const rank = attentionRank({+ needs: !!n || v?.rank === 1,+ failed: !!f || v?.rank === 2,+ review: v?.rank === 3,+ finished: !!d,+ working: !!busy[k.id] && !queued,+ queued: !!busy[k.id] && queued,+ });+ const fromReview = (x: { i: InboxItem; line: string }): AttentionRow<K> => ({ kwant: k, rank, line: x.line, item: x.i as AwayItem, review: x.i, at: ts(x.i as AwayItem) });+ if (rank === 1) return n ? { kwant: k, rank, line: n.r.line, item: n.r.item, needs: n.r, at: n.r.item ? ts(n.r.item) : n.i } : fromReview(v!);+ if (rank === 2) return f && !(v?.rank === 2 && ts(v.i as AwayItem) < ts(f)) ? { kwant: k, rank, line: stuckLine(f), item: f, at: ts(f) } : fromReview(v!);+ if (rank === 3) return fromReview(v!);+ if (rank === 4) return { kwant: k, rank, line: finishedLine(d!), item: d, at: ts(d) };return { kwant: k, rank };});- // Needs-you rows keep needsYouRows' own order (oldest ask first; a browser step has no time)+ // Needs-you rows keep needsYouRows' own order (oldest ask first; a browser step has no time); a review+ // that needs you comes after them, oldest first.const sorted = attentionSort(rows);- const ones = sorted.filter((r) => r.rank === 1).sort((a, b) => needsBy.get(a.kwant.id)!.i - needsBy.get(b.kwant.id)!.i);- return [...ones, ...sorted.filter((r) => r.rank !== 1)];+ const ones = sorted.filter((r) => r.rank === 1);+ const asks = ones.filter((r) => !r.review).sort((a, b) => needsBy.get(a.kwant.id)!.i - needsBy.get(b.kwant.id)!.i);+ return [...asks, ...ones.filter((r) => r.review), ...sorted.filter((r) => r.rank !== 1)];}-/** "2 need you, 1 stuck, 1 finished" (zeros left out). */-export function rollupLabel(counts: { needs: number; stuck: number; finished: number; working?: number }): string {+/** "2 need you, 1 stuck, 1 to review, 1 finished" (zeros left out). */+export function rollupLabel(counts: { needs: number; stuck: number; review?: number; finished: number; working?: number }): string {const parts: string[] = [];if (counts.needs) parts.push(`${counts.needs} ${counts.needs === 1 ? 'needs' : 'need'} you`);if (counts.stuck) parts.push(`${counts.stuck} stuck`);+ if (counts.review) parts.push(`${counts.review} to review`);if (counts.finished) parts.push(`${counts.finished} finished`);if (!parts.length && counts.working) parts.push(`${counts.working} working`);return parts.join(', ');diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsxnew file mode 100644index 00000000..ba5b4e30--- /dev/null+++ b/frontend/src/components/InboxNew.tsx@@ -0,0 +1,826 @@+// 0.9.0 V1: Inbox › New. Two panes at ≥1024 px (the queue is 392 px, the item pane takes the rest); below+// that the queue is the page and an item opens as a full page. The queue keeps H5's order and adds+// To review between Failed or stuck and Finished. Questions, approvals and finished work behave as they+// did on the old page; review items and the Low-risk card open in the item pane.+import React, { useCallback, useEffect, useRef, useState } from 'react';+import {+ AlertTriangle,+ Check,+ CheckCircle2,+ ChevronLeft,+ CircleDashed,+ Hand,+ Info,+ Layers,+ List,+ Loader2,+ MinusCircle,+ RefreshCw,+ RotateCcw,+ ShieldCheck,+ XCircle,+} from 'lucide-react';+import { ModernAvatar } from './ModernAvatar';+import { ModernApprovalCard } from './ModernApprovalCard';+import { ReviewDone, ReviewItemSlot, VERDICT_STYLE } from './ReviewItemStub';+import { approvalFromAway, awayTitle, lateAnswerText } from '../approvals';+import { ApprovalDecision, AwayError, AwayItem, actionFailureNotice, awayApi, awaySummary, itemLabel, windowLabel } from '../away';+import { INBOX_GROUPS, InboxGroup, InboxItem, ReviewItem, VERDICT_WORD, groupItems, isReview } from '../api/inbox';+import {+ BatchRow,+ Crumb,+ approveAll,+ approveOne,+ batchItems,+ checkAgain,+ clearBatch,+ loadInbox,+ nextAfter,+ resolvePending,+ select,+ setCrumb,+ comeBack,+ findItem,+ setNotice,+ stopAfterThisOne,+ useInbox,+ inboxStore,+} from '../inboxStore';++export const WIDE_QUERY = '(min-width: 1024px)';++export function useWide(): boolean {+ const get = () => typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(WIDE_QUERY).matches;+ const [wide, setWide] = useState(get);+ useEffect(() => {+ if (typeof window.matchMedia !== 'function') return;+ const m = window.matchMedia(WIDE_QUERY);+ const on = () => setWide(m.matches);+ m.addEventListener?.('change', on);+ return () => m.removeEventListener?.('change', on);+ }, []);+ return wide;+}++const CRUMB_LABEL: Record<'board' | 'dev', string> = { board: 'Mission board', dev: 'Dev desk' };++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' },+ to_review: { head: 'text-sky-300', icon: <ShieldCheck size={13} aria-hidden="true" />, row: 'border-zinc-800 bg-zinc-900/60' },+ finished: { head: 'text-zinc-400', icon: <CheckCircle2 size={13} aria-hidden="true" />, row: 'border-zinc-800 bg-zinc-900/60' },+};++const okBtn =+ 'kw-focus inline-flex items-center justify-center gap-1.5 rounded-lg bg-teal-300 text-zinc-950 font-semibold hover:bg-teal-200 disabled:opacity-50 disabled:cursor-not-allowed';+const plainBtn =+ 'kw-focus inline-flex items-center justify-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed';++/** "14:08": the queue shows the clock, like the mockups. */+export function clock(ts: string): string {+ const t = Date.parse(ts);+ if (Number.isNaN(t)) return '';+ const d = new Date(t);+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;+}++/** A row's title: an approve that came back says so. */+export function rowTitle(i: InboxItem): string {+ if (isReview(i) && (i.stale || i.approve_error)) return `Couldn’t approve: ${i.title}`;+ return isReview(i) ? i.title : awayTitle(i as AwayItem);+}++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`;+}++const names = (xs: string[]): string => {+ const u = [...new Set(xs)];+ return u.length <= 1 ? u.join('') : `${u.slice(0, -1).join(', ')} and ${u[u.length - 1]}`;+};++// ---------- Rows ----------++const ReviewSubline: React.FC<{ item: ReviewItem }> = ({ item }) => {+ if (item.stale) return <span className="text-rose-300">{staleLine(item.stale.paths)}</span>;+ if (item.approve_error) return <span className="text-rose-300">{item.approve_error.message}</span>;+ const v = VERDICT_STYLE[item.verdict.result];+ const Icon = v.icon;+ const lastRoundFail = item.verdict.result === 'fail' && item.round.n >= item.round.max;+ return (+ <span className="flex flex-wrap items-center gap-x-1.5 gap-y-1">+ {item.round.n > 1 && (+ <span className="px-1.5 rounded-md border border-violet-400/40 bg-violet-500/10 text-violet-200 text-[11px]" data-round-chip>+ Round {item.round.n}+ </span>+ )}+ <span className={`inline-flex items-center gap-1 font-semibold ${v.text}`}>+ <Icon size={12} aria-hidden="true" />+ {VERDICT_WORD[item.verdict.result]}+ </span>+ {item.verdict.confidence && <span className="text-zinc-400">· {item.verdict.confidence}</span>}+ {lastRoundFail && (+ <span className="text-zinc-400">+ · round {item.round.n} of {item.round.max} <span className="text-zinc-300">your call</span>+ </span>+ )}+ {item.risk.level === 'high' && <span className="px-1.5 rounded-md border border-amber-500/40 bg-amber-500/10 text-amber-200 text-[11px]">High risk</span>}+ {item.risk.level === 'low' && <span className="px-1.5 rounded-md border border-zinc-600 text-zinc-300 text-[11px]">Low risk</span>}+ {item.held_actions.length > 0 && <span className="text-zinc-400">{item.held_actions.length} held</span>}+ </span>+ );+};++const AwaySubline: React.FC<{ item: InboxItem }> = ({ item }) => {+ const { label, tone } = itemLabel(item as AwayItem);+ 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);+ 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>}+ </span>+ );+};++interface RowProps {+ item: InboxItem;+ selected: boolean;+ focusable: boolean;+ wide: boolean;+ busy: string | null;+ onPick: (i: InboxItem) => void;+ onAnswer: (i: InboxItem, choice: number) => void;+ onResolve: (i: InboxItem, d: ApprovalDecision) => void;+}++const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve }) => {+ const review = isReview(item) ? item : null;+ const title = rowTitle(item);+ const oneTap = !!review && review.one_tap && !review.stale && !review.approve_error;+ const stale = !!review?.stale;+ const disabled = busy !== null;+ const tint = selected ? 'border-violet-400/70 bg-violet-500/10' : GROUP_STYLE[item.group].row;+ return (+ <li role="presentation" className={`relative rounded-xl border transition-colors ${tint}`} data-row={item.id} data-group={item.group}>+ <div+ role="option"+ id={`inbox-opt-${item.id}`}+ aria-selected={selected}+ tabIndex={focusable ? 0 : -1}+ data-option={item.id}+ data-review={review ? '' : undefined}+ onClick={() => onPick(item)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onPick(item);+ }+ }}+ className={`kw-focus flex items-start gap-3 p-3 rounded-xl cursor-pointer ${oneTap ? (wide ? 'pr-[118px]' : 'pr-[124px]') : ''}`}+ >+ <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">+ {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>+ </div>++ {oneTap && (+ <button+ type="button"+ disabled={disabled}+ onClick={() => approveOne(item)}+ className={`${okBtn} absolute right-3 top-1/2 -translate-y-1/2 px-3 text-xs ${wide ? 'h-7' : 'h-11 min-w-[104px]'}`}+ aria-label={`Approve “${item.title}”`}+ data-inline-approve={item.id}+ >+ {busy === item.id ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={13} aria-hidden="true" />}+ {busy === item.id ? 'Approving…' : 'Approve'}+ </button>+ )}++ {stale && (+ <div className="px-3 pb-3 pl-[54px]">+ <button+ type="button"+ disabled={disabled}+ onClick={() => checkAgain(item)}+ className={`${plainBtn} px-3 text-xs ${wide ? 'h-7' : 'h-11'}`}+ data-check-again={item.id}+ >+ {busy === item.id ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <RotateCcw size={12} aria-hidden="true" />}+ Check again+ </button>+ </div>+ )}++ {item.kind === 'question' && (item.choices?.length ?? 0) > 0 && (+ <div role="group" aria-label={`Answer: ${title}`} className="px-3 pb-3 pl-[54px] flex flex-wrap gap-2">+ {item.choices!.map((c, n) => (+ <button key={n} type="button" disabled={disabled} onClick={() => onAnswer(item, n)} className={`${plainBtn} px-3 text-xs ${wide ? 'min-h-[30px]' : 'min-h-[44px]'}`}>+ {c}+ </button>+ ))}+ </div>+ )}++ {item.kind === 'approval' && (+ <div className="px-3 pb-1 pl-[54px] [&>div]:my-0 [&>div]:mb-2">+ <ModernApprovalCard approval={approvalFromAway(item as AwayItem)} disabled={disabled} onResolve={(_, d) => onResolve(item, d)} />+ </div>+ )}++ {busy === item.id && !review && (+ <p className="px-3 pb-3 pl-[54px] inline-flex items-center gap-1.5 text-[11px] text-zinc-400">+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Sending…+ </p>+ )}+ </li>+ );+};++/** Progress of a run, for the card and the pane. */+export function batchProgress(rows: BatchRow[]) {+ const done = rows.filter((r) => r.status === 'approved' || r.status === 'came_back' || r.status === 'error').length;+ return {+ done,+ total: rows.length,+ approved: rows.filter((r) => r.status === 'approved').length,+ back: rows.filter((r) => r.status === 'came_back').length,+ failed: rows.filter((r) => r.status === 'error').length,+ current: rows.findIndex((r) => r.status === 'approving'),+ };+}++export function progressText(rows: BatchRow[]): string {+ const p = batchProgress(rows);+ const parts = [`${p.done} of ${p.total} done`, `${p.approved} approved`];+ if (p.back) parts.push(`${p.back} came back`);+ if (p.failed) parts.push(`${p.failed} couldn’t be approved`);+ return parts.join(' · ');+}++const ProgressBar: React.FC<{ rows: BatchRow[] }> = ({ rows }) => {+ const p = batchProgress(rows);+ return (+ <div className="h-1.5 rounded-full bg-zinc-800 overflow-hidden" role="progressbar" aria-valuemin={0} aria-valuemax={p.total} aria-valuenow={p.done} aria-label="Approve all">+ <div+ className="h-full w-full origin-left rounded-full bg-violet-400 transition-transform duration-300 motion-reduce:transition-none"+ style={{ transform: `scaleX(${p.total ? p.done / p.total : 0})` }}+ />+ </div>+ );+};++const BatchCard: React.FC<{ items: InboxItem[]; selected: boolean; focusable: boolean; wide: boolean; onPick: () => void }> = ({ items, selected, focusable, wide, onPick }) => {+ const { batch, busy } = useInbox();+ const running = !!batch?.running;+ const n = running ? batch!.rows.length : items.length;+ const people = running ? batch!.rows : items;+ return (+ <li role="presentation" className={`rounded-xl border transition-colors ${selected ? 'border-violet-400/70 bg-violet-500/10' : 'border-violet-400/30 bg-violet-950/20'}`} data-batch-card>+ <div+ role="option"+ id="inbox-opt-batch"+ aria-selected={selected}+ tabIndex={focusable ? 0 : -1}+ data-option="batch"+ onClick={onPick}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onPick();+ }+ }}+ className="kw-focus block p-3 rounded-xl cursor-pointer"+ >+ <span className="flex items-center gap-1.5 text-sm font-semibold text-zinc-100">+ <Layers size={15} className="text-zinc-300" aria-hidden="true" /> Low risk, checks passed · {n}+ </span>+ <span className="block mt-1 text-xs text-zinc-400">+ Each one passed every required check and the checker passed it with high confidence. Nothing held, nothing it couldn’t check.+ </span>+ {running && (+ <span className="block mt-2 space-y-1">+ <ProgressBar rows={batch!.rows} />+ <span className="block text-[11px] text-zinc-400" data-batch-card-progress>+ {progressText(batch!.rows)}+ </span>+ </span>+ )}+ </div>+ <div className="px-3 pb-3 flex items-center gap-2">+ <span className="flex -space-x-1.5 shrink-0" aria-hidden="true">+ {people.slice(0, 5).map((p) => (+ <span key={p.id} className="rounded-full ring-2 ring-zinc-950">+ <ModernAvatar role={p.kwant_name} name={p.kwant_name} size={20} kwantId={p.kwant_id} />+ </span>+ ))}+ </span>+ <span className="min-w-0 flex-1 truncate text-[11px] text-zinc-400">{names(people.map((p) => p.kwant_name))}</span>+ <button+ type="button"+ disabled={running || busy !== null}+ onClick={() => {+ onPick();+ void approveAll();+ }}+ className={`${okBtn} shrink-0 px-3 text-xs ${wide ? 'h-8' : 'h-11'}`}+ data-approve-all+ >+ {running ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={13} aria-hidden="true" />}+ {running ? `Approving ${Math.max(1, batchProgress(batch!.rows).current + 1)} of ${n}…` : `Approve all ${n}`}+ </button>+ </div>+ </li>+ );+};++// ---------- Panes ----------++const ROW_STATUS: Record<BatchRow['status'], { word: string; tone: string; icon: React.ReactNode }> = {+ approved: { word: 'Approved', tone: 'text-teal-300', icon: <Check size={14} className="text-teal-300" aria-hidden="true" /> },+ came_back: { word: 'Came back', tone: 'text-rose-300', icon: <XCircle size={14} className="text-rose-300" aria-hidden="true" /> },+ approving: { word: 'Approving…', tone: 'text-violet-200', icon: <Loader2 size={14} className="text-violet-200 animate-spin motion-reduce:animate-none" aria-hidden="true" /> },+ waiting: { word: 'Waiting', tone: 'text-zinc-400', icon: <CircleDashed size={14} className="text-zinc-500" aria-hidden="true" /> },+ error: { word: 'Couldn’t approve', tone: 'text-rose-300', icon: <AlertTriangle size={14} className="text-rose-300" aria-hidden="true" /> },+ stopped: { word: 'Left in To review', tone: 'text-zinc-400', icon: <MinusCircle size={14} className="text-zinc-500" aria-hidden="true" /> },+};++export const BatchPane: React.FC<{ wide: boolean; onOpenItem: (id: string) => void }> = ({ wide, onOpenItem }) => {+ const { data, batch, busy } = useInbox();+ const items = batchItems(data);+ const rows: BatchRow[] =+ batch?.rows ?? items.map((i) => ({ id: i.id, task_id: i.task_id ?? '', title: i.title, kwant_id: i.kwant_id, kwant_name: i.kwant_name, status: 'waiting' as const }));+ const running = !!batch?.running;+ const finished = !!batch && !running;+ const p = batchProgress(rows);+ return (+ <div className="flex flex-col min-h-full" data-batch-pane>+ <div className="flex-1 space-y-4">+ <header className="flex items-start gap-3">+ <span className="shrink-0 w-[34px] h-[34px] rounded-lg bg-teal-400/10 border border-teal-400/25 grid place-items-center text-teal-300">+ <Layers size={17} aria-hidden="true" />+ </span>+ <span className="min-w-0">+ <h2 className="text-base font-semibold text-zinc-100">Low risk, checks passed</h2>+ <p className="text-xs text-zinc-400">+ {rows.length} items from {names(rows.map((r) => r.kwant_name))}+ </p>+ </span>+ </header>++ <section className="rounded-xl border border-teal-400/25 bg-teal-400/5 p-3 space-y-2">+ <p className="flex items-center gap-1.5 text-sm font-semibold text-zinc-100">+ <Layers size={15} className="text-teal-300" aria-hidden="true" />+ {running ? `Approving ${rows.length} low-risk items, one at a time` : finished ? `Approve all finished` : `Approve ${rows.length} low-risk items, one at a time`}+ </p>+ <p className="text-xs text-zinc-300">+ Before each one, the app checks that its files haven’t changed since the checker looked. One that changed goes back to the queue on its own; the rest carry on.+ </p>+ <ProgressBar rows={rows} />+ <p className="text-[11px] text-zinc-400" data-batch-progress>+ {progressText(rows)}+ </p>+ {batch?.halted && <p className="text-xs text-rose-300">{batch.halted}</p>}+ </section>++ <section aria-labelledby="batch-rows">+ <h3 id="batch-rows" className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-zinc-400">+ <List size={13} aria-hidden="true" /> In this batch <span className="font-normal">{rows.length}</span>+ </h3>+ <ul className="rounded-xl border border-zinc-800 divide-y divide-zinc-800 overflow-hidden">+ {rows.map((r) => {+ const s = ROW_STATUS[r.status];+ const back = r.status === 'came_back' || r.status === 'error';+ return (+ <li key={r.id} className={back ? 'bg-rose-950/20' : ''} data-batch-row={r.id} data-status={r.status}>+ <button+ type="button"+ onClick={() => onOpenItem(r.id)}+ className={`kw-focus w-full flex items-center gap-2.5 px-3 text-left ${wide ? 'min-h-[40px] py-1.5' : 'min-h-[52px] py-2'}`}+ >+ {s.icon}+ <ModernAvatar role={r.kwant_name} name={r.kwant_name} size={20} kwantId={r.kwant_id} />+ <span className="min-w-0 flex-1">+ <span className="text-[13px] font-semibold text-zinc-100">{r.title}</span>+ <span className="text-xs text-zinc-400"> · {r.kwant_name}{r.status !== 'came_back' && r.status !== 'error' ? ' · pass, high' : ''}</span>+ {r.note && <span className="block text-[11px] text-rose-300">{r.note}</span>}+ </span>+ <span className={`shrink-0 text-[11px] ${s.tone}`}>{back ? '' : s.word}</span>+ </button>+ </li>+ );+ })}+ </ul>+ </section>++ <p className="flex items-start gap-1.5 rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 text-xs text-zinc-300">+ <Info size={13} className="mt-0.5 shrink-0" aria-hidden="true" />+ You can leave this page. The batch keeps going, and the Inbox shows what came back.+ </p>+ </div>++ <div className="sticky bottom-0 mt-4 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 border-t border-zinc-800 bg-zinc-950/95 flex flex-wrap gap-2">+ {running ? (+ <>+ <button type="button" disabled className={`${plainBtn} px-4 text-sm ${wide ? 'h-9' : 'h-11'}`} data-batch-running>+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />+ Approving {Math.max(1, p.current + 1)} of {rows.length}…+ </button>+ <button type="button" disabled={batch!.stopRequested} onClick={stopAfterThisOne} className={`${plainBtn} px-4 text-sm ${wide ? 'h-9' : 'h-11'}`} data-stop-after>+ {batch!.stopRequested ? 'Stopping after this one…' : 'Stop after this one'}+ </button>+ </>+ ) : finished ? (+ <button type="button" onClick={clearBatch} className={`${plainBtn} px-4 text-sm ${wide ? 'h-9' : 'h-11'}`} data-batch-done>+ Done+ </button>+ ) : (+ <button type="button" disabled={rows.length < 2 || busy !== null} onClick={() => void approveAll()} className={`${okBtn} px-4 text-sm ${wide ? 'h-9' : 'h-11'}`} data-approve-all-pane>+ <Check size={14} aria-hidden="true" /> Approve all {rows.length}+ </button>+ )}+ </div>+ </div>+ );+};++const EmptyQueue: React.FC = () => (+ <div className="py-16 flex flex-col items-center text-center gap-2" data-all-clear>+ <CheckCircle2 size={30} className="text-teal-300" aria-hidden="true" />+ <p className="text-sm font-semibold text-zinc-100">You’re all caught up</p>+ <p className="text-xs text-zinc-400 max-w-xs">Nothing waits on you and nothing is left to review. Questions, approvals and finished work will show up here.</p>+ </div>+);++const Skeleton: React.FC = () => (+ <ul className="space-y-2" aria-hidden="true" data-skeleton>+ {[0, 1, 2].map((n) => (+ <li key={n} className="h-[74px] rounded-xl border border-zinc-800 bg-zinc-900/60 animate-pulse motion-reduce:animate-none" />+ ))}+ </ul>+);++// ---------- Page ----------++export interface InboxNewProps {+ /** A non-review row: open its chat, as the old page did. */+ onOpen: (item: AwayItem) => void;+ /** Unseen counts for the badge fallback (older servers). */+ onCounts?: (waiting: number) => void;+ onApprovalResolved?: (id: string) => void;+ /** Phone: back to the chat list. */+ onBack?: () => void;+ /** The back crumb: return to the page the item was opened from. */+ onCrumb?: (c: Exclude<Crumb, null>) => void;+ top?: React.ReactNode;+ now?: number;+ /** Tests and screenshots: skip the first load. */+ noLoad?: boolean;+ /** Tests: force the layout. */+ wide?: boolean;+}++/** Writes `?item=` for the open item; the Shell sets the path first, so this waits a tick. */+function writeItemParam(id: string | null) {+ setTimeout(() => {+ const q = new URLSearchParams(window.location.search);+ const had = q.get('item');+ if ((had ?? null) === id) return;+ if (id) q.set('item', id);+ else q.delete('item');+ const s = q.toString();+ window.history.replaceState(window.history.state, '', `${window.location.pathname}${s ? `?${s}` : ''}`);+ }, 0);+}++export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApprovalResolved, onBack, onCrumb, top, now = Date.now(), noLoad = false, wide: forceWide }) => {+ const st = useInbox();+ const mqWide = useWide();+ const wide = forceWide ?? mqWide;+ const { data, loading, error, notice, busy, selectedId, crumb } = st;+ const listRef = useRef<HTMLDivElement>(null);+ const paneRef = useRef<HTMLDivElement>(null);+ const onCountsRef = useRef(onCounts);+ onCountsRef.current = onCounts;++ // First load, then mark the window seen (finished and failed clear; review items stay, ENG).+ useEffect(() => {+ const key = new URLSearchParams(window.location.search).get('item');+ if (key && !inboxStore.get().pendingKey && inboxStore.get().selectedId !== key) inboxStore.patch({ pendingKey: key });+ if (noLoad) return;+ let cancelled = false;+ loadInbox().then(async (first) => {+ if (cancelled || !first) return;+ try {+ await awayApi.seen();+ onCountsRef.current?.(first.counts.waiting_on_you);+ } catch {+ // the badge just stays until the next visit+ }+ });+ return () => {+ cancelled = true;+ };+ }, [noLoad]);++ // A pending `?item=` or Review press resolves once the list has it.+ useEffect(() => {+ if (st.pendingKey && data) resolvePending();+ }, [st.pendingKey, data]);++ const groups = data ? groupItems(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);++ // 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);+ if (first !== selectedId) select(first);+ }, [wide, data, selValid, selectedId, showBatch, st.pendingKey]);++ // The address carries the open item, so a reload or a shared link opens it again.+ useEffect(() => {+ writeItemParam(selValid && selectedId !== 'batch' ? selectedId : null);+ }, [selValid, selectedId]);++ const pick = useCallback(+ (i: InboxItem) => {+ if (isReview(i)) {+ select(i.id);+ setCrumb(null);+ return;+ }+ onOpen(i as AwayItem);+ },+ [onOpen],+ );++ const act = async (item: InboxItem, run: () => Promise<unknown>, denied = false) => {+ if (inboxStore.get().busy) return;+ inboxStore.patch({ busy: item.id, notice: null });+ const title = awayTitle(item as AwayItem);+ try {+ const reply = await run();+ const late = item.kind === 'approval' && !denied ? lateAnswerText(reply, item.kwant_name) : null;+ const done = denied ? 'Denied, nothing ran:' : late ?? `Sent to ${item.kwant_name}:`;+ inboxStore.patch({ busy: null, notice: { text: `${done} “${title}”`, tone: 'ok' } });+ } catch (err) {+ const status = err instanceof AwayError ? err.status : 0;+ const n = actionFailureNotice(status, err instanceof Error ? err.message : 'Something went wrong.', title);+ inboxStore.patch({ busy: null, notice: { text: n.text, tone: n.error ? 'error' : 'info' } });+ }+ const next = await loadInbox();+ if (next) onCountsRef.current?.(next.counts.waiting_on_you);+ };++ const onAnswer = (item: InboxItem, choice: number) => act(item, () => awayApi.answer(item.id, choice));+ const onResolve = (item: InboxItem, decision: ApprovalDecision) =>+ act(+ item,+ async () => {+ try {+ const r = await awayApi.resolve(item.id, decision);+ onApprovalResolved?.(item.id);+ return r;+ } catch (err) {+ if (err instanceof AwayError && (err.status === 409 || err.status === 404)) onApprovalResolved?.(item.id);+ throw err;+ }+ },+ decision === 'deny',+ );++ // J/K and arrows move through the queue; on desktop the selection follows a review row.+ const onListKey = (e: React.KeyboardEvent) => {+ const t = e.target as HTMLElement;+ if (t.getAttribute('role') !== 'option') return;+ const k = e.key;+ const dir = k === 'j' || k === 'J' || k === 'ArrowDown' ? 1 : k === 'k' || k === 'K' || k === 'ArrowUp' ? -1 : 0;+ if (!dir) return;+ e.preventDefault();+ const opts = Array.from(listRef.current?.querySelectorAll<HTMLElement>('[role="option"]') ?? []);+ const at = opts.indexOf(t);+ const next = opts[Math.min(opts.length - 1, Math.max(0, at + dir))];+ if (!next) return;+ next.focus();+ const id = next.dataset.option!;+ if (wide && (id === 'batch' || next.dataset.review !== undefined)) select(id);+ };++ const onDone = (r: ReviewDone) => {+ const s = inboxStore.get();+ setNotice({ text: r.text, tone: r.kind === 'stale' ? 'error' : 'ok' });+ if (r.kind === 'stale') {+ const it = findItem(s.data, r.task_id) ?? findItem(s.data, s.selectedId);+ if (it) comeBack(it, r.paths ?? []);+ return;+ }+ const id = s.selectedId;+ if (id) select(nextAfter(s.data, id));+ void loadInbox();+ };++ const firstFocusable = selectable.includes(selectedId ?? '') ? selectedId : data?.items[0]?.id ?? (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`}>+ {onBack && !wide && (+ <button type="button" onClick={onBack} aria-label="Back to chats" className="kw-focus shrink-0 p-2 -ml-0.5 -mr-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800">+ <ChevronLeft size={18} />+ </button>+ )}+ <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>+ </div>+ <button+ type="button"+ onClick={() => void loadInbox()}+ disabled={loading}+ className="kw-focus inline-flex items-center gap-1.5 px-2.5 py-1 min-h-[32px] rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 disabled:opacity-60"+ >+ <RefreshCw size={12} className={loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />+ Refresh+ </button>+ </div>+ );++ const status = (+ <div role="status" aria-live="polite" data-inbox-status>+ {notice && (+ <p+ className={`px-3 py-2 rounded-lg border text-xs ${+ notice.tone === 'error' ? 'border-rose-500/30 bg-rose-500/10 text-rose-200' : notice.tone === 'info' ? 'border-slate-500/30 bg-slate-500/10 text-slate-200' : 'border-teal-400/30 bg-teal-400/10 text-teal-100'+ }`}+ >+ {notice.text}+ </p>+ )}+ </div>+ );++ const queue = (+ <div className="flex-1 overflow-y-auto p-3 sm:p-4" aria-busy={loading}>+ <div className="space-y-4">+ {top}+ {error && (+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300" data-inbox-error>+ <span>Couldn’t load the Inbox: {error}</span>+ <button type="button" onClick={() => void loadInbox()} className="kw-focus ml-auto px-2 py-0.5 min-h-[28px] rounded border border-rose-500/30 hover:bg-rose-500/10">+ Retry+ </button>+ </div>+ )}+ {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;+ const count = rows.length;+ const g = GROUP_STYLE[key];+ 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>+ </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}+ wide={wide}+ busy={busy}+ onPick={pick}+ onAnswer={onAnswer}+ onResolve={onResolve}+ />+ ))}+ {withBatch && <BatchCard items={bItems} selected={wide && selectedId === 'batch'} focusable={firstFocusable === 'batch'} wide={wide} onPick={() => select('batch')} />}+ </ul>+ ) : (+ <p className="px-1 text-xs text-zinc-400">{none}</p>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ </div>+ );++ const openFromBatch = (id: string) => {+ const it = data?.items.find((i) => i.id === id) ?? bItems.find((i) => i.id === id);+ if (it) select(id);+ };++ const crumbBar = crumb ? (+ <button+ type="button"+ onClick={() => {+ setCrumb(null);+ onCrumb?.(crumb);+ }}+ className="kw-focus mb-3 inline-flex items-center gap-1 min-h-[32px] px-1.5 -ml-1.5 rounded-md text-xs text-zinc-300 hover:text-zinc-100"+ data-crumb={crumb}+ >+ <ChevronLeft size={14} aria-hidden="true" /> Back to {CRUMB_LABEL[crumb]}+ </button>+ ) : null;++ const paneBody =+ selectedId === 'batch' && selValid ? (+ <BatchPane wide={wide} onOpenItem={openFromBatch} />+ ) : selItem && isReview(selItem) ? (+ <ReviewItemSlot item={selItem} entry={crumb ?? 'inbox'} onDone={onDone} onApprove={(i) => void approveOne(i)} busy={busy === selItem.id} />+ ) : empty ? (+ <div className="h-full grid place-items-center text-center" data-pane-empty>+ <div className="space-y-1.5">+ <CheckCircle2 size={26} className="mx-auto text-teal-300" aria-hidden="true" />+ <p className="text-sm font-semibold text-zinc-100">Nothing to review</p>+ <p className="text-xs text-zinc-400">Approved and sent-back items leave the Inbox.</p>+ </div>+ </div>+ ) : null;++ const paneLabel = selectedId === 'batch' ? 'Low risk, checks passed' : selItem ? selItem.title : 'Item';++ if (wide) {+ return (+ <div className="flex-1 min-w-0 flex h-full bg-zinc-950 overflow-hidden" data-inbox-new="wide">+ <div className="w-[392px] shrink-0 flex flex-col border-r border-zinc-800/80 min-h-0">+ {header}+ {queue}+ </div>+ <div ref={paneRef} role="region" aria-label={paneLabel} className={`flex-1 min-w-0 overflow-y-auto px-6 pt-4 ${error ? 'opacity-60' : ''}`} data-item-pane>+ <div className="max-w-[640px] min-h-full flex flex-col pb-4">+ {crumbBar}+ <div className="flex-1">{paneBody}</div>+ </div>+ </div>+ </div>+ );+ }++ // Phone and narrow windows: the queue, or the open item as a full page.+ const open = selValid && selectedId && (selectedId === 'batch' || selItem);+ if (open) {+ const back = () => {+ if (crumb) {+ setCrumb(null);+ select(null);+ onCrumb?.(crumb);+ } else select(null);+ };+ return (+ <div className="flex-1 min-w-0 flex flex-col h-full bg-zinc-950 overflow-hidden" data-inbox-new="item">+ <div className="h-14 shrink-0 border-b border-zinc-800/80 px-2 flex items-center gap-1">+ <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>+ </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">+ {status}+ <div className="flex-1 mt-2">{paneBody}</div>+ </div>+ </div>+ </div>+ );+ }+ return (+ <div className="flex-1 min-w-0 flex flex-col h-full bg-zinc-950 overflow-hidden" data-inbox-new="list">+ {header}+ {queue}+ </div>+ );+};diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsxindex 63a74edb..56e5e22e 100644--- a/frontend/src/components/MissionBoardView.tsx+++ b/frontend/src/components/MissionBoardView.tsx@@ -46,6 +46,8 @@ import { isFactNeedsYou } from '../truthLedger';import { RisksSection } from './RisksSection';import { AuditWaiting, Risk, RiskResolution, TaskRisks, auditCardPlace, auditLive, auditWaiting, openRiskCounts, riskBadgeText, riskResolvedText } from '../auditor';import { awayApi } from '../away';+import { verdictShort } from '../api/inbox';+import { inboxNav, openReview, reviewForTask, useInbox } from '../inboxStore';import { playSfx } from '../audio/chiptune';import {ACTION_DONE,@@ -188,6 +190,7 @@ const quietBtn = `${actionBtn} border border-zinc-700 bg-zinc-800/80 text-zinc-1const subtleBtn = `${actionBtn} -ml-3 text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/60 underline underline-offset-2 decoration-zinc-600`;const mainBtn = `${actionBtn} bg-sky-600 text-white hover:bg-sky-500`;const goodBtn = `${actionBtn} bg-emerald-600 text-white hover:bg-emerald-500`;+const reviewBtn = `${actionBtn} bg-violet-500/80 text-white hover:bg-violet-500`;const dangerBtn = `${actionBtn} border border-rose-500/30 text-rose-200 hover:bg-rose-500/10`;const card = 'rounded-xl border border-zinc-800 bg-zinc-900/40';// Card-sized buttons: compact on desktop, a full 40px tap target on the phone.@@ -674,7 +677,11 @@ export const TaskCard: React.FC<{const flags = openFlags(t);const dimmed = t.state === 'backlog' && !flags.length && !t.held_at;const autofixLive = !!autofixCardText(t, now);- const quick = onQuick && columnOfTask(t) === 'review' ? quickActionsFor(t) : [];+ // 0.9.0 V1: in Review the card's one button is Review (the item in the Inbox); Dismiss and Try again stay.+ useInbox();+ const reviewHere = !!inboxNav.go && t.state === 'review';+ const verdict = reviewHere ? verdictShort(reviewForTask(t.id)?.verdict) : null;+ const quick = onQuick && columnOfTask(t) === 'review' ? quickActionsFor(t).filter((a) => !reviewHere || (a !== 'verify' && a !== 'reject')) : [];const [sending, setSending] = useState(false);const [burst, setBurst] = useState(0);const [note, setNote] = useState('');@@ -740,6 +747,11 @@ export const TaskCard: React.FC<{</span>)}</span>+ {verdict && (+ <span className="block text-[11px] text-zinc-300" data-card-verdict>+ {verdict}+ </span>+ )}{status && (<span className={`block text-[11px] break-words line-clamp-2 ${t.state === 'needs_you' || t.held_at || (t.state === 'review' && approvalHolds(t.checks_summary)) ? 'text-amber-200' : autofixLive ? 'text-violet-200' : t.state === 'blocked' || t.state === 'failed' ? 'text-rose-300' : 'text-zinc-400'}`}>{status}@@ -783,8 +795,19 @@ export const TaskCard: React.FC<{Remove limit and continue</button>)}- {quick.length > 0 && !sending && (+ {(quick.length > 0 || reviewHere) && !sending && (<div className="mt-1.5 flex flex-wrap gap-1.5" data-card-actions>+ {reviewHere && (+ <button+ type="button"+ onClick={() => openReview(t.id, 'board')}+ className={`${cardBtn} border border-violet-400/40 bg-violet-500/15 text-violet-100 hover:bg-violet-500/25`}+ data-card-review+ >+ <ShieldCheck size={12} aria-hidden="true" />+ Review+ </button>+ )}{quick.map((a) => (<buttonkey={a}@@ -2094,7 +2117,11 @@ export const TaskDetailBody: React.FC<{const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;const st = taskStateLabel(t);// Unblocking without a new limit would stop it again at once.- const actions = actionsFor(t).filter((a) => !(limitHit && a === 'unblock'));+ // 0.9.0 V1: a task in Review is decided in the Inbox; the drawer keeps Cancel and shows the verdict.+ useInbox();+ const reviewHere = !!inboxNav.go && t.state === 'review';+ const reviewItem = reviewHere ? reviewForTask(t.id) : null;+ const actions = actionsFor(t).filter((a) => !(limitHit && a === 'unblock') && !(reviewHere && (a === 'verify' || a === 'reject' || a === 'run_checks')));const chat = sourceChat(t);const [showAll, setShowAll] = useState(false);const shownEvents = detail.events.filter((e) => !isQuietEvent(e));@@ -2186,7 +2213,17 @@ export const TaskDetailBody: React.FC<{</div></form>)}- {t.state === 'review' && <p className="text-[11px] text-zinc-500">“Mark verified” records that you checked it yourself.</p>}+ {reviewHere && (+ <div className="flex flex-wrap items-center gap-2" data-drawer-review>+ <p className="text-xs text-zinc-300 min-w-0" data-drawer-verdict>+ {reviewItem ? (verdictShort(reviewItem.verdict) ?? 'Not checked yet') : 'Waiting for the reviewer'}+ {reviewItem?.verdict.line && <span className="text-zinc-400"> · {reviewItem.verdict.line}</span>}+ </p>+ <button type="button" onClick={() => openReview(t.id, 'board')} className={reviewBtn} data-drawer-review-open>+ <ShieldCheck size={13} aria-hidden="true" /> Review in Inbox+ </button>+ </div>+ )}{t.state === 'verified' && onFork && !forking && (<button type="button" disabled={busy} onClick={() => setForking(true)} className={quietBtn} data-fork><Copy size={13} aria-hidden="true" /> Redo as a copydiff --git a/frontend/src/components/ReviewItemStub.tsx b/frontend/src/components/ReviewItemStub.tsxnew file mode 100644index 00000000..ecfe4d27--- /dev/null+++ b/frontend/src/components/ReviewItemStub.tsx@@ -0,0 +1,105 @@+// 0.9.0 V1: a placeholder for Iris's <ReviewItemView item entry onDone>, so the Inbox panes, the deep link+// and the crumb work before it lands. It shows the header, the verdict and anything held, and an Approve+// that follows D3 (disabled while anything is held). Send back and Roll back come with Iris's view.+import React from 'react';+import { CheckCircle2, Hand, Loader2, MinusCircle, XCircle } from 'lucide-react';+import { ModernAvatar } from './ModernAvatar';+import { ReviewItem, VERDICT_WORD, approveState } from '../api/inbox';++// Same shapes as Iris's reviewItem.ts (PR #503), so swapping ReviewItemSlot is one line.+export type ReviewEntry = 'inbox' | 'board' | 'dev';+export interface ReviewDone {+ kind: 'approved' | 'sent_back' | 'rolled_back' | 'stale';+ text: string;+ task_id: string;+ undo_checkpoint_id?: string | null;+ copy_task_id?: string | null;+ /** stale (409): what changed since the verdict. */+ paths?: string[];+}++export interface ReviewItemViewProps {+ item: ReviewItem;+ entry: ReviewEntry;+ onDone: (r: ReviewDone) => void;+ /** Stub only: the store's approve, so the flow can be tried end to end. */+ onApprove?: (item: ReviewItem) => void;+ busy?: boolean;+}++export const VERDICT_STYLE = {+ pass: { icon: CheckCircle2, text: 'text-teal-300', box: 'border-teal-400/25 bg-teal-400/5' },+ fail: { icon: XCircle, text: 'text-rose-300', box: 'border-rose-400/30 bg-rose-400/[.06]' },+ needs_you: { icon: Hand, text: 'text-amber-300', box: 'border-amber-500/30 bg-amber-950/25' },+ none: { icon: MinusCircle, text: 'text-zinc-400', box: 'border-zinc-700 bg-white/[.02]' },+} as const;++export const ReviewItemStub: React.FC<ReviewItemViewProps> = ({ item, onApprove, busy = false }) => {+ const v = VERDICT_STYLE[item.verdict.result];+ const Icon = v.icon;+ const ap = approveState(item);+ return (+ <div className="space-y-4" data-review-stub={item.id}>+ <header className="flex items-start gap-3">+ <ModernAvatar role={item.kwant_name} name={item.kwant_name} size={34} kwantId={item.kwant_id} />+ <div className="min-w-0 flex-1">+ <h2 className="text-base font-semibold text-zinc-100 break-words">{item.title}</h2>+ <div className="mt-1 flex flex-wrap gap-1.5">+ {item.round.n > 1 && <span className="px-1.5 rounded-md border border-violet-400/40 text-[11px] text-violet-200">Round {item.round.n}</span>}+ {item.risk.level && item.risk.level !== 'medium' && (+ <span className={`px-1.5 rounded-md border text-[11px] ${item.risk.level === 'high' ? 'border-amber-500/40 text-amber-200' : 'border-zinc-600 text-zinc-300'}`}>+ {item.risk.level === 'high' ? 'High risk' : 'Low risk'}+ </span>+ )}+ </div>+ <p className="mt-1 text-xs text-zinc-400">+ {[item.project, `round ${item.round.n} of ${item.round.max}`].filter(Boolean).join(' · ')}+ </p>+ </div>+ </header>+ <section className={`rounded-xl border p-3 ${v.box}`} aria-label="Verdict">+ <p className={`flex items-center gap-1.5 text-sm font-semibold ${v.text}`}>+ <Icon size={16} aria-hidden="true" />+ {VERDICT_WORD[item.verdict.result]}+ {item.verdict.confidence && <span className="font-normal text-zinc-400">· {item.verdict.confidence} confidence</span>}+ </p>+ <p className="mt-1 text-sm text-zinc-200">{item.verdict.line}</p>+ </section>+ {item.held_actions.length > 0 && (+ <section className="rounded-xl border border-amber-500/30 bg-amber-950/20 p-3 space-y-2" aria-label="Held">+ {item.held_actions.map((h) => (+ <div key={h.approval_id}>+ <p className="flex items-center gap-1.5 text-xs font-semibold text-amber-200">+ <Hand size={13} aria-hidden="true" /> Held: {item.kwant_name} wants to run this, exactly:+ </p>+ <pre className="mt-1 whitespace-pre-wrap font-mono text-xs text-zinc-200">{h.args_display}</pre>+ </div>+ ))}+ </section>+ )}+ <div className="space-y-1.5">+ <button+ type="button"+ aria-disabled={!!ap.blocked || busy}+ onClick={() => !ap.blocked && !busy && onApprove?.(item)}+ className={`kw-focus inline-flex items-center gap-1.5 min-h-[44px] lg:min-h-[34px] px-4 rounded-lg text-sm font-semibold bg-violet-500/80 text-white ${ap.blocked || busy ? 'opacity-[.42] cursor-not-allowed' : 'hover:bg-violet-500'}`}+ data-stub-approve+ >+ {busy ? <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <CheckCircle2 size={14} aria-hidden="true" />}+ {busy ? 'Approving…' : ap.label}+ </button>+ {ap.blocked && (+ <p className="flex items-center gap-1 text-[11.5px] text-amber-200">+ <Hand size={12} aria-hidden="true" /> {ap.blocked}+ </p>+ )}+ </div>+ <p className="rounded-lg border border-dashed border-zinc-700 p-3 text-xs text-zinc-500" data-stub-note>+ Send back, Roll back and the details (Couldn’t check, Decisions, What done looks like, Evidence) arrive with the full item view.+ </p>+ </div>+ );+};++/** The one item view every entry point mounts. Swap this for Iris's ReviewItemView when it lands. */+export const ReviewItemSlot = ReviewItemStub;diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex ace39abf..3031fa88 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -16,7 +16,8 @@ import { teamChannelOf } from '../teamChannel';import { layaRoutes } from '../channels';import { InstallAppButton } from './InstallAppButton';import { trapFocusTarget } from '../imports';-import { type AttentionRow, type NeedsYouRow, workingIds, directIds, rollupLabel } from '../chatsTab';+import { type AttentionRow, type NeedsYouRow, PINNED_RANK, workingIds, directIds, rollupLabel } from '../chatsTab';+import type { InboxItem } from '../api/inbox';import { DevFlipNote, useDevMode } from './DevModeSwitch';import { SpaceControls } from './SpaceControls';import { DevOnToast } from './DevOnToast';@@ -118,9 +119,11 @@ export interface SidebarProps {browserNeedsYou?: ReadonlySet<string>;/*** H5: every bot in the one attention order (`attentionRows`); undefined until the first status- * fetch lands. Desktop pins ranks 1–3 above Channels; the phone's Chats tab moves bots into sections.+ * fetch lands. Desktop pins ranks 1–4 above Channels; the phone's Chats tab moves bots into sections.*/attention?: AttentionRow<Kwant>[];+ /** 0.9 V1: a row from a review item opens that item in Inbox › New. */+ onOpenReview?: (item: InboxItem) => void;/** Opens a Needs-you row's chat on its card. */onOpenNeedsYou?: (row: NeedsYouRow) => void;onSelectKwant: (kwant: Kwant) => void;@@ -277,7 +280,7 @@ const MoreMenu: React.FC<{export const PINNED_MAX = 5;/**- * H5 desktop: "Needs attention · n", ranks 1–3 above Channels. Gone when empty. The count is announced+ * H5 desktop: "Needs attention · n", ranks 1–4 above Channels. Gone when empty. The count is announced* politely, at most once per 10 s, from a live region holding only the heading's words.*/const NeedsAttention: React.FC<{ rows: AttentionRow<Kwant>[]; row: (a: AttentionRow<Kwant>) => React.ReactNode; onOpenInbox?: () => void }> = ({ rows, row, onOpenInbox }) => {@@ -350,6 +353,7 @@ export const Sidebar: React.FC<SidebarProps> = ({browserNeedsYou,needsYouRows = [],attention,+ onOpenReview,onOpenNeedsYou,onSelectKwant,onSelectChannel,@@ -426,7 +430,7 @@ export const Sidebar: React.FC<SidebarProps> = ({const lingering = useLingeringIds(busyNow.map((k) => k.id));const workingBots = chatsTab && lingering.size ? workingIds(kwants, { ...Object.fromEntries([...lingering].map((id) => [id, 'done'])), ...busyKwants }, needsIds) : busyNow;const directBotsOld = chatsTab ? directIds(kwants, new Set([...needsIds, ...workingBots.map((k) => k.id)])) : [];- // H5: with the attention order, the Chats tab has a section per rank 1–5 and bots move into them (no+ // H5: with the attention order, the Chats tab has a section per rank 1–6 and bots move into them (no// copies); a bot that finished and is read goes back to Direct chats, so no lingering under Working.const attOn = !!attention;const byRank = (r: number) => (chatsTab && attention ? attention.filter((a) => a.rank === r) : []);@@ -434,14 +438,15 @@ export const Sidebar: React.FC<SidebarProps> = ({? ([{ key: 'needs', head: 'Needs you', tone: '!text-[11px] !leading-4 !tracking-[0.06em] !text-warn', rows: byRank(1) },{ key: 'stuck', head: 'Stuck', tone: '!text-rose-300', rows: byRank(2) },- { key: 'finished', head: 'Finished', tone: '', rows: byRank(3) },- { key: 'working', head: 'Working', tone: '', rows: byRank(4) },- { key: 'waiting', head: 'Waiting', tone: '', rows: byRank(5) },+ { key: 'review', head: 'To review', tone: '!text-sky-300', rows: byRank(3) },+ { key: 'finished', head: 'Finished', tone: '', rows: byRank(4) },+ { key: 'working', head: 'Working', tone: '', rows: byRank(5) },+ { key: 'waiting', head: 'Waiting', tone: '', rows: byRank(6) },] as const): [];- const directBots = chatsTab && attention ? directIds(kwants, new Set(attention.filter((a) => a.rank < 6).map((a) => a.kwant.id))) : directBotsOld;- // Desktop: ranks 1–3, pinned above Channels (copies: the team list below keeps every bot in place).- const pinned = !phone && attention ? attention.filter((a) => a.rank <= 3) : [];+ const directBots = chatsTab && attention ? directIds(kwants, new Set(attention.filter((a) => a.rank < 7).map((a) => a.kwant.id))) : directBotsOld;+ // Desktop: ranks 1–4 (0.9 V1 adds To review), pinned above Channels (copies: the team list below keeps every bot in place).+ const pinned = !phone && attention ? attention.filter((a) => a.rank <= PINNED_RANK) : [];const rankOf = new Map((attention ?? []).map((a) => [a.kwant.id, a.rank]));const toggleTeam = (id: string) =>@@ -547,8 +552,11 @@ export const Sidebar: React.FC<SidebarProps> = ({const active = !phone && !isChannel && selectedId === k.id;const att = pin?.att ?? chat?.att;const asked = chat?.needs ?? (att?.rank === 1 ? att.needs : undefined);- // H5 ranks 2 and 3 say what broke or what finished, in rose or zinc-200- const attLine = att && (att.rank === 2 || att.rank === 3) ? att.line : undefined;+ // H5 ranks 2–4 say what broke, what waits for review (0.9 V1) or what finished, in rose, sky or+ // zinc-200; a review that needs you says so in amber+ const attLine = att && (att.rank === 2 || att.rank === 3 || att.rank === 4 || (att.rank === 1 && att.review)) ? att.line : undefined;+ const attTone = !att ? '' : att.rank === 1 ? 'text-warn' : att.rank === 2 ? 'text-rose-300' : att.rank === 3 ? 'text-[#7dd3fc]' : 'text-zinc-200';+ const attDot = !att ? '' : att.rank === 1 ? 'kw-status-warn' : att.rank === 2 ? 'bg-rose-400' : att.rank === 3 ? 'bg-[#38bdf8]' : 'bg-teal-400';const status = asked ? 'needs_you' : statusOf(k.id, botStatus, canRun);const isLead = !!team && k.id === team.lead_kwant_id;const canRemove = !!team && !isLead && !!onUpdateTeamMembers;@@ -568,8 +576,11 @@ export const Sidebar: React.FC<SidebarProps> = ({? 'Needs you in the browser': busyKwants[k.id];// A stuck or finished row opens where that happened (its thread or chat), like its Inbox card+ // A review row opens its item in the Inboxconst open = asked && onOpenNeedsYou? () => onOpenNeedsYou(asked)+ : att?.review && onOpenReview+ ? () => onOpenReview(att.review!): attLine && att?.item && onOpenNeedsYou? () => onOpenNeedsYou({ kwant_id: k.id, line: attLine, item: att.item }): () => onSelectKwant(k);@@ -687,14 +698,14 @@ export const Sidebar: React.FC<SidebarProps> = ({{busyLine ? (<pclassName={`flex items-center gap-1.5 text-meta truncate${actionRoom} ${- warn || asked ? 'text-warn' : attLine ? (att!.rank === 2 ? 'text-rose-300' : 'text-zinc-200') : status === 'queued' ? 'text-zinc-300' : 'text-[#b8adff]'+ warn || asked ? 'text-warn' : attLine ? attTone : status === 'queued' ? 'text-zinc-300' : 'text-[#b8adff]'}`}title={busyLine}data-bot-busy><spanclassName={`kw-status-dot !h-1.5 !w-1.5 ${- warn || asked ? 'kw-status-warn' : attLine ? (att!.rank === 2 ? 'bg-rose-400' : 'bg-teal-400') : status === 'queued' ? 'kw-status-idle' : 'bg-[#9d8fff] kw-pulse'+ warn || asked ? 'kw-status-warn' : attLine ? attDot : status === 'queued' ? 'kw-status-idle' : 'bg-[#9d8fff] kw-pulse'}`}aria-hidden="true"/>@@ -729,19 +740,20 @@ export const Sidebar: React.FC<SidebarProps> = ({);};- // H5: a team header's rollup, one mini dot + count for each of ranks 1–3; else the working count.+ // H5: a team header's rollup, one mini dot + count for each of ranks 1–4; else the working count.const teamRollup = (t: Team) => {if (!attention) return null;- const c = { needs: 0, stuck: 0, finished: 0, working: 0 };+ const c = { needs: 0, stuck: 0, review: 0, finished: 0, working: 0 };for (const id of new Set(memberIdsOf(t))) {const r = rankOf.get(id);if (r === 1) c.needs++;else if (r === 2) c.stuck++;- else if (r === 3) c.finished++;- else if (r === 4) c.working++;+ else if (r === 3) c.review++;+ else if (r === 4) c.finished++;+ else if (r === 5) c.working++;}- const dots: Array<[number, string]> = c.needs || c.stuck || c.finished- ? ([[c.needs, 'bg-amber-400'], [c.stuck, 'bg-rose-400'], [c.finished, 'bg-teal-400']] as Array<[number, string]>).filter(([n]) => n > 0)+ const dots: Array<[number, string]> = c.needs || c.stuck || c.review || c.finished+ ? ([[c.needs, 'bg-amber-400'], [c.stuck, 'bg-rose-400'], [c.review, 'bg-[#38bdf8]'], [c.finished, 'bg-teal-400']] as Array<[number, string]>).filter(([n]) => n > 0): c.working? [[c.working, 'bg-[#9d8fff]']]: [];diff --git a/frontend/src/components/dev/ReviewCard.tsx b/frontend/src/components/dev/ReviewCard.tsxindex 58133ffd..2711fe08 100644--- a/frontend/src/components/dev/ReviewCard.tsx+++ b/frontend/src/components/dev/ReviewCard.tsx@@ -14,6 +14,8 @@ import {} from 'lucide-react';import { FreshEyesChip } from './FreshEyesChip';import { ChangesSection } from './LineNotes';+import { verdictShort } from '../../api/inbox';+import { inboxNav, openReview, reviewForPr, useInbox } from '../../inboxStore';import type { DevFinding, FindingAction, Forge, ReviewCard as Review, ReviewCardProps, Severity, TamperFlag } from '../../dev/types';import {clock,@@ -421,6 +423,9 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,const [tick, setTick] = useState(() => Date.now());useEffect(() => setCard(given), [given]);const now = fixedNow ?? tick;+ // 0.9.0 V1: a PR that belongs to a kwant task in Review is decided in the Inbox; its button goes first.+ useInbox();+ const inboxItem = inboxNav.go && !sample ? reviewForPr(given.links.pr, given.pr) : null;// Tick once a second only while an Undo is on screen.const undoing =@@ -721,6 +726,18 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,{card.cut && <p className="mt-3 text-2xs text-zinc-400">{card.cut}</p>}+ {inboxItem && (+ <div className="mt-4 flex flex-wrap items-center gap-2" data-review-in-inbox={inboxItem.task_id}>+ <button+ type="button"+ onClick={() => openReview(inboxItem.task_id, 'dev')}+ className="kw-focus inline-flex items-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3 rounded-lg text-meta font-semibold bg-violet-500/80 text-white hover:bg-violet-500"+ >+ <ShieldCheck size={13} aria-hidden="true" /> Review in Inbox+ </button>+ {verdictShort(inboxItem.verdict) && <span className="text-2xs text-zinc-400">{verdictShort(inboxItem.verdict)}</span>}+ </div>+ )}{/* 7. Footer: Post to {Forge} (design §5.7) */}{branchCard ? (<footer data-review-footer data-post-state="no_forge" className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-hairline pt-3 text-[12.5px] text-zinc-400">diff --git a/frontend/src/inboxStore.ts b/frontend/src/inboxStore.tsnew file mode 100644index 00000000..d5f3bfcc--- /dev/null+++ b/frontend/src/inboxStore.ts@@ -0,0 +1,411 @@+// 0.9.0 V1: the Inbox store. One module-level store for Inbox › New: the last GET /api/inbox answer,+// the selected item, where the person came from (the back crumb), the status notice, and the Approve all+// run. The run lives here, not in a component, so it keeps going when the person leaves the page.+//+// Nothing here decides what is safe to approve: `one_tap`, `batchable` and `batch` come from the server.+// The client only ever calls verify with the verdict id the server sent.++import { useSyncExternalStore } from 'react';+import { AwayItem, AwayResponse, AwaySection, awayApi, sortAwaySection } from './away';+import { InboxError, InboxGroup, InboxItem, InboxResponse, ReviewItem, cmpSortKey, inboxApi, isReview } from './api/inbox';++export type Crumb = 'board' | 'dev' | null;++export type BatchRowStatus = 'waiting' | 'approving' | 'approved' | 'came_back' | 'error' | 'stopped';++export interface BatchRow {+ id: string;+ task_id: string;+ title: string;+ kwant_id: string;+ kwant_name: string;+ status: BatchRowStatus;+ /** "README.md changed after its check", or the error. */+ note?: string;+}++export interface BatchRun {+ rows: BatchRow[];+ /** Index being approved; -1 when finished. */+ current: number;+ running: boolean;+ stopRequested: boolean;+ /** Set when a sign-in or network error stopped the run. */+ halted: string | null;+}++export interface InboxNotice {+ text: string;+ tone: 'ok' | 'info' | 'error';+}++export interface InboxState {+ data: InboxResponse | null;+ loading: boolean;+ error: string | null;+ /** The item (or 'batch') open in the pane. */+ selectedId: string | null;+ crumb: Crumb;+ notice: InboxNotice | null;+ /** Item id with an inline Approve or Check again in flight. */+ busy: string | null;+ batch: BatchRun | null;+ /** True when /api/inbox isn't there and the list was built from /api/away. */+ fromAway: boolean;+ /** Window start kept from the first load, so refreshes keep the same list. */+ since: string | null;+ /** An item asked for (`?item=`, or Review on the Mission board) that the list may not have loaded yet. */+ pendingKey: string | null;+}++const initial = (): InboxState => ({+ data: null,+ loading: false,+ error: null,+ selectedId: null,+ crumb: null,+ notice: null,+ busy: null,+ batch: null,+ fromAway: false,+ since: null,+ pendingKey: null,+});++let state: InboxState = initial();+const listeners = new Set<() => void>();++function set(patch: Partial<InboxState> | ((s: InboxState) => Partial<InboxState>)) {+ const p = typeof patch === 'function' ? patch(state) : patch;+ state = { ...state, ...p };+ listeners.forEach((l) => l());+}++export const inboxStore = {+ get: () => state,+ subscribe(l: () => void) {+ listeners.add(l);+ return () => listeners.delete(l);+ },+ /** Merges a change into the state (the page's own question and approval actions use it). */+ patch(p: Partial<InboxState>) {+ set(p);+ },+ /** Tests and screenshots only. */+ reset(over: Partial<InboxState> = {}) {+ state = { ...initial(), ...over };+ listeners.forEach((l) => l());+ },+};++export function useInbox(): InboxState {+ return useSyncExternalStore(inboxStore.subscribe, inboxStore.get, inboxStore.get);+}++// ---- Loading ----++const AWAY_GROUP: Record<AwaySection, InboxGroup> = { waiting: 'waiting_on_you', failed: 'failed_or_stuck', finished: 'finished' };+const GROUP_RANK: Record<InboxGroup, number> = { waiting_on_you: 1, failed_or_stuck: 2, to_review: 3, finished: 4 };++/** Older servers have no /api/inbox: the same three sections from /api/away, in today's order. */+export function inboxFromAway(a: AwayResponse): InboxResponse {+ const items: InboxItem[] = [];+ for (const sec of ['waiting', 'failed', 'finished'] as AwaySection[]) {+ sortAwaySection(sec, a[sec], a.last_seen).forEach((i: AwayItem, n) => {+ const group = AWAY_GROUP[sec];+ items.push({ ...i, group, sort_key: [GROUP_RANK[group], 0, n, i.kwant_name, i.id] });+ });+ }+ return {+ now: a.now,+ since: a.since,+ last_seen: a.last_seen,+ counts: { waiting_on_you: a.waiting.length, failed_or_stuck: a.failed.length, to_review: 0, finished: a.finished.length },+ items,+ batch: null,+ };+}++let loadSeq = 0;+/** Overridable for screenshots and tests. */+export const inboxSource: { get: (since?: string) => Promise<InboxResponse | { away: AwayResponse }> } = {+ async get(since) {+ try {+ return await inboxApi.get(since);+ } catch (e) {+ if (e instanceof InboxError && e.status === 404) return { away: await awayApi.get(since) };+ throw e;+ }+ },+};++/** Loads (or refreshes) the list. Keeps the last good list on screen when it fails. */+export async function loadInbox(): Promise<InboxResponse | null> {+ const seq = ++loadSeq;+ set({ loading: true });+ try {+ const got = await inboxSource.get(state.since ?? undefined);+ if (seq !== loadSeq) return state.data;+ const fromAway = 'away' in got;+ const data = fromAway ? inboxFromAway(got.away) : (got as InboxResponse);+ set((s) => ({ data: withLocal(data, s), loading: false, error: null, fromAway, since: s.since ?? data.since }));+ return state.data;+ } catch (e) {+ if (seq !== loadSeq) return state.data;+ set({ loading: false, error: e instanceof Error ? e.message : 'Something went wrong.' });+ return null;+ }+}++/** Items that came back from a batch stay in Failed or stuck until the server says otherwise. */+const cameBack = new Map<string, InboxItem>();++function withLocal(data: InboxResponse, s: InboxState): InboxResponse {+ let items = data.items;+ for (const [id, item] of cameBack) {+ if (items.some((i) => i.id === id && i.group === 'failed_or_stuck')) {+ cameBack.delete(id);+ continue;+ }+ items = [...items.filter((i) => i.id !== id), item];+ }+ // While a run is going, its items stay out of the queue rows (the card shows them).+ const running = s.batch?.running ? new Set(s.batch.rows.map((r) => r.id)) : null;+ const batchIds = data.batch?.ids ?? [];+ if (running) items = items.filter((i) => !running.has(i.id) || i.group === 'failed_or_stuck');+ return { ...data, items: [...items].sort(cmpSortKey), batch: data.batch && batchIds.length ? data.batch : running ? s.data?.batch ?? null : data.batch };+}++// ---- Selection and crumb ----++export function select(id: string | null) {+ set({ selectedId: id });+}++/**+ * Opens an item by its id or task id, from a deep link or another page. It is selected as soon as the+ * list has it; `crumb` says which page the back crumb returns to.+ */+export function openItem(key: string, crumb: Crumb = null) {+ const found = findItem(state.data, key);+ set({ pendingKey: found ? null : key, selectedId: found ? found.id : state.selectedId, crumb });+}++/** Resolves a pending `openItem` once the list has loaded. Returns true when it is now selected. */+export function resolvePending(): boolean {+ if (!state.pendingKey || !state.data) return false;+ const found = findItem(state.data, state.pendingKey);+ set({ pendingKey: null, selectedId: found ? found.id : state.selectedId });+ return !!found;+}++export function setCrumb(c: Crumb) {+ set({ crumb: c });+}++export function setNotice(n: InboxNotice | null) {+ set({ notice: n });+}++/** The item for `?item=`: its id, or its task id (the Mission board and Dev desk know only the task). */+export function findItem(data: InboxResponse | null, key: string | null): InboxItem | null {+ if (!data || !key) return null;+ const all = [...data.items, ...(data.batch_items ?? [])];+ return all.find((i) => i.id === key) ?? all.find((i) => i.task_id === key) ?? null;+}++/** The review item for a task, for the Mission board card and drawer. */+export function reviewForTask(taskId: string): ReviewItem | null {+ const d = state.data;+ if (!d) return null;+ const i = [...d.items, ...(d.batch_items ?? [])].find((x) => x.task_id === taskId);+ return isReview(i) ? i : null;+}++/** The batch's items, in queue order: the server's list when it sends one, else what the queue has. */+export function batchItems(data: InboxResponse | null): InboxItem[] {+ if (!data?.batch) return [];+ const pool = [...(data.batch_items ?? []), ...data.items];+ return data.batch.ids.map((id) => pool.find((i) => i.id === id)).filter((i): i is InboxItem => !!i);+}++// ---- Approve ----++function staleNote(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`;+}++/** Puts an item that failed freshness into Failed or stuck, locally, until the next load agrees. */+export function comeBack(item: InboxItem, paths: string[]) {+ const back: InboxItem = {+ ...item,+ group: 'failed_or_stuck',+ sort_key: [2, 0, Date.now(), item.kwant_name, item.id],+ stale: { paths, at: new Date().toISOString() },+ one_tap: false,+ batchable: false,+ };+ cameBack.set(item.id, back);+ set((s) => (s.data ? { data: { ...s.data, items: [...s.data.items.filter((i) => i.id !== item.id), back].sort(cmpSortKey) } } : {}));+}++function dropItem(id: string) {+ set((s) => {+ if (!s.data) return {};+ const items = s.data.items.filter((i) => i.id !== id);+ return { data: { ...s.data, items } };+ });+}++/** The next item after `id` in queue order, to open once `id` leaves. */+export function nextAfter(data: InboxResponse | null, id: string): string | null {+ if (!data) return null;+ const rows = data.items;+ const at = rows.findIndex((i) => i.id === id);+ const after = rows.slice(at + 1).find((i) => isReview(i)) ?? rows.slice(0, Math.max(0, at)).reverse().find((i) => isReview(i));+ return after ? after.id : data.batch ? 'batch' : null;+}++/** Inline Approve on a one-tap row. */+export async function approveOne(item: InboxItem): Promise<void> {+ if (!isReview(item) || state.busy) return;+ const title = item.title;+ set({ busy: item.id, notice: null });+ try {+ await inboxApi.verify(item.task_id, item.verdict.id);+ const next = state.selectedId === item.id ? nextAfter(state.data, item.id) : state.selectedId;+ dropItem(item.id);+ set({ busy: null, selectedId: next, notice: { text: `Approved: “${title}”.`, tone: 'ok' } });+ } catch (e) {+ if (e instanceof InboxError && e.stale) {+ comeBack(item, e.paths);+ set({ busy: null, notice: { text: `Couldn’t approve: ${title}. ${staleNote(e.paths)}, so nothing was approved.`, tone: 'error' } });+ } else {+ const why = e instanceof Error ? e.message : 'Something went wrong';+ set({ busy: null, notice: { text: `Couldn’t approve “${title}”. ${why}. Nothing was approved.`, tone: 'error' } });+ }+ }+ void loadInbox();+}++/** "Check again" on an item that failed freshness: reruns the checks; it goes back to To review when they pass. */+export async function checkAgain(item: InboxItem): Promise<void> {+ if (!item.task_id || state.busy) return;+ set({ busy: item.id, notice: null });+ try {+ await inboxApi.runChecks(item.task_id);+ cameBack.delete(item.id);+ set({ busy: null, notice: { text: `Checking “${item.title}” again. It goes back to To review when the checks pass.`, tone: 'info' } });+ } catch (e) {+ set({ busy: null, notice: { text: `Couldn’t start the checks for “${item.title}”. ${e instanceof Error ? e.message : ''}`.trim(), tone: 'error' } });+ }+ void loadInbox();+}++// ---- Approve all ----++/** Starts Approve all. One verify at a time, in queue order; keeps going if the page unmounts. */+export async function approveAll(): Promise<void> {+ if (state.batch?.running) return;+ const items = batchItems(state.data).filter(isReview);+ if (items.length < 2) return;+ const rows: BatchRow[] = items.map((i) => ({ id: i.id, task_id: i.task_id, title: i.title, kwant_id: i.kwant_id, kwant_name: i.kwant_name, status: 'waiting' }));+ set({ batch: { rows, current: 0, running: true, stopRequested: false, halted: null }, notice: null, selectedId: state.selectedId ?? 'batch' });+ await runBatch(items);+}++/** Finishes the current item, then leaves the rest in To review. */+export function stopAfterThisOne() {+ set((s) => (s.batch?.running ? { batch: { ...s.batch, stopRequested: true } } : {}));+}++function patchRow(idx: number, patch: Partial<BatchRow>, run: Partial<BatchRun> = {}) {+ set((s) => {+ if (!s.batch) return {};+ const rows = s.batch.rows.map((r, i) => (i === idx ? { ...r, ...patch } : r));+ return { batch: { ...s.batch, ...run, rows } };+ });+}++async function runBatch(items: ReviewItem[]) {+ for (let i = 0; i < items.length; i++) {+ const b = state.batch;+ if (!b) return;+ if (b.stopRequested) {+ set((s) => ({ batch: s.batch && { ...s.batch, rows: s.batch.rows.map((r, n) => (n >= i && r.status === 'waiting' ? { ...r, status: 'stopped' } : r)) } }));+ break;+ }+ const item = items[i];+ patchRow(i, { status: 'approving' }, { current: i });+ try {+ await inboxApi.verify(item.task_id, item.verdict.id);+ patchRow(i, { status: 'approved' });+ announce(`Approved: “${item.title}”.`);+ } catch (e) {+ if (e instanceof InboxError && e.stale) {+ comeBack(item, e.paths);+ patchRow(i, { status: 'came_back', note: `${staleNote(e.paths)} · back in Failed or stuck` });+ announce(`“${item.title}” came back: ${staleNote(e.paths)}.`);+ continue;+ }+ const status = e instanceof InboxError ? e.status : 0;+ const why = e instanceof Error ? e.message : 'Something went wrong';+ patchRow(i, { status: 'error', note: `Couldn’t approve: ${why}. Nothing was approved.` });+ if (status === 0 || status === 401 || status === 403) {+ // Every next call would fail the same way: stop, and leave the rest in To review.+ set((s) => ({+ batch: s.batch && {+ ...s.batch,+ halted: status === 0 ? 'The server didn’t answer, so the batch stopped.' : 'You need to sign in again, so the batch stopped.',+ rows: s.batch.rows.map((r, n) => (n > i && r.status === 'waiting' ? { ...r, status: 'stopped' } : r)),+ },+ }));+ break;+ }+ }+ }+ const done = state.batch;+ if (done) {+ const ok = done.rows.filter((r) => r.status === 'approved').length;+ const back = done.rows.filter((r) => r.status === 'came_back').length;+ const left = done.rows.filter((r) => r.status === 'stopped').length;+ const parts = [`Approved ${ok} of ${done.rows.length}`];+ if (back) parts.push(`${back} came back`);+ if (left) parts.push(`${left} left in To review`);+ set({ batch: { ...done, running: false, current: -1, stopRequested: false }, notice: { text: `${parts.join(' · ')}.`, tone: back || done.halted ? 'info' : 'ok' } });+ }+ await loadInbox();+}++function announce(text: string) {+ set({ notice: { text, tone: 'info' } });+}++/** Clears a finished run's rows (the card goes back to whatever the server sends). */+export function clearBatch() {+ if (state.batch?.running) return;+ set({ batch: null });+}+++/**+ * How other pages reach the Inbox. App sets `go` (show Inbox › New); while it is unset (tests, a page+ * mounted on its own) the Mission board and Dev desk keep their old review buttons.+ */+export const inboxNav: { go: ((crumb: Crumb) => void) | null } = { go: null };++/** The Mission board's Review button and the Dev desk's Review in Inbox: open the task's item, with a crumb back. */+export function openReview(taskId: string, crumb: Crumb): void {+ openItem(taskId, crumb);+ inboxNav.go?.(crumb);+}++/** The review item whose PR is this one (the Dev desk card knows the PR, not the task). */+export function reviewForPr(url: string | null | undefined, number: number | null | undefined): ReviewItem | null {+ const d = state.data;+ if (!d || (!url && number == null)) return null;+ const norm = (u: string) => u.replace(/\/+$/, '').toLowerCase();+ const all = [...d.items, ...(d.batch_items ?? [])].filter(isReview);+ return all.find((i) => !!url && !!i.evidence.pr?.url && norm(i.evidence.pr.url) === norm(url)) ?? null;+}diff --git a/frontend/tests/attentionOrder.test.mjs b/frontend/tests/attentionOrder.test.mjsindex b9f40e8c..21ab629f 100644--- a/frontend/tests/attentionOrder.test.mjs+++ b/frontend/tests/attentionOrder.test.mjs@@ -1,6 +1,6 @@// H5 attention order (release-090/designs/h5-attention-order.md): one order everywhere a list of bots-// or items is scanned. 1 Needs you · 2 Stuck or failed · 3 Finished, not read · 4 Working · 5 Waiting · 6 the rest.-// Desktop pins ranks 1–3 above Channels (copies); the phone's Chats tab moves bots into sections.+// or items is scanned. 1 Needs you · 2 Stuck or failed · 3 To review (0.9.0 V1) · 4 Finished, not read · 5 Working ·+// 6 Waiting · 7 the rest. Desktop pins ranks 1–4 above Channels (copies); the phone's Chats tab moves bots into sections.import assert from 'node:assert/strict';import test from 'node:test';import { JSDOM } from 'jsdom';@@ -42,35 +42,35 @@ const rows = (over = {}) => m.attentionRows({ kwants, needs: m.needsYouRows(waitconst order = (rs) => rs.map((r) => `${r.rank}:${r.kwant.name}`);test('the one order: each bot once, at its highest rank, ties by name', () => {- assert.deepEqual(order(rows()), ['1:Lin', '1:Pixel', '2:Juno', '3:Iris', '4:Rigel', '4:Vega', '5:Mira', '6:Ada']);+ assert.deepEqual(order(rows()), ['1:Lin', '1:Pixel', '2:Juno', '4:Iris', '5:Rigel', '5:Vega', '6:Mira', '7:Ada']);const r = rows();assert.equal(r.find((x) => x.kwant.id === 'jun').line, 'Failed: Claude stopped answering');assert.equal(r.find((x) => x.kwant.id === 'iri').line, 'Finished: legend under the plot');assert.equal(m.attentionRank({ needs: true, failed: true, working: true }), 1);assert.equal(m.attentionRank({ failed: true, finished: true }), 2);- assert.equal(m.attentionRank({ queued: true }), 5);- assert.equal(m.attentionRank({}), 6);+ assert.equal(m.attentionRank({ queued: true }), 6);+ assert.equal(m.attentionRank({}), 7);assert.equal(m.stuckLine({ kind: 'delegation', status: 'stuck', title: 'Long crawl' }), 'Stuck: Long crawl');});-test('inside groups: needs and stuck oldest first, finished newest first, rank 6 keeps its order', () => {+test('inside groups: needs and stuck oldest first, finished newest first, rank 7 keeps its order', () => {const two = [item('delegation', 'jun', { status: 'failed', timestamp: at(10) }), item('delegation', 'rig', { status: 'failed', timestamp: at(40) })];const fin = [item('delegation', 'iri', { status: 'completed', timestamp: at(30) }), item('delegation', 'veg', { status: 'completed', timestamp: at(5) })];const r = rows({ failed: two, finished: fin, busy: {}, status: {} });- assert.deepEqual(order(r).slice(0, 6), ['1:Lin', '1:Pixel', '2:Rigel', '2:Juno', '3:Vega', '3:Iris']);- assert.deepEqual(order(r).slice(6), ['6:Ada', '6:Mira'], 'the stable sidebar order, as given');+ assert.deepEqual(order(r).slice(0, 6), ['1:Lin', '1:Pixel', '2:Rigel', '2:Juno', '4:Vega', '4:Iris']);+ assert.deepEqual(order(r).slice(6), ['7:Ada', '7:Mira'], 'the stable sidebar order, as given');// attentionSort alone- const s = m.attentionSort([{ kwant: { name: 'B' }, rank: 4 }, { kwant: { name: 'A' }, rank: 4 }, { kwant: { name: 'Z' }, rank: 1, at: 2 }, { kwant: { name: 'Y' }, rank: 1, at: 1 }]);+ const s = m.attentionSort([{ kwant: { name: 'B' }, rank: 5 }, { kwant: { name: 'A' }, rank: 5 }, { kwant: { name: 'Z' }, rank: 1, at: 2 }, { kwant: { name: 'Y' }, rank: 1, at: 1 }]);assert.deepEqual(s.map((x) => x.kwant.name), ['Y', 'Z', 'A', 'B']);});-test('rank 2 only counts failures from the last 24 h; rank 3 ends once the chat is opened', () => {+test('rank 2 only counts failures from the last 24 h; rank 4 (finished) ends once the chat is opened', () => {const old = [item('delegation', 'jun', { status: 'failed', timestamp: at(25 * 60) })];- assert.equal(rows({ failed: old }).find((x) => x.kwant.id === 'jun').rank, 6);+ assert.equal(rows({ failed: old }).find((x) => x.kwant.id === 'jun').rank, 7);// Opened Iris's chat after it finished: read- assert.equal(rows({ openedAt: { iri: NOW - 60_000 } }).find((x) => x.kwant.id === 'iri').rank, 6);+ assert.equal(rows({ openedAt: { iri: NOW - 60_000 } }).find((x) => x.kwant.id === 'iri').rank, 7);// Opened before it finished: still unread- assert.equal(rows({ openedAt: { iri: NOW - 3600_000 } }).find((x) => x.kwant.id === 'iri').rank, 3);+ assert.equal(rows({ openedAt: { iri: NOW - 3600_000 } }).find((x) => x.kwant.id === 'iri').rank, 4);});test('rollup words: zeros left out, "1 needs you", working only when nothing else', () => {diff --git a/frontend/tests/inboxV1.test.mjs b/frontend/tests/inboxV1.test.mjsnew file mode 100644index 00000000..b267d805--- /dev/null+++ b/frontend/tests/inboxV1.test.mjs@@ -0,0 +1,149 @@+// 0.9.0 V1 review inbox (release-090/designs/v1-review-inbox.md, verification-plan.md D1–D5): the Approve all+// runner, the badge, H5 rank 3 "To review", the two-pane queue, and the Mission board / Dev desk entry points.+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/', pretendToBeVisual: true });+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'DOMParser', 'localStorage', 'sessionStorage', 'getComputedStyle']) {+ if (k in dom.window) Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });+}++const m = await loadBundled(`+ export { default as React } from 'react';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export * as store from './src/inboxStore';+ export { inboxApi, InboxError, inboxBadge, verdictShort, INBOX_FIXTURE, INBOX_FIXTURE_EMPTY, FIXTURE_BATCH } from './src/api/inbox';+ export { attentionRows, attentionRank, PINNED_RANK, rollupLabel } from './src/chatsTab';+ export { InboxNew } from './src/components/InboxNew';+ export { TaskCard } from './src/components/MissionBoardView';+`);+const { React, store: s, inboxApi, InboxError } = m;+const html = (el) => m.renderToStaticMarkup(el);+const doc = (h) => new DOMParser().parseFromString(`<body>${h}</body>`, 'text/html');+const clone = (x) => JSON.parse(JSON.stringify(x));++const seed = (data = clone(m.INBOX_FIXTURE)) => {+ s.inboxStore.reset();+ s.inboxSource.get = async () => data;+ s.inboxStore.patch({ data });+ return data;+};++test('badge: counts.badge when the server sends it, else unseen + pre-push', () => {+ assert.equal(m.inboxBadge({ counts: { badge: 13 } }, { unseen: { total: 2 } }, 1), 13);+ assert.equal(m.inboxBadge({ counts: {} }, { unseen: { total: 2 } }, 1), 3);+ assert.equal(m.inboxBadge(null, null, 0), 0);+});++test('Approve all: one at a time with verdict_id; a stale item comes back on its own and the rest carry on', async () => {+ seed();+ const calls = [];+ inboxApi.verify = async (taskId, verdictId) => {+ calls.push([taskId, verdictId]);+ if (taskId === m.FIXTURE_BATCH[1].task_id) throw new InboxError(409, 'stale', 'stale', ['src/a.ts']);+ };+ await s.approveAll();+ const b = s.inboxStore.get().batch;+ assert.deepEqual(calls, m.FIXTURE_BATCH.map((i) => [i.task_id, i.verdict.id]), 'every item, in order, each with its verdict id');+ assert.deepEqual(b.rows.map((r) => r.status), ['approved', 'came_back', 'approved', 'approved', 'approved']);+ assert.equal(b.running, false);+ const back = s.inboxStore.get().data.items.find((i) => i.id === m.FIXTURE_BATCH[1].id);+ assert.equal(back?.group, 'failed_or_stuck', 'its own row in Failed or stuck');+ assert.match(s.inboxStore.get().notice.text, /Approved 4 of 5 · 1 came back/);+});++test('Approve all: "Stop after this one" finishes the current item and leaves the rest', async () => {+ seed();+ let n = 0;+ inboxApi.verify = async () => {+ n++;+ if (n === 2) s.stopAfterThisOne();+ };+ await s.approveAll();+ assert.deepEqual(s.inboxStore.get().batch.rows.map((r) => r.status), ['approved', 'approved', 'stopped', 'stopped', 'stopped']);+ assert.equal(n, 2);+});++test('Approve all: signed out halts the run; nothing after it is tried', async () => {+ seed();+ let n = 0;+ inboxApi.verify = async () => {+ if (++n === 2) throw new InboxError(401, 'Sign in again');+ };+ await s.approveAll();+ const b = s.inboxStore.get().batch;+ assert.deepEqual(b.rows.map((r) => r.status), ['approved', 'error', 'stopped', 'stopped', 'stopped']);+ assert.match(b.halted, /sign in again/);+ assert.equal(n, 2);+});++test('deep link: ?item= takes an item id or a task id; the crumb remembers where it came from', () => {+ const data = seed();+ const it = data.items.find((i) => i.kind === 'review');+ s.openItem(it.task_id, 'board');+ assert.equal(s.inboxStore.get().selectedId, it.id);+ assert.equal(s.inboxStore.get().crumb, 'board');+ s.inboxStore.patch({ data: null });+ s.openItem('r-later', null);+ assert.equal(s.inboxStore.get().pendingKey, 'r-later', 'resolved once the list loads');+});++test('H5 rank 3 is To review; the pinned block covers 1–4 and the rollup counts it', () => {+ const data = clone(m.INBOX_FIXTURE);+ const review = data.items.find((i) => i.kind === 'review' && i.group === 'to_review');+ assert.equal(m.attentionRank({ review }), 3);+ assert.equal(m.PINNED_RANK, 4);+ const kw = { id: review.kwant_id, name: review.kwant_name };+ const rows = m.attentionRows({ kwants: [kw, { id: 'zz', name: 'Zed' }], needs: [], failed: [], finished: [], busy: new Set(), status: {}, openedAt: {}, reviews: [review] });+ assert.equal(rows[0].rank, 3);+ assert.match(rows[0].line ?? rows[0].text ?? JSON.stringify(rows[0]), /To review/);+ assert.equal(m.rollupLabel({ needs: 0, stuck: 0, finished: 0, review: 2 }), '2 to review');+});++test('Inbox › New, wide: 392px queue, item pane with the first review selected, Low-risk card with Approve all N', () => {+ seed();+ 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']);+ const card = d.querySelector('[data-batch-card]');+ assert.ok(card);+ assert.match(d.querySelector('[data-approve-all]').textContent, /Approve all 5/);+ assert.ok(d.querySelector('[data-inline-approve]'), 'a one-tap row has inline Approve');+ assert.ok(d.querySelector('[data-item-pane]'));+});++test('Inbox › New, phone: a list; empty shows all clear', () => {+ seed(clone(m.INBOX_FIXTURE_EMPTY));+ const d = doc(html(React.createElement(m.InboxNew, { noLoad: true, wide: false })));+ assert.ok(d.querySelector('[data-inbox-new="list"]'));+ assert.ok(d.querySelector('[data-all-clear]'));+});++const task = (over = {}) => ({+ id: 't1', space_id: 's1', mission_id: 'm1', mission_title: 'M', title: 'Write the pricing copy', acceptance: '', state: 'review', priority: 1,+ owner_kwant_id: 'k_lin', owner_name: 'Lin', suggested_kwant_id: null, budget_tokens: 50000, spent_tokens: 12400,+ attempts: 0, max_attempts: 3, blocked_reason: null, source_kind: 'mission', source_id: 'm1',+ channel_id: 'c1', direct_kwant_id: null, thread_id: null, created_by: 'k_ada',+ created_at: '2026-10-27T09:00:00Z', updated_at: '2026-10-27T11:00:00Z', finished_at: null,+ depends_on: [], waiting_on: [], claim: null, needs_you: [], checks_summary: { status: 'passed', passed: 2, failed: 0, total: 2 }, ...over,+});++test('Mission board card in Review: one "Review" button (verdict under the title), Dismiss stays, no Mark verified or Send back', () => {+ const data = seed();+ const it = data.items.find((i) => i.kind === 'review' && i.verdict.result === 'pass' && i.verdict.confidence);+ const card = (p) => doc(html(React.createElement('ul', null, React.createElement(m.TaskCard, { task: task({ id: it.task_id }), names: {}, onOpen: () => {}, onQuick: () => {}, ...p }))));+ s.inboxNav.go = () => {};+ const d = card();+ assert.ok(d.querySelector('[data-card-review]'));+ assert.equal(d.querySelector('[data-card-action="verify"]'), null);+ assert.equal(d.querySelector('[data-card-action="reject"]'), null);+ assert.ok(d.querySelector('[data-card-action="cancel"]'), 'Dismiss stays');+ assert.equal(d.querySelector('[data-card-verdict]').textContent, m.verdictShort(it.verdict));+ s.inboxNav.go = null;+ const old = card();+ assert.equal(old.querySelector('[data-card-review]'), null, 'without the Inbox the old buttons stay');+ assert.ok(old.querySelector('[data-card-action="verify"]'));+});