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.0 H5: one attention order in the sidebar, phone Chats tab and Inbox (#494)
Oleksandr Ivanchenkod28fef6dd959
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 15c5c36e..bdff416e 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -132,7 +132,7 @@ import {turnsAwaitingAnswer,} from './questions';import { AwayItem, affectsAway, awayApi, awayTarget } from './away';-import { needsYouRows } from './chatsTab';+import { needsYouRows, attentionRows } from './chatsTab';import { Space, eventsUrl, getCurrentSpace, pickInitialChat } from './spaces';import { canRunNow } from './engines';import { useEngines } from './useEngines';@@ -520,6 +520,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const [awayWaiting, setAwayWaiting] = useState(0);/** What waits on you right now (approvals, questions), for the phone Chats tab's Needs you. */const [awayItems, setAwayItems] = useState<AwayItem[]>([]);+ /** H5: unseen failed and finished items (ranks 2 and 3), and whether the first fetch has landed. */+ const [awayDone, setAwayDone] = useState<{ failed: AwayItem[]; finished: AwayItem[] } | null>(null);+ /** H5: when the person last opened each bot's chat (a finished item older than that is read). */+ const [openedAt, setOpenedAt] = useState<Record<string, number>>({});const [pill, setPill] = useState<PillState>(EMPTY_PILL);const [nudgesOn, setNudgesOn] = useState(nudgesEnabled);const nudgesOnRef = useRef(nudgesOn);@@ -534,6 +538,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setPill((prev) => pillAdd(prev, shown));haptic('warning');};+ // H5: the chat open now is read; when it closes, the time it was last seen stays.+ const readChat = page === 'chat' && !isChannel && selectedId ? selectedId : null;+ useEffect(() => {+ if (!readChat) return;+ 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) => {@@ -543,6 +554,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setAwayCount(r.unseen.total);setAwayWaiting(r.unseen.waiting);setAwayItems(r.waiting);+ setAwayDone({ failed: r.failed, finished: r.finished });const fresh = arrivalsRef.current.fromAway(r.waiting);setPill((prev) => pillPrune(prev, new Set(r.waiting.map((i) => `${i.kind}:${i.id}`))));offerNudges(fresh);@@ -3673,6 +3685,20 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({</main>);+ // H5: every bot in the one attention order. Not computed until the Inbox's first fetch lands, so the+ // pinned block never flashes empty-then-full. The open chat counts as read while it is open.+ const attention = awayDone+ ? attentionRows({+ kwants,+ needs: needsYouRows(awayItems, needsYouByKwant, new Set(kwants.map((k) => k.id))),+ failed: awayDone.failed,+ finished: awayDone.finished,+ busy: busyKwants,+ status: botStatus,+ openedAt: page === 'chat' && !isChannel && selectedId ? { ...openedAt, [selectedId]: Date.now() } : openedAt,+ })+ : undefined;+const sidebar = (section: 'all' | 'chats' | 'bots') => (<Sidebarspace={space}@@ -3702,6 +3728,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({botStatus={botStatus}needsYou={needsYouByKwant}needsYouRows={isPhone && section === 'chats' ? needsYouRows(awayItems, needsYouByKwant, new Set(kwants.map((k) => k.id))) : undefined}+ attention={attention}onOpenNeedsYou={(row) => {// A question or approval opens its chat (or thread) on the card; a browser step, the bot's chat.if (row.item) openAwayItem(row.item);diff --git a/frontend/src/away.ts b/frontend/src/away.tsindex 26b92fb1..fc216286 100644--- a/frontend/src/away.ts+++ b/frontend/src/away.ts@@ -50,10 +50,29 @@ export interface AwayResponse {export const AWAY_SECTIONS: { key: AwaySection; label: string; empty: string }[] = [{ key: 'waiting', label: 'Waiting on you', empty: 'No questions or approvals waiting.' },- { key: 'finished', label: 'Finished', empty: 'Nothing finished since you last looked.' },{ key: 'failed', label: 'Failed or stuck', empty: 'Nothing failed or stuck.' },+ { key: 'finished', label: 'Finished', empty: 'Nothing finished since you last looked.' },];+/** H5: how each section is sorted, said after its count on desktop. */+export const AWAY_SORT_HINT: Record<AwaySection, string> = {+ waiting: 'oldest first',+ failed: 'oldest first',+ finished: 'not read first, then newest',+};++/**+ * H5 order inside a section: waiting and failed oldest first (the longest wait on top); finished+ * not read (newer than `lastSeen`) first, then newest first.+ */+export function sortAwaySection(key: AwaySection, items: AwayItem[], lastSeen?: string | null): AwayItem[] {+ const t = (i: AwayItem) => Date.parse(i.timestamp) || 0;+ if (key !== 'finished') return [...items].sort((a, b) => t(a) - t(b));+ const seen = lastSeen ? Date.parse(lastSeen) || 0 : 0;+ const unread = (i: AwayItem) => (t(i) > seen ? 0 : 1);+ return [...items].sort((a, b) => unread(a) - unread(b) || t(b) - t(a));+}+/** "just now", "5 min ago", "3 h ago", "yesterday", "4 days ago", else the date. */export function relativeTime(ts: string, now: number = Date.now()): string {const t = Date.parse(ts);diff --git a/frontend/src/chatsTab.ts b/frontend/src/chatsTab.tsindex bc3b857d..10435b1e 100644--- a/frontend/src/chatsTab.ts+++ b/frontend/src/chatsTab.ts@@ -60,3 +60,121 @@ export const workingIds = <K extends { id: string; name: string }>(kwants: K[],/** Direct chats: every other bot, by name (the client can't tell which direct chats have messages yet). */export const directIds = <K extends { id: string; name: string }>(kwants: K[], shown: Set<string>): K[] =>kwants.filter((k) => !shown.has(k.id)).sort((a, b) => a.name.localeCompare(b.name));++// ---- 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.+ */+export type AttentionRank = 1 | 2 | 3 | 4 | 5 | 6;++export interface AttentionRow<K> {+ kwant: K;+ rank: AttentionRank;+ /** The status line for ranks 1–3 ("Asked you a question", "Stuck: …", "Finished: …"). */+ line?: string;+ /** Ranks 1–3: the ask or Inbox item it comes from (none for a browser step). */+ item?: AwayItem;+ needs?: NeedsYouRow;+ /** When it asked, failed or finished, for the order inside the group. */+ at?: number;+}++export interface AttentionInput<K> {+ kwants: K[];+ /** `needsYouRows()`: already oldest first. */+ needs: NeedsYouRow[];+ /** Inbox `failed` items (until H4 ships its `stuck` status, the only source of rank 2). */+ failed?: AwayItem[];+ /** Inbox `finished` items not seen yet. */+ finished?: AwayItem[];+ /** Live turns per bot (`busyLines`), and each bot's dot status (queued vs working). */+ busy?: Record<string, string>;+ status?: Record<string, string>;+ /** When the person last opened each bot's chat: a finished item older than that has been read. */+ openedAt?: Record<string, number>;+ now?: number;+}++const FAILED_WINDOW_MS = 24 * 3600_000;+const ts = (i?: AwayItem) => (i ? Date.parse(i.timestamp) || 0 : 0);++/** Rank 2's line: what broke, in the Inbox's words. */+export const stuckLine = (i: AwayItem): string => {+ const what = i.status === 'stuck' ? 'Stuck' : i.kind === 'routine_run' ? 'Routine failed' : i.status === 'interrupted' ? 'Interrupted' : 'Failed';+ return i.title ? `${what}: ${i.title}` : what;+};++export const finishedLine = (i: AwayItem): string => (i.title ? `Finished: ${i.title}` : 'Finished');++/** 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 {+ 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;+}++/**+ * 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.+ */+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);+ 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 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>();+ for (const i of failed) {+ const t = ts(i);+ if (now - t > FAILED_WINDOW_MS) continue;+ const had = failedBy.get(i.kwant_id);+ if (!had || t < ts(had)) failedBy.set(i.kwant_id, i);+ }+ const finishedBy = new Map<string, AwayItem>();+ for (const i of finished) {+ const t = ts(i);+ if ((openedAt[i.kwant_id] ?? 0) >= t) continue;+ const had = finishedBy.get(i.kwant_id);+ if (!had || t > ts(had)) finishedBy.set(i.kwant_id, i);+ }+ 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 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) };+ return { kwant: k, rank };+ });+ // Needs-you rows keep needsYouRows' own order (oldest ask first; a browser step has no time)+ 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)];+}++/** "2 need you, 1 stuck, 1 finished" (zeros left out). */+export function rollupLabel(counts: { needs: number; stuck: 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.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/AwayView.tsx b/frontend/src/components/AwayView.tsxindex 25e8553a..6f301241 100644--- a/frontend/src/components/AwayView.tsx+++ b/frontend/src/components/AwayView.tsx@@ -5,6 +5,8 @@ import { ModernApprovalCard } from './ModernApprovalCard';import { approvalFromAway, awayTitle, lateAnswerText } from '../approvals';import {AWAY_SECTIONS,+ AWAY_SORT_HINT,+ sortAwaySection,ApprovalDecision,AwayError,AwayItem,@@ -206,9 +208,14 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice{SECTION_ICON[key]}{label}<span className="font-mono normal-case text-zinc-600">({data[key].length})</span>+ {data[key].length > 1 && (+ <span data-away-hint={key} className="hidden md:inline normal-case tracking-normal font-normal text-zinc-500">+ · {AWAY_SORT_HINT[key]}+ </span>+ )}</h3>{data[key].length > 0 ? (- <ul className="space-y-2">{data[key].map(renderItem)}</ul>+ <ul className="space-y-2">{sortAwaySection(key, data[key], data.last_seen).map(renderItem)}</ul>) : (<p className="px-1 text-xs text-zinc-500">{none}</p>)}diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 0febc7a8..ace39abf 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -16,7 +16,7 @@ import { teamChannelOf } from '../teamChannel';import { layaRoutes } from '../channels';import { InstallAppButton } from './InstallAppButton';import { trapFocusTarget } from '../imports';-import { type NeedsYouRow, workingIds, directIds } from '../chatsTab';+import { type AttentionRow, type NeedsYouRow, workingIds, directIds, rollupLabel } from '../chatsTab';import { DevFlipNote, useDevMode } from './DevModeSwitch';import { SpaceControls } from './SpaceControls';import { DevOnToast } from './DevOnToast';@@ -116,6 +116,11 @@ export interface SidebarProps {onWatchBrowser?: (owner: string) => void;/** Owners whose browser holds an open step for the person: their rows show that, not the globe. */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.+ */+ attention?: AttentionRow<Kwant>[];/** Opens a Needs-you row's chat on its card. */onOpenNeedsYou?: (row: NeedsYouRow) => void;onSelectKwant: (kwant: Kwant) => void;@@ -268,6 +273,58 @@ const MoreMenu: React.FC<{);};+/** H5: the most rows the desktop's pinned block shows before "and n more in Inbox". */+export const PINNED_MAX = 5;++/**+ * H5 desktop: "Needs attention · n", ranks 1–3 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 }) => {+ const n = rows.length;+ const [said, setSaid] = useState(n);+ const lastSaid = React.useRef(0);+ useEffect(() => {+ if (n === said) return;+ const wait = Math.max(0, lastSaid.current + 10_000 - Date.now());+ const t = setTimeout(() => {+ lastSaid.current = Date.now();+ setSaid(n);+ }, wait);+ return () => clearTimeout(t);+ }, [n, said]);+ const more = n - PINNED_MAX;+ return (+ <section data-needs-attention aria-labelledby="needs-attention-head" className="rounded-xl border border-hairline bg-white/[0.015] my-1.5 pb-1.5">+ <h2 id="needs-attention-head" className="px-2 pt-1.5 pb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.06em] text-amber-300" aria-label={`Needs attention, ${n}`}>+ <Hand size={12} aria-hidden="true" />+ <span aria-hidden="true">Needs attention · {n}</span>+ </h2>+ <span className="sr-only" aria-live="polite" data-needs-attention-live>+ {said !== n || lastSaid.current ? `Needs attention, ${said}` : ''}+ </span>+ <div className="space-y-0.5 px-0.5">+ {rows.slice(0, PINNED_MAX).map((a) => (+ <div key={a.kwant.id} className="kw-pin-enter">+ {row(a)}+ </div>+ ))}+ </div>+ {more > 0 && (+ <button+ type="button"+ data-needs-attention-more+ onClick={onOpenInbox}+ disabled={!onOpenInbox}+ className="ml-2 mt-0.5 px-1 rounded text-[12px] text-sky-300 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ >+ and {more} more in Inbox+ </button>+ )}+ </section>+ );+};+export const Sidebar: React.FC<SidebarProps> = ({space,spaces,@@ -292,6 +349,7 @@ export const Sidebar: React.FC<SidebarProps> = ({onWatchBrowser,browserNeedsYou,needsYouRows = [],+ attention,onOpenNeedsYou,onSelectKwant,onSelectChannel,@@ -367,7 +425,24 @@ export const Sidebar: React.FC<SidebarProps> = ({// chats (a new row, with no globe) in the same frame (QA F2 on phone)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 directBots = chatsTab ? directIds(kwants, new Set([...needsIds, ...workingBots.map((k) => k.id)])) : [];+ 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+ // 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) : []);+ const phoneSections = chatsTab && attention+ ? ([+ { 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) },+ ] 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 rankOf = new Map((attention ?? []).map((a) => [a.kwant.id, a.rank]));const toggleTeam = (id: string) =>setCollapsedTeams((prev) => {@@ -467,10 +542,13 @@ export const Sidebar: React.FC<SidebarProps> = ({// team the lead is marked and others can be removed; on phones those sit in a sheet.// On the phone's Chats tab a row is a plain launcher (`chat`): taller, no actions, and a// Needs-you row says in amber what the bot is waiting for and opens the chat on that card.- const botRow = (k: Kwant, team?: Team, chat?: { needs?: NeedsYouRow }) => {+ const botRow = (k: Kwant, team?: Team, chat?: { needs?: NeedsYouRow; att?: AttentionRow<Kwant> }, pin?: { att: AttentionRow<Kwant>; alsoIn?: string }) => {// Phones never light a row: the list is a launcher, and coming back to it shows no stale selectionconst active = !phone && !isChannel && selectedId === k.id;- const asked = chat?.needs;+ 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;const status = asked ? 'needs_you' : statusOf(k.id, botStatus, canRun);const isLead = !!team && k.id === team.lead_kwant_id;const canRemove = !!team && !isLead && !!onUpdateTeamMembers;@@ -484,23 +562,34 @@ export const Sidebar: React.FC<SidebarProps> = ({const warn = needs > 0 || status === 'needs_you';const busyLine = asked? asked.line+ : attLine+ ? attLine: needs > 0 && !busyKwants[k.id]?.startsWith('Needs you in the browser')? 'Needs you in the browser': busyKwants[k.id];- const open = asked && onOpenNeedsYou ? () => onOpenNeedsYou(asked) : () => onSelectKwant(k);+ // A stuck or finished row opens where that happened (its thread or chat), like its Inbox card+ const open = asked && onOpenNeedsYou+ ? () => onOpenNeedsYou(asked)+ : attLine && att?.item && onOpenNeedsYou+ ? () => onOpenNeedsYou({ kwant_id: k.id, line: attLine, item: att.item })+ : () => onSelectKwant(k);// The globe steps aside while the row says it needs you in the browser (that line leads there), and// while the browser it shows holds an open step: one browser per chat, so every row on it hides (Mira 3)const botWatch = browsingBots[k.id] ?? browsingOwners[k.id];const botBrowsing = onWatchBrowser && !warn && !asked && botWatch && !browserNeedsYou?.has(botWatch.owner) ? botWatch : undefined;return (<div- key={`${chat ? 'chat' : team?.id ?? 'none'}:${k.id}`}+ key={`${pin ? 'pin' : chat ? 'chat' : team?.id ?? 'none'}:${k.id}`}role="button"tabIndex={0}onClick={open}// Only the row's own Enter: Enter on its ✕ or Edit is for that button, not for opening the chat.onKeyDown={(e) => e.key === 'Enter' && e.target === e.currentTarget && open()}- data-bot-row={k.id}+ // The pinned copy is not the bot's row: focus returns to the one in its team+ data-bot-row={pin ? undefined : k.id}+ data-pin-row={pin ? k.id : undefined}+ data-rank={att?.rank}+ aria-describedby={pin?.alsoIn ? `pin-also-${k.id}` : undefined}data-chat-row={chat ? (asked ? 'needs' : 'bot') : undefined}className={`group/fleet relative w-full flex items-center gap-2.5 px-2 ${chat ? 'min-h-14 py-2' : 'py-1.5'} rounded-xl text-left cursor-pointer transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${active ? 'bg-accent-soft text-zinc-50 shadow-card border border-sky-300/25' : 'text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.05] border border-transparent'@@ -590,9 +679,25 @@ export const Sidebar: React.FC<SidebarProps> = ({</span>)}</div>+ {pin?.alsoIn && (+ <span id={`pin-also-${k.id}`} className="sr-only">+ Also listed in @{pin.alsoIn}+ </span>+ )}{busyLine ? (- <p className={`flex items-center gap-1.5 text-meta truncate${actionRoom} ${warn ? 'text-warn' : status === 'queued' ? 'text-zinc-300' : 'text-[#b8adff]'}`} title={busyLine} data-bot-busy>- <span className={`kw-status-dot !h-1.5 !w-1.5 ${warn ? 'kw-status-warn' : status === 'queued' ? 'kw-status-idle' : 'bg-[#9d8fff] kw-pulse'}`} aria-hidden="true" />+ <p+ className={`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]'+ }`}+ title={busyLine}+ data-bot-busy+ >+ <span+ className={`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'+ }`}+ aria-hidden="true"+ /><span className="truncate">{busyLine}</span></p>) : (@@ -624,6 +729,35 @@ 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.+ const teamRollup = (t: Team) => {+ if (!attention) return null;+ const c = { needs: 0, stuck: 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++;+ }+ 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)+ : c.working+ ? [[c.working, 'bg-[#9d8fff]']]+ : [];+ if (!dots.length) return null;+ return (+ <span data-team-rollup={t.id} role="img" aria-label={rollupLabel(c)} title={rollupLabel(c)} className="flex items-center gap-2 mr-1">+ {dots.map(([n, dot]) => (+ <span key={dot} className="flex items-center gap-1" aria-hidden="true">+ <span className={`h-1.5 w-1.5 rounded-full ${dot}`} />+ <span className="text-[11px] tabular-nums text-zinc-400">{n}</span>+ </span>+ ))}+ </span>+ );+ };+// A team's chat row: opens the team chat; collapses its members, opens its settings.const teamRow = (t: Team, withMembers: boolean) => {const active = isTeamActive(t);@@ -660,6 +794,7 @@ export const Sidebar: React.FC<SidebarProps> = ({<span className="truncate">@{t.name}</span></div><div className="flex items-center gap-1 flex-shrink-0">+ {withMembers && !phone && teamRollup(t)}{(!expanded || !withMembers) && (<span className="text-2xs px-1.5 py-0.5 rounded-full tabular-nums bg-white/[0.05] text-zinc-300 border border-hairline" title={`${count} ${count === 1 ? 'member' : 'members'}`}>{count}@@ -750,6 +885,7 @@ export const Sidebar: React.FC<SidebarProps> = ({};const groups = botGroups(teams, kwants);+ const teamOf = (id: string) => groups.find((g) => g.team && g.bots.some((b) => b.id === id))?.team?.name;// "+ Team", "+ Bot", "+ Channel": the + says new and the heading says what kind; the full phrase is the label.const headButton = (word: string, label: string, title: string, onClick: () => void) =>phone ? (@@ -897,8 +1033,20 @@ export const Sidebar: React.FC<SidebarProps> = ({</div>)}+ {/* H5 phone Chats tab: Needs you, Stuck, Finished, Working, Waiting; an empty section is not drawn */}+ {phoneSections.map(+ (sec) =>+ sec.rows.length > 0 && (+ <section key={sec.key} data-chats-section={sec.key} aria-labelledby={`chats-${sec.key}-head`}>+ <h2 id={`chats-${sec.key}-head`} className={`${sectionHead} ${sec.tone}`}>+ {sec.head} · {sec.rows.length}+ </h2>+ <div className="mt-1 space-y-0.5">{sec.rows.map((a) => botRow(a.kwant, undefined, { att: a, needs: a.needs }))}</div>+ </section>+ ),+ )}{/* Phones' Chats tab: who needs you, then who is working, above the channels */}- {needsRows.length > 0 && (+ {!attOn && needsRows.length > 0 && (<section data-chats-section="needs" aria-labelledby="chats-needs-head"><h2 id="chats-needs-head" className={`${sectionHead} !text-[11px] !leading-4 !tracking-[0.06em] !text-warn`}>Needs you · {needsRows.length}@@ -908,7 +1056,7 @@ export const Sidebar: React.FC<SidebarProps> = ({</div></section>)}- {workingBots.length > 0 && (+ {!attOn && workingBots.length > 0 && (<section data-chats-section="working" aria-labelledby="chats-working-head"><h2 id="chats-working-head" className={sectionHead}>Working</h2><div className="mt-1 space-y-0.5">{workingBots.map((k) => botRow(k, undefined, {}))}</div>@@ -920,6 +1068,8 @@ export const Sidebar: React.FC<SidebarProps> = ({</div>)}+ {pinned.length > 0 && <NeedsAttention rows={pinned} row={(a) => botRow(a.kwant, undefined, undefined, { att: a, alsoIn: teamOf(a.kwant.id) })} onOpenInbox={onOpenInbox} />}+{/* Channels Section */}{showChats && (<div data-chats-section="channels">diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex a04e7ba9..42547842 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -995,3 +995,12 @@ button.dv-sha { cursor: copy; } button.dv-sha:hover { color: var(--accent); bord@media (prefers-reduced-motion: no-preference) {.kw-prepush-flash::after { display: block; box-shadow: 0 0 0 2px rgb(167 139 250 / 0.6); opacity: 0; animation: kw-prepush-flash 1.2s linear 1 both; }}++/* H5: a row entering the pinned "Needs attention" block (reordering inside it is not animated) */+@keyframes kw-pin-enter {+ from { opacity: 0; transform: translateY(-4px); }+ to { opacity: 1; transform: none; }+}+@media (prefers-reduced-motion: no-preference) {+ .kw-pin-enter { animation: kw-pin-enter 160ms ease-out; }+}diff --git a/frontend/tests/attentionOrder.test.mjs b/frontend/tests/attentionOrder.test.mjsnew file mode 100644index 00000000..b9f40e8c--- /dev/null+++ b/frontend/tests/attentionOrder.test.mjs@@ -0,0 +1,178 @@+// 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.+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 { Sidebar, PINNED_MAX } from './src/components/Sidebar';+ export { needsYouRows, attentionRows, attentionRank, attentionSort, rollupLabel, stuckLine } from './src/chatsTab';+ export { AWAY_SECTIONS, AWAY_SORT_HINT, sortAwaySection } from './src/away';+ export { AwayView } from './src/components/AwayView';+`);+const { React } = m;+const noop = () => {};+const NOW = Date.parse('2026-11-10T12:00:00Z');+const space = { id: 'spc_default', name: 'Trailhead', icon: '💼', color: '#f59e0b', sort: 0, is_default: true, archived_at: null,+ created_at: '', general_channel_id: null, counts: { bots: 0, ready_accounts: 0, unread: 0 }, approvals: 'on' };+const bot = (id, name) => ({ id, name, title: 'Role', persona_prompt: '', avatar_sprite: 'mouse', driver_type: 'claude', preferred_model: '' });+const kwants = [bot('lin', 'Lin'), bot('pix', 'Pixel'), bot('jun', 'Juno'), bot('iri', 'Iris'), bot('rig', 'Rigel'), bot('ada', 'Ada'), bot('mir', 'Mira'), bot('veg', 'Vega')];+const team = { id: 't1', name: 'core', icon: '🚢', lead_kwant_id: 'ada', member_kwants: ['ada', 'lin', 'pix', 'jun', 'iri', 'rig', 'mir', 'veg'] };+const at = (min) => new Date(NOW - min * 60_000).toISOString();+const item = (kind, kwant_id, over = {}) => ({ kind, id: `${kind}-${kwant_id}-${over.timestamp ?? ''}`, kwant_id, kwant_name: kwant_id, title: '', summary: '',+ status: 'waiting', timestamp: at(5), link: { thread_id: null, channel_id: null, direct_kwant_id: kwant_id }, ...over });++// Lin asked 4 min ago, Pixel wants an OK; Juno failed; Iris finished; Rigel and Vega work; Mira is queued.+// Juno also asked nothing, but Lin also failed: Lin stays rank 1 (highest only).+const waiting = [item('question', 'lin', { timestamp: at(4) }), item('approval', 'pix', { timestamp: at(1) })];+const failed = [item('delegation', 'jun', { status: 'failed', title: 'Claude stopped answering', timestamp: at(30) }), item('delegation', 'lin', { status: 'failed', timestamp: at(50) })];+const finished = [item('delegation', 'iri', { status: 'completed', title: 'legend under the plot', timestamp: at(10) })];+const busy = { rig: 'Working on #ci', veg: 'Working here', mir: 'Waiting to work on #site', lin: 'Asked you a question' };+const status = { rig: 'working', veg: 'working', mir: 'queued', lin: 'needs_you' };+const rows = (over = {}) => m.attentionRows({ kwants, needs: m.needsYouRows(waiting, {}, new Set(kwants.map((k) => k.id))), failed, finished, busy, status, now: NOW, ...over });+const 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']);+ 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.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', () => {+ 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');+ // 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 }]);+ 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', () => {+ const old = [item('delegation', 'jun', { status: 'failed', timestamp: at(25 * 60) })];+ assert.equal(rows({ failed: old }).find((x) => x.kwant.id === 'jun').rank, 6);+ // Opened Iris's chat after it finished: read+ assert.equal(rows({ openedAt: { iri: NOW - 60_000 } }).find((x) => x.kwant.id === 'iri').rank, 6);+ // Opened before it finished: still unread+ assert.equal(rows({ openedAt: { iri: NOW - 3600_000 } }).find((x) => x.kwant.id === 'iri').rank, 3);+});++test('rollup words: zeros left out, "1 needs you", working only when nothing else', () => {+ assert.equal(m.rollupLabel({ needs: 2, stuck: 1, finished: 1, working: 3 }), '2 need you, 1 stuck, 1 finished');+ assert.equal(m.rollupLabel({ needs: 1, stuck: 0, finished: 0 }), '1 needs you');+ assert.equal(m.rollupLabel({ needs: 0, stuck: 0, finished: 0, working: 2 }), '2 working');+ assert.equal(m.rollupLabel({ needs: 0, stuck: 0, finished: 0, working: 0 }), '');+});++const render = (over = {}) => m.renderToStaticMarkup(React.createElement(m.Sidebar, {+ space, spaces: [space], onSwitchSpace: noop, onCreateSpace: noop, onOpenSpaceSettings: noop, onOpenArchived: noop, onOpenSearch: noop,+ kwants, channels: [{ id: 'c1', name: 'general', space_id: 'spc_default' }], teams: [team], selectedId: 'iri', isChannel: false,+ onSelectKwant: noop, onSelectChannel: noop, onSelectTeam: noop, onSummonKwant: noop, onCreateTeam: noop, onOpenInbox: noop, onOpenNeedsYou: noop,+ busyKwants: busy, botStatus: status, attention: rows(), ...over,+}));+const doc = (html) => new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');++test('desktop: pinned "Needs attention · 4" above Channels, copies with "Also listed in @core"', () => {+ const d = doc(render());+ const block = d.querySelector('[data-needs-attention]');+ assert.ok(block);+ assert.equal(block.querySelector('h2').getAttribute('aria-label'), 'Needs attention, 4');+ assert.match(block.querySelector('h2').textContent, /Needs attention · 4/);+ assert.match(block.querySelector('h2').getAttribute('class'), /text-amber-300/);+ const pins = [...block.querySelectorAll('[data-pin-row]')];+ assert.deepEqual(pins.map((p) => p.getAttribute('data-pin-row')), ['lin', 'pix', 'jun', 'iri']);+ // The block sits before Channels, and the team list still has every bot+ const html = d.body.innerHTML;+ assert.ok(html.indexOf('data-needs-attention') < html.indexOf('data-chats-section="channels"'));+ assert.equal(d.querySelectorAll('[data-team-group] [data-bot-row]').length, kwants.length);+ // Copies are real buttons that point at their team; the pinned copy carries no data-bot-row+ for (const p of pins) {+ assert.equal(p.getAttribute('role'), 'button');+ assert.equal(p.hasAttribute('data-bot-row'), false);+ assert.equal(d.getElementById(p.getAttribute('aria-describedby')).textContent, 'Also listed in @core');+ }+ // Line tones: amber, rose, zinc-200+ const tone = (id) => block.querySelector(`[data-pin-row="${id}"] [data-bot-busy]`).getAttribute('class');+ assert.match(tone('lin'), /text-warn/);+ assert.match(tone('jun'), /text-rose-300/);+ assert.match(tone('iri'), /text-zinc-200/);+ assert.match(block.querySelector('[data-pin-row="iri"] [data-bot-busy]').textContent, /Finished: legend under the plot/);+ // The open chat (Iris) is lit in both places+ assert.match(block.querySelector('[data-pin-row="iri"]').getAttribute('class'), /bg-accent-soft/);+ assert.match(d.querySelector('[data-bot-row="iri"]').getAttribute('class'), /bg-accent-soft/);+});++test('desktop: more than 5 shows 5 rows and "and n more in Inbox"; none, or before the first fetch, shows nothing', () => {+ const many = kwants.map((k, i) => item('question', k.id, { timestamp: at(60 - i) }));+ const d = doc(render({ attention: rows({ needs: m.needsYouRows(many, {}, new Set(kwants.map((k) => k.id))) }) }));+ assert.equal(d.querySelectorAll('[data-pin-row]').length, m.PINNED_MAX);+ assert.equal(d.querySelector('[data-needs-attention-more]').textContent, 'and 3 more in Inbox');+ assert.equal(d.querySelector('[data-needs-attention] h2').getAttribute('aria-label'), 'Needs attention, 8');+ const calm = rows({ needs: [], failed: [], finished: [] });+ assert.equal(doc(render({ attention: calm })).querySelector('[data-needs-attention]'), null);+ assert.equal(doc(render({ attention: undefined })).querySelector('[data-needs-attention]'), null);+});++test('team header rollup: dots for ranks 1–3 with words for screen readers; working count when calm', () => {+ const d = doc(render());+ const r = d.querySelector('[data-team-rollup="t1"]');+ assert.equal(r.getAttribute('aria-label'), '2 need you, 1 stuck, 1 finished');+ assert.deepEqual([...r.querySelectorAll('.tabular-nums')].map((n) => n.textContent), ['2', '1', '1']);+ const calm = doc(render({ attention: rows({ needs: [], failed: [], finished: [] }) }));+ assert.equal(calm.querySelector('[data-team-rollup="t1"]').getAttribute('aria-label'), '3 working', 'Lin is still busy');+ const idle = doc(render({ attention: rows({ needs: [], failed: [], finished: [], busy: {} }) }));+ assert.equal(idle.querySelector('[data-team-rollup]'), null);+});++test('phone Chats tab: Needs you, Stuck, Finished, Working, Waiting, then channels; bots move, not copied', () => {+ const d = doc(render({ phone: true, section: 'chats' }));+ const secs = [...d.querySelectorAll('[data-chats-section]')].map((s) => s.getAttribute('data-chats-section'));+ assert.deepEqual(secs, ['needs', 'stuck', 'finished', 'working', 'waiting', 'channels', 'teams', 'direct']);+ const head = (k) => d.querySelector(`#chats-${k}-head`).textContent;+ assert.deepEqual(['needs', 'stuck', 'finished', 'working', 'waiting'].map(head), ['Needs you · 2', 'Stuck · 1', 'Finished · 1', 'Working · 2', 'Waiting · 1']);+ assert.match(d.querySelector('#chats-needs-head').getAttribute('class'), /!text-warn/);+ assert.match(d.querySelector('#chats-stuck-head').getAttribute('class'), /!text-rose-300/);+ const names = (k) => [...d.querySelectorAll(`[data-chats-section="${k}"] [data-bot-name]`)].map((n) => n.textContent);+ assert.deepEqual(names('working'), ['Rigel', 'Vega']);+ assert.deepEqual(names('direct'), ['Ada']);+ assert.equal(d.querySelectorAll('[data-chat-row]').length, kwants.length);+ assert.equal(d.querySelector('[data-needs-attention]'), null, 'no pinned block on the phone');+ // Empty sections are not drawn+ const calm = doc(render({ phone: true, section: 'chats', attention: rows({ needs: [], failed: [], finished: [] }) }));+ assert.deepEqual([...calm.querySelectorAll('[data-chats-section]')].map((s) => s.getAttribute('data-chats-section')).slice(0, 2), ['working', 'waiting']);+});++test('Inbox: Waiting on you, Failed or stuck, Finished; oldest first, finished unread first then newest', () => {+ assert.deepEqual(m.AWAY_SECTIONS.map((s) => s.key), ['waiting', 'failed', 'finished']);+ const lastSeen = at(20);+ const f = [item('delegation', 'a', { timestamp: at(30) }), item('delegation', 'b', { timestamp: at(10) }), item('delegation', 'c', { timestamp: at(40) }), item('delegation', 'd', { timestamp: at(5) })];+ assert.deepEqual(m.sortAwaySection('finished', f, lastSeen).map((i) => i.kwant_id), ['d', 'b', 'a', 'c']);+ assert.deepEqual(m.sortAwaySection('failed', f).map((i) => i.kwant_id), ['c', 'a', 'b', 'd']);+ assert.deepEqual(m.sortAwaySection('waiting', f).map((i) => i.kwant_id), ['c', 'a', 'b', 'd']);+ const data = { since: at(600), last_seen: lastSeen, now: at(0), stuck_after_minutes: 30, waiting: [item('question', 'lin', { timestamp: at(2) }), item('question', 'pix', { timestamp: at(9) })],+ failed: [], finished: f, unseen: { waiting: 2, finished: 4, failed: 0, total: 6 } };+ const html = m.renderToStaticMarkup(React.createElement(m.AwayView, { data, loading: false, error: null, now: NOW, onRefresh: noop, onOpen: noop, onAnswer: noop, onResolve: noop }));+ const d = doc(html);+ const hint = (k) => d.querySelector(`[data-away-hint="${k}"]`);+ assert.match(hint('waiting').textContent, /oldest first/);+ assert.match(hint('finished').textContent, /not read first, then newest/);+ assert.match(hint('finished').getAttribute('class'), /hidden md:inline/, 'desktop only');+ assert.equal(hint('failed'), null, 'no hint on an empty section');+ assert.ok(html.indexOf('id="away-waiting"') < html.indexOf('id="away-failed"') && html.indexOf('id="away-failed"') < html.indexOf('id="away-finished"'));+});diff --git a/frontend/tests/away.test.mjs b/frontend/tests/away.test.mjsindex 774adb10..3f4576a9 100644--- a/frontend/tests/away.test.mjs+++ b/frontend/tests/away.test.mjs@@ -111,7 +111,7 @@ const view = (over = {}) => ui.render({ data: resp(), loading: false, error: nultest('three sections with agent, title, summary and time; one-tap actions', () => {const html = view();- const order = ['Waiting on you', 'Finished', 'Failed or stuck'].map((s) => html.indexOf(s));+ const order = ['Waiting on you', 'Failed or stuck', 'Finished'].map((s) => html.indexOf(s));assert.ok(order.every((i) => i > 0) && order[0] < order[1] && order[1] < order[2]);assert.match(html, /Scout/);assert.match(html, /Write the brief/);