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.

22i: every Needs-attention row lands on its ask; a Needs you strip above the composer (#701)

Oleksandr Ivanchenko480df5086d52
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4fbadaa3..0f3d4a42 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -153,7 +153,10 @@ import {
questionsApi,
turnsAwaitingAnswer,
} from './questions';
-import { AwayItem, affectsAway, awayApi, awayTarget } from './away';
+import { AwayError, AwayItem, affectsAway, awayApi } from './away';
+import { asksHere, closedId, isHandOff, dismissKind, dropClosed, openTarget as askOpenTarget, resendTarget, retryRoute, switchFor, type AskAction, type Here } from './askHere';
+import { NeedsYouStrip } from './components/NeedsYouStrip';
+import { chainBudgetApi } from './chainBudget';
import { needsYouRows, attentionRows } from './chatsTab';
import { Space, eventsUrl, getCurrentSpace, pickInitialChat } from './spaces';
import { canRunNow } from './engines';
@@ -500,6 +503,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [isSearchOpen, setIsSearchOpen] = useState(false);
const [editingChannelInstructions, setEditingChannelInstructions] = useState<Channel | null>(null);
const [highlightMessageId, setHighlightMessageId] = useState<string | null>(null);
+ // 22i: the highlight a Needs-attention row asked for also gets the pre-push ring.
+ const [ringId, setRingId] = useState<string | null>(null);
// Older messages shown instead of the latest (a search hit beyond them). Kept apart from the
// cache, which live updates keep current underneath.
const [historyWindow, setHistoryWindow] = useState<{ ctx: string; messages: ChatMessage[] } | null>(null);
@@ -622,9 +627,23 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// "Needs you" nudges (attention.ts): what waits on the person, the pill, and the "Show nudges" setting.
const [awayWaiting, setAwayWaiting] = useState(0);
/** What waits on you right now (approvals, questions), for the phone Chats tab's Needs you. */
- const [awayItems, setAwayItems] = useState<AwayItem[]>([]);
+ const [awayList, 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);
+ // 22i: items the person just resolved from the strip go from the row and the strip at once; an id
+ // leaves this set once the server's list no longer has it.
+ const [clearedAsks, setClearedAsks] = useState<ReadonlySet<string>>(() => new Set());
+ const awayItems = useMemo(() => (clearedAsks.size ? awayList.filter((i) => !clearedAsks.has(i.id)) : awayList), [awayList, clearedAsks]);
+ // Rank-2 failed rows, minus any just cleared (a failed hand-off's "Done, clear it").
+ const awayFailed = useMemo(() => (awayDone?.failed ?? []).filter((i) => !clearedAsks.has(i.id)), [awayDone, clearedAsks]);
+ useEffect(() => {
+ setClearedAsks((prev) => {
+ if (!prev.size) return prev;
+ const live = new Set([...awayList, ...(awayDone?.failed ?? [])].map((i) => i.id));
+ const next = new Set([...prev].filter((id) => live.has(id)));
+ return next.size === prev.size ? prev : next;
+ });
+ }, [awayList, awayDone]);
/** 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).
@@ -1273,6 +1292,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
sse.onmessage = (e) => {
try {
const event = JSON.parse(e.data);
+ if (event.type === 'waiting_updated' || event.type === 'WaitingUpdated') {
+ // 22i (#700): a closed item leaves Needs attention and the strip now; an open one comes with the refetch.
+ const gone = closedId(event.data);
+ if (gone) {
+ setAwayItems((prev) => dropClosed(prev, gone));
+ setAwayDone((prev) => (prev ? { failed: dropClosed(prev.failed, gone), finished: prev.finished } : prev));
+ }
+ }
if (affectsAway(event.type)) refreshAwayCount(800);
if (changesBots(event.type, event.data)) {
setRosterFresh(false);
@@ -2342,7 +2369,65 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
openPlaceRef.current = openPlace;
- /** Opens the thread, channel or direct chat an away item links to. */
+ // 22i: whether the last open came from the keyboard (Enter or Space), so a row's open focuses the strip.
+ const keyboardOpenRef = useRef(false);
+ useEffect(() => {
+ const key = (e: KeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') keyboardOpenRef.current = true;
+ };
+ const pointer = () => {
+ keyboardOpenRef.current = false;
+ };
+ window.addEventListener('keydown', key, true);
+ window.addEventListener('pointerdown', pointer, true);
+ return () => {
+ window.removeEventListener('keydown', key, true);
+ window.removeEventListener('pointerdown', pointer, true);
+ };
+ }, []);
+ const [stripFocusKey, setStripFocusKey] = useState(0);
+ // The messages the chat shows now (the latest page, or a history window), and the pending landing.
+ const shownMessagesRef = useRef<ChatMessage[]>([]);
+ const highlightRef = useRef<string | null>(null);
+ highlightRef.current = highlightMessageId;
+
+ /**
+ * 22i: scrolls to an ask's card or message in the chat on screen and rings it (design.md §1). Loads the
+ * messages around it when it is older than the latest page. False when it can't be found, or (quiet,
+ * when stepping) isn't already rendered.
+ */
+ const findAsk = async (item: AwayItem, quiet = false): Promise<boolean> => {
+ const t = awayLanding(item);
+ const focus = t.focus;
+ if (!focus) return false;
+ const ring = () => {
+ setRingId(focus);
+ setHighlightMessageId(focus);
+ return true;
+ };
+ if (t.focusKind === 'approval') return document.querySelector(`[data-approval-card="${CSS.escape(focus)}"]`) ? ring() : false;
+ if (shownMessagesRef.current.some((m) => m.id === focus)) return ring();
+ if (quiet || t.thread_id) return false;
+ const ctx = t.channel_id ?? t.kwant_id;
+ try {
+ const res = await fetch(`/api/channels/${encodeURIComponent(ctx)}/messages?around=${encodeURIComponent(focus)}`);
+ if (!res.ok) return false;
+ const around: ChatMessage[] = await res.json();
+ if (!around.some((m) => m.id === focus) || selectedIdRef.current !== ctx) return false;
+ setHistoryWindow({ ctx, messages: around });
+ return ring();
+ } catch {
+ return false;
+ }
+ };
+
+ /** 22i: where an away item lands: its exact chat, and its own message or card to ring there. */
+ const awayLanding = (item: AwayItem) =>
+ askOpenTarget(item, {
+ questionMessage: (id) => questionsRef.current[id]?.message_id,
+ stepMessage: (id) => humanStepsRef.current[id]?.message_id,
+ });
+ /** Opens the thread, channel or direct chat an away item links to, scrolled to its ask and ringed. */
const openAwayItem = (item: AwayItem) => {
// 0.9.0 P1: a watch item opens its mission's report on the board, where the needs-you line is.
if (item.kind === 'watch' && item.mission_id) {
@@ -2351,17 +2436,27 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
showPage('board');
return;
}
- const t = awayTarget(item);
- // 0.8.1 F6: the same opener as a notification's tap, so a gone chat lands in the bot's 1:1 and
- // an approval row shows its card
- openPlace({
- channel_id: 'channel' in t ? t.channel : null,
- kwant_id: 'thread' in t ? t.kwant : 'direct' in t ? t.direct : item.kwant_id,
- thread_id: 'thread' in t ? t.thread : null,
- card_id: item.kind === 'approval' ? item.id : null,
- });
+ const t = awayLanding(item);
+ // 0.8.1 F6: the same opener as a notification's tap, so a gone chat lands in the bot's 1:1. 22i:
+ // every kind names its message (a question's or browser step's card, a stopped reply's notice),
+ // not only approvals, and the landing gets the ring.
+ if (!openPlace({ channel_id: t.channel_id, kwant_id: t.kwant_id, thread_id: t.thread_id, card_id: t.focus })) return;
+ setRingId(t.focus);
+ // Enter on a row: focus goes to the strip, so a screen reader reads the ask and Tab reaches its button.
+ if (keyboardOpenRef.current) setStripFocusKey((k) => k + 1);
+ // Older than the latest page: once the chat has loaded, load the messages around it and ring it. Not
+ // found at all: no toast and no scroll, the strip is the landing (design.md §1).
+ const focus = t.focus;
+ if (!focus || t.focusKind === 'approval') return;
+ window.setTimeout(() => {
+ if (highlightRef.current !== focus || shownMessagesRef.current.some((m) => m.id === focus)) return;
+ void findAsk(item).then((found) => {
+ if (found) return;
+ setHighlightMessageId((h) => (h === focus ? null : h));
+ setRingId((r) => (r === focus ? null : r));
+ });
+ }, 700);
};
-
/** 0.8.0 B3: a pre-push Inbox item opens the bot's chat at its card. */
const openPrepush = (c: PrepushCardData) => {
if (!openTarget({ channel_id: null, kwant_id: c.kwant_id })) return pushToast('That bot no longer exists.');
@@ -3915,6 +4010,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
const viewingHistory = !!historyWindow && historyWindow.ctx === openCtx;
+
+ shownMessagesRef.current = viewingHistory ? historyWindow.messages : messages;
const errorBar = messagesError ? (
<div role="alert" className="px-3 sm:px-6 py-2 border-b border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">
<span>{messagesError}</span>
@@ -4062,7 +4159,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
? attentionRows({
kwants,
needs: needsYouRows(awayItems, needsYouByKwant, new Set(kwants.map((k) => k.id))),
- failed: awayDone.failed,
+ failed: awayFailed,
finished: awayDone.finished,
busy: busyKwants,
status: botStatus,
@@ -4212,6 +4309,88 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
/>
);
+ // 22i: the "Needs you" strip above the composer: the open asks of the chat on screen, from the same
+ // list as the Needs-attention rows, so both go the moment the item closes.
+ const askHere: Here | null =
+ page !== 'chat' || !selectedId ? null : openThreadId ? { thread: openThreadId, kwant: selectedId } : isChannel ? { channel: selectedId } : { direct: selectedId };
+ // A failed hand-off or run also shows on its thread's strip (#700: Retry with a board task, else Done only).
+ const asks = asksHere([...awayItems, ...awayFailed.filter(isHandOff)], askHere);
+ const askHereKey = !askHere ? '' : 'thread' in askHere ? `t:${askHere.thread}` : 'channel' in askHere ? `c:${askHere.channel}` : `d:${askHere.direct}`;
+ const runAsk = async (item: AwayItem, action: AskAction) => {
+ playSfx('click');
+ if (action === 'answer' || action === 'decide') return findAsk(item);
+ if (action === 'browser') {
+ const st = item.human_step_id ? humanStepsRef.current[item.human_step_id] : undefined;
+ if (!st) return findAsk(item);
+ pickPage(st.page_key);
+ setIsVmPaneOpen(true);
+ return;
+ }
+ if (action === 'ask_again') {
+ if (item.retry?.type !== 'approval') throw new Error('this ask has no approval to ask again');
+ await awayApi.retryApproval(item.retry.approval_id);
+ } else if (action === 'continue') {
+ if (!item.message_id) throw new Error('its notice isn’t in this chat anymore');
+ await chainBudgetApi.continue(item.message_id);
+ } else {
+ // Retry (#700 has no /api/waiting/:id/retry): an approval that ran out asks again, a failed task
+ // or run retries its task, a stopped turn or reply sends the person's last message again.
+ const route = retryRoute(item);
+ if (!route) throw new Error('there’s nothing here to run again');
+ if (route.via === 'approval') await awayApi.retryApproval(route.id);
+ else if (route.via === 'task') await awayApi.retryTask(route.id);
+ else {
+ const target = resendTarget(messages, item.message_id);
+ if (!target) throw new Error('there’s no message of yours here to send again');
+ const sent = await handleSendMessage(target.text, target.attachments);
+ if (sent === false) throw new Error('your message wasn’t sent');
+ if (typeof sent === 'string') throw new Error(sent);
+ }
+ }
+ // Sent: the strip waits for the close event (design.md §2); the list refreshes in case it was missed.
+ refreshAwayCount(300);
+ };
+ const dismissAsk = async (item: AwayItem): Promise<{ use: AskAction } | void> => {
+ if (item.human_step_id && item.dismissable === undefined) {
+ // An older server: a browser step clears by marking it done.
+ const err = await answerHumanStep(item.human_step_id, 'done');
+ if (err) throw new Error(err);
+ } else {
+ try {
+ await awayApi.dismiss(item.id, dismissKind(item));
+ } catch (e) {
+ if (!(e instanceof AwayError)) throw e;
+ // 409: it has its own answer, which tells the bot; the strip switches to that button.
+ const use = e.status === 409 ? switchFor(e.code) : null;
+ if (use) return { use };
+ if (e.code === 'person_only') throw new Error('only you can clear it, from your own sign-in');
+ if (e.code === 'not_found') {
+ // Already gone on the server: it leaves the row and the strip now.
+ setClearedAsks((prev) => new Set(prev).add(item.id));
+ refreshAwayCount(300);
+ return;
+ }
+ if (e.status === 404 || e.status === 405) throw new Error('this version can’t clear it yet. Update the app, or resolve it in the chat');
+ throw e;
+ }
+ }
+ // Cleared at once, with its sidebar row, before the server's close event (design.md §2).
+ setClearedAsks((prev) => new Set(prev).add(item.id));
+ refreshAwayCount(300);
+ };
+ const needsYouStrip = (
+ <NeedsYouStrip
+ asks={asks}
+ onAction={runAsk}
+ onDismiss={dismissAsk}
+ onShow={(item, o) => findAsk(item, o?.quiet)}
+ onOpenInbox={() => showPage('inbox', 'new')}
+ focusKey={stripFocusKey}
+ hereKey={askHereKey}
+ phone={isPhone}
+ />
+ );
+
const away = (
<InboxNew
onOpen={openAwayItem}
@@ -4416,7 +4595,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
continuedFrom={continuedFrom}
focusComposerKey={focusComposerKey}
highlightMessageId={highlightMessageId}
- onHighlightDone={() => setHighlightMessageId(null)}
+ highlightRing={!!ringId && ringId === highlightMessageId}
+ onHighlightDone={() => {
+ setHighlightMessageId(null);
+ setRingId(null);
+ }}
+ needsYouStrip={needsYouStrip}
+ needsYouOpen={asks.length > 0}
subHeader={subHeader}
threadLine={isPhone && threadBarProps ? <ThreadPicker {...threadBarProps} /> : undefined}
notice={
diff --git a/frontend/src/askHere.ts b/frontend/src/askHere.ts
new file mode 100644
index 00000000..022cd14b
--- /dev/null
+++ b/frontend/src/askHere.ts
@@ -0,0 +1,299 @@
+// 22i "a Needs-attention row always shows what it needs": where a row (or its Inbox card) lands, the
+// one action that resolves it, and which open asks belong in the chat on screen (the "Needs you"
+// strip above the composer). Pure, so the node tests cover them without a DOM.
+import { awayTarget, type AwayItem } from './away';
+import { parseAttachments } from './attachments';
+import type { ChatMessage } from './components/ChatView';
+import { retryTargets, type RetryTarget } from './interruptions';
+
+/** What resolves an item. Servers with Lin's 22i part send it as `action`; older ones get it inferred. */
+export type AskAction = 'retry' | 'continue' | 'ask_again' | 'answer' | 'decide' | 'browser';
+
+const ACTIONS: ReadonlySet<string> = new Set(['retry', 'continue', 'ask_again', 'answer', 'decide', 'browser']);
+
+/** The kinds an ask in a chat can be: these get a strip and land on their message. */
+const ASK_KINDS: ReadonlySet<string> = new Set(['question', 'approval', 'stopped']);
+
+export const isAsk = (item: Pick<AwayItem, 'kind'>): boolean => ASK_KINDS.has(item.kind);
+
+/** Shown in the strip: every Needs-you item that lives in a chat, except a sign-in to redo (its fix is in the Inbox). */
+export const onStrip = (item: Pick<AwayItem, 'kind'>): boolean => item.kind !== 'connection';
+
+/**
+ * The one action for an item: the server's `action` when it sends a known one, else from its kind.
+ * A stopped item resumes by Ask again (an approval that expired), Continue (a paused chain), the
+ * browser step it waits on, or Retry (resend the person's message).
+ */
+export function askAction(item: Pick<AwayItem, 'kind' | 'retry' | 'human_step_id'> & { action?: unknown; task_id?: string | null }): AskAction | null {
+ // A failed hand-off or run retries only through its board task (#700, Ada): no task_id, no Retry,
+ // whatever the server says; the person asks the bot again in the thread.
+ if (isHandOff(item) && !item.task_id && (item.action === 'retry' || item.action === undefined)) return null;
+ if (typeof item.action === 'string' && ACTIONS.has(item.action)) return item.action as AskAction;
+ // A 22i server says "nothing resolves it" with an explicit null: only Done, clear it.
+ if (item.action === null) return null;
+ switch (item.kind) {
+ case 'question':
+ return 'answer';
+ case 'approval':
+ return 'decide';
+ case 'stopped': {
+ const r = item.retry;
+ if (r && r.type === 'approval' && r.approval_id) return 'ask_again';
+ if (r && r.type === 'continue') return 'continue';
+ if (item.human_step_id) return 'browser';
+ return 'retry';
+ }
+ }
+ return null;
+}
+
+/** A hand-off or routine run (a failed one is pinned as a rank-2 row and shown on its thread's strip). */
+export const isHandOff = (item: Pick<AwayItem, 'kind'>): boolean => item.kind === 'delegation' || item.kind === 'routine_run';
+
+/** The action's button words (design.md §2, final copy). */
+export const ACTION_LABEL: Record<AskAction, string> = {
+ retry: 'Retry',
+ continue: 'Continue',
+ ask_again: 'Ask again',
+ answer: 'Go to the question',
+ decide: 'Go to the approval',
+ browser: 'Open the browser step',
+};
+
+/** The pressed button's words while its request runs (only the actions that resolve the ask). */
+export const BUSY_LABEL: Partial<Record<AskAction, string>> = { retry: 'Retrying…', continue: 'Continuing…', ask_again: 'Asking…' };
+
+/** Actions that resolve the ask (the strip waits on the server); the rest only take the person to it. */
+export const RESOLVES: ReadonlySet<AskAction> = new Set(['retry', 'continue', 'ask_again']);
+
+const failed = (item: Pick<AwayItem, 'status'>) => item.status === 'failed' || item.status === 'interrupted' || item.status === 'error';
+
+/** The strip's kind word, the same words as the sidebar tooltip (design.md §2, §4). */
+export function askKind(item: Pick<AwayItem, 'kind' | 'status'>, action: AskAction | null): string {
+ switch (action) {
+ case 'retry':
+ return failed(item) ? 'Failed' : 'Stopped';
+ case 'continue':
+ return 'Paused';
+ case 'ask_again':
+ return 'Approval ran out';
+ case 'answer':
+ return 'Question';
+ case 'decide':
+ return 'Approval';
+ case 'browser':
+ return 'Browser step';
+ }
+ return failed(item) ? 'Failed' : 'Stuck';
+}
+
+/** The strip's hint under the line: what the button does, so pressing it is never a guess. */
+export function askHint(item: Pick<AwayItem, 'kind' | 'status'>, action: AskAction | null, bot: string, clearable = true): string {
+ // No button and nothing to clear it with: it clears on its own once handled (Mira's fix 4).
+ if (!action && !clearable) return `Write to ${bot} in the chat. This clears once it’s handled.`;
+ // design.md §2 "no action", for a hand-off: the bot is asked again where the strip shows (its thread, else its chat).
+ // A failed routine run never lives in a thread, and asking the bot again doesn't re-run it (Mira, round 2).
+ if (!action && item.kind === 'routine_run' && failed(item)) return 'There’s no button for this one. Press Run now on it in Routines, or clear it once it’s handled.';
+ if (!action && isHandOff(item) && failed(item)) return `There’s no button for this one. Ask ${bot} again here, or clear it once it’s handled.`;
+ switch (action) {
+ case 'retry':
+ return failed(item) ? 'Retry runs it again from the start.' : `Retry sends your last message to ${bot} again.`;
+ case 'continue':
+ return `Continue picks up where ${bot} stopped. Nothing is sent again.`;
+ case 'ask_again':
+ return 'Ask again starts a new turn. Nothing runs until you say yes.';
+ case 'answer':
+ return 'Answer it on the card in the chat.';
+ case 'decide':
+ return 'Allow or Deny it on the card in the chat.';
+ case 'browser':
+ return `Do it in ${bot}’s browser, then press Done there.`;
+ }
+ return `There’s no button for this one. Write to ${bot}, or clear it once it’s handled.`;
+}
+
+/** The action button's accessible name: its words plus whose ask it is (design.md §5). */
+export function actionName(action: AskAction, bot: string): string {
+ switch (action) {
+ case 'retry':
+ return `Retry ${bot}’s reply`;
+ case 'continue':
+ return `Continue ${bot}’s reply`;
+ case 'ask_again':
+ return `Ask ${bot} again`;
+ case 'answer':
+ return `Go to ${bot}’s question`;
+ case 'decide':
+ return `Go to ${bot}’s approval`;
+ case 'browser':
+ return `Open ${bot}’s browser step`;
+ }
+}
+
+/** A failed press, in the server's own words when it gave some (design.md §2, error lines). */
+export function failLine(what: AskAction | 'dismiss', reason: string | null, bot: string): string {
+ const why = (reason ?? '').trim().replace(/[.\s]+$/, '');
+ if (what === 'dismiss') return why ? `Couldn’t clear it: ${why}.` : 'Couldn’t clear it.';
+ const verb = what === 'continue' ? 'continue' : what === 'ask_again' ? 'ask again' : 'retry';
+ return why ? `Couldn’t ${verb}: ${why}. Try again, or write to ${bot}.` : `Couldn’t ${verb}. Try again, or write to ${bot}.`;
+}
+
+/** The ask's full line: the item's own title, whole; its summary when the title is empty or was cut for a row. */
+export function askLine(item: Pick<AwayItem, 'kind' | 'title' | 'summary' | 'question'>): string {
+ const t = (s?: string | null) => (s ?? '').trim();
+ const title = t(item.title);
+ const summary = t(item.summary);
+ if (item.kind === 'approval' && t(item.question)) return t(item.question);
+ // The kind word sits right above the line, so the line doesn't say it again (Mira's fix 1).
+ const bare = (x: string) => {
+ const rest = x.replace(/^(Failed|Stuck|Stopped|Paused)\s*:\s*/i, '');
+ return rest === x || !rest ? x : rest.charAt(0).toUpperCase() + rest.slice(1);
+ };
+ if (!title) return bare(summary);
+ // A title cut for one row ("The model sent nothing for 120 s, so…") gives way to the whole sentence.
+ const cut = /(…|\.\.\.)$/.test(title);
+ if (cut && summary && summary.length > title.length) return bare(summary);
+ return bare(title);
+}
+
+/** The place a chat is: what the pane shows now, or where an item lives. */
+export type Here = { thread: string; kwant: string } | { channel: string } | { direct: string };
+
+/** Lookups for the message an item's card sits in, when the item doesn't name it. */
+export interface OpenLookups {
+ /** An open question's card message (`questions[id].message_id`). */
+ questionMessage?: (questionId: string) => string | null | undefined;
+ /** An open browser step's card message (`humanSteps[id].message_id`). */
+ stepMessage?: (stepId: string) => string | null | undefined;
+}
+
+/** Where a row opens and what it rings there. `focus` is a message id, or an approval's card id. */
+export interface OpenTarget {
+ channel_id: string | null;
+ kwant_id: string;
+ thread_id: string | null;
+ focus: string | null;
+ focusKind: 'approval' | 'question' | 'browser_step' | 'message' | null;
+}
+
+/**
+ * Every Needs-attention row and its Inbox card: the exact conversation (thread, channel or direct)
+ * and the item's own message to scroll to and ring. Before 22i only approvals named their card.
+ */
+export function openTarget(item: AwayItem, look: OpenLookups = {}): OpenTarget {
+ const t = awayTarget(item);
+ const place = {
+ channel_id: 'channel' in t ? t.channel : null,
+ kwant_id: 'thread' in t ? t.kwant : 'direct' in t ? t.direct : item.kwant_id,
+ thread_id: 'thread' in t ? t.thread : null,
+ };
+ const msg = item.message_id || null;
+ if (item.kind === 'approval') return { ...place, focus: item.id, focusKind: 'approval' };
+ if (item.kind === 'question') {
+ const m = msg ?? look.questionMessage?.(item.id) ?? null;
+ return { ...place, focus: m, focusKind: m ? 'question' : null };
+ }
+ if (item.kind === 'stopped') {
+ const m = msg ?? (item.human_step_id ? look.stepMessage?.(item.human_step_id) : null) ?? null;
+ return { ...place, focus: m, focusKind: m ? (item.human_step_id ? 'browser_step' : 'message') : null };
+ }
+ return { ...place, focus: msg, focusKind: msg ? 'message' : null };
+}
+
+/** Whether an item lives in the chat on screen. */
+export function isHere(item: Pick<AwayItem, 'kwant_id' | 'link'>, here: Here | null): boolean {
+ if (!here) return false;
+ const t = awayTarget(item);
+ if ('thread' in here) return 'thread' in t && t.thread === here.thread;
+ if ('channel' in here) return 'channel' in t && t.channel === here.channel;
+ return 'direct' in t && t.direct === here.direct;
+}
+
+/** The open asks in the chat on screen, oldest first (the order the strip steps through), minus any just cleared. */
+export function asksHere(waiting: AwayItem[], here: Here | null, cleared: ReadonlySet<string> = new Set()): AwayItem[] {
+ const ts = (i: AwayItem) => Date.parse(i.timestamp) || 0;
+ return waiting.filter((i) => onStrip(i) && !cleared.has(i.id) && isHere(i, here)).sort((a, b) => ts(a) - ts(b) || a.id.localeCompare(b.id));
+}
+
+/** The strip's eyebrow and its name: "Quant needs you" for one, "2 things need you" for more. */
+export const stripHeading = (asks: Pick<AwayItem, 'kwant_name'>[]): string =>
+ asks.length > 1 ? `${asks.length} things need you` : `${asks[0]?.kwant_name || 'A bot'} needs you`;
+
+/** Which ask the strip shows after the list changed: the same id if it is still there, else the same place. */
+export function stripIndex(asks: Pick<AwayItem, 'id'>[], shownId: string | null, prevIndex: number): number {
+ if (!asks.length) return 0;
+ const at = shownId ? asks.findIndex((a) => a.id === shownId) : -1;
+ if (at >= 0) return at;
+ return Math.min(Math.max(0, prevIndex), asks.length - 1);
+}
+
+/**
+ * Whether the strip offers "Done, clear it": the server's `dismissable` (Lin, #700) when it sends one;
+ * older servers leave it out and every ask keeps the button (its 404 says the version can't clear it).
+ */
+export const canClear = (item: Pick<AwayItem, 'dismissable'>): boolean => (typeof item.dismissable === 'boolean' ? item.dismissable : true);
+
+/**
+ * A dismiss refused with 409 because the ask has its own answer, which tells the bot (#700): the button
+ * the strip switches to instead. Anything else is an error.
+ */
+export function switchFor(code: string | null | undefined): AskAction | null {
+ switch (code) {
+ case 'use_question_answer':
+ return 'answer';
+ case 'use_approval_decide':
+ case 'use_watch_decide':
+ return 'decide';
+ case 'use_step_decline':
+ return 'browser';
+ }
+ return null;
+}
+
+/** The kind the dismiss body names (#700 takes the item's kind from /api/away; a browser step is "browser"). */
+export const dismissKind = (item: Pick<AwayItem, 'kind' | 'human_step_id'>): string => (item.kind === 'stopped' && item.human_step_id ? 'browser' : item.kind);
+
+/**
+ * Where Retry goes. There is no `POST /api/waiting/:id/retry` (#700 won't add one):
+ * - an approval that ran out asks again (`POST /api/approvals/:id/retry`);
+ * - a failed task or routine run that names its task retries it (`POST /api/tasks/:id/retry`);
+ * - a stopped turn or a reply sends the person's last message again, as the server's notice says, which
+ * closes the item with reason `person_wrote`;
+ * - a failed hand-off or run with no task to retry: null (the strip says to write to the bot).
+ */
+export type RetryRoute = { via: 'approval'; id: string } | { via: 'task'; id: string } | { via: 'resend' };
+export function retryRoute(item: Pick<AwayItem, 'kind' | 'retry' | 'task_id'>): RetryRoute | null {
+ if (item.retry && item.retry.type === 'approval' && item.retry.approval_id) return { via: 'approval', id: item.retry.approval_id };
+ if (item.kind === 'delegation' || item.kind === 'routine_run') return item.task_id ? { via: 'task', id: item.task_id } : null;
+ return { via: 'resend' };
+}
+
+/**
+ * SSE `waiting_updated` (#700): an item that closed leaves Needs attention and the strip at once,
+ * without waiting for the refetch. `closedId` is the closed item's id, or null when the event isn't a
+ * close (an open item: the refetch picks it up); `dropClosed` returns the same list when it has no such item.
+ */
+export function closedId(data: unknown): string | null {
+ const item = (data as { item?: { id?: unknown; status?: unknown } } | null)?.item;
+ return item && item.status === 'closed' && typeof item.id === 'string' && item.id ? item.id : null;
+}
+export function dropClosed<T extends { id: string }>(list: T[], id: string | null): T[] {
+ if (!id || !list.some((i) => i.id === id)) return list;
+ return list.filter((i) => i.id !== id);
+}
+
+/**
+ * What the strip's Retry sends again for a stopped turn or a reply: the notice's
+ * own Retry target when the notice is loaded (none when a step may already have gone out), else the
+ * person's newest message in this chat, which is what Retry in the chat resends.
+ */
+export function resendTarget(messages: ChatMessage[], noticeId: string | null | undefined): RetryTarget | null {
+ if (noticeId && messages.some((m) => m.id === noticeId)) return retryTargets(messages).get(noticeId) ?? null;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const m = messages[i];
+ if (m.sender_role !== 'user') continue;
+ const attachments = parseAttachments(m.meta);
+ if (m.text.trim() || attachments.length) return { text: m.text, attachments };
+ }
+ return null;
+}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index f98445ab..d83cfdfc 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -9,6 +9,8 @@ export interface AwayLink {
thread_id: string | null;
channel_id: string | null;
direct_kwant_id: string | null;
+ /** 22i (Lin, #700): set only when the item's thread belongs to another bot; open the thread under it. */
+ thread_kwant_id?: string | null;
}
export interface AwayItem {
@@ -46,6 +48,10 @@ export interface AwayItem {
/** "sign_in" or "reconnect" (an app to connect again); older servers may leave it out. */
cause?: string;
fix?: { label: string; opens?: string } | null;
+ /** 22i (Lin's server part): what resolves the item. Older servers leave it out; `askAction` infers it. */
+ action?: 'retry' | 'continue' | 'ask_again' | 'answer' | 'decide' | 'browser' | null;
+ /** 22i (Lin, #700): whether "Done, clear it" may close it. Older servers leave it out (the strip infers). */
+ dismissable?: boolean;
}
export interface AwayCounts {
@@ -169,7 +175,7 @@ export type AwayTarget = { thread: string; kwant: string } | { channel: string }
export function awayTarget(item: Pick<AwayItem, 'kwant_id' | 'link'>): AwayTarget {
const l = item.link;
- if (l.thread_id) return { thread: l.thread_id, kwant: item.kwant_id };
+ if (l.thread_id) return { thread: l.thread_id, kwant: l.thread_kwant_id || item.kwant_id };
if (l.channel_id) return { channel: l.channel_id };
return { direct: l.direct_kwant_id || item.kwant_id };
}
@@ -229,8 +235,13 @@ export function actionFailureNotice(status: number, serverMessage: string, title
}
export class AwayError extends Error {
+ /** The server's machine-readable `code` (22i dismiss: `not_found`, `person_only`, `use_*`), when it sent one. */
+ public code: string | null;
+ /** `body`: the parsed JSON error body (22f: a 409 `needs_backup` floor refusal), when there was one. */
constructor(public status: number, message: string, public body: unknown = null) {
super(message);
+ const c = body && typeof body === 'object' ? (body as { code?: unknown }).code : undefined;
+ this.code = typeof c === 'string' && c ? c : null;
}
}
@@ -299,6 +310,10 @@ export const awayApi = {
approvals: (status: string) => call<unknown>('GET', `/api/approvals?status=${enc(status)}`),
/** 0.9.5: ask again for an approval that expired unanswered (starts a new turn; grants nothing). */
retryApproval: (approvalId: string) => call<unknown>('POST', `/api/approvals/${enc(approvalId)}/retry`),
+ /** 22i: Retry on a failed task or routine run that names its task (`missions` retry_task). */
+ retryTask: (taskId: string) => call<unknown>('POST', `/api/tasks/${enc(taskId)}/retry`),
+ /** 22i: "Done, clear it" (the person only, Lin #700): closes one item kwant can't close by itself. */
+ dismiss: (id: string, kind: string) => call<unknown>('POST', `/api/waiting/${enc(id)}/dismiss`, { kind }),
};
/**
@@ -319,5 +334,10 @@ const AWAY_EVENTS = new Set([
'delegation_updated', 'DelegationUpdated',
'routine_run', 'RoutineRun',
'ApprovalRequired', 'ApprovalWithdrawn',
+ // 22i: a stopped item closes when a later reply there ends, a browser step when it is done, and
+ // any item when it is cleared; each refreshes Needs attention and the strip without a reload.
+ 'turn_ended', 'TurnEnded',
+ 'human_step_updated', 'HumanStepUpdated',
+ 'waiting_updated', 'WaitingUpdated', 'waiting_closed', 'WaitingClosed',
]);
export const affectsAway = (type: unknown): boolean => typeof type === 'string' && AWAY_EVENTS.has(type);
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 01fad9f5..a6c71b68 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -99,6 +99,7 @@ import { awayApi } from '../away';
import { parseBudgetNotice } from '../botBudget';
import { BudgetNotice, BudgetPausedBanner, useBudgets } from './BotBudget';
import { isSystemNotice, parseExpiredApproval, parseInterruption, retryTargets } from '../interruptions';
+import { ringElement } from '../ring';
import { parseIsolationFailed, parseRequestLimit } from '../isolationNotice';
import { IsolationNotice, RequestLimitNotice } from './IsolationNotice';
import { IDEA_MAX, isIdeaCommand } from '../ideas';
@@ -342,6 +343,12 @@ export interface ChatViewProps {
focusComposerKey?: number;
/** A message to scroll to and flash (from search). */
highlightMessageId?: string | null;
+ /** 22i: also ring what `highlightMessageId` lands on (a Needs-attention row's ask), like a pre-push card. */
+ highlightRing?: boolean;
+ /** 22i: the "Needs you" strip, right above the composer. */
+ needsYouStrip?: React.ReactNode;
+ /** 22i: the strip shows an ask here, so the working line drops its own "Answer ↑". */
+ needsYouOpen?: boolean;
onHighlightDone?: () => void;
/** Set while `messages` is an older window (a search hit beyond the latest page). */
viewingHistory?: boolean;
@@ -618,6 +625,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
pinned = [],
onEditInstructions,
highlightMessageId,
+ highlightRing,
+ needsYouStrip,
+ needsYouOpen,
onContinueFrom,
threadKind,
continuedFrom,
@@ -1007,7 +1017,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
awaitingAnswer={!!awaitingAnswer}
awaitingBrowser={!!awaitingBrowser}
writing={writing}
- onAnswer={showWaitingCard}
+ // 22i: one ask gets one button. While the Needs-you strip shows it, the strip's Go to … is that button.
+ onAnswer={needsYouOpen ? undefined : showWaitingCard}
onWatch={onWatchBrowser && !vmOpen ? onWatchBrowser : undefined}
phone={phone}
audit={liveAudit}
@@ -1070,7 +1081,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
// Runs after the auto-scroll above, so it wins.
const [flashId, setFlashId] = useState<string | null>(null);
// A search hit glows amber for 2.4 s; the original of a reply quote gets a violet ring for 1.6 s.
- const [flashKind, setFlashKind] = useState<'search' | 'quote'>('search');
+ // 22i: a Needs-attention landing ('ask') is the same amber flash as search, tagged so tests tell them apart.
+ const [flashKind, setFlashKind] = useState<'search' | 'quote' | 'ask'>('search');
useEffect(() => {
if (!highlightMessageId) return;
// 0.8.1 F6: an approval's card (a notification names it), not a message
@@ -1079,7 +1091,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (!card) return;
const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
card.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
- setFlashKind('search');
+ if (highlightRing) ringElement(card);
+ setFlashKind(highlightRing ? 'ask' : 'search');
setFlashId(highlightMessageId);
onHighlightDone?.();
return;
@@ -1096,10 +1109,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (!el) return;
const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
el.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
- setFlashKind('search');
+ setFlashKind(highlightRing ? 'ask' : 'search');
setFlashId(highlightMessageId);
onHighlightDone?.();
- }, [highlightMessageId, messages, openThoughts, onHighlightDone, pendingApprovals]);
+ }, [highlightMessageId, highlightRing, messages, openThoughts, onHighlightDone, pendingApprovals]);
useEffect(() => {
if (!flashId) return;
const t = setTimeout(() => setFlashId(null), flashKind === 'quote' ? 1600 : 2400);
@@ -1790,6 +1803,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div
key={msg.id}
data-message-id={msg.id}
+ data-flash-kind={flashId === msg.id ? flashKind : undefined}
tabIndex={-1}
data-shared-under={underReply ? '' : undefined}
// The log's space-y gap would win over a margin class; inline style pulls the tiles up to the reply's actions
@@ -2778,6 +2792,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Phone and desktop (0.8.1 F4): the quiet line sits inside the composer section, right above the box. */}
{budgetBanner}
{workingStrip}
+ {/* 22i: below the working line, right above the box (design.md §2 order). */}
+ {needsYouStrip}
<form
onSubmit={handleSubmit}
diff --git a/frontend/src/components/NeedsYouStrip.tsx b/frontend/src/components/NeedsYouStrip.tsx
new file mode 100644
index 00000000..1cdc119d
--- /dev/null
+++ b/frontend/src/components/NeedsYouStrip.tsx
@@ -0,0 +1,385 @@
+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { ArrowUp, Check, ChevronLeft, ChevronRight, Globe, Hand, Inbox, Loader2, Play, RotateCcw, type LucideIcon } from 'lucide-react';
+import type { AwayItem } from '../away';
+import { localClock } from '../clock';
+import {
+ ACTION_LABEL,
+ BUSY_LABEL,
+ RESOLVES,
+ actionName,
+ askAction,
+ askHint,
+ askKind,
+ askLine,
+ canClear,
+ retryRoute,
+ failLine,
+ stripHeading,
+ stripIndex,
+ type AskAction,
+} from '../askHere';
+
+export interface NeedsYouStripProps {
+ /** The open asks in this chat, oldest first (`asksHere`). Nothing shows when empty. */
+ asks: AwayItem[];
+ /** Runs Retry, Continue, Ask again or Open the browser step. A throw shows its message as the reason. */
+ onAction: (item: AwayItem, action: AskAction) => Promise<unknown> | void;
+ /**
+ * "Done, clear it": closes the item (the person only). Resolves `{ use }` when the server refused it
+ * because the ask has its own answer (#700's 409 `use_*`): the strip switches its button to that one.
+ */
+ onDismiss: (item: AwayItem) => Promise<{ use: AskAction } | void | unknown>;
+ /**
+ * Go to the question / approval: scroll to its card and ring it, loading history around it when needed.
+ * Resolves false when the card can't be found; the strip then offers Open in Inbox. With `quiet`, only
+ * rings a card that is already rendered (stepping between asks) and never loads or scrolls far.
+ */
+ onShow?: (item: AwayItem, opts?: { quiet?: boolean }) => boolean | Promise<boolean>;
+ /** Open in Inbox, when the card is gone from the chat. */
+ onOpenInbox?: (item: AwayItem) => void;
+ /** Bumped when a row was opened from the keyboard: focus moves to the strip, so its ask is read. */
+ focusKey?: number;
+ /** The chat on screen; announcements only compare asks within one chat. */
+ hereKey?: string;
+ phone?: boolean;
+ /** Tests: the clock's "now", and how long a sent action waits before its button comes back. */
+ now?: number;
+ sentWaitMs?: number;
+}
+
+const ICON: Record<AskAction, LucideIcon> = {
+ retry: RotateCcw,
+ continue: Play,
+ ask_again: RotateCcw,
+ answer: ArrowUp,
+ decide: ArrowUp,
+ browser: Globe,
+};
+
+/** How long a sent Retry / Continue / Ask again waits for the close event before its button comes back. */
+export const SENT_WAIT_MS = 5000;
+/** At most one spoken update per this many ms (the sidebar's `data-needs-attention-live` pattern). */
+const SAY_EVERY_MS = 10_000;
+
+const motionOk = () => typeof window !== 'undefined' && !!window.matchMedia && !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const focusComposer = () => document.querySelector<HTMLElement>('textarea[data-composer]')?.focus();
+
+/**
+ * 22i: the "Needs you" strip above the composer (design.md §2). While an open ask sits in the chat on
+ * screen it says the whole ask, what kind it is, what its one button does, and "Done, clear it", and steps
+ * through several. It reads the Needs-you list, not the messages, so it shows even when the ask's message
+ * isn't loaded, and it goes in the same render as the sidebar row once the list drops the item.
+ */
+export const NeedsYouStrip: React.FC<NeedsYouStripProps> = ({ asks, onAction, onDismiss, onShow, onOpenInbox, focusKey, hereKey, phone, now, sentWaitMs = SENT_WAIT_MS }) => {
+ const [index, setIndex] = useState(0);
+ const shownId = useRef<string | null>(null);
+ // The action can be sending while "Done, clear it" stays pressable; clearing stops both.
+ const [acting, setActing] = useState(false);
+ const [clearing, setClearing] = useState(false);
+ // A second press before the first re-renders: the state isn't set yet, so refs hold the locks.
+ const actLock = useRef(false);
+ const clearLock = useRef(false);
+ const [error, setError] = useState<string | null>(null);
+ const [sent, setSent] = useState(false);
+ const [gone, setGone] = useState(false);
+ // A dismiss the server refused (409 use_*): the ask's own button instead, and no Done.
+ const [switched, setSwitched] = useState<AskAction | null>(null);
+ const actionRef = useRef<HTMLButtonElement | null>(null);
+ const sentTimer = useRef<number | null>(null);
+ const sectionRef = useRef<HTMLElement | null>(null);
+ const hadFocus = useRef(false);
+ const [narrow, setNarrow] = useState(false);
+
+ // Leaving: the last ask fades for 120 ms (none under reduced motion) instead of vanishing mid-read.
+ const [ghost, setGhost] = useState<AwayItem[] | null>(null);
+ const prevAsks = useRef<AwayItem[]>(asks);
+ const shown = asks.length ? asks : ghost ?? [];
+ const leaving = !asks.length && !!ghost;
+ useLayoutEffect(() => {
+ const before = prevAsks.current;
+ prevAsks.current = asks;
+ if (asks.length || !before.length) {
+ if (asks.length) setGhost(null);
+ return;
+ }
+ // The strip is going: focus that was in it goes to the composer, never to the page body.
+ if (hadFocus.current) {
+ hadFocus.current = false;
+ focusComposer();
+ }
+ if (!motionOk()) return;
+ setGhost(before);
+ const t = window.setTimeout(() => setGhost(null), 120);
+ return () => window.clearTimeout(t);
+ }, [asks]);
+
+ const i = stripIndex(shown, shownId.current, index);
+ const item = shown[i];
+ useEffect(() => {
+ if (i !== index) setIndex(i);
+ }, [i, index]);
+ // A new ask on screen starts clean: no leftover error, spinner or "Sent" from the one before.
+ const itemId = item?.id ?? null;
+ useEffect(() => {
+ if (shownId.current !== itemId) {
+ setError(null);
+ setActing(false);
+ setClearing(false);
+ setSent(false);
+ setGone(false);
+ setSwitched(null);
+ actLock.current = false;
+ clearLock.current = false;
+ if (sentTimer.current) window.clearTimeout(sentTimer.current);
+ }
+ shownId.current = itemId;
+ }, [itemId]);
+ useEffect(() => () => {
+ if (sentTimer.current) window.clearTimeout(sentTimer.current);
+ }, []);
+
+ // A keyboard open lands on the strip, so a screen reader reads the ask and Tab reaches its button.
+ useEffect(() => {
+ if (focusKey) sectionRef.current?.focus();
+ }, [focusKey]);
+
+ // Under 640 px of composer the buttons drop below the hint (design.md §2).
+ useEffect(() => {
+ const el = sectionRef.current;
+ if (!el || phone || typeof ResizeObserver === 'undefined') return;
+ const ro = new ResizeObserver(([e]) => setNarrow(e.contentRect.width < 640));
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [phone, !!item]);
+
+ // One polite line: an ask that arrives in the open chat, the last one closing, and a clear.
+ const [said, setSaid] = useState('');
+ const saidAt = useRef(0);
+ const cleared = useRef(false);
+ const seen = useRef<{ here?: string; ids: Set<string> }>({ here: hereKey, ids: new Set(asks.map((a) => a.id)) });
+ useEffect(() => {
+ const was = seen.current;
+ const ids = new Set(asks.map((a) => a.id));
+ seen.current = { here: hereKey, ids };
+ if (was.here !== hereKey) return;
+ const say = (text: string, always = false) => {
+ const t = Date.now();
+ if (!always && t - saidAt.current < SAY_EVERY_MS) return;
+ saidAt.current = t;
+ setSaid(text);
+ };
+ if (cleared.current && ids.size < was.ids.size) {
+ cleared.current = false;
+ return say('Cleared.', true);
+ }
+ if (!ids.size && was.ids.size) return say('Nothing needs you here now.');
+ const fresh = asks.find((a) => !was.ids.has(a.id));
+ if (fresh) {
+ const act = askAction(fresh);
+ say(`${fresh.kwant_name} needs you: ${act ? ACTION_LABEL[act] : canClear(fresh) ? 'Done, clear it' : `write to ${fresh.kwant_name}`}`);
+ }
+ }, [asks, hereKey]);
+ const live = (
+ <span className="sr-only" aria-live="polite" data-needs-you-live>
+ {said}
+ </span>
+ );
+
+ if (!item) return live;
+ // A Retry with nowhere to go (a failed hand-off with no board task) isn't offered (Mira's fix 3).
+ const base = askAction(item);
+ const action = switched ?? (base === 'retry' && !retryRoute(item) ? null : base);
+ const clearable = canClear(item) && !switched;
+ const n = shown.length;
+ const bot = item.kwant_name || 'the bot';
+ const heading = stripHeading(shown);
+ const headId = `needs-you-head-${item.id}`;
+ const manyBots = new Set(shown.map((a) => a.kwant_id)).size > 1 || n > 1;
+ const time = localClock(item.timestamp, now);
+ const goTo = action === 'answer' || action === 'decide';
+ const resolving = !!action && RESOLVES.has(action);
+
+ const step = (d: number) => {
+ const next = Math.min(Math.max(0, i + d), n - 1);
+ if (next === i) return;
+ shownId.current = shown[next].id;
+ setIndex(next);
+ void onShow?.(shown[next], { quiet: true });
+ };
+ const clear = async () => {
+ if (clearLock.current || leaving) return;
+ clearLock.current = true;
+ setError(null);
+ setClearing(true);
+ cleared.current = true;
+ try {
+ const r = await onDismiss(item);
+ const use = r && typeof r === 'object' && 'use' in r ? (r as { use: AskAction }).use : null;
+ if (use) {
+ // Not an error: this ask is resolved on its own card, so the button goes there.
+ cleared.current = false;
+ setSwitched(use);
+ window.setTimeout(() => actionRef.current?.focus(), 0);
+ }
+ } catch (e) {
+ cleared.current = false;
+ setError(failLine('dismiss', e instanceof Error && e.message ? e.message : null, bot));
+ } finally {
+ clearLock.current = false;
+ setClearing(false);
+ }
+ };
+ const act = async () => {
+ if (actLock.current || clearLock.current || leaving || !action) return;
+ if (gone) return onOpenInbox?.(item);
+ actLock.current = true;
+ setError(null);
+ setSent(false);
+ setActing(true);
+ let waiting = false;
+ try {
+ if (goTo) {
+ const found = onShow ? await onShow(item) : true;
+ if (!found) setGone(true);
+ } else {
+ await onAction(item, action);
+ if (resolving) {
+ // Sent: wait for the close event. Still open after 5 s, the button comes back with a note.
+ waiting = true;
+ sentTimer.current = window.setTimeout(() => {
+ sentTimer.current = null;
+ actLock.current = false;
+ setActing(false);
+ setSent(true);
+ }, sentWaitMs);
+ }
+ }
+ } catch (e) {
+ setError(failLine(action, e instanceof Error && e.message ? e.message : null, bot));
+ } finally {
+ if (!waiting) {
+ actLock.current = false;
+ setActing(false);
+ }
+ }
+ };
+
+ const stacked = phone || narrow;
+ const btnH = phone ? 'h-11 text-[14px]' : 'h-8';
+ const Icon = gone ? Inbox : action ? ICON[action] : null;
+ const busyAct = acting && resolving;
+ const label = gone ? 'Open in Inbox' : action ? (busyAct ? BUSY_LABEL[action] ?? ACTION_LABEL[action] : ACTION_LABEL[action]) : '';
+ // After a 409 switch: why Done went away (Mira's fix 5).
+ const switchedHint =
+ switched === 'answer'
+ ? 'This one clears when you answer it on its card.'
+ : switched === 'decide'
+ ? 'This one clears when you Allow or Deny it on its card.'
+ : switched === 'browser'
+ ? `This one clears when you finish or decline it in ${bot}’s browser.`
+ : null;
+ const hint = gone ? 'Its card isn’t in this chat anymore.' : sent ? `Sent. This clears once ${bot} answers.` : switchedHint ?? askHint(item, action, bot, clearable);
+ const stepBtn =
+ 'kws-hit inline-flex items-center justify-center w-7 h-7 rounded-lg border border-hairline-strong text-zinc-200 hover:bg-white/[0.08] disabled:opacity-40 disabled:cursor-default kw-focus';
+
+ const buttons = (
+ <div
+ data-strip-buttons
+ className={phone ? `mt-2.5 flex gap-2 ${action === 'browser' && !gone ? 'flex-col-reverse' : ''}` : stacked ? 'mt-2 flex justify-end gap-2' : 'flex items-center gap-2 self-center row-start-2 col-start-2'}
+ >
+ {clearable && (
+ <button
+ type="button"
+ data-strip-dismiss
+ disabled={clearing || leaving}
+ aria-busy={clearing || undefined}
+ aria-label="Done, clear it from Needs attention"
+ onClick={() => void clear()}
+ className={`kw-btn-ghost ${btnH} ${phone ? 'flex-1' : ''} disabled:opacity-60 disabled:cursor-default`}
+ >
+ {clearing ? <Loader2 size={13} aria-hidden="true" className="kw-dict-spin" /> : <Check size={13} aria-hidden="true" />}
+ {clearing ? 'Clearing…' : 'Done, clear it'}
+ </button>
+ )}
+ {action && (
+ <button
+ ref={actionRef}
+ type="button"
+ data-strip-action={gone ? 'inbox' : action}
+ disabled={busyAct || clearing || leaving}
+ aria-busy={busyAct || undefined}
+ aria-label={gone ? 'Open in Inbox' : actionName(action, bot)}
+ onClick={() => void act()}
+ className={`kw-btn-primary ${btnH} ${phone ? 'flex-[1.4]' : ''} whitespace-nowrap`}
+ >
+ {busyAct ? <Loader2 size={14} aria-hidden="true" className="kw-dict-spin shrink-0" /> : Icon && <Icon size={14} aria-hidden="true" className="shrink-0" />}
+ {label}
+ </button>
+ )}
+ </div>
+ );
+
+ return (
+ <>
+ {live}
+ <section
+ ref={sectionRef}
+ tabIndex={-1}
+ data-needs-you-strip={item.id}
+ data-action={action ?? 'none'}
+ data-strip-state={clearing ? 'clearing' : busyAct ? 'busy' : gone ? 'gone' : error ? 'error' : sent ? 'sent' : 'idle'}
+ aria-labelledby={headId}
+ onFocus={() => (hadFocus.current = true)}
+ onBlur={(e) => {
+ if (e.relatedTarget && !e.currentTarget.contains(e.relatedTarget as Node)) hadFocus.current = false;
+ }}
+ className={`${leaving ? 'kw-needs-leave' : 'kw-pin-enter'} max-w-4xl mx-auto mb-2 rounded-xl border border-amber-300/35 bg-surface-main px-3 py-2.5 kw-focus ${
+ phone ? 'max-h-[45vh]' : 'max-h-[240px]'
+ } overflow-y-auto ${stacked ? '' : 'grid grid-cols-[1fr_auto] gap-x-4'}`}
+ style={{ backgroundImage: 'linear-gradient(rgb(252 211 77 / 0.06), rgb(252 211 77 / 0.06))' }}
+ >
+ <div className="flex items-center gap-1.5 min-w-0 col-span-2">
+ <Hand size={12} aria-hidden="true" className="shrink-0 text-amber-300" />
+ <h2 id={headId} className="text-[11px] font-semibold uppercase tracking-[0.06em] text-amber-300 truncate">
+ {heading}
+ </h2>
+ {n > 1 && (
+ <span className="ml-auto flex items-center gap-1.5 shrink-0" data-strip-steps>
+ <button type="button" data-compact className={stepBtn} onClick={() => step(-1)} disabled={i === 0} aria-label="Previous ask">
+ <ChevronLeft size={14} aria-hidden="true" />
+ </button>
+ <span className="text-meta tabular-nums text-zinc-300" aria-live="polite" data-strip-count>
+ {i + 1} of {n}
+ </span>
+ <button type="button" data-compact className={stepBtn} onClick={() => step(1)} disabled={i === n - 1} aria-label="Next ask">
+ <ChevronRight size={14} aria-hidden="true" />
+ </button>
+ </span>
+ )}
+ </div>
+ {/* Stepping cross-fades the ask (opacity only); keyed so each ask enters on its own. */}
+ <div key={item.id} className={`kw-needs-fade min-w-0 ${stacked ? '' : 'col-start-1 row-start-2'}`}>
+ <p className="mt-0.5 text-meta text-zinc-400" data-strip-kind>
+ <span className="font-semibold text-amber-200">{askKind(item, action)}</span>
+ {manyBots && <> · {bot}</>}
+ {time && <> · {time}</>}
+ </p>
+ {/* The whole line, never cut: it wraps, and the box scrolls past 240 px. */}
+ <p data-strip-line className="mt-0.5 text-body font-medium text-zinc-50 break-words">
+ {askLine(item)}
+ </p>
+ <p data-strip-hint className={`mt-0.5 text-meta ${gone ? 'text-zinc-300' : 'text-zinc-400'}`}>
+ {hint}
+ </p>
+ {error && (
+ <p role="alert" data-strip-error className="mt-1 text-meta text-bad break-words">
+ {error}
+ </p>
+ )}
+ </div>
+ {clearable || action ? buttons : null}
+ </section>
+ </>
+ );
+};
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index e365b00e..1e3cd9cb 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Hash, Plus, CheckCircle2, ShieldCheck, KeyRound, Loader2, Users, ChevronDown, Settings, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, Split, Hand, MoreHorizontal, UserMinus, MessageSquare, KanbanSquare, CalendarClock } from 'lucide-react';
import { ModernAvatar, useModelBadge } from './ModernAvatar';
import { playSfx } from '../audio/chiptune';
@@ -18,6 +18,8 @@ import { layaRoutes } from '../channels';
import { PhoneAppTip } from './PhoneAppTip';
import { trapFocusTarget } from '../imports';
import { type AttentionRow, type NeedsYouRow, PINNED_RANK, NEEDS_YOU_LABEL, workingIds, directIds, rollupLabel } from '../chatsTab';
+import { askAction, askKind, askLine, isAsk } from '../askHere';
+import { localClock } from '../clock';
import type { InboxItem } from '../api/inbox';
import { useDevMode } from './DevModeSwitch';
import { MovedPointer, SpaceSubline } from './FirstScreenBits';
@@ -470,6 +472,28 @@ 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.
+ // 22i: the pinned row's tooltip (design.md §4): 300 ms after hover, at once on keyboard focus; to the
+ // right of the row, or below it when the window has less than 328 px there.
+ const [rowTip, setRowTip] = useState<{ id: string; top: number; left: number } | null>(null);
+ const rowTipTimer = useRef<number | null>(null);
+ const showRowTip = (id: string, el: HTMLElement, delay: number) => {
+ if (rowTipTimer.current) window.clearTimeout(rowTipTimer.current);
+ const place = () => {
+ const r = el.getBoundingClientRect();
+ const below = window.innerWidth - r.right < 328;
+ setRowTip({ id, top: below ? r.bottom + 8 : r.top, left: below ? r.left : r.right + 8 });
+ };
+ if (delay) rowTipTimer.current = window.setTimeout(place, delay);
+ else place();
+ };
+ const hideRowTip = () => {
+ if (rowTipTimer.current) window.clearTimeout(rowTipTimer.current);
+ rowTipTimer.current = null;
+ setRowTip(null);
+ };
+ useEffect(() => () => {
+ if (rowTipTimer.current) window.clearTimeout(rowTipTimer.current);
+ }, []);
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 selection
const active = !phone && !isChannel && selectedId === k.id;
@@ -507,6 +531,28 @@ export const Sidebar: React.FC<SidebarProps> = ({
: busyKwants[k.id];
// A teammate who finished its part of a team turn that now waits on the person (UX audit #2)
const doneLine = !busyLine && !warn ? doneKwants[k.id] : undefined;
+ // 22i: a pinned row's line is cut to one line; hover and focus give the whole ask (the stopped
+ // reply's full sentence, the approval's question), as a tooltip and as the row's name.
+ // 22i: a pinned row's line is cut to one line; hover and focus show the whole ask in a small tooltip
+ // (design.md §4): "Quant · Stopped · 18:44" over the full line. A native title never shows on focus.
+ const rowItem = asked?.item ?? att?.item;
+ const fullLine = pin && busyLine ? (rowItem && isAsk(rowItem) ? askLine(rowItem) || busyLine : busyLine) : undefined;
+ const tipKind = !att
+ ? undefined
+ : att.rank === 3
+ ? 'To review'
+ : att.rank === 4
+ ? 'Finished'
+ : rowItem
+ ? askKind(rowItem, askAction(rowItem))
+ : att.rank === 2
+ ? 'Failed'
+ : needs > 0
+ ? 'Browser step'
+ : undefined;
+ const tipHead = fullLine ? [k.name, tipKind, rowItem ? localClock(rowItem.timestamp) : null].filter(Boolean).join(' · ') : undefined;
+ const tipId = fullLine ? `pin-tip-${k.id}` : undefined;
+ const tipOpen = !!tipId && rowTip?.id === k.id;
// A stuck or finished row opens where that happened (its thread or chat), like its Inbox card
// A review row opens its item in the Inbox
const open = asked && onOpenNeedsYou
@@ -527,12 +573,19 @@ export const Sidebar: React.FC<SidebarProps> = ({
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()}
+ onKeyDown={(e) => {
+ if (tipId && e.key === 'Escape') hideRowTip();
+ if (e.key === 'Enter' && e.target === e.currentTarget) open?.();
+ }}
+ onMouseEnter={tipId ? (e) => showRowTip(k.id, e.currentTarget, 300) : undefined}
+ onMouseLeave={tipId ? hideRowTip : undefined}
+ onFocus={tipId ? (e) => e.target === e.currentTarget && e.currentTarget.matches?.(':focus-visible') && showRowTip(k.id, e.currentTarget, 0) : undefined}
+ onBlur={tipId ? hideRowTip : undefined}
// 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}
+ aria-describedby={[tipId, pin?.alsoIn ? `pin-also-${k.id}` : null].filter(Boolean).join(' ') || 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'
@@ -621,6 +674,19 @@ export const Sidebar: React.FC<SidebarProps> = ({
</span>
)}
</div>
+ {tipId && (
+ <div
+ role="tooltip"
+ id={tipId}
+ data-pin-tip={k.id}
+ hidden={!tipOpen}
+ style={tipOpen ? { top: rowTip!.top, left: rowTip!.left } : undefined}
+ className="fixed z-50 max-w-[320px] rounded-lg border border-hairline-strong bg-surface-overlay px-2.5 py-2 text-meta shadow-[0_8px_24px_rgb(0_0_0/0.5)] pointer-events-none"
+ >
+ <span className="block text-zinc-400">{tipHead}</span>
+ <span className="block text-zinc-100 break-words whitespace-normal">{fullLine}</span>
+ </div>
+ )}
{pin?.alsoIn && (
<span id={`pin-also-${k.id}`} className="sr-only">
Also listed in @{pin.alsoIn}
@@ -631,7 +697,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
className={`flex items-center gap-1.5 text-meta truncate${actionRoom} ${
warn || asked ? 'text-warn' : attLine ? attTone : status === 'queued' ? 'text-zinc-300' : 'text-[#b8adff]'
}`}
- title={busyLine === busyKwants[k.id] ? busyTitles?.[k.id] ?? busyLine : busyLine}
+ title={fullLine ? undefined : busyLine === busyKwants[k.id] ? busyTitles?.[k.id] ?? busyLine : busyLine}
data-bot-busy
>
<span
@@ -640,7 +706,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
}`}
aria-hidden="true"
/>
- <span className="truncate">{busyLine}</span>
+ <span className={chat && (asked || attLine) ? 'line-clamp-2 whitespace-normal' : 'truncate'}>{busyLine}</span>
</p>
) : doneLine ? (
<p className={`flex items-center gap-1.5 text-meta text-zinc-400 truncate${actionRoom}`} title={doneLine} data-bot-done="">
diff --git a/frontend/src/ring.ts b/frontend/src/ring.ts
new file mode 100644
index 00000000..8fd8c0da
--- /dev/null
+++ b/frontend/src/ring.ts
@@ -0,0 +1,18 @@
+// 22i: the ring a Needs-attention row's landing gets (design.md §1): the search jump's amber `kw-flash`,
+// a 2.4 s glow that becomes a static outline under reduced motion, so the landing is shown either way.
+// ChatView rings messages through its own flash state; this is for cards outside the message list
+// (an approval card), which have no flash class of their own.
+
+export const RING_MS = 2400;
+
+/** Rings an element once with `kw-flash`, tagged `data-flash-kind="ask"` so tests can tell it from search. */
+export function ringElement(el: HTMLElement): void {
+ el.classList.remove('kw-flash');
+ void el.offsetWidth;
+ el.classList.add('kw-flash');
+ el.dataset.flashKind = 'ask';
+ window.setTimeout(() => {
+ el.classList.remove('kw-flash');
+ delete el.dataset.flashKind;
+ }, RING_MS);
+}
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
index c60a5a12..0e5d5666 100644
--- a/frontend/src/styles/modern.css
+++ b/frontend/src/styles/modern.css
@@ -1069,3 +1069,14 @@ button.dv-sha { cursor: copy; } button.dv-sha:hover { color: var(--accent); bord
.kw-st-pop { animation: kw-st-pop 140ms ease-out both; }
.kw-st-sheet { animation: kw-st-sheet 180ms ease-out both; }
}
+
+/* 22i Needs-you strip (design.md §2 Motion): it leaves by fading 120 ms, and stepping between asks
+ cross-fades the ask 120 ms (opacity only). Nothing moves under reduced motion. */
+@keyframes kw-needs-fade {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+@media (prefers-reduced-motion: no-preference) {
+ .kw-needs-fade { animation: kw-needs-fade 120ms var(--kw-ease, ease-out); }
+ .kw-needs-leave { opacity: 0; transition: opacity 120ms var(--kw-ease, ease-out); }
+}
diff --git a/frontend/tests/askHere.test.mjs b/frontend/tests/askHere.test.mjs
new file mode 100644
index 00000000..4065f329
--- /dev/null
+++ b/frontend/tests/askHere.test.mjs
@@ -0,0 +1,572 @@
+// 22i (brief: autonomy/attention-shows-the-ask/brief.md): every Needs-attention row lands on and rings its
+// ask; the "Needs you" strip above the composer says the whole ask, its one action and "Done, clear it",
+// steps through several, shows when the message isn't rendered, and goes when the item closes.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+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', 'Node', 'DOMParser', 'localStorage', 'sessionStorage', 'getComputedStyle']) {
+ if (k in dom.window) Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.IS_REACT_ACT_ENVIRONMENT = false;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export * from './src/askHere';
+ export { NeedsYouStrip } from './src/components/NeedsYouStrip';
+ export { Sidebar } from './src/components/Sidebar';
+ export { needsYouRows, attentionRows } from './src/chatsTab';
+ export { ringElement } from './src/ring';
+`);
+const h = m.React.createElement;
+const noop = () => {};
+
+const link = (over = {}) => ({ thread_id: null, channel_id: null, direct_kwant_id: null, ...over });
+const item = (kind, over = {}) => ({
+ kind, id: `${kind}-1`, kwant_id: 'quant', kwant_name: 'Quant', title: '', summary: '', status: 'open',
+ timestamp: '2026-11-15T17:40:00Z', link: link({ direct_kwant_id: 'quant' }), ...over,
+});
+// Oleks's row: the title is cut for one line; the summary is the whole ask.
+const STALL = 'The model sent nothing for 120 s, so this reply was stopped. Retry in the chat sends your message again.';
+const stopped = item('stopped', { id: 'w1', title: 'The model sent nothing for 120 s, so this…', summary: STALL, message_id: 'm-notice', retry: null });
+
+test('open target: every kind lands on its own chat and message, not only approvals', () => {
+ // approval: its card id, in a channel
+ assert.deepEqual(m.openTarget(item('approval', { id: 'ap1', link: link({ channel_id: 'c1' }) })), {
+ channel_id: 'c1', kwant_id: 'quant', thread_id: null, focus: 'ap1', focusKind: 'approval',
+ });
+ // question: the card message from the open questions when the item doesn't name it; in a thread
+ const q = item('question', { id: 'q1', link: link({ thread_id: 't9' }) });
+ assert.deepEqual(m.openTarget(q, { questionMessage: (id) => (id === 'q1' ? 'm-q' : null) }), {
+ channel_id: null, kwant_id: 'quant', thread_id: 't9', focus: 'm-q', focusKind: 'question',
+ });
+ // a question with no card known: the chat, nothing to ring
+ assert.equal(m.openTarget(q).focus, null);
+ // stopped: the notice that carries Retry, in the direct chat
+ assert.deepEqual(m.openTarget(stopped), { channel_id: null, kwant_id: 'quant', thread_id: null, focus: 'm-notice', focusKind: 'message' });
+ // stopped on a browser step: the step's card (from the step when the item has no message_id)
+ const step = item('stopped', { id: 'hs1', human_step_id: 'hs1', message_id: null });
+ assert.deepEqual(m.openTarget(step, { stepMessage: (id) => (id === 'hs1' ? 'm-step' : null) }), {
+ channel_id: null, kwant_id: 'quant', thread_id: null, focus: 'm-step', focusKind: 'browser_step',
+ });
+ // direct chat named by another bot's id (a lead's chat), and an Inbox item with a message
+ assert.equal(m.openTarget(item('stopped', { link: link({ direct_kwant_id: 'lead' }) })).kwant_id, 'lead');
+ assert.deepEqual(m.openTarget(item('delegation', { message_id: 'm-r', link: link({ thread_id: 't2' }) })), {
+ channel_id: null, kwant_id: 'quant', thread_id: 't2', focus: 'm-r', focusKind: 'message',
+ });
+});
+
+test('one action per item: the server says it, else it is inferred from the kind', () => {
+ assert.equal(m.askAction(item('question')), 'answer');
+ assert.equal(m.askAction(item('approval')), 'decide');
+ assert.equal(m.askAction(stopped), 'retry');
+ assert.equal(m.askAction(item('stopped', { retry: { type: 'continue' } })), 'continue');
+ assert.equal(m.askAction(item('stopped', { retry: { type: 'approval', approval_id: 'a9' } })), 'ask_again');
+ assert.equal(m.askAction(item('stopped', { human_step_id: 'hs1' })), 'browser');
+ assert.equal(m.askAction({ ...stopped, action: 'continue' }), 'continue', "Lin's action wins");
+ assert.equal(m.askAction({ ...stopped, action: 'bogus' }), 'retry', 'an unknown action is ignored (older shape)');
+ assert.equal(m.askAction({ ...stopped, action: null }), null, 'an explicit null: nothing resolves it but Done');
+ assert.equal(m.askAction(item('delegation')), null);
+ assert.deepEqual(Object.values(m.ACTION_LABEL), ['Retry', 'Continue', 'Ask again', 'Go to the question', 'Go to the approval', 'Open the browser step']);
+});
+
+test('the full line: the title whole; a title cut for a row gives way to the summary; an approval its question', () => {
+ assert.equal(m.askLine(stopped), STALL);
+ assert.equal(m.askLine(item('stopped', { title: 'The model sent nothing for 120 s, so this reply was stopped.', summary: 'Short.' })), 'The model sent nothing for 120 s, so this reply was stopped.');
+ assert.equal(m.askLine(item('approval', { title: 'Wants to run a command', question: 'Run “deploy.sh prod”?' })), 'Run “deploy.sh prod”?');
+ assert.equal(m.askLine(item('approval', { title: 'Wants to run a command' })), 'Wants to run a command');
+ assert.equal(m.askLine(item('question', { title: 'Ship tonight?', summary: 'Choices: Yes · No' })), 'Ship tonight?');
+ assert.equal(m.askLine(item('question', { title: '', summary: 'Pick one' })), 'Pick one');
+});
+
+test("the strip's words: kind, hint, the button's name and the error lines (design.md §2, §5)", () => {
+ const rows = [
+ [stopped, 'Stopped', 'Retry sends your last message to Quant again.', 'Retry Quant’s reply'],
+ [{ ...stopped, status: 'failed' }, 'Failed', 'Retry runs it again from the start.', 'Retry Quant’s reply'],
+ [item('stopped', { retry: { type: 'continue' } }), 'Paused', 'Continue picks up where Quant stopped. Nothing is sent again.', 'Continue Quant’s reply'],
+ [item('stopped', { retry: { type: 'approval', approval_id: 'a' } }), 'Approval ran out', 'Ask again starts a new turn. Nothing runs until you say yes.', 'Ask Quant again'],
+ [item('question'), 'Question', 'Answer it on the card in the chat.', 'Go to Quant’s question'],
+ [item('approval'), 'Approval', 'Allow or Deny it on the card in the chat.', 'Go to Quant’s approval'],
+ [item('stopped', { human_step_id: 'h' }), 'Browser step', 'Do it in Quant’s browser, then press Done there.', 'Open Quant’s browser step'],
+ [item('delegation'), 'Stuck', 'There’s no button for this one. Write to Quant, or clear it once it’s handled.', null],
+ ];
+ for (const [it, kind, hint, name] of rows) {
+ const a = m.askAction(it);
+ assert.equal(m.askKind(it, a), kind);
+ assert.equal(m.askHint(it, a, 'Quant'), hint);
+ assert.equal(a ? m.actionName(a, 'Quant') : null, name);
+ }
+ assert.equal(m.failLine('retry', 'Quant’s engine is out until 20:50.', 'Quant'), 'Couldn’t retry: Quant’s engine is out until 20:50. Try again, or write to Quant.');
+ assert.equal(m.failLine('continue', 'no budget', 'Quant'), 'Couldn’t continue: no budget. Try again, or write to Quant.');
+ assert.equal(m.failLine('ask_again', 'gone', 'Quant'), 'Couldn’t ask again: gone. Try again, or write to Quant.');
+ assert.equal(m.failLine('retry', null, 'Quant'), 'Couldn’t retry. Try again, or write to Quant.');
+ assert.equal(m.failLine('dismiss', 'not yours', 'Quant'), 'Couldn’t clear it: not yours.');
+});
+
+test('asks here: only the open chat (thread, channel or direct), oldest first, minus cleared', () => {
+ const a = item('approval', { id: 'a', timestamp: '2026-11-15T17:41:00Z' });
+ const t = item('question', { id: 't', link: link({ thread_id: 'th' }) });
+ const c = item('question', { id: 'c', link: link({ channel_id: 'ch' }) });
+ const w = item('watch', { id: 'w', timestamp: '2026-11-15T17:50:00Z' });
+ const sign = item('connection', { id: 'x' });
+ const all = [a, stopped, t, c, w, sign];
+ assert.deepEqual(m.asksHere(all, { direct: 'quant' }).map((i) => i.id), ['w1', 'a', 'w'], 'a sign-in to redo stays in the Inbox');
+ assert.deepEqual(m.asksHere(all, { thread: 'th', kwant: 'quant' }).map((i) => i.id), ['t']);
+ assert.deepEqual(m.asksHere(all, { channel: 'ch' }).map((i) => i.id), ['c']);
+ assert.deepEqual(m.asksHere(all, { direct: 'other' }), []);
+ assert.deepEqual(m.asksHere(all, null), []);
+ assert.deepEqual(m.asksHere(all, { direct: 'quant' }, new Set(['w1'])).map((i) => i.id), ['a', 'w']);
+ assert.equal(m.stripHeading([stopped]), 'Quant needs you');
+ assert.equal(m.stripHeading([stopped, a]), '2 things need you');
+ // the strip keeps the ask it showed when the list changes, else the same place
+ assert.equal(m.stripIndex([{ id: 'x' }, { id: 'y' }], 'y', 0), 1);
+ assert.equal(m.stripIndex([{ id: 'x' }], 'gone', 1), 0);
+ assert.equal(m.stripIndex([], null, 3), 0);
+});
+
+test('Retry of a stopped turn resends the notice target, else the newest message of yours', () => {
+ const you = (id, text) => ({ id, sender_role: 'user', sender_id: 'you', text, meta: null, created_at: '' });
+ const bot = (id, text, meta = null) => ({ id, sender_role: 'kwant', sender_id: 'quant', text, meta, created_at: '' });
+ // The notice isn't loaded (Oleks's case): the newest message of the person's
+ assert.deepEqual(m.resendTarget([you('u1', 'first'), bot('b1', 'ok'), you('u2', 'Fix what the pre-push check found'), bot('b2', 'step failed')], 'm-notice'), {
+ text: 'Fix what the pre-push check found', attachments: [],
+ });
+ assert.equal(m.resendTarget([bot('b1', 'hi')], 'm-notice'), null);
+});
+
+// ---- the strip, rendered ----
+const mount = (props) => {
+ const host = document.createElement('div');
+ document.body.append(host);
+ const root = m.createRoot(host);
+ let last = props;
+ const render = (p) => {
+ last = { ...last, ...p };
+ m.flushSync(() => root.render(h(m.NeedsYouStrip, { onAction: noop, onDismiss: async () => {}, ...last })));
+ };
+ render({});
+ return { host, render, unmount: () => { root.unmount(); host.remove(); } };
+};
+const tick = () => new Promise((r) => setTimeout(r, 0));
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+const parse = (el) => new DOMParser().parseFromString(m.renderToStaticMarkup(el), 'text/html');
+const NOW = Date.parse('2026-11-15T17:45:00Z');
+
+test('strip, one ask in each state A1–A8: eyebrow, kind, the whole line, hint, "Done, clear it" then the action', () => {
+ const cases = [
+ [stopped, 'retry', 'Stopped', 'Retry'],
+ [{ ...stopped, status: 'failed' }, 'retry', 'Failed', 'Retry'],
+ [item('stopped', { retry: { type: 'continue' }, title: 'Quant stopped after 40 steps, the most one reply can take.' }), 'continue', 'Paused', 'Continue'],
+ [item('stopped', { retry: { type: 'approval', approval_id: 'a9' }, title: 'Your OK ran out after 2 hours.' }), 'ask_again', 'Approval ran out', 'Ask again'],
+ [item('question', { title: 'Should I rebalance into BTC now, or wait for the 4-hour close at 20:00?' }), 'answer', 'Question', 'Go to the question'],
+ [item('approval', { title: 'Wants to run a command', question: 'Run “npm run deploy” on production?' }), 'decide', 'Approval', 'Go to the approval'],
+ [item('stopped', { human_step_id: 'hs1', title: 'Quant needs you to sign in to binance.com.' }), 'browser', 'Browser step', 'Open the browser step'],
+ [item('delegation', { title: 'Stuck: Quant has been on the same step for 25 minutes.' }), 'none', 'Stuck', null],
+ ];
+ for (const [it, action, kind, label] of cases) {
+ const d = parse(h(m.NeedsYouStrip, { asks: [it], onAction: noop, onDismiss: async () => {}, onShow: noop, now: NOW }));
+ const s = d.querySelector('[data-needs-you-strip]');
+ assert.equal(s.getAttribute('data-action'), action);
+ assert.equal(s.getAttribute('tabindex'), '-1', 'a keyboard open can focus it');
+ const head = d.getElementById(s.getAttribute('aria-labelledby'));
+ assert.equal(head.textContent, 'Quant needs you', 'named by its eyebrow');
+ assert.match(s.querySelector('[data-strip-kind]').textContent, new RegExp(`^${kind} · `));
+ assert.doesNotMatch(s.querySelector('[data-strip-kind]').textContent, /Quant/, 'one bot in view: no name in the kind line');
+ assert.equal(s.querySelector('[data-strip-line]').textContent, m.askLine(it), 'the whole line');
+ assert.doesNotMatch(s.querySelector('[data-strip-line]').getAttribute('class'), /truncate|line-clamp/, 'never cut');
+ assert.equal(s.querySelector('[data-strip-hint]').textContent, m.askHint(it, m.askAction(it), 'Quant'));
+ const buttons = [...s.querySelectorAll('[data-strip-buttons] button')];
+ assert.ok(buttons[0].hasAttribute('data-strip-dismiss'), 'Done, clear it always shows, left of the action');
+ assert.equal(buttons[0].textContent, 'Done, clear it');
+ assert.equal(buttons[0].getAttribute('aria-label'), 'Done, clear it from Needs attention');
+ if (label) {
+ assert.equal(buttons[1].getAttribute('data-strip-action'), action);
+ assert.equal(buttons[1].textContent, label);
+ assert.equal(buttons[1].getAttribute('aria-label'), m.actionName(action, 'Quant'));
+ assert.match(buttons[1].className, /kw-btn-primary/);
+ } else assert.equal(buttons.length, 1, 'A8: only Done, clear it');
+ assert.equal(s.querySelector('[data-strip-steps]'), null, 'one ask: no stepping');
+ }
+ const none = parse(h(m.NeedsYouStrip, { asks: [], onAction: noop, onDismiss: async () => {} }));
+ assert.equal(none.querySelector('[data-needs-you-strip]'), null, 'nothing open: no strip');
+});
+
+test('strip: it reads the list, not the chat, so it shows when the notice is not rendered', () => {
+ // No messages anywhere: the strip still says the ask (Oleks's row opened onto nothing)
+ const d = parse(h(m.NeedsYouStrip, { asks: [stopped], onAction: noop, onDismiss: async () => {} }));
+ assert.equal(d.querySelector('[data-strip-line]').textContent, STALL);
+});
+
+test('strip: steps through several asks (M1, M2), rings each one shown, and goes live when they close', async () => {
+ const shown = [];
+ const two = [stopped, item('question', { id: 'q2', title: 'Should I rebalance now?', timestamp: '2026-11-15T17:44:00Z' })];
+ const { host, render, unmount } = mount({ asks: two, onShow: (it, o) => (shown.push(`${it.id}:${!!o?.quiet}`), true), now: NOW });
+ const q = (s) => host.querySelector(s);
+ const head = () => host.querySelector(`#${q('[data-needs-you-strip]').getAttribute('aria-labelledby')}`).textContent;
+ assert.equal(head(), '2 things need you');
+ assert.equal(q('[data-strip-count]').textContent, '1 of 2');
+ assert.equal(q('[data-strip-count]').getAttribute('aria-live'), 'polite');
+ assert.ok(q('[aria-label="Previous ask"]').disabled, 'at the start: Previous is disabled, not hidden');
+ assert.match(q('[data-strip-kind]').textContent, /^Stopped · Quant · /, 'several asks: the bot is named');
+ m.flushSync(() => q('[aria-label="Next ask"]').click());
+ assert.equal(q('[data-strip-count]').textContent, '2 of 2');
+ assert.equal(q('[data-needs-you-strip]').getAttribute('data-needs-you-strip'), 'q2');
+ assert.ok(q('[aria-label="Next ask"]').disabled, 'at the end: Next is disabled');
+ assert.deepEqual(shown, ['q2:true'], 'stepping rings that ask if its card is rendered');
+ // A new, older ask arrives: the strip stays on the question it shows
+ render({ asks: [item('question', { id: 'q0', timestamp: '2026-11-15T17:00:00Z' }), ...two] });
+ await tick();
+ assert.equal(q('[data-needs-you-strip]').getAttribute('data-needs-you-strip'), 'q2');
+ assert.equal(q('[data-strip-count]').textContent, '3 of 3');
+ // The shown one closes and it was last: the strip moves to the one before it
+ render({ asks: [item('question', { id: 'q0', timestamp: '2026-11-15T17:00:00Z' }), stopped] });
+ await tick();
+ assert.equal(q('[data-needs-you-strip]').getAttribute('data-needs-you-strip'), 'w1');
+ render({ asks: [stopped] });
+ await tick();
+ assert.equal(head(), 'Quant needs you');
+ assert.equal(q('[data-strip-steps]'), null);
+ render({ asks: [] });
+ assert.equal(q('[data-needs-you-strip]'), null, 'gone without a reload');
+ unmount();
+});
+
+test('strip: Retry sends once, waits for the close (busy), and comes back with a note when it stays open', async () => {
+ const calls = [];
+ const { host, unmount } = mount({
+ asks: [stopped],
+ sentWaitMs: 30,
+ onAction: async (it, action) => void calls.push(`${action}:${it.id}`),
+ onDismiss: async (it) => void calls.push(`dismiss:${it.id}`),
+ });
+ const q = (s) => host.querySelector(s);
+ q('[data-strip-action]').click();
+ q('[data-strip-action]').click(); // a double press sends once
+ await tick();
+ await tick();
+ assert.deepEqual(calls, ['retry:w1']);
+ // A1b: busy until the close event, Done, clear it still pressable
+ assert.equal(q('[data-strip-action]').textContent, 'Retrying…');
+ assert.equal(q('[data-strip-action]').getAttribute('aria-busy'), 'true');
+ assert.ok(q('[data-strip-action]').disabled);
+ assert.ok(!q('[data-strip-dismiss]').disabled);
+ await wait(60);
+ await tick();
+ assert.equal(q('[data-strip-action]').textContent, 'Retry', 'still open after the wait: the button comes back');
+ assert.equal(q('[data-strip-hint]').textContent, 'Sent. This clears once Quant answers.');
+ unmount();
+});
+
+test('strip: a failed press says why in the server’s words (A1c), and clearing shows Clearing… (A9)', async () => {
+ let release;
+ const { host, unmount } = mount({
+ asks: [stopped],
+ onAction: async () => {
+ throw new Error('Quant’s engine is out until 20:50.');
+ },
+ onDismiss: () => new Promise((r) => (release = r)),
+ });
+ const q = (s) => host.querySelector(s);
+ q('[data-strip-action]').click();
+ await tick();
+ await tick();
+ assert.equal(q('[data-strip-error]').textContent, 'Couldn’t retry: Quant’s engine is out until 20:50. Try again, or write to Quant.');
+ assert.equal(q('[data-strip-error]').getAttribute('role'), 'alert');
+ assert.equal(q('[data-strip-action]').textContent, 'Retry', 'the button is back');
+ q('[data-strip-dismiss]').click();
+ await tick();
+ assert.equal(q('[data-strip-dismiss]').textContent, 'Clearing…');
+ assert.ok(q('[data-strip-dismiss]').disabled && q('[data-strip-action]').disabled, 'clearing stops both');
+ assert.equal(q('[data-strip-error]'), null, 'the error clears on the next try');
+ release();
+ await tick();
+ unmount();
+});
+
+test('strip: Go to the question rings it; a card that is gone offers Open in Inbox (A5b)', async () => {
+ const shown = [];
+ let found = true;
+ const opened = [];
+ const ap = item('approval', { id: 'ap', title: 'Run deploy?' });
+ const { host, unmount } = mount({ asks: [ap], onShow: async (it) => (shown.push(it.id), found), onOpenInbox: (it) => opened.push(it.id) });
+ const q = (s) => host.querySelector(s);
+ q('[data-strip-action]').click();
+ await tick();
+ await tick();
+ assert.deepEqual(shown, ['ap']);
+ assert.equal(q('[data-strip-action]').textContent, 'Go to the approval', 'found: the strip stays until it is answered');
+ found = false;
+ q('[data-strip-action]').click();
+ await tick();
+ await tick();
+ assert.equal(q('[data-strip-hint]').textContent, 'Its card isn’t in this chat anymore.');
+ assert.equal(q('[data-strip-action]').textContent, 'Open in Inbox');
+ assert.equal(q('[data-strip-action]').getAttribute('data-strip-action'), 'inbox');
+ q('[data-strip-action]').click();
+ await tick();
+ assert.deepEqual(opened, ['ap']);
+ unmount();
+});
+
+test('strip: a keyboard open focuses it; when the last ask closes, focus goes to the composer; it says so', async () => {
+ const composer = document.createElement('textarea');
+ composer.setAttribute('data-composer', '');
+ document.body.append(composer);
+ const { host, render, unmount } = mount({ asks: [], hereKey: 'd:quant' });
+ const live = () => host.querySelector('[data-needs-you-live]').textContent;
+ // An ask arrives live in the open chat: one polite line, bot plus button
+ render({ asks: [stopped] });
+ await tick();
+ assert.equal(live(), 'Quant needs you: Retry');
+ render({ focusKey: 1 });
+ await tick();
+ assert.equal(document.activeElement, host.querySelector('[data-needs-you-strip]'));
+ host.querySelector('[data-strip-action]').focus();
+ render({ asks: [] });
+ await tick();
+ assert.equal(host.querySelector('[data-needs-you-strip]'), null);
+ assert.equal(document.activeElement, composer, 'never dropped to the page body');
+ // Opening another chat with asks in it says nothing; a clear says "Cleared." at once
+ render({ asks: [stopped], hereKey: 'd:other' });
+ await tick();
+ host.querySelector('[data-strip-dismiss]').click();
+ await tick();
+ render({ asks: [] });
+ await tick();
+ assert.equal(live(), 'Cleared.');
+ unmount();
+ composer.remove();
+});
+
+test('ring: a card outside the message list gets the amber kw-flash, tagged as an ask', () => {
+ const el = document.createElement('div');
+ document.body.append(el);
+ m.ringElement(el);
+ assert.ok(el.classList.contains('kw-flash'), 'kw-flash: a static outline under reduced motion, never nothing');
+ assert.equal(el.dataset.flashKind, 'ask');
+});
+
+// ---- the pinned row ----
+const space = { id: 'spc_default', name: 'Binan', 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: '' });
+
+test('pinned row: hover and focus give the whole ask in a tooltip the row is described by', () => {
+ const kwants = [bot('quant', 'Quant'), bot('builder', 'Builder')];
+ const waiting = [stopped, item('approval', { id: 'ap', kwant_id: 'builder', kwant_name: 'Builder', tool_name: 'bash', question: 'Run “deploy.sh prod”?', link: link({ direct_kwant_id: 'builder' }) })];
+ const needs = m.needsYouRows(waiting, {}, new Set(kwants.map((k) => k.id)));
+ const html = m.renderToStaticMarkup(h(m.Sidebar, {
+ space, spaces: [space], onSwitchSpace: noop, onCreateSpace: noop, onOpenSpaceSettings: noop, onOpenArchived: noop, onOpenSearch: noop,
+ kwants, channels: [], teams: [], selectedId: null, isChannel: false, onSelectKwant: noop, onSelectChannel: noop, onSelectTeam: noop,
+ onSummonKwant: noop, onCreateTeam: noop, onOpenInbox: noop, onOpenNeedsYou: noop, busyKwants: {}, botStatus: {},
+ attention: m.attentionRows({ kwants, needs, now: Date.parse('2026-11-15T17:45:00Z') }),
+ }));
+ const d = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
+ const row = d.querySelector('[data-pin-row="quant"]');
+ assert.equal(row.getAttribute('title'), null, 'no native title: it never shows on focus');
+ assert.equal(row.getAttribute('aria-label'), null, 'the row keeps its name');
+ const tip = d.getElementById('pin-tip-quant');
+ assert.equal(tip.getAttribute('role'), 'tooltip');
+ assert.ok(row.getAttribute('aria-describedby').split(' ').includes('pin-tip-quant'));
+ assert.ok(tip.hasAttribute('hidden'), 'hidden until hover or focus');
+ const [top, line] = tip.querySelectorAll('span');
+ assert.match(top.textContent, /^Quant · Stopped · /);
+ assert.equal(line.textContent, STALL, 'the whole line, not the row’s cut one');
+ assert.equal(row.querySelector('[data-bot-busy]').getAttribute('title'), null);
+ assert.equal(d.querySelector('#pin-tip-builder span:last-child').textContent, 'Run “deploy.sh prod”?');
+ assert.match(d.querySelector('#pin-tip-builder span').textContent, /^Builder · Approval · /);
+ // The bot's own row in the list is not a pinned copy: no tooltip there
+ assert.equal(d.querySelector('[data-bot-row="quant"] [role="tooltip"]'), null);
+});
+
+test('pinned row tooltip: shows at once on keyboard focus, after 300 ms on hover, hides on Esc', async () => {
+ const kwants = [bot('quant', 'Quant')];
+ const needs = m.needsYouRows([stopped], {}, new Set(['quant']));
+ const host = document.createElement('div');
+ document.body.append(host);
+ const root = m.createRoot(host);
+ m.flushSync(() => root.render(h(m.Sidebar, {
+ space, spaces: [space], onSwitchSpace: noop, onCreateSpace: noop, onOpenSpaceSettings: noop, onOpenArchived: noop, onOpenSearch: noop,
+ kwants, channels: [], teams: [], selectedId: null, isChannel: false, onSelectKwant: noop, onSelectChannel: noop, onSelectTeam: noop,
+ onSummonKwant: noop, onCreateTeam: noop, onOpenInbox: noop, onOpenNeedsYou: noop, busyKwants: {}, botStatus: {},
+ attention: m.attentionRows({ kwants, needs, now: Date.parse('2026-11-15T17:45:00Z') }),
+ })));
+ const row = host.querySelector('[data-pin-row="quant"]');
+ const tip = () => host.querySelector('#pin-tip-quant');
+ row.dispatchEvent(new window.MouseEvent('mouseover', { bubbles: true, relatedTarget: document.body }));
+ await tick();
+ assert.ok(tip().hidden, 'not yet: hover waits 300 ms');
+ await wait(330);
+ assert.ok(!tip().hidden, 'shown after hover');
+ row.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await tick();
+ assert.ok(tip().hidden, 'Esc hides it');
+ m.flushSync(() => root.unmount());
+ host.remove();
+});
+
+// ---- round 2: Lin's #700 API (docs/live-activity.md §3) ----
+
+test('open target: link.thread_kwant_id opens the thread under the bot that owns it (Oleks’s Quant case)', () => {
+ // The thread belongs to Builder, not to the item's bot: looking it up under Quant found nothing.
+ const it = item('stopped', { id: 'w9', message_id: 'm-n', link: link({ thread_id: 't-b', thread_kwant_id: 'builder' }) });
+ assert.deepEqual(m.openTarget(it), { channel_id: null, kwant_id: 'builder', thread_id: 't-b', focus: 'm-n', focusKind: 'message' });
+ // Absent (the bot's own thread, or an older server): the item's kwant_id, as before
+ assert.equal(m.openTarget(item('stopped', { link: link({ thread_id: 't-q' }) })).kwant_id, 'quant');
+ assert.equal(m.openTarget(item('stopped', { link: link({ thread_id: 't-q', thread_kwant_id: null }) })).kwant_id, 'quant');
+ // The strip still finds it in that thread
+ assert.ok(m.isHere(it, { thread: 't-b', kwant: 'builder' }));
+});
+
+test('Done, clear it follows dismissable; older servers keep it; the body names the kind', () => {
+ assert.equal(m.canClear({ dismissable: true }), true);
+ assert.equal(m.canClear({ dismissable: false }), false);
+ assert.equal(m.canClear({}), true, 'missing (an older server): the round-1 inference, always offered');
+ assert.equal(m.dismissKind(stopped), 'stopped');
+ assert.equal(m.dismissKind(item('stopped', { human_step_id: 'hs' })), 'browser');
+ assert.equal(m.dismissKind(item('routine_run')), 'routine_run');
+});
+
+test('a 409 use_* dismiss switches to the ask’s own button; other codes are errors', () => {
+ assert.equal(m.switchFor('use_question_answer'), 'answer');
+ assert.equal(m.switchFor('use_approval_decide'), 'decide');
+ assert.equal(m.switchFor('use_watch_decide'), 'decide');
+ assert.equal(m.switchFor('use_step_decline'), 'browser');
+ for (const c of ['person_only', 'not_found', 'bad_kind', null, undefined]) assert.equal(m.switchFor(c), null);
+});
+
+test('Retry never goes to /api/waiting/:id/retry: approval, task, or resend', () => {
+ assert.deepEqual(m.retryRoute(item('stopped', { retry: { type: 'approval', approval_id: 'ap9' } })), { via: 'approval', id: 'ap9' });
+ assert.deepEqual(m.retryRoute(item('routine_run', { status: 'error', task_id: 'tk1' })), { via: 'task', id: 'tk1' });
+ assert.deepEqual(m.retryRoute(item('delegation', { status: 'failed', task_id: 'tk2' })), { via: 'task', id: 'tk2' });
+ assert.equal(m.retryRoute(item('delegation', { status: 'failed' })), null, 'no task to retry: write to the bot');
+ assert.deepEqual(m.retryRoute(stopped), { via: 'resend' });
+ // The client has no waiting-retry call at all.
+ const src = readFileSync(new URL('../src/away.ts', import.meta.url), 'utf8');
+ assert.ok(!/waiting\/\$\{[^}]+\}\/retry/.test(src) && !/retryWaiting/.test(src));
+});
+
+test('waiting_updated: a closed item drops at once; an open one waits for the refetch', () => {
+ const list = [stopped, item('question', { id: 'q1' })];
+ const ev = (status, id = 'w1') => ({ item: { id, kind: 'stopped', status, reason: status === 'closed' ? 'person_wrote' : null } });
+ assert.equal(m.closedId(ev('closed')), 'w1');
+ assert.deepEqual(m.dropClosed(list, m.closedId(ev('closed'))).map((i) => i.id), ['q1']);
+ assert.equal(m.closedId(ev('open')), null);
+ assert.equal(m.dropClosed(list, m.closedId(ev('open'))), list, 'open: unchanged (same list)');
+ assert.equal(m.dropClosed(list, m.closedId(ev('closed', 'other'))), list, 'not in the list: unchanged');
+ assert.equal(m.closedId(null), null);
+ assert.equal(m.closedId({}), null);
+});
+
+test('strip: Done hidden when not dismissable; a 409 use_* switches the button and drops Done', async () => {
+ const shown = [];
+ const step = item('stopped', { id: 'hs2', human_step_id: 'hs2', action: 'browser', dismissable: false, title: 'Sign in to the exchange' });
+ let r1 = mount({ asks: [step] });
+ assert.equal(r1.host.querySelector('[data-strip-dismiss]'), null, 'not dismissable: no Done');
+ assert.equal(r1.host.querySelector('[data-strip-action]').getAttribute('data-strip-action'), 'browser');
+ r1.unmount();
+ // An older-server stall with no action the client knows; the server says use the question
+ const odd = item('stopped', { id: 'w5', action: null, title: 'Waiting on your answer' });
+ const { host, unmount } = mount({ asks: [odd], onDismiss: async () => ({ use: 'answer' }), onShow: async (it) => (shown.push(it.id), true) });
+ const q = (s) => host.querySelector(s);
+ assert.equal(q('[data-strip-action]'), null);
+ q('[data-strip-dismiss]').click();
+ await tick();
+ await tick();
+ assert.equal(q('[data-strip-dismiss]'), null, 'Done goes');
+ assert.equal(q('[data-strip-action]').textContent, 'Go to the question');
+ assert.equal(q('[data-strip-error]'), null, 'not an error');
+ assert.equal(q('[data-strip-hint]').textContent, 'This one clears when you answer it on its card.', 'says why Done went (fix 5)');
+ q('[data-strip-action]').click();
+ await tick();
+ assert.deepEqual(shown, ['w5']);
+ unmount();
+});
+
+// ---- round 2 addition (Ada, #700 decision): failed hand-off rows ----
+const handOff = (over = {}) => item('delegation', { id: 'd1', status: 'failed', kwant_name: 'Builder', title: 'The hand-off to Builder failed', link: link({ thread_id: 't-h' }), ...over });
+
+test('failed hand-off with task_id: Retry, and it retries the board task', async () => {
+ const h = handOff({ action: 'retry', task_id: 'tk7', dismissable: true });
+ assert.equal(m.askAction(h), 'retry');
+ assert.deepEqual(m.retryRoute(h), { via: 'task', id: 'tk7' });
+ const calls = [];
+ const { host, unmount } = mount({ asks: [h], onAction: async (it, a) => void calls.push(`${a}:${it.id}`) });
+ assert.equal(host.querySelector('[data-strip-action]').textContent, 'Retry');
+ assert.ok(host.querySelector('[data-strip-dismiss]'));
+ host.querySelector('[data-strip-action]').click();
+ await tick();
+ assert.deepEqual(calls, ['retry:d1']);
+ unmount();
+});
+
+test('failed hand-off without task_id: no action button, only Done, and the hint says ask again here', () => {
+ const h = handOff({ action: null, dismissable: true });
+ assert.equal(m.askAction(h), null);
+ const { host, unmount } = mount({ asks: [h] });
+ assert.equal(host.querySelector('[data-strip-action]'), null);
+ assert.ok(host.querySelector('[data-strip-dismiss]'), 'Done, clear it');
+ assert.equal(host.querySelector('[data-strip-hint]').textContent, 'There’s no button for this one. Ask Builder again here, or clear it once it’s handled.');
+ assert.equal(m.askKind(h, null), 'Failed');
+ unmount();
+ // the bot's later reply closes it live (waiting_updated, reason later_reply)
+ assert.deepEqual(m.dropClosed([h], m.closedId({ item: { id: 'd1', kind: 'delegation', status: 'closed', reason: 'later_reply' } })), []);
+});
+
+test('failed routine run without task_id: the hint points at Run now in Routines, not at asking the bot again', () => {
+ const r = item('routine_run', { id: 'r1', status: 'error', kwant_name: 'Quant' });
+ assert.equal(m.askAction(r), null);
+ assert.equal(m.askHint(r, null, 'Quant'), 'There’s no button for this one. Press Run now on it in Routines, or clear it once it’s handled.');
+});
+
+test('older server: a hand-off row with no task_id never gets an inferred Retry', () => {
+ assert.equal(m.askAction(handOff()), null, 'no action field, no task');
+ assert.equal(m.askAction(handOff({ status: 'interrupted' })), null);
+ assert.equal(m.askAction(handOff({ action: 'retry' })), null, 'even a retry the server sent needs the task');
+ assert.equal(m.askAction(item('routine_run', { status: 'error' })), null);
+ assert.equal(m.retryRoute(handOff()), null);
+});
+
+// ---- round 2: Mira's design check (design-check.md, fixes 1-9) ----
+test('fix 1: the line drops a Failed: / Stuck: prefix the kind word already says', () => {
+ assert.equal(m.askLine(item('delegation', { title: 'Stuck: Quant has been on the same step for 25 minutes.' })), 'Quant has been on the same step for 25 minutes.');
+ assert.equal(m.askLine(item('stopped', { status: 'failed', title: 'Failed: Backtest maker-first-rebalance.' })), 'Backtest maker-first-rebalance.');
+ assert.equal(m.askLine(item('stopped', { title: 'Failed:' })), 'Failed:', 'nothing left: keep it');
+ assert.equal(m.askLine(item('delegation', { title: 'Failed: the hand-off stopped.' })), 'The hand-off stopped.', 'starts with a capital');
+ assert.equal(m.askLine(stopped), STALL, 'other lines unchanged');
+});
+
+test('fixes 3 and 4: no Retry with nowhere to go; no action and not dismissable: no button row and its own hint', async () => {
+ // fix 3: the server says retry, but there is no task: no button, only Done
+ let r = mount({ asks: [handOff({ action: 'retry', dismissable: true })] });
+ assert.equal(r.host.querySelector('[data-strip-action]'), null);
+ assert.ok(r.host.querySelector('[data-strip-dismiss]'));
+ r.unmount();
+ // fix 4
+ const lone = item('delegation', { id: 'z', action: null, dismissable: false, title: 'Quant is still on it.' });
+ assert.equal(m.askHint(lone, null, 'Quant', false), 'Write to Quant in the chat. This clears once it’s handled.');
+ r = mount({ asks: [lone] });
+ assert.equal(r.host.querySelector('[data-strip-buttons]'), null, 'no empty button row');
+ assert.equal(r.host.querySelector('[data-strip-hint]').textContent, 'Write to Quant in the chat. This clears once it’s handled.');
+ r.unmount();
+});
+
+test('fixes 2, 7, 8: phone browser step stacks, icons never shrink, compact steppers, a focus ring on the strip', () => {
+ const step = item('stopped', { id: 'hs3', human_step_id: 'hs3', action: 'browser', dismissable: true, title: 'Sign in' });
+ let r = mount({ asks: [step], phone: true });
+ assert.match(r.host.querySelector('[data-strip-buttons]').className, /flex-col-reverse/);
+ assert.match(r.host.querySelector('[data-strip-action] svg').getAttribute('class'), /shrink-0/);
+ assert.match(r.host.querySelector('[data-needs-you-strip]').className, /kw-focus/);
+ assert.doesNotMatch(r.host.querySelector('[data-needs-you-strip]').className, /outline-none/);
+ r.unmount();
+ r = mount({ asks: [stopped, item('question', { id: 'q2' })], phone: true });
+ for (const l of ['Previous ask', 'Next ask']) assert.ok(r.host.querySelector(`[aria-label="${l}"]`).hasAttribute('data-compact'));
+ r.unmount();
+});
diff --git a/frontend/tests/attentionOrder.test.mjs b/frontend/tests/attentionOrder.test.mjs
index f29df7b8..99bbea3a 100644
--- a/frontend/tests/attentionOrder.test.mjs
+++ b/frontend/tests/attentionOrder.test.mjs
@@ -105,7 +105,9 @@ test('desktop: pinned "Needs you · 4" above Channels, copies with "Also listed
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');
+ // 22i: described by its tooltip (the whole ask) and by where else it is listed
+ const also = p.getAttribute('aria-describedby').split(' ').find((id) => id.startsWith('pin-also-'));
+ assert.equal(d.getElementById(also).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');
diff --git a/frontend/tests/mobileCards.test.mjs b/frontend/tests/mobileCards.test.mjs
index 0f2e645a..43edb91d 100644
--- a/frontend/tests/mobileCards.test.mjs
+++ b/frontend/tests/mobileCards.test.mjs
@@ -236,7 +236,9 @@ test('ChatView puts the strip inside the composer section, right above the box,
const formAt = src.indexOf('<form', at);
assert.ok(sectionAt > 0 && at > sectionAt, 'inside the composer section');
assert.ok(src.indexOf('aria-label="Ask a member"', sectionAt) < at, 'below the Ask chips');
- assert.equal(src.slice(at + '{workingStrip}'.length, formAt).trim(), '', 'directly above the box');
+ // 22i (design.md §2): the Needs-you strip sits between the working line and the box, nothing else
+ const between = src.slice(at + '{workingStrip}'.length, formAt).replace(/\{\/\*[\s\S]*?\*\/\}/g, '').trim();
+ assert.equal(between, '{needsYouStrip}', 'directly above the box, under the Needs-you strip');
assert.doesNotMatch(src, /\{!?phone && workingStrip\}/, 'no layout-specific place (Rigel: 390 sat outside the section)');
assert.equal(src.split('{workingStrip}').length - 1, 1, 'rendered once');
assert.equal(src.match(/<WorkingStrip\b/g).length, 1, 'one element');