Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Reply chrome: Done marker, Approve / Change…, quiet Copy, Details in words (#602)
Oleksandr Ivanchenko3b06a56e0f86
diff --git a/frontend/src/approvalAsk.ts b/frontend/src/approvalAsk.tsnew file mode 100644index 00000000..7afb5336--- /dev/null+++ b/frontend/src/approvalAsk.ts@@ -0,0 +1,47 @@+// reply-chrome part 2 (autonomy/reply-chrome/design.md): a bot reply that ends by asking for the person's OK+// ("once you approve the draft.", "Shall I send it?") gets Approve / Change… under it. Only the last two+// sentences count, so an OK asked for early on and then settled doesn't light the row up.++const ASKS: RegExp[] = [+ /\b(once|when|after|if) you(?:'ve|’ve| have)? (approve|confirm(?:ed)?|ok|okay|sign off on|give (me )?the go[- ]ahead)\b/i,+ /\bwaiting (for|on) your (approval|ok|okay|go[- ]ahead|sign[- ]off)\b/i,+ /\b(shall|should|can) i (go ahead|send|schedule|publish|post|launch)\b[^.?!]*\?/i,+ /\b(ok|okay) to (send|schedule|publish|post|go ahead)\b[^.?!]*\?/i,+];+const SETTLED: RegExp[] = [/\b(no need to|don't need to|don’t need to|already) (approve|approved|confirm)/i, /\bapproved\b/i];++/** The text without code, links' targets and markdown marks, so a sentence reads as words. */+function plain(text: string): string {+ return text+ .replace(/```[\s\S]*?```/g, ' ')+ .replace(/`[^`]*`/g, ' ')+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')+ .replace(/[*_>#~]+/g, ' ')+ .replace(/[ \t]+/g, ' ')+ .trim();+}++/** The last two sentences: split after . ! ? (or a line break) followed by a space. */+export function lastSentences(text: string, n = 2): string {+ const parts = plain(text)+ .split(/(?<=[.!?…])\s+|\s*\n\s*/)+ .map((s) => s.trim())+ .filter(Boolean);+ return parts.slice(-n).join(' ');+}++/** True when the reply's last two sentences ask the person for an OK and nothing there says it's settled. */+export function asksApproval(text: string | null | undefined): boolean {+ if (!text) return false;+ const tail = lastSentences(text);+ if (!tail) return false;+ if (SETTLED.some((r) => r.test(tail))) return false;+ return ASKS.some((r) => r.test(tail));+}++/** What Approve sends, as an ordinary reply to that message. */+export const APPROVE_TEXT = 'Approved, go ahead.';+/** The composer's placeholder after Change…. */+export const changePlaceholder = (name: string): string => `What should ${name} change?`;+/** The row's caption and group name. */+export const waitingCaption = (name: string): string => `${name} is waiting for your OK`;diff --git a/frontend/src/components/ApproveRow.tsx b/frontend/src/components/ApproveRow.tsxnew file mode 100644index 00000000..4466427e--- /dev/null+++ b/frontend/src/components/ApproveRow.tsx@@ -0,0 +1,46 @@+// reply-chrome part 2 (autonomy/reply-chrome/design.md): Approve / Change… under the newest bot reply when it+// ends by asking for the person's OK and no question card is open. Approve sends an ordinary reply to that+// message; Change… starts a reply and leaves the words to the person. No server action.++import React from 'react';+import { Check, PenLine } from 'lucide-react';+import { waitingCaption } from '../approvalAsk';++const ring = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-surface-main';+const size = 'h-11 sm:h-8 w-full sm:w-auto px-3.5 rounded-[10px] text-[13px] font-semibold disabled:opacity-60 disabled:cursor-not-allowed';++export const ApproveRow: React.FC<{+ name: string;+ busy?: boolean;+ onApprove: () => void;+ onChange: () => void;+}> = ({ name, busy = false, onApprove, onChange }) => {+ const caption = waitingCaption(name);+ return (+ <div role="group" aria-label={caption} data-approve-row="" className="mt-2.5 grid w-full max-w-full grid-cols-2 gap-2 sm:flex sm:w-auto sm:items-center">+ <p className="col-span-2 text-xs text-zinc-300 sm:mr-1">+ <b className="font-semibold text-zinc-100">{name}</b> is waiting for your OK+ </p>+ <button+ type="button"+ onClick={onApprove}+ disabled={busy}+ data-approve=""+ className={`inline-flex items-center justify-center gap-1.5 bg-accent-gradient text-white shadow-card transition-[filter] duration-[120ms] hover:brightness-110 motion-reduce:transition-none ${size} ${ring}`}+ >+ <Check size={14} aria-hidden="true" />+ Approve+ </button>+ <button+ type="button"+ onClick={onChange}+ disabled={busy}+ data-change=""+ className={`inline-flex items-center justify-center gap-1.5 border border-hairline-strong bg-transparent text-zinc-100 transition-colors duration-[120ms] hover:bg-zinc-800 motion-reduce:transition-none ${size} ${ring}`}+ >+ <PenLine size={14} aria-hidden="true" />+ Change…+ </button>+ </div>+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex ad58602f..5772f7ff 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -11,7 +11,7 @@ import { parsePick } from '../engines';import { onContinuity } from '../continuity';import { TrialWaitsCard } from './SkillsPanel';import { agentSenderLabel } from '../agentConnections';-import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, CircleSlash } from 'lucide-react';+import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, CircleSlash } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { WorkingAvatar } from './WorkingAvatar';import { AccountCard, BotHome } from './BotHome';@@ -73,11 +73,17 @@ import { ToolFailureLine } from './ToolFailureLine';import { parseToolFailureMeta } from '../toolFailures';import { ToolNoteLine } from './ToolNoteLine';import { ranOnLabel } from '../engines';-import { replyTokens } from '../modelUsage';-import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';+import { replyCostWords, replyTokens } from '../modelUsage';+import { parseRoutingMeta, ranOnAccount } from '../spaces';import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';import { ConnectionSuggestionMeta, parseConnectionMeta } from '../connectionSuggestions';-import { routeChipLabel, routeReasonText } from '../routeReason';+import { routeReasonText, routeWhyText } from '../routeReason';+import { useInbox } from '../inboxStore';+import { doneItemsOf, doneOf } from '../replyDone';+import { APPROVE_TEXT, asksApproval, changePlaceholder } from '../approvalAsk';+import { DoneCheckLine } from './DoneMarker';+import { ApproveRow } from './ApproveRow';+import { CopyGhost } from './CopyGhost';import { RoutineRow } from './RoutineRow';import { routineOf } from '../routineRow';import { BudgetPausedNotice, ExpiredApprovalNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';@@ -97,7 +103,7 @@ import { consultedNames, hideStreamingDecisions, messageDecisions, parseWorkAheaimport { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';import { RouteChoiceMeta, parseRouteChoiceMeta, questionsOfReplies } from '../routeChoice';-import { SmartActionsSlot, actionClass } from './results/SmartActions';+import { SmartActionsSlot } from './results/SmartActions';import { WorkingStrip } from './WorkingStrip';import { ScrollRow } from './ScrollRow';import { liveBubble, waitingOn } from '../workingStrip';@@ -1004,14 +1010,22 @@ export const ChatView: React.FC<ChatViewProps> = ({};const startReply = (msg: ChatMessage) => {setReplyTo(msg);+ setChangeFor(null);focusComposer();};+ // reply-chrome part 2: Change… starts a reply whose placeholder asks what to change; any other reply drops it.+ const [changeFor, setChangeFor] = useState<string | null>(null);+ useEffect(() => {+ if (!replyTo) setChangeFor(null);+ }, [replyTo]);+ const [approving, setApproving] = useState<string | null>(null);/** The chip's name: the bot by id or name, else this chat's title. */const replyBotName = (msg: ChatMessage) => {return botDisplayName(msg.sender_id, knownBots);};const cancelReply = () => {setReplyTo(null);+ setChangeFor(null);focusComposer();};/**@@ -1046,6 +1060,30 @@ export const ChatView: React.FC<ChatViewProps> = ({// Thumbs on the bot's newest question are a yes or no; once one has answered it, they're feedback again.const [answered, setAnswered] = useState<ReadonlySet<string>>(() => new Set());const questionId = questionMessageId(messages, isStreaming);+ // reply-chrome part 1: Inbox done items (finished, to review) by the reply they point at, for the Done marker.+ const inboxData = useInbox().data;+ const doneItems = useMemo(() => doneItemsOf([...(inboxData?.items ?? []), ...(inboxData?.batch_items ?? [])]), [inboxData]);+ // reply-chrome part 2: the newest message, when it's a bot reply asking for an OK and nothing else is open.+ const approveId = useMemo(() => {+ const last = messages[messages.length - 1];+ if (!last || last.sender_role !== 'kwant' || last.id.startsWith('temp-') || isStreaming || awaitingAnswer || pendingApprovals.length > 0) return null;+ const meta = parseMetaObject(last.meta);+ if (meta && (meta.blocked || meta.question_id || meta.kind)) return null;+ return asksApproval(last.text) ? last.id : null;+ }, [messages, isStreaming, awaitingAnswer, pendingApprovals.length]);+ const approve = async (msg: ChatMessage) => {+ if (approving) return;+ setApproving(msg.id);+ playSfx('click');+ stickRef.current = true;+ try {+ const sent = await onSendMessage(APPROVE_TEXT, [], { replyTo: msg });+ // A failed send keeps the row (it is still the newest message) and offers the words in the composer.+ if (sent === false) setInputVal((now) => now || APPROVE_TEXT);+ } finally {+ setApproving(null);+ }+ };const react = async (msg: ChatMessage, reaction: Reaction | null): Promise<boolean> => {const result = await onReact?.(msg, reaction);if (result?.answered) setAnswered((prev) => new Set(prev).add(msg.id));@@ -1545,6 +1583,10 @@ export const ChatView: React.FC<ChatViewProps> = ({const ranOn = isUser ? null : ranOnLabel(msg.meta);const account = isUser ? null : ranOnAccount(msg.meta);const tokens = isUser ? null : replyTokens(msg.tokens_used, msg.meta);+ const cost = isUser ? null : replyCostWords(msg.meta);+ const asksOk = msg.id === approveId;+ // A reply that asks (the Approve row, or the thumbs as yes/no) is never marked done.+ const done = isUser ? null : doneOf(msg, doneItems, { asks: asksOk || (msg.id === questionId && !answered.has(msg.id)) });// Any auto-routed channel, not only #general: the server attaches `routing` wherever it picked the bot.const routed = isUser ? null : parseRoutingMeta(msg.meta);// Older channel replies still hold a raw [DECISIONS] block: hidden here, its lines shown as chips@@ -1617,14 +1659,22 @@ export const ChatView: React.FC<ChatViewProps> = ({ranOn={ranOn}account={account}tokens={tokens}+ cost={cost}+ done={done}failed={!!savedActivity?.steps.some((s) => s.status === 'failed')}note={savedFailoverNotice(msg.meta) ?? switchNoteFor.get(msg.id)}handoff={savedFailoverHandoff(msg.meta)}route={routed? {- label: routeChipLabel({ basis: routed.basis, fallback: routed.fallback }),- text: routingLine(routed, spaceName ?? 'this space', (id) => activeKwants.find((k) => k.id === id)?.name),+ text: routeWhyText({+ kwantName: routed.kwant_name,+ basis: routed.basis,+ reason: routed.reason,+ fallback: routed.fallback,+ matchedTerms: routed.matched_terms,+ handedBackBy: routed.handed_back_by ? activeKwants.find((k) => k.id === routed.handed_back_by)?.name : undefined,+ }),fallback: !!routed.fallback,reroute:onSendToOtherBot && questionOf.get(msg.id)@@ -1741,39 +1791,35 @@ export const ChatView: React.FC<ChatViewProps> = ({{!isUser && msg.tool_calls && !savedActivity && <ToolCallsList raw={msg.tool_calls} />}+ {done && <DoneCheckLine done={done} />}++ {asksOk && (+ <ApproveRow+ name={displayName}+ busy={approving === msg.id}+ onApprove={() => void approve(msg)}+ onChange={() => {+ startReply(msg);+ setChangeFor(displayName);+ }}+ />+ )}++ {/* Action row (reply-chrome part 3): Reply, the thumbs, then Copy as a quiet icon; smart-result actions portal in after Copy */}{/* 0.9.8: on a phone the browsed chip gets its own 44 px row above the action row (it would wrap) */}{!isUser && !filesOnly && phone && savedActivity && (<div className="mt-1 flex items-center min-h-[44px] max-w-full min-w-0"><BrowsedChip botName={displayName} steps={savedActivity.steps} live={false} phone onOpen={() => openBrowserFor(msg.id)} /></div>)}- {/* Action row: icon chips; the smart-result actions portal in after Copy */}{!isUser && !filesOnly && (- <div className="mt-2 flex flex-wrap items-center gap-2 text-zinc-400 text-xs max-w-full min-w-0">+ <div className="mt-2 flex flex-wrap items-center gap-0 sm:gap-1 text-zinc-400 text-xs max-w-full min-w-0">{!phone && savedActivity && (<BrowsedChip botName={displayName} steps={savedActivity.steps} live={false} onOpen={() => openBrowserFor(msg.id)} />)}- <button- type="button"- onClick={() => handleCopy(text, msg.id)}- className={actionClass}- title="Copy response"- >- {copiedId === msg.id ? (- <>- <Check size={14} className="text-emerald-400" aria-hidden="true" />- <span className="text-emerald-400">Copied</span>- </>- ) : (- <>- <Copy size={14} aria-hidden="true" />- <span className="sm:hidden">Copy</span>- <span className="hidden sm:inline">Copy markdown</span>- </>- )}- </button>{msg.sender_role === 'kwant' && !workAhead && !msg.id.startsWith('temp-') && (<>+ <ReplyButton botName={displayName} active={replyTo?.id === msg.id} onReply={() => startReply(msg)} />{onReact && (<ReactionButtonsmessageId={msg.id}@@ -1782,9 +1828,9 @@ export const ChatView: React.FC<ChatViewProps> = ({onReact={(r) => react(msg, r)}/>)}- <ReplyButton botName={displayName} active={replyTo?.id === msg.id} onReply={() => startReply(msg)} /></>)}+ <CopyGhost copied={copiedId === msg.id} tipId={`copy-tip-${msg.id}`} onCopy={() => handleCopy(text, msg.id)} />{msg.results != null && <SmartActionsSlot messageId={msg.id} />}</div>)}@@ -1961,7 +2007,7 @@ export const ChatView: React.FC<ChatViewProps> = ({const showAnswers = !ideaMode && (!phone || home?.kind !== 'bot' || target.kind === 'mention');const showHintText = !(phone && touch);const measure16 = (t: string) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : '');- const placeholder = askOnly+ const placeholder = changeFor && replyTo ? changePlaceholder(changeFor) : askOnly? phone? fitPlaceholder(answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title), 'Your answer…', fieldWidth, measure16): answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title)diff --git a/frontend/src/components/CopyGhost.tsx b/frontend/src/components/CopyGhost.tsxnew file mode 100644index 00000000..4fee133d--- /dev/null+++ b/frontend/src/components/CopyGhost.tsx@@ -0,0 +1,33 @@+// reply-chrome part 3 (autonomy/reply-chrome/design.md): Copy as a quiet icon, after Reply and the thumbs, with+// its label in a tooltip on hover (not on touch) and on keyboard focus. Copied shows a check and "Copied" for the+// parent's copied window, announced once.++import React from 'react';+import { Check, Copy } from 'lucide-react';++export const CopyGhost: React.FC<{ copied: boolean; tipId: string; onCopy: () => void }> = ({ copied, tipId, onCopy }) => (+ <span className="relative inline-flex shrink-0" data-copy-ghost="">+ <button+ type="button"+ onClick={onCopy}+ aria-label="Copy reply"+ aria-describedby={tipId}+ data-copy-reply=""+ className="peer relative inline-flex h-11 w-11 sm:h-8 sm:w-8 items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100 transition-colors duration-[120ms] motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 cursor-pointer"+ >+ {copied ? <Check size={14} className="text-ok" aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}+ </button>+ <span+ id={tipId}+ role="tooltip"+ className={`pointer-events-none absolute bottom-full left-1/2 z-20 mb-1.5 -translate-x-1/2 whitespace-nowrap rounded-md border border-hairline-strong bg-surface-overlay px-2 py-1 text-xs text-zinc-100 shadow transition-opacity duration-[120ms] motion-reduce:transition-none [@media(hover:hover)]:peer-hover:opacity-100 peer-focus-visible:opacity-100 ${+ copied ? 'opacity-100' : 'opacity-0'+ }`}+ >+ {copied ? 'Copied' : 'Copy reply'}+ </span>+ <span className="sr-only" aria-live="polite">+ {copied ? 'Copied' : ''}+ </span>+ </span>+);diff --git a/frontend/src/components/DoneMarker.tsx b/frontend/src/components/DoneMarker.tsxnew file mode 100644index 00000000..b8efe8d3--- /dev/null+++ b/frontend/src/components/DoneMarker.tsx@@ -0,0 +1,66 @@+// reply-chrome part 1 (autonomy/reply-chrome/design.md): the quiet marker on a job's final reply, after the name,+// and the one check line under the card when the Inbox item says how it was checked. No motion, no action: the+// marker is a labelled image, not a control. Server text (the done line, the check line) is drawn as text only.++import React from 'react';+import { CircleCheck, Shield, ShieldCheck, ShieldHalf, ShieldX, type LucideIcon } from 'lucide-react';+import { type CheckState, splitLine } from '../doneCheck';+import { DONE_WORD, type ReplyDone, doneLabel } from '../replyDone';+import { Sticker } from './Sticker';++const PILL = 'inline-flex h-5 shrink-0 items-center gap-1 rounded-full border pl-1.5 pr-2 text-[11px] font-semibold whitespace-nowrap';++const TONE: Record<'done' | Exclude<CheckState, 'checked'>, { cls: string; Icon: LucideIcon }> = {+ done: { cls: 'border-teal-300/30 bg-teal-300/10 text-ok', Icon: CircleCheck },+ partly: { cls: 'border-amber-300/35 bg-amber-300/10 text-warn', Icon: ShieldHalf },+ failed: { cls: 'border-rose-300/35 bg-rose-300/10 text-bad', Icon: ShieldX },+ not_checked: { cls: 'border-hairline-strong bg-transparent text-zinc-300', Icon: CircleCheck },+};++/** The marker on the name line: "Done", or the check's word; holographic only for the earned "Checked". */+export const DoneMarker: React.FC<{ done: ReplyDone }> = ({ done }) => {+ const state = done.checked?.state;+ const label = doneLabel(done);+ const title = done.text ?? undefined;+ if (state === 'checked')+ return (+ <span role="img" aria-label={label} title={title} className="inline-flex shrink-0" data-done-marker="checked">+ <Sticker tone="holo" size="sm" tilt={-2} icon={<ShieldCheck size={10} aria-hidden="true" />}>+ {DONE_WORD.checked}+ </Sticker>+ </span>+ );+ const key = state ?? 'done';+ const { cls, Icon } = TONE[key];+ return (+ <span role="img" aria-label={label} title={title} className={`${PILL} ${cls}`} data-done-marker={key}>+ <Icon size={12} aria-hidden="true" className="shrink-0" />+ <span aria-hidden="true">{DONE_WORD[key]}</span>+ </span>+ );+};++const LINE: Record<CheckState, { cls: string; Icon: LucideIcon }> = {+ checked: { cls: 'text-ok', Icon: ShieldCheck },+ partly: { cls: 'text-warn', Icon: ShieldHalf },+ failed: { cls: 'text-bad', Icon: ShieldX },+ not_checked: { cls: 'text-zinc-300', Icon: Shield },+};++/** The one line under a done reply's card, only when the Inbox item carries a check (#566/#577). */+export const DoneCheckLine: React.FC<{ done: ReplyDone }> = ({ done }) => {+ const c = done.checked;+ if (!c) return null;+ const { prefix, rest } = splitLine(c.state, c.line);+ const { cls, Icon } = LINE[c.state];+ return (+ <p className="mt-2 flex max-w-full min-w-0 items-start gap-1.5 text-xs leading-snug" data-done-check-line={c.state}>+ <Icon size={13} aria-hidden="true" className={`mt-px shrink-0 ${cls}`} />+ <span className="min-w-0 break-words [overflow-wrap:anywhere] text-zinc-300">+ {prefix && <b className={`font-semibold ${cls}`}>{prefix}</b>}+ {prefix ? ' ' : ''}+ {rest}+ </span>+ </p>+ );+};diff --git a/frontend/src/components/ReplyMeta.tsx b/frontend/src/components/ReplyMeta.tsxindex 07d5a053..e4ac0cc6 100644--- a/frontend/src/components/ReplyMeta.tsx+++ b/frontend/src/components/ReplyMeta.tsx@@ -4,12 +4,17 @@ import { localClock } from '../clock';import { RouteInfo, useRouteChip } from './RouteChip';import { EngineChip } from './Signature';import { SentToTelegram } from './TelegramMarks';+import { DoneMarker } from './DoneMarker';+import { ranOnWords } from '../modelUsage';+import type { ReplyDone } from '../replyDone';export interface ReplyFacts {/** "Claude · Opus 5.5": the engine and model the reply ran on. */ranOn?: string | null;account?: string | null;tokens?: { label: string; detail: string } | null;+ /** Details' Cost row in words (replyCostWords); `tokens.detail` is its tooltip. */+ cost?: { text: string; note: string | null } | null;}export interface ReplyMetaProps extends ReplyFacts {@@ -22,9 +27,12 @@ export interface ReplyMetaProps extends ReplyFacts {failed?: boolean;/** One muted line under the name, e.g. "Claude is out until 03:00 · answered on Codex (GPT-6.1)". */note?: string | null;- /** Why this bot answered: a chip beside the name that opens the full reason (and "Wrong bot?"). */+ /** Why this bot answered: Details' first row, in words, with "Wrong bot?" after it. */route?: RouteInfo | null;- /** Set after a failover: the engines the reply moved between, with the reason on hover. */+ /** A job's final reply (replyDone.doneOf): the quiet marker after the name. */+ done?: ReplyDone | null;+ /** Set after a failover: the engines the reply moved between, with the reason on hover. Only then is+ * the engine on the name line; otherwise it waits in Details. */handoff?: { from: string; to: string; why: string } | null;now?: number;/** The reply also went out to Telegram (G4): "· sent to Telegram too" after the time. */@@ -42,26 +50,40 @@ export const FailoverNote: React.FC<{ text: string }> = ({ text }) => (const hasContent = (n: React.ReactNode) => React.Children.toArray(n).length > 0;-/** A bot reply's header: one line, "Name · 3:42 PM", and a Details toggle holding the rest. */-export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, account, tokens, failed = false, note, route, handoff, now, sentToTelegram = false, children }) => {+/** A bot reply's header: one line, "Name · [Done] · 3:42 PM · Details", and a Details toggle holding the rest in words. */+export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, account, tokens, cost, failed = false, note, route, done, handoff, now, sentToTelegram = false, children }) => {const [open, setOpen] = useState(false);const why = useRouteChip(route);const panelId = useId();const time = localClock(at, now);const facts: Array<[string, React.ReactNode]> = [];- if (ranOn) facts.push(['Model', ranOn]);- if (account) facts.push(['Account', account]);- if (tokens) facts.push(['Tokens', <span title={tokens.detail}>{tokens.label}<span className="text-zinc-400"> · {tokens.detail}</span></span>]);- const hasDetails = facts.length > 0 || hasContent(children);+ if (why.reason)+ facts.push([+ `Why ${name}`,+ <>+ {why.reason}+ {why.wrongBot}+ </>,+ ]);+ const ran = ranOnWords(ranOn, account);+ if (ran) facts.push(['Ran on', ran]);+ if (cost)+ facts.push([+ 'Cost',+ <span title={tokens?.detail}>+ {cost.text}+ {cost.note && <span className="text-zinc-400"> {cost.note}</span>}+ </span>,+ ]);+ else if (tokens) facts.push(['Cost', <span title={tokens.detail}>{tokens.label}</span>]);+ const hasDetails = facts.length > 0 || hasContent(children) || !!why.panel;return (<div className="w-full max-w-full min-w-0"><div className="mb-1.5 flex min-w-0 max-w-full flex-nowrap sm:flex-wrap items-center gap-x-2 gap-y-1 text-xs text-zinc-400 font-medium">{avatar && <span className="sm:hidden shrink-0 inline-flex">{avatar}</span>}- <span className="shrink-0 text-[13px] font-semibold text-zinc-50">{name}</span>- {why.chip}- {(ranOn || handoff) && (- <EngineChip label={[ranOn, account].filter(Boolean).join(' · ')} short={ranOn ? ranOn.split(' · ').pop() : null} handoff={handoff} />- )}+ <span className="min-w-0 truncate text-[13px] font-semibold text-zinc-50">{name}</span>+ {done && <DoneMarker done={done} />}+ {handoff && <EngineChip label={[ranOn, account].filter(Boolean).join(' · ')} short={ranOn ? ranOn.split(' · ').pop() : null} handoff={handoff} />}{time && (<span className="shrink-0 whitespace-nowrap text-zinc-400" data-reply-time=""><span aria-hidden="true" className="sm:hidden">· </span>@@ -84,20 +106,20 @@ export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, a</button>)}</div>- {why.panel}{note && <FailoverNote text={note} />}{open && hasDetails && (- <div id={panelId} className="mb-2 w-full max-w-2xl">+ <div id={panelId} className="mb-2 w-full max-w-2xl" data-reply-details="">{facts.length > 0 && (- <dl className="mb-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">+ <dl className="mb-2 grid grid-cols-1 sm:grid-cols-[auto_1fr] gap-x-3 gap-y-0 sm:gap-y-1 text-xs">{facts.map(([k, v]) => (<React.Fragment key={k}><dt className="text-zinc-400">{k}</dt>- <dd className="text-zinc-300 min-w-0 break-words">{v}</dd>+ <dd className="mb-1.5 sm:mb-0 text-zinc-200 min-w-0 break-words leading-snug">{v}</dd></React.Fragment>))}</dl>)}+ {why.panel}{children}</div>)}diff --git a/frontend/src/components/RouteChip.tsx b/frontend/src/components/RouteChip.tsxindex 60bf78f4..b5697a8f 100644--- a/frontend/src/components/RouteChip.tsx+++ b/frontend/src/components/RouteChip.tsx@@ -1,5 +1,5 @@import React, { useState } from 'react';-import { Loader2, Sparkles } from 'lucide-react';+import { Loader2 } from 'lucide-react';export interface Reroute {/** The reply's id, for element ids. */@@ -9,30 +9,25 @@ export interface Reroute {}export interface RouteInfo {- /** The two or three words on the chip ("Matched skills"). */- label: string;- /** The whole reason, shown when the chip is opened and as the chip's tooltip. */+ /** Why this bot answered, in words (routeWhyText): Details' "Why {Name}" row. */text: string;fallback?: boolean;reroute?: Reroute;}/**- * Why this bot answered, split in two so the header can put the chip on its own line next to the name- * while the opened reason and the "Send to another bot" picker sit under the header. With `reroute`,- * "Wrong bot?" opens the other bots; picking one teaches routing and asks that bot.+ * Why this bot answered, for a reply's Details (reply-chrome part 4: no chip on the name line). Returns the+ * sentence, the "Wrong bot?" button that goes after it, and the panel (the "Send to another bot" picker and+ * its result) that goes under the Details facts. With `reroute`, picking a bot teaches routing and asks it.*/-export function useRouteChip(route: RouteInfo | null | undefined): { chip: React.ReactNode; panel: React.ReactNode } {- const [open, setOpen] = useState(false);+export function useRouteChip(route: RouteInfo | null | undefined): { reason: string | null; wrongBot: React.ReactNode; panel: React.ReactNode } {const [picking, setPicking] = useState(false);const [busy, setBusy] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [sentTo, setSentTo] = useState<string | null>(null);- if (!route) return { chip: null, panel: null };+ if (!route) return { reason: null, wrongBot: null, panel: null };const { reroute } = route;- const warn = !!route.fallback;- const reasonId = `why-${reroute?.key ?? 'reply'}`;const pickerId = reroute ? `reroute-${reroute.key}` : undefined;const canReroute = !!reroute && reroute.targets.length > 0;@@ -49,47 +44,23 @@ export function useRouteChip(route: RouteInfo | null | undefined): { chip: React}};- const chip = (- <span className="inline-flex min-w-0 max-w-full items-center gap-1" data-routing-line>+ const wrongBot =+ canReroute && !sentTo ? (<buttontype="button"data-compact- onClick={() => setOpen((v) => !v)}- aria-expanded={open}- aria-controls={open ? reasonId : undefined}- title={route.text}- className={`inline-flex min-h-6 max-w-full min-w-0 items-center gap-1 rounded-full border px-2 text-[11px] font-medium transition-colors motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 ${- warn- ? 'border-amber-400/40 bg-amber-400/10 text-amber-200 hover:bg-amber-400/15'- : 'border-sky-400/35 bg-sky-400/10 text-sky-200 hover:bg-sky-400/15'- }`}+ data-wrong-bot=""+ onClick={() => setPicking((v) => !v)}+ aria-expanded={picking}+ aria-controls={picking ? pickerId : undefined}+ className="ml-1 inline rounded px-1 text-xs text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 underline decoration-dotted underline-offset-2 transition-colors motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400">- <Sparkles size={11} className="shrink-0" aria-hidden="true" />- <span className="truncate">{route.label}</span>- <span className="sr-only">: why this bot answered</span>+ Wrong bot?</button>- {canReroute && !sentTo && (- <button- type="button"- data-compact- onClick={() => setPicking((v) => !v)}- aria-expanded={picking}- aria-controls={picking ? pickerId : undefined}- className="shrink-0 rounded-full px-2 min-h-6 text-[11px] text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 underline decoration-dotted underline-offset-2 transition-colors motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400"- >- Wrong bot?- </button>- )}- </span>- );+ ) : null;const panel = (<>- {open && (- <p id={reasonId} className="mb-1.5 max-w-2xl break-words text-xs leading-snug text-zinc-300">- {route.text}- </p>- )}{picking && reroute && (<div id={pickerId} role="group" aria-label="Send to another bot" className="mb-2 max-w-full rounded-xl border border-zinc-700/70 bg-zinc-900/80 px-3 py-2.5 shadow-[var(--kws-shadow)]"><p className="mb-2 text-xs text-zinc-300">Send your message to:</p>@@ -132,5 +103,5 @@ export function useRouteChip(route: RouteInfo | null | undefined): { chip: React</>);- return { chip, panel };+ return { reason: route.text, wrongBot, panel };}diff --git a/frontend/src/modelUsage.ts b/frontend/src/modelUsage.tsindex b31b254d..dc4eee21 100644--- a/frontend/src/modelUsage.ts+++ b/frontend/src/modelUsage.ts@@ -140,6 +140,31 @@ export function replyTokens(tokensUsed: number | null | undefined, meta: stringreturn { count: tokensUsed, label: `${compactTokens(tokensUsed)} tokens`, detail: `${tokensUsed.toLocaleString('en-US')} tokens, cache reads included` };}+/**+ * reply-chrome part 4: a reply's cost row in words, "About $0.04 · 11,812 tokens of new work", with the cache+ * reads as a separate note. Every number is the server's (or a sum of its parts, as replyTokens counts them).+ */+export function replyCostWords(meta: string | null | undefined): { text: string; note: string | null } | null {+ const u = parseTurnUsage(meta);+ if (!u) return null;+ const fresh = u.fresh_input + u.cache_write + u.output;+ const fmt = (n: number) => n.toLocaleString('en-US');+ const parts: string[] = [];+ if (u.cost_usd != null && Number.isFinite(u.cost_usd) && u.cost_usd >= 0) parts.push(u.cost_usd < 0.01 ? 'Under 1¢' : `About $${u.cost_usd.toFixed(2)}`);+ parts.push(`${fmt(fresh)} ${fresh === 1 ? 'token' : 'tokens'} of new work`);+ const note = u.cache_read > 0 ? `(plus ${fmt(u.cache_read)} re-read from earlier at a small part of the price)` : null;+ return { text: parts.join(' · '), note };+}++/** reply-chrome part 4: "Claude Sonnet 5.5, on your Work account" from ranOnLabel's "Claude · Sonnet 5.5" and the account. */+export function ranOnWords(ranOn: string | null | undefined, account: string | null | undefined): string | null {+ const model = ranOn ? ranOn.split(' · ').join(' ') : null;+ const acct = account?.trim();+ if (!model) return acct ? (/account$/i.test(acct) ? `Your ${acct}` : `The ${acct} account`) : null;+ if (!acct) return model;+ return /account$/i.test(acct) ? `${model}, on your ${acct}` : `${model}, on the ${acct} account`;+}+export const modelUsageApi = {get: (kwantId: string, limit = 20) =>request<ModelUsage>('GET', `/api/kwants/${encodeURIComponent(kwantId)}/model-usage?limit=${limit}`),diff --git a/frontend/src/replyDone.ts b/frontend/src/replyDone.tsnew file mode 100644index 00000000..9d16cf59--- /dev/null+++ b/frontend/src/replyDone.ts@@ -0,0 +1,103 @@+// reply-chrome part 1 (autonomy/reply-chrome/design.md, Mira): whether a bot reply is a job's final answer, so+// its name line gets a quiet "Done" marker, and the done-check state when the Inbox item carries one. Nothing+// here computes a number; it reads what the server stamped (`meta.chain_done`, the `Done:` line, the Inbox item).++import { type CheckState, knownChecked, type Checked } from './doneCheck';++export interface ReplyDone {+ /** The done text ("Compared both shops' 1 kg price and shipping"), for the marker's tooltip; null when none. */+ text: string | null;+ /** The Inbox item's check (#566/#577), when it has a known state. */+ checked: (Checked & { state: CheckState }) | null;+}++/** The Inbox done items this chat can match on, by the reply they point at. */+export type DoneItems = ReadonlyMap<string, { checked?: unknown; answer_excerpt?: string | null }>;++/**+ * What follows `Done:` on the reply's last non-empty line, the way the server reads it (keep_going::done_line):+ * leading `* _ - > \`` and spaces stripped, the head compared case-insensitively. Null when it doesn't end so.+ */+export function doneLineOf(text: string | null | undefined): string | null {+ if (!text) return null;+ const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);+ const last = lines[lines.length - 1];+ if (!last) return null;+ const bare = last.replace(/^[*_\->` ]+/, '');+ if (bare.slice(0, 5).toLowerCase() !== 'done:') return null;+ const what = bare.slice(5).trim().replace(/^[*_` ]+|[*_` ]+$/g, '').trim();+ return what || null;+}++function metaOf(meta: string | null | undefined): Record<string, unknown> | null {+ if (!meta) return null;+ try {+ const v = JSON.parse(meta);+ return v && typeof v === 'object' ? (v as Record<string, unknown>) : null;+ } catch {+ return null;+ }+}++export interface DoneMsg {+ id: string;+ sender_role: string;+ text: string;+ meta?: string | null;+}++/**+ * The reply's done state, first match wins: the server's `chain_done` stamp, a `Done:` last line, or an Inbox done+ * item whose result is this message. Never on a user message, a temp or streaming one, a blocked reply, or one+ * that asks (`asks`: the Approve row or an open question card is on it).+ */+export function doneOf(msg: DoneMsg, doneItems: DoneItems | null | undefined, opts: { asks?: boolean; streaming?: boolean; failed?: boolean } = {}): ReplyDone | null {+ if (msg.sender_role !== 'kwant' || msg.id.startsWith('temp-') || opts.asks || opts.streaming || opts.failed) return null;+ const meta = metaOf(msg.meta);+ if (meta?.blocked || meta?.interrupted === true || meta?.error) return null;+ const item = doneItems?.get(msg.id);+ const checked = item ? knownChecked(item.checked) : null;+ const stamp = meta?.chain_done;+ if (stamp && typeof stamp === 'object') {+ const t = (stamp as { text?: unknown }).text;+ return { text: typeof t === 'string' && t.trim() ? t.trim() : doneLineOf(msg.text), checked };+ }+ const line = doneLineOf(msg.text);+ if (line) return { text: line, checked };+ if (item) return { text: null, checked };+ return null;+}++/** The Inbox items whose result is a reply, keyed by that reply's id: finished and to-review only. */+export function doneItemsOf(items: ReadonlyArray<{ group: string; result_message_id?: string | null; checked?: unknown; answer_excerpt?: string | null }>): Map<string, { checked?: unknown; answer_excerpt?: string | null }> {+ const out = new Map<string, { checked?: unknown; answer_excerpt?: string | null }>();+ for (const i of items) {+ if ((i.group === 'finished' || i.group === 'to_review') && i.result_message_id && !out.has(i.result_message_id)) out.set(i.result_message_id, i);+ }+ return out;+}++/** The marker's words per check state (the Inbox list's words, done-check design section 2); plain "Done" without one. */+export const DONE_WORD: Record<CheckState | 'done', string> = {+ done: 'Done',+ checked: 'Checked',+ partly: 'Partly checked',+ failed: 'Check failed',+ not_checked: 'Not checked',+};++/** The marker's screen-reader name. */+export function doneLabel(d: ReplyDone): string {+ switch (d.checked?.state) {+ case 'checked':+ return 'Checked: this job is finished and every check passed';+ case 'partly':+ return 'Partly checked: this job is finished and some checks passed';+ case 'failed':+ return 'Check failed: this job is finished but a check failed';+ case 'not_checked':+ return 'Done: this job is finished, nothing verified it';+ default:+ return 'Done: this job is finished';+ }+}diff --git a/frontend/src/routeReason.ts b/frontend/src/routeReason.tsindex 323fcaa0..9a84d4ad 100644--- a/frontend/src/routeReason.ts+++ b/frontend/src/routeReason.ts@@ -1,6 +1,9 @@// The line under "Sending your question to X" on Laya's routing card: why that bot, in words that// match how it was actually picked.+/** The router bot's name. One place, so the routing line and Details say the same name. */+export const ROUTER_NAME = 'Laya';+export type RouteBasis =| 'skills'| 'lead'@@ -77,36 +80,18 @@ export function routeReasonText(r: RouteReasonInput): string | null {}}-/** The two or three words on the chip beside a reply's name: how this bot was picked. The full- * sentence (routeReasonText / routingLine) opens when the chip is tapped. */-export function routeChipLabel(r: { basis?: string; fallback?: boolean }): string {- if (r.fallback) return 'By keywords';- switch (r.basis) {- case 'skills':- return 'Matched skills';- case 'keywords':- return 'Matched words';- case 'lead':- case 'team':- return 'Team lead';- case 'only':- return 'Only bot here';- case 'several':- return 'Best of several';- case 'discuss':- return 'Team discussion';- case 'asked':- case 'ask':- return 'You chose';- case 'last':- return 'Same as last time';- case 'concierge':- return 'General answer';- case 'handback':- return 'Handed over';- case 'learned':- return 'Learned from you';- default:- return 'Picked by Laya';+/**+ * reply-chrome part 4: "Why {Name}" in a reply's Details, in words. A keyword fallback says who was offline and+ * which words matched; any other pick reads as routeReasonText; with nothing known, who picked it.+ */+export function routeWhyText(r: RouteReasonInput, routerName: string = ROUTER_NAME): string {+ const name = r.kwantName || 'this bot';+ if (r.fallback) {+ const terms = (r.matchedTerms ?? []).filter(Boolean).slice(0, 4);+ const head = `${routerName}, who picks the bot, was offline, so ${name} was picked by matching words in your message`;+ return terms.length ? `${head}: ${terms.join(', ')}.` : `${head}.`;}+ const said = routeReasonText(r);+ if (said && !/^laya picked\b/i.test(said)) return /[.!?]$/.test(said) ? said : `${said}.`;+ return `${routerName} picked ${name} for this.`;}diff --git a/frontend/src/spaces.ts b/frontend/src/spaces.tsindex 075818f7..8e2c50ca 100644--- a/frontend/src/spaces.ts+++ b/frontend/src/spaces.ts@@ -2,7 +2,7 @@// `/api` call as `?space=` (added by the fetch wrapper in auth.ts) and on the event stream.import { parseView, viewSegment, type SpaceView } from './nav';-import { pickedLine, serverReason } from './routeReason';+import { ROUTER_NAME, pickedLine, serverReason } from './routeReason';import { NeedsBitwardenError } from './approvalMode';import { needsBitwardenFrom } from './passwordStore';@@ -328,10 +328,10 @@ export function routingLine(r: RoutingMeta, spaceName: string, nameOf?: (kwantIdconst own = serverReason(r);if (own) return `${own} Chosen ${pool}.`;const matched = r.matched_terms?.length ? ` · matched ${r.matched_terms.map((t) => `'${t}'`).join(', ')}` : '';- if (r.fallback) return `Picked by keywords (Laya is offline) · ${r.kwant_name} ${pool}${matched}`;+ if (r.fallback) return `Picked by keywords (${ROUTER_NAME} is offline) · ${r.kwant_name} ${pool}${matched}`;if (r.basis === 'lead') return `No one’s role matched, so the team lead ${r.kwant_name} took it ${pool}`;if (r.basis === 'only') return `${r.kwant_name} is the only bot that can answer ${pool}`;- return `Laya picked ${r.kwant_name} ${pool}${matched}`;+ return `${ROUTER_NAME} picked ${r.kwant_name} ${pool}${matched}`;}/** "ran on Work account" from a reply's `ran_on`, or null. */diff --git a/frontend/tests/mobileCards.test.mjs b/frontend/tests/mobileCards.test.mjsindex dd24ef88..18c37b60 100644--- a/frontend/tests/mobileCards.test.mjs+++ b/frontend/tests/mobileCards.test.mjs@@ -285,11 +285,12 @@ test('engine chip: the model alone on a phone, the full label from sm up and onassert.match(html, /<span class="[^"]*hidden sm:inline[^"]*">Claude · claude-opus-5-5 · Booktuning<\/span>/);});-test('reply header on a phone: one row, the time never shrinks, the chip gives way', () => {+test('reply header on a phone: one row, the time never shrinks, no engine chip (reply-chrome part 4)', () => {const html = m.meta({ name: 'Architect', at: '2026-11-02T11:42:00Z', now: Date.parse('2026-11-02T12:00:00Z'), ranOn: 'Custom API · claude-opus-5-5', account: 'Anthropic API' });assert.match(html, /<div class="[^"]*flex-nowrap sm:flex-wrap[^"]*">/);assert.match(html, /<span class="[^"]*shrink-0 whitespace-nowrap[^"]*" data-reply-time="">/);- assert.match(html, /<span class="[^"]*sm:hidden[^"]*max-w-\[160px\][^"]*"[^>]*>claude-opus-5-5<\/span>/);+ assert.doesNotMatch(html, /data-engine-chip/);+ assert.doesNotMatch(html, /claude-opus-5-5/);});// --- Rigel's #309 HOLD on b48683c ------------------------------------------------------------diff --git a/frontend/tests/quickWins.test.mjs b/frontend/tests/quickWins.test.mjsindex c281d683..d594450c 100644--- a/frontend/tests/quickWins.test.mjs+++ b/frontend/tests/quickWins.test.mjs@@ -44,7 +44,7 @@ test('quotaLine: "Out of quota until …" while the limit lasts, the server wordassert.equal(m.quotaLine(null, undefined, NOW), null);});-test('reply meta is one line, name · engine chip (engine + account, spec §4) · time, with tokens behind Details', () => {+test('reply meta is one line, name · time, with the engine, account and tokens behind Details (reply-chrome part 4)', () => {const html = m.meta({name: 'Architect',at: '2026-11-02T11:42:00Z',@@ -57,8 +57,9 @@ test('reply meta is one line, name · engine chip (engine + account, spec §4)assert.match(html, /data-reply-time/);assert.match(html, /aria-expanded="false"/);assert.match(html, />Details</);- // The engine chip reads "engine · account" (Mira's spec §4); folded, the tokens stay hidden. No cost, no duration.- assert.match(html, /data-engine-chip[^>]*>.*Claude · Opus 5\.5 · Personal/);+ // reply-chrome: the engine waits in Details now (only a mid-reply engine switch shows on the line); folded, nothing else shows.+ assert.doesNotMatch(html, /data-engine-chip/);+ assert.doesNotMatch(html, /Opus 5\.5/);assert.doesNotMatch(html, /1\.2k tokens/);});diff --git a/frontend/tests/replyChrome.test.mjs b/frontend/tests/replyChrome.test.mjsnew file mode 100644index 00000000..8ac4ca3a--- /dev/null+++ b/frontend/tests/replyChrome.test.mjs@@ -0,0 +1,283 @@+// reply-chrome (autonomy/reply-chrome/design.md, Mira; UX audit #10): a done reply looks done, a reply asking for+// an OK gets Approve / Change…, Copy is a quiet icon, and the name line is "Name · time · Details" with routing,+// engine and cost in words inside Details.+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';++process.env.TZ = 'UTC';+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });+}+globalThis.IS_REACT_ACT_ENVIRONMENT = false;++const m = await loadBundled(`+ export * from './src/replyDone';+ export * from './src/approvalAsk';+ export { routeWhyText, routeReasonText, ROUTER_NAME } from './src/routeReason';+ export { routingLine } from './src/spaces';+ export { replyCostWords, ranOnWords, replyTokens } from './src/modelUsage';+`);+const ui = await loadBundled(`+ import React from 'react';+ import { flushSync } from 'react-dom';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { ReplyMeta } from './src/components/ReplyMeta';+ import { DoneMarker, DoneCheckLine } from './src/components/DoneMarker';+ import { ApproveRow } from './src/components/ApproveRow';+ import { CopyGhost } from './src/components/CopyGhost';+ export { createRoot } from 'react-dom/client';+ export const html = (C, p) => renderToStaticMarkup(React.createElement(C, p));+ export { React, flushSync, ReplyMeta, DoneMarker, DoneCheckLine, ApproveRow, CopyGhost };+`);++const mount = (Comp, props) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = ui.createRoot(host);+ ui.flushSync(() => root.render(ui.React.createElement(Comp, props)));+ return { host, unmount: () => (root.unmount(), host.remove()) };+};+const tick = () => new Promise((r) => setTimeout(r, 0));+const click = async (el) => {+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await tick();+ await tick();+};++// ---- 1. Done marker ----++const reply = (o = {}) => ({ id: 'm1', sender_role: 'kwant', text: 'Here are both prices.', meta: null, ...o });++test('doneLineOf reads the last line like keep_going::done_line', () => {+ assert.equal(m.doneLineOf('Compared them.\n\nDone: compared both shops'), 'compared both shops');+ assert.equal(m.doneLineOf('x\n**Done:** compared both shops\n\n'), 'compared both shops');+ assert.equal(m.doneLineOf('x\n> done: it ships'), 'it ships');+ assert.equal(m.doneLineOf('Done: early\nThen more words.'), null, 'only the last line counts');+ assert.equal(m.doneLineOf('Done:'), null, 'nothing after the head');+ assert.equal(m.doneLineOf('Undone: no'), null);+ assert.equal(m.doneLineOf(''), null);+});++test('doneOf: chain_done stamp, a Done: last line, or an Inbox done item; first match wins', () => {+ const stamped = m.doneOf(reply({ meta: JSON.stringify({ chain_done: { text: 'Compared both shops’ 1 kg price', at: '2026-11-13T10:00:00Z' } }) }), null);+ assert.deepEqual(stamped, { text: 'Compared both shops’ 1 kg price', checked: null });+ assert.deepEqual(m.doneOf(reply({ text: 'Both found.\nDone: priced both' }), null), { text: 'priced both', checked: null });+ const items = m.doneItemsOf([+ { group: 'finished', result_message_id: 'm1', checked: { state: 'checked', items: [], items_dropped: 0, line: 'Checked: every check passed.' } },+ { group: 'waiting_on_you', result_message_id: 'm2' },+ ]);+ const fromInbox = m.doneOf(reply(), items);+ assert.equal(fromInbox.text, null);+ assert.equal(fromInbox.checked.state, 'checked');+ assert.equal(m.doneOf(reply({ id: 'm2' }), items), null, 'a waiting item is not done');+ assert.equal(m.doneOf(reply({ id: 'm3' }), items), null, 'a plain reply has no marker');+});++test('doneOf: never on a reply that asks, a blocked or interrupted one, a temp, or a user message', () => {+ const done = { text: 'x\nDone: shipped it' };+ assert.equal(m.doneOf(reply({ ...done }), null, { asks: true }), null);+ assert.equal(m.doneOf(reply({ ...done, meta: JSON.stringify({ blocked: { text: 'needs a key' } }) }), null), null);+ assert.equal(m.doneOf(reply({ ...done, meta: JSON.stringify({ interrupted: true }) }), null), null);+ assert.equal(m.doneOf(reply({ ...done, id: 'temp-1' }), null), null);+ assert.equal(m.doneOf(reply({ ...done, sender_role: 'user' }), null), null);+ assert.equal(m.doneOf(reply({ ...done }), null, { streaming: true }), null);+});++test('doneItemsOf keeps finished and to-review items with a result message only', () => {+ const map = m.doneItemsOf([+ { group: 'to_review', result_message_id: 'a' },+ { group: 'finished', result_message_id: null },+ { group: 'failed_or_stuck', result_message_id: 'b' },+ ]);+ assert.deepEqual([...map.keys()], ['a']);+});++test('DoneMarker: a teal "Done" pill, labelled, no motion; holo only for Checked; check words match the Inbox', () => {+ const plain = ui.html(ui.DoneMarker, { done: { text: 'Priced both', checked: null } });+ assert.match(plain, /role="img"/);+ assert.match(plain, /aria-label="Done: this job is finished"/);+ assert.match(plain, /title="Priced both"/);+ assert.match(plain, /text-ok/);+ assert.match(plain, />Done</);+ assert.doesNotMatch(plain, /kw-sticker|animate|transition|tabindex|<button/);+ const chk = (state) => ({ text: null, checked: { state, items: [], items_dropped: 0, line: '' } });+ assert.match(ui.html(ui.DoneMarker, { done: chk('checked') }), /kw-sticker-holo[\s\S]*Checked/);+ for (const [state, word, tone] of [['partly', 'Partly checked', 'text-warn'], ['failed', 'Check failed', 'text-bad'], ['not_checked', 'Not checked', 'text-zinc-300']]) {+ const h = ui.html(ui.DoneMarker, { done: chk(state) });+ assert.match(h, new RegExp(`>${word}<`), state);+ assert.match(h, new RegExp(tone), state);+ assert.doesNotMatch(h, /kw-sticker/, `${state} is never holo`);+ }+});++test('DoneCheckLine: only with a check; the server line, or done-check’s default sentence', () => {+ assert.equal(ui.html(ui.DoneCheckLine, { done: { text: null, checked: null } }), '');+ const h = ui.html(ui.DoneCheckLine, { done: { text: null, checked: { state: 'partly', items: [], items_dropped: 0, line: 'Partly checked: 1 of 2 prices matched the shop page.' } } });+ assert.match(h, /data-done-check-line="partly"/);+ assert.match(h, /<b class="[^"]*text-warn[^"]*">Partly checked:<\/b> 1 of 2 prices matched the shop page\./);+ const d = ui.html(ui.DoneCheckLine, { done: { text: null, checked: { state: 'not_checked', items: [], items_dropped: 0, line: '' } } });+ assert.match(d, /Not checked:<\/b> nothing verified this result\./);+});++// ---- 2. Approve / Change… ----++test('asksApproval: the design’s true and false cases', () => {+ for (const t of ['I drafted the newsletter. It goes out once you approve the draft.', 'The post is ready. Shall I send it?', 'Waiting for your go-ahead.', 'All set. Should I publish it on Friday?', 'OK to schedule it for 9:00?', 'I’ll send it once you’ve confirmed.']) {+ assert.equal(m.asksApproval(t), true, t);+ }+ for (const t of ['I approved the refund.', 'No need to approve anything.', 'You can approve it later in Settings, but it’s live now.', 'Here are both prices.', '', null]) {+ assert.equal(m.asksApproval(t), false, String(t));+ }+});++test('asksApproval looks only at the last two sentences', () => {+ assert.equal(m.asksApproval('Shall I send it? You said yes. I sent it. It went out at 9:00.'), false);+ assert.equal(m.asksApproval('Here is the draft.\n\n**Subject:** Spring sale\n\nShall I send it?'), true);+ assert.equal(m.asksApproval('Once you approve, I send it.\n\n```\nonce you approve\n```\nIt is live now. Nothing else to do.'), false);+});++test('ApproveRow: a labelled group, Approve first, Change… second; both call back and lock while busy', async () => {+ const calls = [];+ const { host, unmount } = mount(ui.ApproveRow, { name: 'Ben', onApprove: () => calls.push('approve'), onChange: () => calls.push('change') });+ const group = host.querySelector('[role=group]');+ assert.equal(group.getAttribute('aria-label'), 'Ben is waiting for your OK');+ assert.match(group.textContent, /Ben is waiting for your OK/);+ const [a, c] = group.querySelectorAll('button');+ assert.equal(a.textContent, 'Approve');+ assert.equal(c.textContent, 'Change…');+ assert.match(a.className, /h-11 sm:h-8/);+ assert.match(a.className, /focus-visible:ring-2/);+ await click(a);+ await click(c);+ assert.deepEqual(calls, ['approve', 'change']);+ unmount();+ const busy = ui.html(ui.ApproveRow, { name: 'Ben', busy: true, onApprove() {}, onChange() {} });+ assert.equal((busy.match(/disabled=""/g) ?? []).length, 2);+});++test('approval words', () => {+ assert.equal(m.APPROVE_TEXT, 'Approved, go ahead.');+ assert.equal(m.changePlaceholder('Ben'), 'What should Ben change?');+});++// ---- 3. Copy ----++test('CopyGhost: an icon button named "Copy reply" with a tooltip, no border, 44 px on phone', () => {+ const h = ui.html(ui.CopyGhost, { copied: false, tipId: 't1', onCopy() {} });+ assert.match(h, /aria-label="Copy reply"/);+ assert.match(h, /aria-describedby="t1"/);+ assert.match(h, /id="t1" role="tooltip"/);+ assert.match(h, /h-11 w-11 sm:h-8 sm:w-8/);+ assert.doesNotMatch(h, /<button[^>]*class="[^"]*\bborder\b/, 'the button has no border');+ assert.doesNotMatch(h, /title=/);+ assert.doesNotMatch(h, /Copy markdown/);+ assert.match(h, /\[@media\(hover:hover\)\]:peer-hover:opacity-100 peer-focus-visible:opacity-100/);+ const done = ui.html(ui.CopyGhost, { copied: true, tipId: 't1', onCopy() {} });+ assert.match(done, /text-ok/);+ assert.match(done, /role="tooltip"[^>]*class="[^"]*opacity-100[^"]*">Copied</);+ assert.match(done, /aria-live="polite">Copied</);+});++test('ChatView: the action row is Reply, thumbs, Copy, then smart actions', () => {+ const src = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');+ const row = src.slice(src.indexOf('{/* Action row (reply-chrome part 3)'));+ const at = (s) => row.indexOf(s);+ assert.ok(at('<ReplyButton') > 0 && at('<ReplyButton') < at('<ReactionButtons'));+ assert.ok(at('<ReactionButtons') < at('<CopyGhost'));+ assert.ok(at('<CopyGhost') < at('<SmartActionsSlot'));+ assert.doesNotMatch(src, /Copy markdown/);+ assert.doesNotMatch(src, /routeChipLabel/);+});++// ---- 4. Name line and Details in words ----++test('routeWhyText: a keyword fallback in words; other picks as routeReasonText', () => {+ assert.equal(+ m.routeWhyText({ kwantName: 'Cody', fallback: true, basis: 'keywords', matchedTerms: ['newsletter', 'draft'] }),+ 'Laya, who picks the bot, was offline, so Cody was picked by matching words in your message: newsletter, draft.',+ );+ assert.equal(m.routeWhyText({ kwantName: 'Cody', fallback: true }), 'Laya, who picks the bot, was offline, so Cody was picked by matching words in your message.');+ assert.equal(m.routeWhyText({ kwantName: 'Ben', basis: 'ask' }), 'You picked Ben.');+ assert.equal(m.routeWhyText({ kwantName: 'Ann', basis: 'lead' }), 'No one’s role matched this, so it went to the team lead, Ann.');+ assert.equal(m.routeWhyText({ kwantName: 'Ben', basis: 'skills', reason: 'Ben compares shop prices' }), 'Ben compares shop prices.');+ assert.equal(m.routeWhyText({ kwantName: 'Ben', reason: 'Laya picked Ben from 3 bots' }), 'Laya picked Ben for this.');+ assert.doesNotMatch(m.routeWhyText({ kwantName: 'Cody', fallback: true, matchedTerms: ['x'] }), /By keywords/);+ assert.equal(m.ROUTER_NAME, 'Laya');+ assert.match(m.routingLine({ kwant_name: 'Cody', fallback: true }, 'Home'), /\(Laya is offline\)/, 'routingLine uses the same name');+});++test('ranOnWords: "Claude Sonnet 5.5, on your Work account"', () => {+ assert.equal(m.ranOnWords('Claude · Sonnet 5.5', 'Work account'), 'Claude Sonnet 5.5, on your Work account');+ assert.equal(m.ranOnWords('Claude · Sonnet 5.5', 'Booktuning'), 'Claude Sonnet 5.5, on the Booktuning account');+ assert.equal(m.ranOnWords('Codex', null), 'Codex');+ assert.equal(m.ranOnWords(null, null), null);+});++test('replyCostWords: cost and new work, cache reads as a note; never "fresh" or "cache"', () => {+ const meta = (u) => JSON.stringify({ usage: u });+ const full = m.replyCostWords(meta({ fresh_input: 9120, cache_write: 1880, output: 812, cache_read: 38400, cost_usd: 0.0412 }));+ assert.deepEqual(full, { text: 'About $0.04 · 11,812 tokens of new work', note: '(plus 38,400 re-read from earlier at a small part of the price)' });+ assert.equal(m.replyCostWords(meta({ fresh_input: 10, cache_write: 0, output: 5, cache_read: 0, cost_usd: 0.002 })).text, 'Under 1¢ · 15 tokens of new work');+ assert.deepEqual(m.replyCostWords(meta({ fresh_input: 10, cache_write: 0, output: 5, cache_read: 0 })), { text: '15 tokens of new work', note: null });+ assert.equal(m.replyCostWords(null), null);+ assert.doesNotMatch(JSON.stringify(full), /fresh|cache|input|output/);+});++test('ReplyMeta: the line is Name, Done, time, Details; no route chip or engine chip unless the engine switched', () => {+ const props = {+ name: 'Cody',+ at: '2026-11-13T16:24:00Z',+ now: Date.parse('2026-11-13T17:00:00Z'),+ ranOn: 'Claude · Sonnet 5.5',+ account: 'Work account',+ tokens: { label: '11.8k fresh', detail: '11,812 fresh tokens: …' },+ cost: { text: 'About $0.04 · 11,812 tokens of new work', note: '(plus 38,400 re-read from earlier at a small part of the price)' },+ route: { text: 'Laya, who picks the bot, was offline, so Cody was picked by matching words in your message: newsletter, draft.', fallback: true },+ done: { text: 'Drafted it', checked: null },+ };+ const line = ui.html(ui.ReplyMeta, props);+ assert.doesNotMatch(line, /By keywords|Matched words|data-routing-line|data-engine-chip|Sonnet/);+ assert.match(line, />Cody<\/span><span role="img" aria-label="Done: this job is finished"/, 'Done right after the name');+ assert.match(line, /data-reply-time/);+ const switched = ui.html(ui.ReplyMeta, { ...props, handoff: { from: 'Claude', to: 'Codex', why: 'Claude is out' } });+ assert.match(switched, /data-engine-chip/);+});++test('ReplyMeta: Details opens to Why, Ran on and Cost in words, with Wrong bot?', async () => {+ const picks = [];+ const { host, unmount } = mount(ui.ReplyMeta, {+ name: 'Cody',+ ranOn: 'Claude · Sonnet 5.5',+ account: 'Work account',+ tokens: { label: '11.8k fresh', detail: '11,812 fresh tokens: 9,120 new input' },+ cost: { text: 'About $0.04 · 11,812 tokens of new work', note: '(plus 38,400 re-read from earlier at a small part of the price)' },+ route: {+ text: 'Laya, who picks the bot, was offline, so Cody was picked by matching words in your message: newsletter, draft.',+ fallback: true,+ reroute: { key: 'm1', targets: [{ id: 'k2', name: 'Ann', title: 'Lead' }], onPick: async (id) => void picks.push(id) },+ },+ });+ const toggle = [...host.querySelectorAll('button')].find((b) => /Details/.test(b.textContent));+ assert.equal(toggle.getAttribute('aria-expanded'), 'false');+ await click(toggle);+ const panel = host.querySelector('[data-reply-details]');+ const rows = [...panel.querySelectorAll('dt')].map((dt) => [dt.textContent, dt.nextElementSibling.textContent]);+ assert.deepEqual(rows.map(([k]) => k), ['Why Cody', 'Ran on', 'Cost']);+ assert.match(rows[0][1], /was offline, so Cody was picked by matching words in your message: newsletter, draft\.Wrong bot\?/);+ assert.equal(rows[1][1], 'Claude Sonnet 5.5, on your Work account');+ assert.equal(rows[2][1], 'About $0.04 · 11,812 tokens of new work (plus 38,400 re-read from earlier at a small part of the price)');+ assert.equal(panel.querySelector('dd span[title]').getAttribute('title'), '11,812 fresh tokens: 9,120 new input', 'the full split stays in the tooltip');+ assert.doesNotMatch(panel.textContent.replace('Wrong bot?', ''), /fresh|cache|By keywords/);+ await click(panel.querySelector('[data-wrong-bot]'));+ const picker = host.querySelector('[aria-label="Send to another bot"]');+ assert.ok(picker, 'Wrong bot? opens the picker');+ await click([...picker.querySelectorAll('button')].find((b) => b.textContent.startsWith('Ann')));+ assert.deepEqual(picks, ['k2']);+ assert.match(host.textContent, /Sent to Ann\./);+ unmount();+});