Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.9.0 H5/H1 follow-ups (#510)

Oleksandr Ivanchenko1b7542f5b474
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 86a0ce33..94907596 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -81,6 +81,8 @@ import { browserTabDoc, createTabSignal, needsYouCount } from './tabSignal';
import { recentWork, type ChatHome } from './botHome';
import { approvalsDiffers } from './components/Sidebar';
import { botStatuses, busyLines } from './botStatus';
+import { type H4Status, type HeldSend, afterRelease, applyBotStatusEvent, h4Api, heldFromReply, heldLine, heldMessages, stillHeld } from './h4Status';
+import { HeldLine } from './components/HeldLine';
import { type BrowsingMap, expireBrowsing, globeRows, noteBrowser, ownerStillRunning, pruneBrowsing, seedBrowsing, switchEntries } from './watchLive';
import { LiveMissPage } from './components/WatchLive';
import {
@@ -540,6 +542,27 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
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>>({});
+ // H4 (#499): each bot's status from the server; null on an older server (today's lines stay).
+ const [h4Status, setH4Status] = useState<Record<string, H4Status> | null>(null);
+ // H3: messages the server held instead of starting a turn (a stuck bot, or one waiting on you).
+ const [heldSends, setHeldSends] = useState<HeldSend[]>([]);
+ useEffect(() => {
+ let live = true;
+ setH4Status(null);
+ setHeldSends([]);
+ h4Api.list(space.id).then((m) => live && setH4Status(m), () => {});
+ return () => {
+ live = false;
+ };
+ }, [space.id]);
+ // A held line goes once the bot's status no longer lists its message (the turn started).
+ useEffect(() => {
+ if (!h4Status) return;
+ setHeldSends((prev) => {
+ const next = prev.filter((h) => stillHeld(h, h4Status[h.kwantId]));
+ return next.length === prev.length ? prev : next;
+ });
+ }, [h4Status]);
const [pill, setPill] = useState<PillState>(EMPTY_PILL);
const [nudgesOn, setNudgesOn] = useState(nudgesEnabled);
const nudgesOnRef = useRef(nudgesOn);
@@ -1108,6 +1131,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setRosterFresh(false);
refreshRoster();
}
+ if (event.type === 'bot_status') setH4Status((prev) => applyBotStatusEvent(prev ?? {}, event.data));
switch (event.type) {
case 'turn_queued':
case 'TurnQueued':
@@ -1806,6 +1830,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
throw new Error(message);
}
const reply = await res.json().catch(() => null);
+ const held = heldFromReply(reply, tempId);
+ if (held) {
+ // H3: saved, but no turn starts yet, so no "thinking" for it; the line under the message says why.
+ if (turnsIn(turnsRef.current, targetId).length === 0) clearLive(targetId);
+ if (streamingContextIdRef.current === targetId) streamingContextIdRef.current = null;
+ setHeldSends((prev) => [...prev.filter((h) => h.messageId !== held.messageId), held]);
+ h4Api.list(space.id).then((m) => m && setH4Status(m), () => {});
+ }
if (isAskingReply(reply)) {
// A close call: Laya posted "Who should answer this?" and nothing runs until the person picks.
if (turnsIn(turnsRef.current, targetId).length === 0) clearLive(targetId);
@@ -3740,10 +3772,33 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
busy: busyKwants,
status: botStatus,
reviews: reviewItems,
+ h4: h4Status ?? undefined,
openedAt: page === 'chat' && !isChannel && selectedId ? { ...openedAt, [selectedId]: Date.now() } : openedAt,
})
: undefined;
+ // H3 + N3: the line under each held message of this space, keyed by the bubble's temp and saved ids.
+ const tryAgainFor = (kwantId: string, name: string) => async (): Promise<string | void> => {
+ haptic('tap');
+ try {
+ const out = await h4Api.retry(kwantId);
+ if (out.status) setH4Status((prev) => ({ ...(prev ?? {}), [kwantId]: out.status! }));
+ setHeldSends((prev) => afterRelease(prev, kwantId, out.status));
+ pushToast(out.released > 0 ? `Sent to ${name} again.` : `${name} can take messages again.`);
+ } catch {
+ haptic('warning');
+ return 'Couldn’t try again. Check your connection, then press it again.';
+ }
+ };
+ const heldNotes: Record<string, React.ReactNode> = {};
+ // The session's send replies plus every message the server still holds (reload, other device, earlier sends).
+ for (const h of heldMessages(heldSends, h4Status, (id) => kwants.find((k) => k.id === id)?.name)) {
+ const { text, tryAgain } = heldLine(h, h4Status?.[h.kwantId]);
+ const node = <HeldLine key={h.messageId} text={text} onTryAgain={tryAgain ? tryAgainFor(h.kwantId, h.name) : undefined} />;
+ heldNotes[h.tempId] = node;
+ heldNotes[h.messageId] = node;
+ }
+
const sidebar = (section: 'all' | 'chats' | 'bots') => (
<Sidebar
space={space}
@@ -3930,6 +3985,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={inboxCount} onBack={backToList} newPage={away} loosePage={loose} />;
const chat = (
<ChatView
+ heldNotes={heldNotes}
dropOff={!!spaceSettingsTab}
title={chatTitle}
subtitle={chatSubtitle}
@@ -4134,7 +4190,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}}
/>
);
- const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} teams={devTeamRefs(teams, kwants)} bots={kwants.map((k) => ({ id: k.id, name: k.name, role: k.title }))} defaultBotId={!isChannel ? selectedId : null} onOpenChat={(id, thread) => { if (thread) { openThread(id, thread); return; } if (!openTarget({ channel_id: null, kwant_id: id })) pushToast('That bot no longer exists.'); }} />;
+ const attentionRankOf = new Map((attention ?? []).map((a) => [a.kwant.id, a.rank]));
+ const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} teams={devTeamRefs(teams, kwants)} bots={kwants.map((k) => ({ id: k.id, name: k.name, role: k.title, rank: attentionRankOf.get(k.id) }))} defaultBotId={!isChannel ? selectedId : null} onOpenChat={(id, thread) => { if (thread) { openThread(id, thread); return; } if (!openTarget({ channel_id: null, kwant_id: id })) pushToast('That bot no longer exists.'); }} />;
const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'dev' && devOn ? devDeskPage : page === 'jar' ? jarPage : page === 'inbox' ? inbox : !loaded ? (
<main className="flex-1 flex items-center justify-center text-xs text-zinc-500">
<Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…
diff --git a/frontend/src/chatsTab.ts b/frontend/src/chatsTab.ts
index 656364e9..7043e744 100644
--- a/frontend/src/chatsTab.ts
+++ b/frontend/src/chatsTab.ts
@@ -2,6 +2,7 @@
// 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';
+import { type H4Status, h4StuckAt, h4StuckLine, h4StartedAt } from './h4Status';
/** One bot waiting on you: the newest approval or question it asked, or an open browser step. */
export interface NeedsYouRow {
@@ -10,6 +11,8 @@ export interface NeedsYouRow {
line: string;
/** Opens the chat with this card; none for a browser step (its chat shows the step). */
item?: AwayItem;
+ /** When this bot's oldest open ask began (any kind); none for a browser step alone. */
+ at?: number;
}
// Tools people approve most, in words; anything else falls back to "Wants your approval".
@@ -35,8 +38,9 @@ export const approvalLine = (tool?: string | null): string => {
};
/**
- * Bots that need you, in the order they asked, one row each. An approval wins over a question,
- * a question over a browser step: the line names the thing that blocks the bot hardest.
+ * Bots that need you, oldest ask first (S1: by how long the ask has waited, whatever its kind), one row
+ * each. The line names the thing that blocks the bot hardest (an approval over a question over a browser
+ * step), but the row's time is the bot's oldest open ask. A browser step alone has no time and goes last.
*/
export function needsYouRows(waiting: AwayItem[], openSteps: Record<string, number>, kwantIds: Set<string>): NeedsYouRow[] {
const rank = (r: NeedsYouRow) => (r.item?.kind === 'approval' ? 0 : r.item ? 1 : 2);
@@ -44,14 +48,17 @@ export function needsYouRows(waiting: AwayItem[], openSteps: Record<string, numb
const put = (r: NeedsYouRow) => {
if (!kwantIds.has(r.kwant_id)) return;
const had = rows.get(r.kwant_id);
- if (!had || rank(r) < rank(had)) rows.set(r.kwant_id, r);
+ const t = r.item ? Date.parse(r.item.timestamp) : NaN;
+ const at = Number.isFinite(t) ? (had?.at !== undefined ? Math.min(had.at, t) : t) : had?.at;
+ rows.set(r.kwant_id, { ...(!had || rank(r) < rank(had) ? r : had), ...(at !== undefined ? { at } : {}) });
};
for (const item of waiting) {
if (item.kind === 'approval') put({ kwant_id: item.kwant_id, line: approvalLine(item.tool_name), item });
else if (item.kind === 'question') put({ kwant_id: item.kwant_id, line: 'Asked you a question', item });
}
for (const [id, n] of Object.entries(openSteps)) if (n > 0) put({ kwant_id: id, line: 'Needs you in the browser' });
- return [...rows.values()];
+ const last = Number.POSITIVE_INFINITY;
+ return [...rows.values()].sort((a, b) => (a.at ?? last) - (b.at ?? last));
}
/** Working: bots with a live turn that are not already under Needs you, by name. */
@@ -89,10 +96,12 @@ export interface AttentionRow<K> {
export interface AttentionInput<K> {
kwants: K[];
- /** `needsYouRows()`: already oldest first. */
+ /** `needsYouRows()`: each row carries its oldest ask's time. */
needs: NeedsYouRow[];
- /** Inbox `failed` items (until H4 ships its `stuck` status, the only source of rank 2). */
+ /** Inbox `failed` items from the last 24 h: rank 2 with H4's `stuck`. */
failed?: AwayItem[];
+ /** H4 status per bot (#499): `stuck` is rank 2 without an Inbox item; a turn's start orders rank 5. */
+ h4?: Record<string, H4Status>;
/** Inbox `finished` items not seen yet. */
finished?: AwayItem[];
/** 0.9 V1: the Inbox's review items (any group), including the Low-risk card's. */
@@ -138,15 +147,18 @@ export function attentionRank(bot: { needs?: boolean; failed?: boolean; review?:
}
/**
- * 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.
+ * The order inside and across groups: rank first; then oldest first for 1–3 and running longest first
+ * for 5 (a row without a time after those with one), newest first for 4; 6 by name; ties by name A→Z.
+ * Rank 7 keeps its input order. `attentionRows` then puts rank 1's plain asks in needsYouRows' order,
+ * ahead of the reviews that need you.
*/
export function attentionSort<K extends { name: string }>(rows: AttentionRow<K>[]): AttentionRow<K>[] {
const pos = new Map(rows.map((r, i) => [r, i]));
+ const last = Number.POSITIVE_INFINITY;
return [...rows].sort((a, b) => {
if (a.rank !== b.rank) return a.rank - b.rank;
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 <= 3 || a.rank === 5) && a.at !== b.at) return (a.at ?? last) - (b.at ?? last);
if (a.rank === 4 && a.at !== b.at) return (b.at ?? 0) - (a.at ?? 0);
return a.kwant.name.localeCompare(b.kwant.name);
});
@@ -154,7 +166,7 @@ export function attentionSort<K extends { name: string }>(rows: AttentionRow<K>[
/** 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 = [], reviews = [], busy = {}, status = {}, openedAt = {}, now = Date.now() } = input;
+ const { kwants, needs, failed = [], finished = [], reviews = [], busy = {}, status = {}, h4 = {}, 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>();
@@ -184,20 +196,30 @@ export function attentionRows<K extends { id: string; name: string }>(input: Att
const f = failedBy.get(k.id);
const d = finishedBy.get(k.id);
const v = reviewBy.get(k.id);
+ const s = h4[k.id];
+ const stuck = s?.status === 'stuck' ? s : undefined;
const queued = status[k.id] === 'queued';
const rank = attentionRank({
needs: !!n || v?.rank === 1,
- failed: !!f || v?.rank === 2,
+ failed: !!f || !!stuck || 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 === 1) return n ? { kwant: k, rank, line: n.r.line, item: n.r.item, needs: n.r, at: n.r.at } : fromReview(v!);
+ if (rank === 2) {
+ // The Inbox failure or the review that couldn't be approved, whichever is older, gives the item; a
+ // live H4 stuck status says more than either, so its line wins. The group order uses the oldest.
+ const rv = v?.rank === 2 ? v : undefined;
+ const base: AttentionRow<K> = f && !(rv && ts(rv.i as AwayItem) < ts(f)) ? { kwant: k, rank, line: stuckLine(f), item: f } : rv ? fromReview(rv) : { kwant: k, rank };
+ const at = Math.min(stuck ? h4StuckAt(stuck) : Infinity, f ? ts(f) : Infinity, rv ? ts(rv.i as AwayItem) : Infinity);
+ return { ...base, line: stuck ? h4StuckLine(stuck) : base.line, at };
+ }
if (rank === 3) return fromReview(v!);
if (rank === 4) return { kwant: k, rank, line: finishedLine(d!), item: d, at: ts(d) };
+ if (rank === 5) return { kwant: k, rank, at: h4StartedAt(s) };
return { kwant: k, rank };
});
// Needs-you rows keep needsYouRows' own order (oldest ask first; a browser step has no time); a review
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index ad9a3c30..d37b3919 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -182,6 +182,8 @@ export interface RoutingState {
}
export interface ChatViewProps {
+ /** H3: a line under the person's held message ("Waiting for Juno: …", Try again), by message id. */
+ heldNotes?: Record<string, React.ReactNode>;
/**
* The chat is mounted but covered by a page (Settings): it isn't a drop target, so a file drag
* shows the "Open a chat" pill instead of a layer nobody can see (#478 L4).
@@ -446,6 +448,7 @@ const useNarrow = () => {
};
export const ChatView: React.FC<ChatViewProps> = ({
+ heldNotes,
dropOff = false,
title,
subtitle,
@@ -1537,6 +1540,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
</div>
)}
{files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} sharedBy={filesOnly && !isUser ? displayName : undefined} at={msg.created_at ?? null} />}
+ {isUser && heldNotes?.[msg.id]}
{filesOnly && !isUser && files.length > 0 && shareInfo(msg.meta).auto && (
// P4: kwnt posted the turn's last screenshot because the reply claimed a picture and none was shared
<p data-shared-auto="" className="mt-1 text-[11px] text-zinc-500">
diff --git a/frontend/src/components/DevDesk.tsx b/frontend/src/components/DevDesk.tsx
index a8673c75..d80215cd 100644
--- a/frontend/src/components/DevDesk.tsx
+++ b/frontend/src/components/DevDesk.tsx
@@ -217,7 +217,7 @@ export interface DevDeskViewProps {
/** The space's teams, so a team with no repo gets "Link a repo" in the repo list. */
teams?: DevTeamRef[];
/** 0.7.6: the space's bots, so a ticket's work reads "Built by Ann and Ben", not ids. */
- bots?: { id: string; name: string; role?: string | null }[];
+ bots?: { id: string; name: string; role?: string | null; rank?: number }[];
/** Opens a bot's chat: 0.9.0 G1 "Open {bot}'s chat" after line notes are sent (1:1, no thread), and
* 0.9.0 H1 the Worktrees tab's "Open chat" (that thread when the worktree has one). */
onOpenChat?: (botId: string, threadId?: string | null) => void;
diff --git a/frontend/src/components/HeldLine.tsx b/frontend/src/components/HeldLine.tsx
new file mode 100644
index 00000000..75e15859
--- /dev/null
+++ b/frontend/src/components/HeldLine.tsx
@@ -0,0 +1,49 @@
+// H3 (Mira's h4-why-status.md "H3 copy"): the line under the person's own message when the server
+// held it instead of starting a turn. N3 (Rigel's qa-499.md): after the stall check gave up, it offers
+// Try again, or the person would think the app is ignoring them.
+import React, { useState } from 'react';
+import { Clock } from 'lucide-react';
+
+export interface HeldLineProps {
+ text: string;
+ /** Shown only when the bot gave up (`stalled_gave_up`): releases the held message now. */
+ onTryAgain?: () => Promise<string | void>;
+}
+
+export const HeldLine: React.FC<HeldLineProps> = ({ text, onTryAgain }) => {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const tryAgain = async () => {
+ if (!onTryAgain || busy) return;
+ setBusy(true);
+ setError(null);
+ const err = await onTryAgain().catch(() => 'Couldn’t try again. Check your connection, then press it again.');
+ setBusy(false);
+ if (err) setError(err);
+ };
+ return (
+ <div data-held-line="" className="mt-1.5 flex max-w-full flex-wrap items-center justify-end gap-x-2 gap-y-1 text-right text-[12.5px] text-zinc-300">
+ <span className="min-w-0" role="status">
+ <Clock size={13} className="mr-1.5 inline-block -mt-0.5 align-middle text-zinc-400" aria-hidden="true" />
+ {text}
+ </span>
+ {onTryAgain && (
+ <button
+ type="button"
+ data-held-try-again=""
+ onClick={tryAgain}
+ disabled={busy}
+ aria-busy={busy || undefined}
+ className="min-h-[32px] rounded-lg border border-zinc-600 px-2.5 py-1 text-[12px] font-medium text-zinc-100 hover:border-sky-500/60 hover:text-sky-100 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-300"
+ >
+ {busy ? 'Trying…' : 'Try again'}
+ </button>
+ )}
+ {error && (
+ <span data-held-error="" role="alert" className="basis-full text-[12px] text-rose-300">
+ {error}
+ </span>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/dev/WorktreesTab.tsx b/frontend/src/components/dev/WorktreesTab.tsx
index 99ba7b4e..9531d155 100644
--- a/frontend/src/components/dev/WorktreesTab.tsx
+++ b/frontend/src/components/dev/WorktreesTab.tsx
@@ -31,6 +31,12 @@ import {
upToDate,
worktreeApi,
worktreeStore,
+ type RankOf,
+ repoRollup,
+ repoRollupParts,
+ type RollupRank,
+ sortRepos,
+ sortWorktrees,
} from '../../dev/worktrees';
import { ModernAvatar } from '../ModernAvatar';
import { threadsApi } from '../../threads';
@@ -43,8 +49,13 @@ export interface WtBot {
id: string;
name: string;
role?: string | null;
+ /** H5 rank (1 needs you … 7 the rest) for the repo rollup and the row order; none = no order data. */
+ rank?: number;
}
+// H5 mini dots (the sidebar's team rollup colours).
+const RANK_DOT: Record<RollupRank, string> = { 1: 'bg-amber-400', 2: 'bg-rose-400', 3: 'bg-[#38bdf8]', 4: 'bg-teal-400', 5: 'bg-[#9d8fff]' };
+
export function useWorktrees(space: string, on: boolean): WorktreesData {
const data = useSyncExternalStore(worktreeStore.subscribe, () => worktreeStore.get(space), () => worktreeStore.get(space));
useEffect(() => {
@@ -75,6 +86,7 @@ export interface WorktreesPanelProps {
export const WorktreesPanel: React.FC<WorktreesPanelProps> = ({ space, data, bots, defaultBotId, onOpenChat, phone = false, now: nowProp, home = null }) => {
const now = nowProp ?? Date.now();
const botName = useCallback((id: string | null) => (id ? bots.find((b) => b.id === id)?.name ?? null : null), [bots]);
+ const rankOf = useCallback<RankOf>((id) => (id ? bots.find((b) => b.id === id)?.rank : undefined), [bots]);
const [creating, setCreating] = useState<WorktreeRepo | null>(null);
const [removing, setRemoving] = useState<Worktree | null>(null);
const [menu, setMenu] = useState<Worktree | null>(null);
@@ -177,9 +189,9 @@ export const WorktreesPanel: React.FC<WorktreesPanelProps> = ({ space, data, bot
else if (!list || !list.repos.length)
body = <EmptyTerm out="(no repo yet)" title="Worktrees show up once there’s a repo." line="Link a repo from Dev mode in the sidebar." data="no-repo" />;
else
- body = list.repos.map((r) => (
- <RepoGroup key={r.repo} space={space} repo={r} home={home} phone={phone} onNew={(el) => openCreate(r, el)}>
- {r.worktrees.map((w) => (
+ body = sortRepos(list.repos, rankOf).map((r) => (
+ <RepoGroup key={r.repo} space={space} repo={r} home={home} phone={phone} rankOf={rankOf} onNew={(el) => openCreate(r, el)}>
+ {sortWorktrees(r.worktrees, rankOf).map((w) => (
<WorktreeRow key={w.id} w={w} repo={r.repo} {...rowProps} />
))}
{r.other.map((o) => (
@@ -266,9 +278,22 @@ export const WorktreesPanel: React.FC<WorktreesPanelProps> = ({ space, data, bot
// ---------------------------------------------------------------------------
// Groups and rows
-const RepoGroup: React.FC<{ space: string; repo: WorktreeRepo; home: string | null; phone: boolean; onNew: (el: HTMLElement) => void; children: React.ReactNode }> = ({ space, repo, home, phone, onNew, children }) => {
+const RepoGroup: React.FC<{ space: string; repo: WorktreeRepo; home: string | null; phone: boolean; rankOf: RankOf; onNew: (el: HTMLElement) => void; children: React.ReactNode }> = ({ space, repo, home, phone, rankOf, onNew, children }) => {
const n = repo.worktrees.length + repo.other.length;
const headId = useId();
+ // H5 N1: "● 1 needs you ● 2 working" on the right of the header (ranks 1–4, words; zeros left out).
+ const parts = repoRollupParts(repoRollup(repo, rankOf));
+ const rollup = parts.length ? (
+ <span data-wt-rollup={repo.repo} className={`flex flex-wrap items-center gap-x-2.5 gap-y-1 text-[12px] text-zinc-300 ${phone ? 'mb-2 ml-[23px]' : 'shrink-0'}`}>
+ {parts.map((p, i) => (
+ <span key={p.rank} className="inline-flex items-center gap-1.5" data-wt-rollup-rank={p.rank}>
+ <span className={`h-1.5 w-1.5 rounded-full ${RANK_DOT[p.rank]}`} aria-hidden="true" />
+ {i > 0 && <span className="sr-only">, </span>}
+ {p.text}
+ </span>
+ ))}
+ </span>
+ ) : null;
return (
<section aria-labelledby={headId} data-wt-repo={repo.repo}>
<div className="mb-2 flex items-center gap-2">
@@ -285,6 +310,7 @@ const RepoGroup: React.FC<{ space: string; repo: WorktreeRepo; home: string | nu
)}
</h3>
<span className="flex-1" />
+ {!phone && rollup}
{!repo.error && (
<button
type="button"
@@ -298,6 +324,7 @@ const RepoGroup: React.FC<{ space: string; repo: WorktreeRepo; home: string | nu
</button>
)}
</div>
+ {phone && rollup}
{repo.error ? (
<RepoError space={space} repo={repo.repo} />
) : n === 0 ? (
diff --git a/frontend/src/dev/worktrees.ts b/frontend/src/dev/worktrees.ts
index 72335f61..db68ea31 100644
--- a/frontend/src/dev/worktrees.ts
+++ b/frontend/src/dev/worktrees.ts
@@ -530,3 +530,65 @@ export function shortPath(p: string, home: string | null = null): string {
const m = p.match(/^\/(?:home|Users)\/[^/]+(\/.*)$/);
return m ? `~${m[1]}` : p;
}
+
+// ---- H5 N1: the repo header rollup and the one attention order on the Worktrees tab ----
+
+/** A bot's H5 rank (1 needs you · 2 stuck · 3 to review · 4 finished · 5 working · 6 waiting · 7 the rest). */
+export type RankOf = (botId: string | null) => number | undefined;
+
+/**
+ * One row's rank. The bot's ranks 1–4 follow it to each of its worktrees (the ask, the review or the result
+ * is about that bot); working counts only for the worktree a turn actually runs in, so a bot busy elsewhere
+ * doesn't light up an idle folder. Removed rows and rows without a bot rank 7.
+ */
+export function rowRank(w: Worktree, rankOf: RankOf): number {
+ if (w.removed_at) return 7;
+ const r = rankOf(w.kwant_id);
+ if (r !== undefined && r <= 4) return r;
+ return w.working ? 5 : 7;
+}
+
+export interface RepoRollup {
+ needs: number;
+ stuck: number;
+ review: number;
+ finished: number;
+ working: number;
+}
+
+export function repoRollup(repo: WorktreeRepo, rankOf: RankOf): RepoRollup {
+ const c: RepoRollup = { needs: 0, stuck: 0, review: 0, finished: 0, working: 0 };
+ for (const w of repo.worktrees) {
+ const r = rowRank(w, rankOf);
+ if (r === 1) c.needs++;
+ else if (r === 2) c.stuck++;
+ else if (r === 3) c.review++;
+ else if (r === 4) c.finished++;
+ else if (r === 5) c.working++;
+ }
+ return c;
+}
+
+export type RollupRank = 1 | 2 | 3 | 4 | 5;
+
+/** "1 needs you" / "2 need you", "1 stuck", "1 to review", "1 finished", "2 working" (H5 copy), zeros left out, in rank order. */
+export function repoRollupParts(c: RepoRollup): { rank: RollupRank; text: string }[] {
+ const out: { rank: RollupRank; text: string }[] = [];
+ if (c.needs) out.push({ rank: 1, text: `${c.needs} ${c.needs === 1 ? 'needs' : 'need'} you` });
+ if (c.stuck) out.push({ rank: 2, text: `${c.stuck} stuck` });
+ if (c.review) out.push({ rank: 3, text: `${c.review} to review` });
+ if (c.finished) out.push({ rank: 4, text: `${c.finished} finished` });
+ if (c.working) out.push({ rank: 5, text: `${c.working} working` });
+ return out;
+}
+
+/** Rows inside a repo in the one order: rank first, then the server's order (stable). */
+export function sortWorktrees(list: Worktree[], rankOf: RankOf): Worktree[] {
+ return list.map((w, i) => ({ w, i, r: rowRank(w, rankOf) })).sort((a, b) => a.r - b.r || a.i - b.i).map((x) => x.w);
+}
+
+/** Repos by their best-ranked row, then by name. */
+export function sortRepos(repos: WorktreeRepo[], rankOf: RankOf): WorktreeRepo[] {
+ const best = (r: WorktreeRepo) => Math.min(7, ...r.worktrees.map((w) => rowRank(w, rankOf)));
+ return [...repos].sort((a, b) => best(a) - best(b) || a.repo.localeCompare(b.repo));
+}
diff --git a/frontend/src/h4Status.ts b/frontend/src/h4Status.ts
new file mode 100644
index 00000000..ca8ecc40
--- /dev/null
+++ b/frontend/src/h4Status.ts
@@ -0,0 +1,215 @@
+// H4 (release-090/h4-contract.md, Vega's #499): the server's status object per bot. The frontend
+// here only reads what H5 and H3 need: `stuck` for the attention order's rank 2, the turn start for
+// "running longest first", `held` for the line under a held message, and Try again.
+import { personFetch } from './auth';
+
+export type H4StatusKind = 'working' | 'queued' | 'needs_you' | 'quiet' | 'stuck' | 'paused' | 'available';
+
+export interface H4Held {
+ kind: 'message' | 'handoff';
+ id: string;
+ since?: string;
+ reason_code?: string;
+ context_id?: string;
+}
+
+export interface H4Status {
+ kwant_id: string;
+ status: H4StatusKind;
+ reason_code: string;
+ since?: string;
+ waits_on?: { kind: string; label?: string };
+ turn?: { started_at?: string; turn_id?: string; context_id?: string; thread_id?: string | null };
+ retry?: { at?: string; try?: number; of?: number };
+ stuck?: { gave_up_at?: string; tries?: number };
+ /** needs_you/asked_question: the open question (its time goes in a waits_on_you held line). */
+ question?: { asked_at?: string };
+ held: H4Held[];
+}
+
+const rec = (v: unknown): Record<string, unknown> | null => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null);
+const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);
+const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
+const KINDS: readonly H4StatusKind[] = ['working', 'queued', 'needs_you', 'quiet', 'stuck', 'paused', 'available'];
+
+/** One status object, or null when it isn't one (unknown statuses are dropped, not guessed). */
+export function parseH4Status(v: unknown): H4Status | null {
+ const o = rec(v);
+ const kwant_id = str(o?.kwant_id);
+ const status = str(o?.status) as H4StatusKind | undefined;
+ if (!o || !kwant_id || !status || !KINDS.includes(status)) return null;
+ const w = rec(o.waits_on);
+ const t = rec(o.turn);
+ const r = rec(o.retry);
+ const s = rec(o.stuck);
+ const q = rec(o.question);
+ const held = (Array.isArray(o.held) ? o.held : []).flatMap((h): H4Held[] => {
+ const x = rec(h);
+ const id = str(x?.id);
+ const kind = x?.kind === 'handoff' ? 'handoff' : x?.kind === 'message' ? 'message' : null;
+ return x && id && kind ? [{ kind, id, since: str(x.since), reason_code: str(x.reason_code), context_id: str(x.context_id) }] : [];
+ });
+ return {
+ kwant_id,
+ status,
+ reason_code: str(o.reason_code) ?? '',
+ since: str(o.since),
+ waits_on: w && str(w.kind) ? { kind: str(w.kind)!, label: str(w.label) } : undefined,
+ turn: t ? { started_at: str(t.started_at), turn_id: str(t.turn_id), context_id: str(t.context_id), thread_id: str(t.thread_id) ?? null } : undefined,
+ retry: r ? { at: str(r.at), try: num(r.try), of: num(r.of) } : undefined,
+ stuck: s ? { gave_up_at: str(s.gave_up_at), tries: num(s.tries) } : undefined,
+ question: q ? { asked_at: str(q.asked_at) } : undefined,
+ held,
+ };
+}
+
+/** `GET /api/bots/status` body → map by bot. */
+export function parseH4List(v: unknown): Record<string, H4Status> {
+ const out: Record<string, H4Status> = {};
+ for (const b of Array.isArray(rec(v)?.bots) ? (rec(v)!.bots as unknown[]) : []) {
+ const s = parseH4Status(b);
+ if (s) out[s.kwant_id] = s;
+ }
+ return out;
+}
+
+/** A `bot_status` event (`{kwant_id, status:{…}}`) applied to the map; the same map when it isn't one. */
+export function applyBotStatusEvent(map: Record<string, H4Status>, data: unknown): Record<string, H4Status> {
+ const d = rec(data);
+ const s = parseH4Status(d?.status);
+ if (!s || s.kwant_id !== str(d?.kwant_id)) return map;
+ return { ...map, [s.kwant_id]: s };
+}
+
+export const h4Api = {
+ /** Every bot's status, or null on an older server (404) so callers keep today's lines. */
+ list: async (space: string): Promise<Record<string, H4Status> | null> => {
+ const res = await fetch(`/api/bots/status?space=${encodeURIComponent(space)}`);
+ if (res.status === 404) return null;
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return parseH4List(await res.json());
+ },
+ /** "Try again" after the stall check gave up: releases the bot's held messages and hand-offs. */
+ retry: async (kwantId: string): Promise<{ released: number; status: H4Status | null }> => {
+ const res = await personFetch(`/api/kwants/${encodeURIComponent(kwantId)}/status/retry`, { method: 'POST' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const o = rec(await res.json().catch(() => null));
+ return { released: num(o?.released) ?? 0, status: parseH4Status(o?.status) };
+ },
+};
+
+const hhmm = (iso?: string): string | null => {
+ const t = iso ? Date.parse(iso) : NaN;
+ return Number.isFinite(t) ? new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }) : null;
+};
+
+export const isGaveUp = (s?: H4Status | null): boolean => s?.status === 'stuck' && s.reason_code === 'stalled_gave_up';
+
+/** The sidebar's rank-2 line for an H4 stuck bot (H5 copy "Stuck: Claude stopped answering"; tries per §4). */
+export function h4StuckLine(s: H4Status): string {
+ if (isGaveUp(s)) {
+ const at = hhmm(s.stuck?.gave_up_at ?? s.since);
+ return `Stuck: stopped after ${s.stuck?.tries ?? 2} tries${at ? ` · ${at}` : ''}`;
+ }
+ return `Stuck: ${s.waits_on?.label ?? 'the AI'} stopped answering`;
+}
+
+/** When the bot became stuck, for "oldest first" inside rank 2. */
+export const h4StuckAt = (s: H4Status): number => Date.parse(s.stuck?.gave_up_at ?? s.since ?? '') || 0;
+
+/** When the bot's primary turn started running, for "running longest first" inside rank 4. */
+export const h4StartedAt = (s?: H4Status): number | undefined => {
+ const t = Date.parse(s?.turn?.started_at ?? '');
+ return Number.isFinite(t) ? t : undefined;
+};
+
+// ---- H3: a message the server held instead of starting a turn ----
+
+/** `POST /api/chat/send` answered `held`: what the line under the message needs. */
+export interface HeldSend {
+ /** The optimistic bubble's id, then the saved message's id. */
+ tempId: string;
+ messageId: string;
+ kwantId: string;
+ name: string;
+ reason: string;
+ questionAt?: string;
+}
+
+/** A `held` send reply → HeldSend, or null when the send wasn't held. */
+export function heldFromReply(reply: unknown, tempId: string): HeldSend | null {
+ const o = rec(reply);
+ const h = rec(o?.held);
+ if (o?.status !== 'held' || !h) return null;
+ const kwantId = str(h.kwant_id);
+ if (!kwantId) return null;
+ return {
+ tempId,
+ messageId: str(o.user_message_id) ?? tempId,
+ kwantId,
+ name: str(h.kwant_name) ?? 'The bot',
+ reason: str(h.reason_code) ?? '',
+ questionAt: str(rec(h.question)?.asked_at),
+ };
+}
+
+/** Still held: the bot's status lists the message (or no status has arrived since the send). */
+export function stillHeld(h: HeldSend, status?: H4Status): boolean {
+ if (!status) return true;
+ return status.held.some((x) => x.kind === 'message' && (x.id === h.messageId || x.id === h.tempId));
+}
+
+/**
+ * Every held message to show a line under (qa-510 S1/S2): the send replies of this session (the
+ * instant case, before the status catches up) plus each `kind:"message"` the server's status lists,
+ * so a reload, another device or an earlier held message still gets its line. One line per message.
+ */
+export function heldMessages(sends: HeldSend[], status: Record<string, H4Status> | null | undefined, nameOf: (kwantId: string) => string | undefined): HeldSend[] {
+ const out = [...sends];
+ const seen = new Set(sends.flatMap((h) => [h.messageId, h.tempId]));
+ for (const s of Object.values(status ?? {})) {
+ for (const x of s.held) {
+ if (x.kind !== 'message' || seen.has(x.id)) continue;
+ seen.add(x.id);
+ const reason = x.reason_code ?? (s.status === 'stuck' ? 'stuck' : s.status === 'needs_you' ? 'waits_on_you' : '');
+ out.push({
+ tempId: x.id,
+ messageId: x.id,
+ kwantId: s.kwant_id,
+ name: nameOf(s.kwant_id) ?? 'The bot',
+ reason,
+ questionAt: reason === 'waits_on_you' ? s.question?.asked_at : undefined,
+ });
+ }
+ }
+ return out;
+}
+
+/** After Try again: keep only the session's lines the server still holds (nit 2); all of the bot's without a status. */
+export function afterRelease(sends: HeldSend[], kwantId: string, status: H4Status | null): HeldSend[] {
+ return sends.filter((h) => h.kwantId !== kwantId || (status ? stillHeld(h, status) : false));
+}
+
+/** The line under a held message (Mira's H3 copy) and whether it offers Try again (N3). */
+export function heldLine(h: HeldSend, status?: H4Status): { text: string; tryAgain: boolean } {
+ const n = h.name;
+ if (h.reason === 'waits_on_you') {
+ const at = hhmm(h.questionAt);
+ return {
+ text: h.questionAt
+ ? `Queued for ${n}: ${n} is waiting for your answer to its question${at ? ` (${at})` : ''}. It goes through when you answer.`
+ : `Queued for ${n}: ${n} is waiting for you in another chat. It goes through when you’re done there.`,
+ tryAgain: false,
+ };
+ }
+ if (h.reason === 'paused') return { text: `Waiting for ${n}: ${n} is paused at its monthly budget.`, tryAgain: false };
+ // Stuck. Retrying: the retry is already running, so there's nothing to press. Gave up (or not known yet): Try again.
+ if (status?.status === 'stuck' && status.reason_code === 'stalled_retrying') {
+ return { text: `Waiting for ${n}: ${n} is stuck (${status.waits_on?.label ?? 'the AI'} stopped answering). Your message waits until ${n} runs again.`, tryAgain: false };
+ }
+ const at = hhmm(status?.stuck?.gave_up_at);
+ return {
+ text: `Waiting for ${n}: ${n} stopped after ${status?.stuck?.tries ?? 2} tries${at ? ` at ${at}` : ''}. Your message is kept and goes through when ${n} runs again.`,
+ tryAgain: true,
+ };
+}
diff --git a/frontend/tests/h5Followups.test.mjs b/frontend/tests/h5Followups.test.mjs
new file mode 100644
index 00000000..f117e0d9
--- /dev/null
+++ b/frontend/tests/h5Followups.test.mjs
@@ -0,0 +1,269 @@
+// 0.9.0 H5/H1 follow-ups (Pixel): S1 "Needs you" oldest ask first whatever its kind (qa-494.md S1);
+// N2 H4 `stuck` reaches rank 2 and rank 5 (working) runs longest first; N1 the Dev desk repo rollup and order;
+// N3 the held-send line offers Try again after `stalled_gave_up` (qa-499.md N3).
+process.env.TZ = 'UTC';
+
+import assert from 'node:assert/strict';
+import test, { afterEach, beforeEach } 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 });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'HTMLSelectElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'DOMParser']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+
+const m = await loadBundled(`
+ export { needsYouRows, attentionRows } from './src/chatsTab';
+ export * from './src/h4Status';
+ export { HeldLine } from './src/components/HeldLine';
+ export { rowRank, repoRollup, repoRollupParts, sortRepos, sortWorktrees, worktreeStore } from './src/dev/worktrees';
+ export * as fx from './src/dev/worktreeFixtures';
+ export { WorktreesPanel } from './src/components/dev/WorktreesTab';
+ export { createRoot } from 'react-dom/client';
+ export { createElement } from 'react';
+`);
+const { fx } = m;
+const h = m.createElement;
+const NOW = Date.parse('2026-11-10T12:00:00Z');
+const at = (min) => new Date(NOW - min * 60_000).toISOString();
+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('veg', 'Vega')];
+const all = new Set(kwants.map((k) => k.id));
+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 });
+const st = (kwant_id, status, over = {}) => ({ kwant_id, status, reason_code: '', held: [], ...over });
+const order = (rs) => rs.map((r) => `${r.rank}:${r.kwant.name}`);
+
+// ---------------------------------------------------------------------------------------------------
+// S1
+
+test('S1: "Needs you" puts the oldest ask first, whatever its kind', () => {
+ // /api/away lists approvals first; Juno's question is older than Pixel's approval.
+ const waiting = [item('approval', 'pix', { timestamp: at(2) }), item('question', 'jun', { timestamp: at(30) })];
+ const rows = m.needsYouRows(waiting, {}, all);
+ assert.deepEqual(rows.map((r) => r.kwant_id), ['jun', 'pix']);
+ const att = m.attentionRows({ kwants, needs: rows, failed: [], finished: [], busy: {}, status: {}, now: NOW });
+ assert.deepEqual(order(att).slice(0, 2), ['1:Juno', '1:Pixel']);
+});
+
+test('S1: one bot with two asks keeps the strongest line and waits since its oldest ask', () => {
+ const waiting = [item('approval', 'lin', { timestamp: at(3), title: 'Run the migration' }), item('question', 'lin', { timestamp: at(40) }), item('question', 'pix', { timestamp: at(20) })];
+ const rows = m.needsYouRows(waiting, {}, all);
+ assert.deepEqual(rows.map((r) => r.kwant_id), ['lin', 'pix']);
+ assert.equal(rows[0].at, NOW - 40 * 60_000);
+ assert.match(rows[0].line, /OK|approv|Run the migration/i, 'the approval line wins over the question line');
+});
+
+test('S1: an ask with no time (a browser step) goes last', () => {
+ const rows = m.needsYouRows([item('question', 'pix', { timestamp: at(1) })], { jun: 1 }, all);
+ assert.deepEqual(rows.map((r) => r.kwant_id), ['pix', 'jun']);
+ assert.equal(rows[1].line, 'Needs you in the browser');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// N2
+
+test('N2: an H4-stuck bot with no Inbox item reaches rank 2 with the stuck line', () => {
+ const h4 = { veg: st('veg', 'stuck', { reason_code: 'stalled_retrying', since: at(8), waits_on: { kind: 'ai', label: 'Claude' } }) };
+ const att = m.attentionRows({ kwants, needs: [], failed: [], finished: [], busy: {}, status: {}, h4, now: NOW });
+ const v = att.find((r) => r.kwant.id === 'veg');
+ assert.equal(v.rank, 2);
+ assert.equal(v.line, 'Stuck: Claude stopped answering');
+ assert.equal(att[0].kwant.id, 'veg');
+});
+
+test('N2: gave up reads "stopped after 2 tries"; needs-you still beats stuck; stuck oldest first', () => {
+ const h4 = {
+ veg: st('veg', 'stuck', { reason_code: 'stalled_gave_up', since: at(5), stuck: { gave_up_at: '2026-11-10T11:55:00Z', tries: 2 } }),
+ rig: st('rig', 'stuck', { reason_code: 'stalled_retrying', since: at(50) }),
+ lin: st('lin', 'stuck', { reason_code: 'stalled_retrying', since: at(60) }),
+ };
+ const needs = m.needsYouRows([item('question', 'lin', { timestamp: at(1) })], {}, all);
+ const att = m.attentionRows({ kwants, needs, failed: [], finished: [], busy: {}, status: {}, h4, now: NOW });
+ assert.deepEqual(order(att).slice(0, 3), ['1:Lin', '2:Rigel', '2:Vega']);
+ assert.equal(att.find((r) => r.kwant.id === 'veg').line, 'Stuck: stopped after 2 tries · 11:55');
+ assert.equal(att.find((r) => r.kwant.id === 'rig').line, 'Stuck: the AI stopped answering');
+});
+
+test('N2: rank 5 (working) runs longest first by the H4 turn start', () => {
+ const h4 = { iri: st('iri', 'working', { turn: { started_at: at(3) } }), rig: st('rig', 'working', { turn: { started_at: at(45) } }) };
+ const att = m.attentionRows({ kwants, needs: [], failed: [], finished: [], busy: { iri: 'Working', rig: 'Working' }, status: { iri: 'working', rig: 'working' }, h4, now: NOW });
+ assert.deepEqual(order(att).filter((x) => x.startsWith('5:')), ['5:Rigel', '5:Iris']);
+});
+
+test('N2: status list and bot_status events parse; an older server (404) gives null', async () => {
+ const body = { bots: [st('lin', 'stuck', { reason_code: 'stalled_retrying' }), { kwant_id: 'x', status: 'weird' }, { nope: 1 }], now: at(0) };
+ const map = m.parseH4List(body);
+ assert.deepEqual(Object.keys(map), ['lin']);
+ const next = m.applyBotStatusEvent(map, { kwant_id: 'pix', status: st('pix', 'working') });
+ assert.equal(next.pix.status, 'working');
+ assert.equal(m.applyBotStatusEvent(map, { kwant_id: 'pix', status: st('lin', 'working') }), map, 'mismatched ids are ignored');
+ g.fetch = async () => new Response('{}', { status: 404 });
+ assert.equal(await m.h4Api.list('sp1'), null);
+ g.fetch = async () => new Response(JSON.stringify(body), { status: 200 });
+ assert.equal((await m.h4Api.list('sp1')).lin.reason_code, 'stalled_retrying');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// N3
+
+const reply = (reason, extra = {}) => ({ status: 'held', user_message_id: 'm-9', held: { kwant_id: 'jun', kwant_name: 'Juno', reason_code: reason, since: at(2), ...extra } });
+
+test('N3: a held reply becomes a held line; only gave-up offers Try again', () => {
+ assert.equal(m.heldFromReply({ status: 'started' }, 't1'), null);
+ const hs = m.heldFromReply(reply('stuck'), 't1');
+ assert.deepEqual([hs.tempId, hs.messageId, hs.kwantId, hs.name], ['t1', 'm-9', 'jun', 'Juno']);
+
+ const retrying = m.heldLine(hs, st('jun', 'stuck', { reason_code: 'stalled_retrying', waits_on: { kind: 'ai', label: 'Claude' } }));
+ assert.equal(retrying.tryAgain, false);
+ assert.equal(retrying.text, 'Waiting for Juno: Juno is stuck (Claude stopped answering). Your message waits until Juno runs again.');
+
+ const gaveUp = m.heldLine(hs, st('jun', 'stuck', { reason_code: 'stalled_gave_up', stuck: { gave_up_at: '2026-11-10T11:50:00Z', tries: 2 } }));
+ assert.equal(gaveUp.tryAgain, true);
+ assert.equal(gaveUp.text, 'Waiting for Juno: Juno stopped after 2 tries at 11:50. Your message is kept and goes through when Juno runs again.');
+
+ const q = m.heldLine(m.heldFromReply(reply('waits_on_you', { question: { asked_at: '2026-11-10T14:08:00Z' } }), 't2'));
+ assert.equal(q.tryAgain, false);
+ assert.equal(q.text, 'Queued for Juno: Juno is waiting for your answer to its question (14:08). It goes through when you answer.');
+ assert.equal(m.heldLine(m.heldFromReply(reply('paused'), 't3')).tryAgain, false);
+});
+
+test('N3: the line goes once the status no longer holds the message', () => {
+ const hs = m.heldFromReply(reply('stuck'), 't1');
+ assert.equal(m.stillHeld(hs, undefined), true);
+ assert.equal(m.stillHeld(hs, st('jun', 'stuck', { held: [{ kind: 'message', id: 'm-9' }] })), true);
+ assert.equal(m.stillHeld(hs, st('jun', 'working')), false);
+});
+
+const mounted = [];
+afterEach(() => {
+ for (const u of mounted.splice(0)) u();
+ document.body.replaceChildren();
+});
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const render = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(el);
+ await settle();
+ mounted.push(() => { root.unmount(); host.remove(); });
+ return host;
+};
+const click = async (el) => {
+ assert.ok(el, 'element to click exists');
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+
+test('N3: Try again calls back, shows "Trying…", and says so when it fails', async () => {
+ let release;
+ let calls = 0;
+ const host = await render(h(m.HeldLine, { text: 'Waiting for Juno', onTryAgain: () => { calls++; return new Promise((r) => { release = r; }); } }));
+ const btn = host.querySelector('[data-held-try-again]');
+ assert.equal(btn.textContent, 'Try again');
+ assert.equal(host.querySelector('[role=status]').textContent, 'Waiting for Juno');
+ await click(btn);
+ assert.equal(calls, 1);
+ assert.equal(btn.textContent, 'Trying…');
+ assert.equal(btn.disabled, true);
+ release('Couldn’t try again. Check your connection, then press it again.');
+ await settle();
+ assert.equal(btn.textContent, 'Try again');
+ assert.match(host.querySelector('[data-held-error][role=alert]').textContent, /Couldn’t try again/);
+
+ const plain = await render(h(m.HeldLine, { text: 'Queued for Lin' }));
+ assert.equal(plain.querySelector('[data-held-try-again]'), null, 'no button unless the bot gave up');
+});
+
+test('N3: retry posts to the person-only route', async () => {
+ const seen = [];
+ g.fetch = async (url, init = {}) => {
+ seen.push(`${init.method ?? 'GET'} ${url}`);
+ return new Response(JSON.stringify({ released: 1, status: st('jun', 'working') }), { status: 200 });
+ };
+ const r = await m.h4Api.retry('jun');
+ assert.equal(r.released, 1);
+ assert.equal(r.status.status, 'working');
+ assert.ok(seen.some((s) => s.startsWith('POST /api/kwants/jun/status/retry')));
+});
+
+// ---------------------------------------------------------------------------------------------------
+// N1
+
+const rankOf = (ranks) => (id) => (id ? ranks[id] : undefined);
+
+test('N1: row ranks, the repo rollup in words, and the order of rows and repos', () => {
+ const r = rankOf({ 'k-lin': 1, 'k-rigel': 6 });
+ const shop = fx.LIST.repos[0];
+ assert.deepEqual(shop.worktrees.map((w) => m.rowRank(w, r)), [5, 1, 7, 7], 'Pixel works (5), Lin needs you (1), Rigel is waiting (7), mine (7)');
+ assert.deepEqual(m.sortWorktrees(shop.worktrees, r).map((w) => w.id), ['w2', 'w1', 'w3', 'w4']);
+ const c = m.repoRollup(shop, r);
+ assert.deepEqual(c, { needs: 1, stuck: 0, review: 0, finished: 0, working: 1 });
+ assert.deepEqual(m.repoRollupParts(c).map((p) => p.text), ['1 needs you', '1 working']);
+ assert.deepEqual(m.repoRollupParts({ needs: 2, stuck: 1, review: 1, finished: 3, working: 0 }).map((p) => p.text), ['2 need you', '1 stuck', '1 to review', '3 finished']);
+ assert.equal(m.rowRank({ ...shop.worktrees[0], removed_at: at(1) }, r), 7);
+ // A repo with a stuck bot goes above one that is only working; ties by name.
+ const a = { ...shop, repo: 'zed', worktrees: [{ ...fx.WORKING, kwant_id: 'k-x' }] };
+ const b = { ...shop, repo: 'alpha', worktrees: [{ ...fx.MINE }] };
+ const z = { ...shop, repo: 'mid', worktrees: [{ ...fx.FINISHED_DUE, kwant_id: 'k-y' }] };
+ assert.deepEqual(m.sortRepos([b, a, z], rankOf({ 'k-y': 2 })).map((x) => x.repo), ['mid', 'zed', 'alpha']);
+});
+
+test('N1: the Worktrees tab shows the rollup on the repo header and orders repos by their best row', async () => {
+ const list = { repos: [fx.LIST.repos[1], { ...fx.LIST.repos[0] }] }; // site first in the reply
+ g.fetch = async (url) => {
+ const path = String(url).split('?')[0];
+ if (path === '/api/spaces/sp1/dev/worktrees') return new Response(JSON.stringify(list), { status: 200 });
+ if (path === '/api/spaces/sp1/dev/worktrees/branches') return new Response(JSON.stringify(fx.BRANCHES), { status: 200 });
+ return new Response('{}', { status: 404 });
+ };
+ m.worktreeStore._reset();
+ await m.worktreeStore.load('sp1');
+ const bots = fx.BOTS.map((b) => ({ ...b, rank: b.id === 'k-lin' ? 1 : b.id === 'k-pixel' ? 5 : undefined }));
+ const host = await render(h(m.WorktreesPanel, { space: 'sp1', data: m.worktreeStore.get('sp1'), bots, now: fx.NOW, home: '/home/ann' }));
+ const roll = host.querySelector('[data-wt-rollup="shop"]');
+ assert.ok(roll, 'shop has a rollup');
+ assert.equal(roll.textContent.replace(/\s+/g, ' ').trim(), '1 needs you, 1 working', 'read as a list, with a hidden comma');
+ assert.deepEqual([...roll.querySelectorAll('[data-wt-rollup-rank]')].map((e) => e.getAttribute('data-wt-rollup-rank')), ['1', '5']);
+ assert.equal(host.querySelector('[data-wt-rollup="site"]'), null, 'no rollup on a repo with nothing going on');
+ const ids = [...host.querySelectorAll('[data-wt-row]')].map((e) => e.getAttribute('data-wt-row'));
+ assert.deepEqual(ids.slice(0, 2), ['w2', 'w1'], 'Lin needs you, so its worktree is first; Pixel works next');
+ const repos = [...host.querySelectorAll('section[data-wt-repo]')].map((e) => e.getAttribute('data-wt-repo'));
+ assert.deepEqual(repos, ['shop', 'site'], 'the repo with the ask comes before the quiet one');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Union with 0.9 V1 (#506 "To review") on the integrated tree
+
+const rv = (kwant_id, group, min, title = 'PR') => ({ ...item('review', kwant_id, { timestamp: at(min), title }), group, sort_key: [] });
+
+test('Union: plain asks first in needsYouRows order, then reviews that need you oldest first', () => {
+ const needs = m.needsYouRows([item('question', 'pix', { timestamp: at(2) }), item('approval', 'jun', { timestamp: at(10) })], { iri: 1 }, all);
+ const reviews = [rv('lin', 'waiting_on_you', 90), rv('veg', 'waiting_on_you', 120)];
+ const att = m.attentionRows({ kwants, needs, failed: [], finished: [], reviews, busy: {}, status: {}, now: NOW });
+ assert.deepEqual(order(att).slice(0, 5), ['1:Juno', '1:Pixel', '1:Iris', '1:Vega', '1:Lin'], 'reviews come after every plain ask, even older ones; a browser step stays last among asks');
+});
+
+test('Union: stuck from an Inbox failure, a live H4 stuck or a review at rank 2; to review oldest; working longest first', () => {
+ const h4 = {
+ lin: st('lin', 'stuck', { reason_code: 'stalled_retrying', since: at(5), waits_on: { kind: 'ai', label: 'Claude' } }),
+ rig: st('rig', 'working', { turn: { started_at: at(20) } }),
+ iri: st('iri', 'working', {}),
+ };
+ const failed = [item('turn', 'lin', { status: 'failed', timestamp: at(30), title: 'Deploy' }), item('turn', 'pix', { status: 'failed', timestamp: at(10), title: 'Build' })];
+ const reviews = [rv('jun', 'failed_or_stuck', 15, 'Couldn’t'), rv('lin', 'failed_or_stuck', 60), rv('veg', 'to_review', 40, 'Old'), rv('pix', 'to_review', 5)];
+ const att = m.attentionRows({ kwants, needs: [], failed, finished: [], reviews, busy: { rig: 'Working', iri: 'Working' }, status: { rig: 'working', iri: 'working' }, h4, now: NOW });
+ assert.deepEqual(order(att), ['2:Lin', '2:Juno', '2:Pixel', '3:Vega', '5:Rigel', '5:Iris']);
+ const lin = att[0];
+ assert.equal(lin.at, NOW - 60 * 60_000, 'the oldest of failure, stuck and review orders the group');
+ assert.equal(lin.line, 'Stuck: Claude stopped answering', 'the live H4 line wins');
+ assert.equal(lin.review?.kwant_id, 'lin', 'the older review gives the item it opens');
+ assert.equal(att[1].line, 'Couldn’t approve: Couldn’t');
+});
diff --git a/frontend/tests/heldReload.test.mjs b/frontend/tests/heldReload.test.mjs
new file mode 100644
index 00000000..5c0c2bc1
--- /dev/null
+++ b/frontend/tests/heldReload.test.mjs
@@ -0,0 +1,65 @@
+// 0.9.0 #510 QA should-fix 1+2 (qa-510.md): the held line comes back from the server's `held[]` after a
+// reload, on another device, and for every earlier held message; nit 2: Try again clears only released lines.
+process.env.TZ = 'UTC';
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`export * from './src/h4Status';`);
+
+const names = { jun: 'Juno', lin: 'Lin' };
+const nameOf = (id) => names[id];
+const msg = (id, extra = {}) => ({ kind: 'message', id, since: '2026-11-11T04:10:00Z', reason_code: 'stuck', ...extra });
+const gaveUp = (held) => m.parseH4Status({ kwant_id: 'jun', status: 'stuck', reason_code: 'stalled_gave_up', stuck: { gave_up_at: '2026-11-11T04:05:00Z', tries: 2 }, held });
+
+test('reload with 1 held message: its line comes back from the status, with Try again', () => {
+ const status = { jun: gaveUp([msg('m-1')]) };
+ const rows = m.heldMessages([], status, nameOf);
+ assert.equal(rows.length, 1);
+ assert.deepEqual([rows[0].messageId, rows[0].kwantId, rows[0].name, rows[0].reason], ['m-1', 'jun', 'Juno', 'stuck']);
+ const line = m.heldLine(rows[0], status.jun);
+ assert.equal(line.tryAgain, true);
+ assert.match(line.text, /^Waiting for Juno: Juno stopped after 2 tries at 04:05\. Your message is kept/);
+});
+
+test('reload with 3 held messages to one bot: every one gets its own line; hand-offs get none', () => {
+ const status = { jun: gaveUp([msg('m-1'), msg('m-2'), { kind: 'handoff', id: 'd-1' }, msg('m-3')]) };
+ const rows = m.heldMessages([], status, nameOf);
+ assert.deepEqual(rows.map((r) => r.messageId), ['m-1', 'm-2', 'm-3']);
+ assert.ok(rows.every((r) => m.heldLine(r, status.jun).tryAgain));
+});
+
+test('the instant send reply and the status entry for the same message make one line, not two', () => {
+ const sent = m.heldFromReply({ status: 'held', user_message_id: 'm-3', held: { kwant_id: 'jun', kwant_name: 'Juno', reason_code: 'stuck' } }, 'tmp-3');
+ // Before the status catches up: the reply's line alone.
+ assert.deepEqual(m.heldMessages([sent], { jun: gaveUp([msg('m-1')]) }, nameOf).map((r) => r.messageId), ['m-3', 'm-1']);
+ // After: still one line for m-3 (the reply's, keyed by its temp id too).
+ const rows = m.heldMessages([sent], { jun: gaveUp([msg('m-1'), msg('m-3')]) }, nameOf);
+ assert.deepEqual(rows.map((r) => r.messageId), ['m-3', 'm-1']);
+ assert.equal(rows[0].tempId, 'tmp-3');
+});
+
+test('a waits_on_you hold rebuilt from the status keeps the question time; unknown bot falls back to "The bot"', () => {
+ const s = m.parseH4Status({ kwant_id: 'lin', status: 'needs_you', reason_code: 'asked_question', question: { id: 'q', asked_at: '2026-11-11T03:58:00Z' }, held: [msg('m-7', { reason_code: 'waits_on_you' })] });
+ const [row] = m.heldMessages([], { lin: s }, nameOf);
+ assert.equal(row.reason, 'waits_on_you');
+ assert.match(m.heldLine(row, s).text, /^Queued for Lin: Lin is waiting for your answer to its question \(03:58\)\./);
+ const [anon] = m.heldMessages([], { zed: { ...s, kwant_id: 'zed' } }, nameOf);
+ assert.equal(anon.name, 'The bot');
+});
+
+test('release clears the lines: no held[] means no line; Try again keeps only what the server still holds', () => {
+ assert.deepEqual(m.heldMessages([], { jun: gaveUp([]) }, nameOf), []);
+ assert.deepEqual(m.heldMessages([], null, nameOf), []);
+ const a = m.heldFromReply({ status: 'held', user_message_id: 'm-1', held: { kwant_id: 'jun', reason_code: 'stuck' } }, 't1');
+ const b = m.heldFromReply({ status: 'held', user_message_id: 'm-2', held: { kwant_id: 'jun', reason_code: 'stuck' } }, 't2');
+ const c = m.heldFromReply({ status: 'held', user_message_id: 'm-5', held: { kwant_id: 'lin', reason_code: 'stuck' } }, 't5');
+ // Server released m-1 but still holds m-2: only m-1's line goes; Lin's is untouched.
+ assert.deepEqual(m.afterRelease([a, b, c], 'jun', gaveUp([msg('m-2')])).map((h) => h.messageId), ['m-2', 'm-5']);
+ // Released everything (status back to available).
+ const avail = m.parseH4Status({ kwant_id: 'jun', status: 'available', reason_code: '', held: [] });
+ assert.deepEqual(m.afterRelease([a, b, c], 'jun', avail).map((h) => h.messageId), ['m-5']);
+ // No status in the reply: today's behaviour, all of that bot's lines go.
+ assert.deepEqual(m.afterRelease([a, b, c], 'jun', null).map((h) => h.messageId), ['m-5']);
+});