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.

Smart Results: UI frame, registry, comparison and steps v2 (#226)

Oleksandr Ivanchenko68fd466301b2
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index e0771123..2206af0d 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -46,6 +46,8 @@ import { consultedNames, hideStreamingDecisions, messageDecisions, parseWorkAhea
import { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';
import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';
import { RouteChoiceMeta, parseRouteChoiceMeta, questionsOfReplies } from '../routeChoice';
+import { SmartActionsSlot } from './results/SmartActions';
+import { COMPOSE_PREFILL_EVENT } from './results/SmartResult';
/** A swipeable chip row whose right fade edge (phones only, see .kw-scroll-row) goes away once
* it is scrolled to the end, or when everything already fits. */
@@ -89,6 +91,8 @@ export interface ChatMessage {
/** JSON string kwnt sets on messages it writes itself, e.g. delegation notes. */
meta?: string | null;
created_at?: string | null;
+ /** Smart Results blocks for a bot reply; null or absent while the setting is off. */
+ results?: unknown;
}
/** The open chat's turn is waiting for a free slot. */
@@ -904,6 +908,25 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
};
+ // "Ask about this" on a Smart Results row, card or finding: fill in the composer, never send.
+ useEffect(() => {
+ const prefill = (e: Event) => {
+ const text = (e as CustomEvent<{ text?: unknown }>).detail?.text;
+ if (typeof text !== 'string' || !text) return;
+ setInputVal((prev) => (prev.trim() ? `${prev.trimEnd()}\n${text}` : text));
+ requestAnimationFrame(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(el.value.length, el.value.length);
+ el.style.height = 'auto';
+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
+ });
+ };
+ window.addEventListener(COMPOSE_PREFILL_EVENT, prefill);
+ return () => window.removeEventListener(COMPOSE_PREFILL_EVENT, prefill);
+ }, []);
+
const handlePromptSuggestion = (prompt: string) => {
setInputVal(prompt);
playSfx('click');
@@ -1110,7 +1133,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
) : workAhead ? (
<WorkAheadBody messageId={msg.id} text={text} />
) : (
- <MarkdownRenderer content={text} />
+ <MarkdownRenderer content={text} results={msg.results} messageId={msg.id} />
)}
</div>
)}
@@ -1129,7 +1152,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Copy action */}
{!isUser && !filesOnly && (
- <div className="mt-1.5 flex items-center gap-2 text-zinc-500 text-xs max-w-full min-w-0">
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-zinc-500 text-xs max-w-full min-w-0">
<button
type="button"
onClick={() => handleCopy(text, msg.id)}
@@ -1149,6 +1172,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
</>
)}
</button>
+ {msg.results != null && <SmartActionsSlot messageId={msg.id} />}
</div>
)}
</div>
diff --git a/frontend/src/components/MarkdownRenderer.tsx b/frontend/src/components/MarkdownRenderer.tsx
index 49dcb718..764410c2 100644
--- a/frontend/src/components/MarkdownRenderer.tsx
+++ b/frontend/src/components/MarkdownRenderer.tsx
@@ -3,6 +3,9 @@ import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Copy, Check, Terminal } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
+import { HastNode, blockAt, hastText, rehypeSmartIndex, resultBlocks } from '../smartResults';
+import type { ReplyPart, ReplySource } from './results/registry';
+import { SmartResult } from './results/SmartResult';
interface CodeBlockProps {
language?: string;
@@ -80,17 +83,99 @@ interface MarkdownRendererProps {
content: string;
className?: string;
isStreaming?: boolean;
+ /** The message's `results` (Smart Results). Only for a final bot reply. */
+ results?: unknown;
+ messageId?: string;
+}
+
+// Smart Results: hand the reply's own rendered cells or items to the block, which checks them against
+// its data (results/registry.ts). Any mismatch and the table or list renders as plain markdown.
+type MdElement = React.ReactElement<{ node?: HastNode; children?: React.ReactNode }>;
+const elementsOf = (children: React.ReactNode) => React.Children.toArray(children).filter(React.isValidElement) as MdElement[];
+const tagOf = (el: MdElement) => el.props.node?.tagName ?? (typeof el.type === 'string' ? el.type : '');
+const shown = (el: MdElement) => React.Children.map(el.props.children, formatTextMentions);
+const part = (el: MdElement, node: React.ReactNode = shown(el)): ReplyPart => ({ node, text: hastText(el.props.node) });
+const hasClass = (n: HastNode | undefined, c: string) => {
+ const cls = n?.properties?.className;
+ return Array.isArray(cls) ? cls.includes(c) : cls === c;
+};
+const isTaskItem = (n: HastNode | undefined) => hasClass(n, 'task-list-item');
+
+const checkClass = 'mt-[5px] h-3.5 w-3.5 shrink-0 rounded-sm accent-sky-500';
+
+/** A task item's content without its checkbox or the space after it. */
+function taskContent(children: React.ReactNode): React.ReactNode[] {
+ const out = React.Children.toArray(children).filter((c) => !(React.isValidElement(c) && tagOf(c as MdElement) === 'input'));
+ if (typeof out[0] === 'string') out[0] = out[0].replace(/^\s+/, '');
+ return out;
+}
+
+function tableSource(children: React.ReactNode): ReplySource | null {
+ let head: ReplyPart[] | null = null;
+ const body: ReplyPart[][] = [];
+ for (const section of elementsOf(children)) {
+ const tag = tagOf(section);
+ if (tag !== 'thead' && tag !== 'tbody') return null;
+ for (const tr of elementsOf(section.props.children)) {
+ if (tagOf(tr) !== 'tr') return null;
+ const cells = elementsOf(tr.props.children).map((el) => part(el));
+ if (tag === 'thead') {
+ if (head) return null;
+ head = cells;
+ } else body.push(cells);
+ }
+ }
+ return head ? { kind: 'table', head, body } : null;
+}
+
+function listSource(node: HastNode, children: React.ReactNode): ReplySource {
+ const lis = elementsOf(children).filter((el) => tagOf(el) === 'li');
+ const task = lis.length > 0 && lis.every((li) => isTaskItem(li.props.node));
+ // A loose list wraps each item in <p>; unwrap it so the item reads as one line of text.
+ const inline = (li: MdElement): React.ReactNode => {
+ const kids = elementsOf(li.props.children);
+ const content = task ? taskContent(shown(li)) : shown(li);
+ // A tight task item's only element is its checkbox: that is not a loose item.
+ if (!kids.some((el) => tagOf(el) === 'p') || kids.some((el) => tagOf(el) !== 'p' && tagOf(el) !== 'input')) return content;
+ const ps = kids.filter((el) => tagOf(el) === 'p');
+ return ps.flatMap((p, i) => {
+ const c = task && i === 0 ? taskContent(shown(p)) : shown(p);
+ return i ? [' ', c] : [c];
+ });
+ };
+ const start = Number(node.properties?.start);
+ return {
+ kind: 'list',
+ items: lis.map((li) => part(li, inline(li))),
+ start: Number.isInteger(start) && start >= 0 ? start : 1,
+ ordered: node.tagName === 'ol',
+ task,
+ };
}
export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
content,
className = '',
isStreaming = false,
+ results,
+ messageId,
}) => {
+ // Never while streaming: the block appears when the final message arrives.
+ const smart = !isStreaming && !!messageId && resultBlocks(results).length > 0;
+ const slot = smart ? blockAt(results, { kind: 'slot' }) : null;
+
+ const listView = (node: HastNode | undefined, children: React.ReactNode, plain: React.ReactElement) => {
+ if (!smart || !node || node.data?.smartTop !== true || typeof node.data.smartIndex !== 'number') return plain;
+ const raw = blockAt(results, { kind: 'list', index: node.data.smartIndex, ordered: node.tagName === 'ol' });
+ if (!raw) return plain;
+ return <SmartResult raw={raw} reply={listSource(node, children)} messageId={messageId as string} fallback={plain} />;
+ };
+
return (
<div className={`markdown-content text-sm leading-relaxed text-zinc-200 ${className}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
+ rehypePlugins={smart ? [rehypeSmartIndex as never] : undefined}
components={{
// Pre element pass-through to let CodeBlock handle layout
pre: ({ children }) => <>{children}</>,
@@ -121,13 +206,19 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
},
// Tables
- table: ({ children }) => (
- <div className="my-3.5 overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-950/70 shadow-sm">
- <table className="w-full text-left border-collapse text-xs font-sans">
- {children}
- </table>
- </div>
- ),
+ table: ({ node, children }) => {
+ const plain = (
+ <div className="my-3.5 overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-950/70 shadow-sm">
+ <table className="w-full text-left border-collapse text-xs font-sans">
+ {children}
+ </table>
+ </div>
+ );
+ const index = (node as HastNode | undefined)?.data?.smartIndex;
+ const raw = smart && typeof index === 'number' ? blockAt(results, { kind: 'table', index }) : null;
+ const reply = raw ? tableSource(children) : null;
+ return raw && reply ? <SmartResult raw={raw} reply={reply} messageId={messageId as string} fallback={plain} /> : plain;
+ },
thead: ({ children }) => (
<thead className="bg-zinc-900/90 text-zinc-200 border-b border-zinc-800 font-medium">
{children}
@@ -193,22 +284,43 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
</em>
),
- // Lists
- ul: ({ children }) => (
- <ul className="list-disc list-outside pl-5 my-2.5 space-y-1 text-zinc-300">
- {children}
- </ul>
- ),
- ol: ({ children }) => (
- <ol className="list-decimal list-outside pl-5 my-2.5 space-y-1 text-zinc-300">
- {children}
- </ol>
- ),
- li: ({ children }) => (
- <li className="leading-relaxed pl-0.5">
- {React.Children.map(children, formatTextMentions)}
- </li>
- ),
+ // Lists. A GFM task list keeps its boxes in the bullet's place, read-only until it becomes a
+ // checklist block (results/Steps.tsx draws the same box).
+ ul: ({ node, children }) => {
+ const task = hasClass(node as HastNode | undefined, 'contains-task-list');
+ const plain = (
+ <ul className={`${task ? 'list-none pl-1' : 'list-disc list-outside pl-5'} my-2.5 space-y-1 text-zinc-300`}>
+ {children}
+ </ul>
+ );
+ return listView(node as HastNode | undefined, children, plain);
+ },
+ ol: ({ node, children }) => {
+ const task = hasClass(node as HastNode | undefined, 'contains-task-list');
+ const plain = (
+ <ol className={`${task ? 'list-none pl-1' : 'list-decimal list-outside pl-5'} my-2.5 space-y-1 text-zinc-300`}>
+ {children}
+ </ol>
+ );
+ return listView(node as HastNode | undefined, children, plain);
+ },
+ li: ({ node, children }) =>
+ isTaskItem(node as HastNode | undefined) ? (
+ <li className="flex items-start gap-2 leading-relaxed">
+ {React.Children.toArray(children).filter((c) => React.isValidElement(c) && tagOf(c as MdElement) === 'input')}
+ <span className="min-w-0 [overflow-wrap:anywhere]">{React.Children.map(taskContent(children), formatTextMentions)}</span>
+ </li>
+ ) : (
+ <li className="leading-relaxed pl-0.5">
+ {React.Children.map(children, formatTextMentions)}
+ </li>
+ ),
+ input: ({ node: _node, ...props }) =>
+ props.type === 'checkbox' ? (
+ <input type="checkbox" checked={!!props.checked} disabled readOnly className={checkClass} />
+ ) : (
+ <input {...props} />
+ ),
// Quotes & Dividers
blockquote: ({ children }) => (
@@ -233,6 +345,15 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
>
{content}
</ReactMarkdown>
+ {slot && (
+ <SmartResult
+ raw={slot}
+ reply={null}
+ messageId={messageId as string}
+ fallback={null}
+ renderText={(md) => <MarkdownRenderer content={md} />}
+ />
+ )}
{isStreaming && (
<span className="inline-block w-1.5 h-4 ml-0.5 align-middle bg-sky-400 animate-pulse rounded-sm" />
diff --git a/frontend/src/components/results/Comparison.tsx b/frontend/src/components/results/Comparison.tsx
new file mode 100644
index 00000000..6699234b
--- /dev/null
+++ b/frontend/src/components/results/Comparison.tsx
@@ -0,0 +1,233 @@
+import React, { useId, useMemo, useState } from 'react';
+import { ArrowDown, ArrowUp, ChevronsUpDown, MessageSquare, Minus, Plus } from 'lucide-react';
+import { ColumnRole, ComparisonBlock, Sort, nextSort, plainText, sortRows } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+// Pros and cons cells: split on ";", "•", "·" or a line break, else on commas when every part is short.
+export function shortList(text: string): string[] | null {
+ const t = plainText(text);
+ let parts = t.split(/\s*(?:;|•|·|\n)\s*/).filter(Boolean);
+ if (parts.length < 2) {
+ const commas = t.split(/\s*,\s*/).filter(Boolean);
+ parts = commas.length >= 2 && commas.every((p) => p.split(/\s+/).length <= 5) ? commas : [];
+ }
+ return parts.length >= 2 ? parts : null;
+}
+
+const ROLE_TINT: Partial<Record<ColumnRole, string>> = { pros: 'text-emerald-300', cons: 'text-rose-300' };
+
+const PickLabel: React.FC<{ reason: string | null; inline?: boolean; className?: string }> = ({ reason, inline, className = '' }) => (
+ <span
+ className={`${className} ${inline ? 'ml-1.5 ' : ''}rounded border border-sky-500/30 bg-sky-500/10 px-1 py-px align-[1px] text-[10px] font-medium leading-none text-sky-300 [box-decoration-break:clone]`}
+ title={reason ?? undefined}
+ >
+ Pick in this reply
+ </span>
+);
+
+/** A pros or cons cell in a stacked card: a short list with + or −, else the reply's cell. */
+const Cell: React.FC<{ role: ColumnRole; text: string; node: React.ReactNode }> = ({ role, text, node }) => {
+ const parts = role === 'pros' || role === 'cons' ? shortList(text) : null;
+ if (!parts) return <>{node}</>;
+ const Mark = role === 'pros' ? Plus : Minus;
+ return (
+ <ul role="list" className="space-y-0.5">
+ {parts.map((p, i) => (
+ <li key={i} className="flex items-start gap-1">
+ <Mark size={11} aria-hidden="true" className={`mt-[3px] shrink-0 ${ROLE_TINT[role]}`} />
+ <span>{p}</span>
+ </li>
+ ))}
+ </ul>
+ );
+};
+
+/**
+ * A bot reply's table, sortable. On wide screens it keeps the markdown table's exact geometry, so the
+ * swap from the streamed table moves nothing; below 640 px it becomes one card per row.
+ */
+export const Comparison: React.FC<RendererProps<ComparisonBlock>> = ({ block, reply, ask }) => {
+ const table = reply?.kind === 'table' ? reply : null;
+ // A slot block (declared by the bot, no table in the reply) draws its cells as plain text.
+ const head = block.columns.map((c, j) => table?.head[j]?.node ?? plainText(c.label));
+ const body = block.rows.map((r, i) => r.cells.map((c, j) => table?.body[i]?.[j]?.node ?? plainText(c)));
+ const [sort, setSort] = useState<Sort | null>(null);
+ const [said, setSaid] = useState('');
+ const uid = useId();
+ const order = useMemo(() => {
+ const pos = new Map(block.rows.map((r, i) => [r.id, i]));
+ return sortRows(block, sort).map((r) => pos.get(r.id) as number);
+ }, [block, sort]);
+ const labels = block.columns.map((c) => plainText(c.label));
+ const askRow = (i: number) => ask(`About ${plainText(block.rows[i].cells[0])} in your ${labels[0]} table: `);
+
+ const applySort = (next: Sort | null) => {
+ setSort(next);
+ setSaid(next ? `Sorted by ${labels[next.col]}, ${next.dir}` : "Back in the reply's order");
+ };
+
+ return (
+ <div data-smart-result="comparison" data-block-id={block.id}>
+ <span className="sr-only" aria-live="polite">
+ {said}
+ </span>
+
+ {/* 640 px and up: the reply's table with header sort buttons. */}
+ <div className="my-3.5 hidden sm:block">
+ <div className="overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-950/70 shadow-sm">
+ <table className="w-full text-left border-collapse text-xs font-sans">
+ <thead className="bg-zinc-900/90 text-zinc-200 border-b border-zinc-800 font-medium">
+ <tr>
+ {block.columns.map((col, j) => {
+ const dir = sort?.col === j ? sort.dir : null;
+ const Icon = dir === 'ascending' ? ArrowUp : dir === 'descending' ? ArrowDown : ChevronsUpDown;
+ return (
+ <th
+ key={col.key}
+ scope="col"
+ aria-sort={dir ?? 'none'}
+ className="relative px-3.5 py-2.5 text-xs font-semibold text-zinc-200 whitespace-nowrap"
+ >
+ <button
+ type="button"
+ onClick={() => applySort(nextSort(sort, j))}
+ className={`group font-semibold ${ROLE_TINT[col.role] ?? 'text-zinc-200'} hover:text-zinc-50 focus-visible:outline-none after:absolute after:inset-0 after:rounded-sm after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-sky-500/70`}
+ >
+ {head[j]}
+ {/* Zero width: the icon sits in the cell's padding, so headers don't widen. */}
+ <span className="inline-block w-0 align-[-1px]" aria-hidden="true">
+ <Icon
+ size={10}
+ className={`ml-1 ${dir ? 'text-sky-400' : 'text-zinc-600 group-hover:text-zinc-400 group-focus-visible:text-zinc-400'}`}
+ />
+ </span>
+ </button>
+ </th>
+ );
+ })}
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-zinc-800/60 font-normal text-zinc-300">
+ {order.map((i) => {
+ const row = block.rows[i];
+ const picked = row.id === block.highlight_row;
+ return (
+ <tr
+ key={row.id}
+ data-pick={picked ? '' : undefined}
+ className={`group/row transition-colors ${picked ? 'bg-sky-500/[0.07] hover:bg-sky-500/10' : 'hover:bg-zinc-900/50'}`}
+ >
+ {block.columns.map((col, j) => (
+ <td
+ key={col.key}
+ className={`px-3.5 py-2.5 text-xs text-zinc-300 leading-relaxed align-top ${picked && j === 0 ? 'shadow-[inset_2px_0_0_0_theme(colors.sky.400)]' : ''} ${j === block.columns.length - 1 ? 'relative' : ''}`}
+ >
+ {j === block.columns.length - 1 && (
+ // Over the cell's corner, shown on row hover or focus: the table keeps its size.
+ <button
+ type="button"
+ onClick={() => askRow(i)}
+ aria-label={`Ask about ${plainText(row.cells[0])}`}
+ title="Ask about this (fills in the message box, sends nothing)"
+ className="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-md border border-zinc-700 bg-zinc-900 text-zinc-400 opacity-0 hover:text-zinc-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70 group-hover/row:opacity-100 [@media(hover:none)]:hidden"
+ >
+ <MessageSquare size={12} />
+ </button>
+ )}
+ {picked && j === 0 ? (
+ // The label only takes room left on the cell's first line, so the table keeps the
+ // streamed reply's exact size (see .smart-pick in modern.css).
+ <div className="flex items-baseline">
+ <span>{body[i][j]}</span>
+ <span className="smart-pick min-w-0 flex-1">
+ <PickLabel reason={block.highlight_reason} inline className="smart-pick-full" />
+ <span
+ aria-hidden="true"
+ title={block.highlight_reason ? `Pick in this reply: ${block.highlight_reason}` : 'Pick in this reply'}
+ className="smart-pick-short ml-1.5 rounded border border-sky-500/30 bg-sky-500/10 px-1 py-px align-[1px] text-[10px] font-medium leading-none text-sky-300">
+ Pick
+ </span>
+ </span>
+ </div>
+ ) : (
+ body[i][j]
+ )}
+ </td>
+ ))}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ {/* Below 640 px: one card per row, label: value pairs, nothing clipped. */}
+ <div className="my-3.5 space-y-2 sm:hidden">
+ <div className="flex items-center gap-2">
+ <label htmlFor={`${uid}-sort`} className="shrink-0 text-[11px] text-zinc-500">
+ Sort by
+ </label>
+ <select
+ id={`${uid}-sort`}
+ value={sort ? `${sort.col}:${sort.dir}` : ''}
+ onChange={(e) => {
+ const [c, d] = e.target.value.split(':');
+ applySort(e.target.value ? { col: Number(c), dir: d as Sort['dir'] } : null);
+ }}
+ className="h-8 min-w-0 flex-1 truncate rounded-lg border border-zinc-800 bg-zinc-900 px-2 text-xs text-zinc-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70"
+ >
+ <option value="">Reply order</option>
+ {block.columns.map((col, j) => (
+ <React.Fragment key={col.key}>
+ <option value={`${j}:ascending`}>
+ {labels[j]}, {col.numeric ? 'low to high' : 'A to Z'}
+ </option>
+ <option value={`${j}:descending`}>
+ {labels[j]}, {col.numeric ? 'high to low' : 'Z to A'}
+ </option>
+ </React.Fragment>
+ ))}
+ </select>
+ </div>
+ <ul role="list" aria-label={labels[0]} className="space-y-2">
+ {order.map((i) => {
+ const row = block.rows[i];
+ const picked = row.id === block.highlight_row;
+ return (
+ <li
+ key={row.id}
+ data-pick={picked ? '' : undefined}
+ className={`rounded-xl border px-3 py-2.5 text-xs ${picked ? 'border-sky-500/40 bg-sky-500/[0.07]' : 'border-zinc-800 bg-zinc-950/70'}`}
+ >
+ <div className="text-[13px] font-semibold leading-snug text-zinc-100 [overflow-wrap:anywhere]">
+ {body[i][0]}
+ {picked && <PickLabel reason={block.highlight_reason} inline />}
+ </div>
+ <dl className="mt-1.5 grid grid-cols-[minmax(0,2fr)_minmax(0,3fr)] gap-x-3 gap-y-1">
+ {block.columns.slice(1).map((col, k) => (
+ <React.Fragment key={col.key}>
+ <dt className="text-zinc-500 [overflow-wrap:anywhere]">{head[k + 1]}</dt>
+ <dd className="text-zinc-300 leading-relaxed [overflow-wrap:anywhere]">
+ <Cell role={col.role} text={row.cells[k + 1]} node={body[i][k + 1]} />
+ </dd>
+ </React.Fragment>
+ ))}
+ </dl>
+ <button
+ type="button"
+ onClick={() => askRow(i)}
+ className="-mx-1 mt-1.5 flex items-center gap-1.5 rounded-md px-1 py-1 text-[11px] text-zinc-500 hover:text-zinc-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70"
+ >
+ <MessageSquare size={12} aria-hidden="true" />
+ Ask about this
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+
+ </div>
+ );
+};
diff --git a/frontend/src/components/results/SmartActions.tsx b/frontend/src/components/results/SmartActions.tsx
new file mode 100644
index 00000000..8cf562b2
--- /dev/null
+++ b/frontend/src/components/results/SmartActions.tsx
@@ -0,0 +1,26 @@
+import React, { useLayoutEffect, useState } from 'react';
+import { createPortal } from 'react-dom';
+
+/** The spot in a bot message's action row (next to "Copy markdown") where a block puts its buttons. */
+export const SmartActionsSlot: React.FC<{ messageId: string }> = ({ messageId }) => (
+ <span data-smart-actions={messageId} className="contents" />
+);
+
+/** Same look as the message's "Copy markdown" button. */
+export const actionClass =
+ 'px-2 py-1 rounded-md whitespace-nowrap shrink-0 hover:bg-zinc-900 hover:text-zinc-300 transition-colors flex items-center gap-1.5 text-[11px] cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70';
+
+/**
+ * A block's buttons go in its message's action row, so the reply itself keeps the streamed text's exact
+ * size when the block replaces it. Outside a chat (no action row), they sit right under the block.
+ */
+export const SmartActions: React.FC<{ messageId: string; children: React.ReactNode }> = ({ messageId, children }) => {
+ const [slot, setSlot] = useState<Element | null | undefined>(undefined);
+ useLayoutEffect(() => {
+ const found = [...document.querySelectorAll('[data-smart-actions]')].find((el) => el.getAttribute('data-smart-actions') === messageId);
+ setSlot(found ?? null);
+ }, [messageId]);
+ if (slot) return createPortal(children, slot);
+ if (slot === null) return <div className="mt-1.5 flex items-center gap-2 text-xs text-zinc-500">{children}</div>;
+ return null;
+};
diff --git a/frontend/src/components/results/SmartResult.tsx b/frontend/src/components/results/SmartResult.tsx
new file mode 100644
index 00000000..ba1f80f0
--- /dev/null
+++ b/frontend/src/components/results/SmartResult.tsx
@@ -0,0 +1,246 @@
+import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { Check, ChevronDown, Copy } from 'lucide-react';
+import type { SmartBlock } from '../../smartResults';
+import { readDoneSteps } from '../../smartResults';
+import { playSfx } from '../../audio/chiptune';
+import { ReplySource, resolveBlock } from './registry';
+import { blockCsv, blockJson, blockMarkdown } from './exporters';
+import { SmartActions, actionClass } from './SmartActions';
+
+/** "Ask about this": ChatView puts `text` in the composer and focuses it. Nothing is sent. */
+export const COMPOSE_PREFILL_EVENT = 'kwnt:compose-prefill';
+export const askAbout = (text: string) => window.dispatchEvent(new CustomEvent(COMPOSE_PREFILL_EVENT, { detail: { text } }));
+
+const textKey = (messageId: string) => `kwnt:smart-text:${messageId}`;
+const readAsText = (messageId: string) => {
+ try {
+ return localStorage.getItem(textKey(messageId)) === '1';
+ } catch {
+ return false;
+ }
+};
+const saveAsText = (messageId: string, on: boolean) => {
+ try {
+ if (on) localStorage.setItem(textKey(messageId), '1');
+ else localStorage.removeItem(textKey(messageId));
+ } catch {
+ // Private mode: the choice lasts until the page reloads.
+ }
+};
+
+const TYPE_LABEL: Record<SmartBlock['type'], string> = {
+ comparison: 'Comparison',
+ chart: 'Chart',
+ metrics: 'Key numbers',
+ facts: 'Facts',
+ steps: 'Steps',
+ cards: 'Links',
+ findings: 'Findings',
+ verification: 'Checks',
+ files: 'Files',
+};
+
+/** Where the block's data came from, in plain words (plan §A.6). */
+export function evidenceText(block: SmartBlock): string {
+ const p = block.provenance;
+ if (p.kind !== 'kwant_data') return 'From this reply';
+ if (p.ref.startsWith('task:')) return 'From task checks';
+ const id = p.ref.slice('attachment:'.length);
+ const file = block.type === 'files' ? block.items.find((f) => f.attachment_id === id) : undefined;
+ return file ? `From attachment ${file.name}` : block.type === 'files' && block.items.length > 1 ? 'From attachments' : 'From an attachment';
+}
+
+/** A block that throws while rendering shows the reply's markdown instead. */
+export class SmartResultBoundary extends React.Component<
+ { fallback: React.ReactNode; children: React.ReactNode },
+ { failed: boolean }
+> {
+ state = { failed: false };
+
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+
+ componentDidCatch(error: unknown) {
+ console.warn('A smart result failed to render, so the reply shows as text.', error);
+ }
+
+ render() {
+ return this.state.failed ? this.props.fallback : this.props.children;
+ }
+}
+
+type Format = 'Markdown' | 'CSV' | 'JSON';
+const FORMATS: Format[] = ['Markdown', 'CSV', 'JSON'];
+
+/** Copy data: one button, a three-item menu. Arrow keys move, Escape closes and returns focus. */
+const CopyData: React.FC<{ block: SmartBlock; messageId: string }> = ({ block, messageId }) => {
+ const [open, setOpen] = useState(false);
+ // The menu lines up with the button's left edge, or with its right edge when it would leave the screen.
+ const [flip, setFlip] = useState(false);
+ const menu = useRef<HTMLSpanElement>(null);
+ const [said, setSaid] = useState<{ ok: boolean; text: string } | null>(null);
+ const menuId = useId();
+ const wrap = useRef<HTMLSpanElement>(null);
+ const button = useRef<HTMLButtonElement>(null);
+ const items = useRef<(HTMLButtonElement | null)[]>([]);
+ const timer = useRef<number>();
+
+ useLayoutEffect(() => {
+ if (!open) return setFlip(false);
+ const r = menu.current?.getBoundingClientRect();
+ if (r && r.right > window.innerWidth - 8) setFlip(true);
+ }, [open]);
+ useEffect(() => {
+ if (!open) return;
+ items.current[0]?.focus();
+ const away = (e: PointerEvent) => {
+ if (!wrap.current?.contains(e.target as Node)) setOpen(false);
+ };
+ document.addEventListener('pointerdown', away);
+ return () => document.removeEventListener('pointerdown', away);
+ }, [open]);
+ useEffect(() => () => window.clearTimeout(timer.current), []);
+
+ const copy = async (f: Format) => {
+ setOpen(false);
+ button.current?.focus();
+ const text =
+ f === 'CSV' ? blockCsv(block) : f === 'JSON' ? blockJson(block) : blockMarkdown(block, block.type === 'steps' && block.variant === 'checklist' ? readDoneSteps(messageId, block) : undefined);
+ try {
+ await navigator.clipboard.writeText(text);
+ setSaid({ ok: true, text: `Copied as ${f}` });
+ playSfx('click');
+ } catch {
+ setSaid({ ok: false, text: 'Could not copy' });
+ }
+ window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => setSaid(null), 2000);
+ };
+
+ const onMenuKey = (e: React.KeyboardEvent) => {
+ const i = items.current.findIndex((el) => el === document.activeElement);
+ const move = (to: number) => {
+ e.preventDefault();
+ items.current[(to + FORMATS.length) % FORMATS.length]?.focus();
+ };
+ if (e.key === 'ArrowDown') move(i + 1);
+ else if (e.key === 'ArrowUp') move(i - 1);
+ else if (e.key === 'Home') move(0);
+ else if (e.key === 'End') move(FORMATS.length - 1);
+ else if (e.key === 'Escape' || e.key === 'Tab') {
+ if (e.key === 'Escape') e.preventDefault();
+ setOpen(false);
+ if (e.key === 'Escape') button.current?.focus();
+ }
+ };
+
+ return (
+ <span ref={wrap} className="relative">
+ <button
+ ref={button}
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded={open}
+ aria-controls={open ? menuId : undefined}
+ onClick={() => setOpen((o) => !o)}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ setOpen(true);
+ }
+ }}
+ className={actionClass}
+ >
+ {said?.ok ? <Check size={12} className="text-emerald-400" /> : <Copy size={12} />}
+ <span className={said?.ok ? 'font-medium text-emerald-400' : said ? 'text-rose-300' : ''}>{said?.ok ? 'Copied' : said ? 'Copy failed' : 'Copy data'}</span>
+ <ChevronDown size={11} aria-hidden="true" />
+ </button>
+ <span className="sr-only" aria-live="polite">
+ {said?.text ?? ''}
+ </span>
+ {open && (
+ <span
+ ref={menu}
+ id={menuId}
+ role="menu"
+ aria-label="Copy data as"
+ onKeyDown={onMenuKey}
+ className={`absolute bottom-full ${flip ? 'right-0' : 'left-0'} z-20 mb-1 flex min-w-[8rem] flex-col rounded-lg border border-zinc-800 bg-zinc-900 p-1 shadow-lg`}
+ >
+ {FORMATS.map((f, i) => (
+ <button
+ key={f}
+ ref={(el) => (items.current[i] = el)}
+ type="button"
+ role="menuitem"
+ tabIndex={-1}
+ onClick={() => copy(f)}
+ className="rounded-md px-2.5 py-1.5 text-left text-[11px] text-zinc-300 hover:bg-zinc-800 hover:text-zinc-100 focus:bg-zinc-800 focus:text-zinc-100 focus:outline-none"
+ >
+ {f}
+ </button>
+ ))}
+ </span>
+ )}
+ </span>
+ );
+};
+
+/** The footer every block shares, in the message's action row: Evidence, Show as text, Copy data. */
+const Footer: React.FC<{ block: SmartBlock; messageId: string; asText: boolean; onToggle: () => void }> = ({ block, messageId, asText, onToggle }) => (
+ <SmartActions messageId={messageId}>
+ <span className="min-w-0 px-1 text-[11px] text-zinc-500" data-evidence>
+ {evidenceText(block)}
+ </span>
+ <button type="button" aria-pressed={asText} onClick={onToggle} className={`${actionClass} ${asText ? 'bg-zinc-900 text-zinc-300' : ''}`}>
+ Show as text
+ </button>
+ <CopyData block={block} messageId={messageId} />
+ </SmartActions>
+);
+
+export interface SmartResultProps {
+ /** The message's block for this place, unchecked. */
+ raw: unknown;
+ /** The reply's own table or list here; null for the block drawn after the reply. */
+ reply: ReplySource | null;
+ messageId: string;
+ /** What the reply shows without a block: its markdown here, or (for a slot block) nothing. */
+ fallback: React.ReactNode;
+ /** Draws markdown, for "Show as text" on a block that has no text of its own in the reply. */
+ renderText?: (markdown: string) => React.ReactNode;
+}
+
+/**
+ * One block in its frame. A block that replaces the reply's table or list keeps that spot's exact size
+ * (its title is the group's accessible name, not a heading); a block after the reply shows its title.
+ */
+export const SmartResult: React.FC<SmartResultProps> = ({ raw, reply, messageId, fallback, renderText }) => {
+ const resolved = resolveBlock(raw, reply);
+ const [asText, setAsText] = useState(() => readAsText(messageId));
+ if (!resolved) return <>{fallback}</>;
+ const { block, renderer } = resolved;
+ const { Component } = renderer;
+ const slot = reply === null;
+ const text = slot ? renderText?.(blockMarkdown(block)) ?? null : fallback;
+ const toggle = () => {
+ saveAsText(messageId, !asText);
+ setAsText(!asText);
+ };
+ const name = block.title ?? TYPE_LABEL[block.type];
+
+ return (
+ <div role="group" aria-label={name} data-smart-frame={block.type} className={slot ? 'mt-3' : undefined}>
+ {slot && block.title && <div className="mb-1.5 text-xs font-semibold text-zinc-300">{block.title}</div>}
+ {asText ? (
+ text
+ ) : (
+ <SmartResultBoundary fallback={text}>
+ <Component block={block} messageId={messageId} reply={reply} ask={askAbout} />
+ </SmartResultBoundary>
+ )}
+ <Footer block={block} messageId={messageId} asText={asText} onToggle={toggle} />
+ </div>
+ );
+};
diff --git a/frontend/src/components/results/Steps.tsx b/frontend/src/components/results/Steps.tsx
new file mode 100644
index 00000000..38a2acd0
--- /dev/null
+++ b/frontend/src/components/results/Steps.tsx
@@ -0,0 +1,82 @@
+import React, { useId, useState } from 'react';
+import { StepsBlock, plainText, readDoneSteps, saveDoneSteps } from '../../smartResults';
+import type { RendererProps } from './registry';
+
+const boxClass =
+ 'mt-[5px] h-3.5 w-3.5 shrink-0 cursor-pointer rounded-sm accent-sky-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70 focus-visible:ring-offset-1 focus-visible:ring-offset-zinc-900';
+
+/**
+ * A reply's steps (numbered, tickable), checklist (ticks start from the reply's own [x]) or timeline (a
+ * rail in the list's marker gutter). Each keeps the streamed list's size. Ticks stay on this device.
+ */
+export const Steps: React.FC<RendererProps<StepsBlock>> = ({ block, messageId, reply }) => {
+ const list = reply?.kind === 'list' ? reply : null;
+ // A slot block draws its items as plain text.
+ const items = block.items.map((it, i) => list?.items[i]?.node ?? plainText(it.text));
+ const start = list?.start ?? 1;
+ const [done, setDone] = useState(() => readDoneSteps(messageId, block));
+ const uid = useId();
+
+ const toggle = (id: string) => {
+ const next = new Set(done);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ setDone(next);
+ saveDoneSteps(messageId, block, next);
+ };
+
+ if (block.variant === 'timeline') {
+ return (
+ <ol role="list" className="my-2.5 space-y-1 pl-5 text-zinc-300" data-smart-result="steps" data-variant="timeline" data-block-id={block.id}>
+ {block.items.map((it, i) => {
+ const last = i === block.items.length - 1;
+ return (
+ <li key={it.id} className="relative leading-relaxed pl-0.5">
+ {/* The rail sits where the list's bullets were, so nothing moves. */}
+ <span aria-hidden="true" className="absolute -left-[13px] top-[7px] h-2 w-2 rounded-full border border-sky-400/70 bg-zinc-950" />
+ {!last && <span aria-hidden="true" className="absolute -left-[10px] top-[17px] -bottom-[11px] w-px bg-zinc-700" />}
+ {list ? (
+ items[i]
+ ) : (
+ <>
+ <span className="font-medium text-zinc-200">{it.when}</span>
+ {': '}
+ {items[i]}
+ {it.owner && <span className="text-zinc-500"> (owner: {it.owner})</span>}
+ </>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ );
+ }
+
+ const numbered = block.variant === 'steps';
+ const List = list && !list.ordered ? 'ul' : 'ol';
+ return (
+ <div className="my-2.5" data-smart-result="steps" data-variant={block.variant} data-block-id={block.id}>
+ <List role="list" className={`space-y-1 text-zinc-300 ${numbered ? '' : 'pl-1'}`}>
+ {block.items.map((item, i) => {
+ const id = `${uid}-${item.id}`;
+ const on = done.has(item.id);
+ return (
+ <li key={item.id} className="flex items-start gap-2 leading-relaxed">
+ <input id={id} type="checkbox" checked={on} onChange={() => toggle(item.id)} className={boxClass} />
+ <label
+ htmlFor={id}
+ className={`min-w-0 cursor-pointer [overflow-wrap:anywhere] motion-safe:transition-colors ${on ? 'text-zinc-500 line-through decoration-zinc-600' : ''}`}
+ >
+ {numbered && <span className="mr-1 tabular-nums text-zinc-500">{start + i}.</span>}
+ {items[i]}
+ </label>
+ </li>
+ );
+ })}
+ </List>
+ <span className="sr-only" aria-live="polite">
+ {done.size} of {block.items.length} done
+ </span>
+ </div>
+ );
+};
diff --git a/frontend/src/components/results/exporters.ts b/frontend/src/components/results/exporters.ts
new file mode 100644
index 00000000..fbe3020a
--- /dev/null
+++ b/frontend/src/components/results/exporters.ts
@@ -0,0 +1,66 @@
+// Copy data (Markdown, CSV, JSON) for any block. Comparison and steps have their own shapes; every other
+// type exports its item list (or points, or checks) with one column per plain field. A renderer can
+// override this with `markdown` / `csv` in its registry entry.
+
+import type { SmartBlock } from '../../smartResults';
+import { comparisonCsv, csvCell, plainText, stepsMarkdown } from '../../smartResults';
+
+type Row = Record<string, unknown>;
+
+/** The block's rows as flat records: the thing Copy data copies. */
+export function blockRows(block: SmartBlock): Row[] {
+ switch (block.type) {
+ case 'comparison':
+ return block.rows.map((r) => Object.fromEntries(block.columns.map((c, j) => [plainText(c.label), plainText(r.cells[j])])));
+ case 'chart':
+ return block.points.map((p) => ({
+ [plainText(block.x.label)]: plainText(p.x),
+ ...Object.fromEntries(block.series.map((s, k) => [plainText(s.label), plainText(p.cells[k] ?? '')])),
+ }));
+ case 'verification':
+ return block.checks.map(({ label, kind, status, excerpt, checked_at }) => ({ check: label, kind, status, excerpt, checked_at }));
+ case 'findings':
+ return block.items.map(({ severity_text, title, detail, refs }) => ({
+ severity: severity_text,
+ title,
+ detail,
+ refs: refs.map((r) => (r.line == null ? r.path : `${r.path}:${r.line}`)).join(' '),
+ }));
+ case 'cards':
+ return block.items.map(({ title, url, description, meta }) => ({ title, url, description, meta: meta.join(' · ') }));
+ case 'files':
+ return block.items.map(({ name, mime, size_bytes }) => ({ name, type: mime, bytes: size_bytes }));
+ case 'steps':
+ return block.items.map(({ text, done, when, owner }) => ({ ...(when != null ? { when } : {}), step: text, ...(owner != null ? { owner } : {}), ...(done != null ? { done } : {}) }));
+ default:
+ return block.items.map(({ id: _id, ...rest }) => rest as Row);
+ }
+}
+
+const cell = (v: unknown) => (v == null ? '' : typeof v === 'string' ? plainText(v) : String(v));
+
+export function blockCsv(block: SmartBlock): string {
+ if (block.type === 'comparison') return comparisonCsv(block);
+ const rows = blockRows(block);
+ const keys = [...new Set(rows.flatMap((r) => Object.keys(r)))];
+ return [keys, ...rows.map((r) => keys.map((k) => cell(r[k])))].map((r) => r.map(csvCell).join(',')).join('\n');
+}
+
+const mdCell = (v: unknown) => cell(v).replace(/\|/g, '\\|').replace(/\n/g, ' ');
+
+export function blockMarkdown(block: SmartBlock, done?: Set<string>): string {
+ if (block.type === 'steps') return stepsMarkdown(block, done);
+ const rows = blockRows(block);
+ const keys = [...new Set(rows.flatMap((r) => Object.keys(r)))];
+ const table = [
+ `| ${keys.map(mdCell).join(' | ')} |`,
+ `| ${keys.map(() => '---').join(' | ')} |`,
+ ...rows.map((r) => `| ${keys.map((k) => mdCell(r[k])).join(' | ')} |`),
+ ].join('\n');
+ const head = block.title ? `**${plainText(block.title)}**\n\n` : '';
+ const tail = block.type === 'verification' || block.type === 'chart' ? (block.summary ? `\n\n${block.summary}` : '') : '';
+ return head + table + tail;
+}
+
+/** The block as checked, without internal ids, for pasting into other tools. */
+export const blockJson = (block: SmartBlock) => JSON.stringify(block, null, 2);
diff --git a/frontend/src/components/results/fixtures.ts b/frontend/src/components/results/fixtures.ts
new file mode 100644
index 00000000..fccd778e
--- /dev/null
+++ b/frontend/src/components/results/fixtures.ts
@@ -0,0 +1,289 @@
+// One sample bot reply and its `results` for every block type in plan §A.3, for building renderers and
+// for tests. Names, prices and numbers are made up. Every value is copied from the reply text, the way
+// the server copies it (or, for verification and files, from typed kwant data).
+
+import type { ResultSet, SmartBlock } from '../../smartResults';
+
+export interface Fixture {
+ /** The reply's markdown, as streamed and stored. */
+ reply: string;
+ results: ResultSet;
+}
+
+const table = (head: string[], rows: string[][]) =>
+ [`| ${head.join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.join(' | ')} |`)].join('\n');
+const set = (block: SmartBlock): ResultSet => ({ version: 1, blocks: [block] });
+const fromReply = { kind: 'reply_text' } as const;
+
+// comparison: a pick, plus pros and cons columns.
+const cmpHead = ['Host', 'Price per month', 'Build minutes', 'Pros', 'Cons'];
+const cmpRows = [
+ ['Pagecraft', 'EUR 19', '500', 'Cheapest; simple setup', 'No preview builds'],
+ ['**Northdeck**', 'EUR 49', '3,000', 'Preview builds; EU region; chat support', 'Two seats only'],
+ ['Fernlane', 'EUR 129', '10,000', 'SSO; audit log', 'Pricey under 10 people'],
+];
+const comparison: Fixture = {
+ reply: `Three hosts fit the docs site.\n\n${table(cmpHead, cmpRows)}\n\n**Northdeck** is the one I'd pick for five of us.`,
+ results: set({
+ id: 'b-cmp',
+ type: 'comparison',
+ title: 'Docs hosting',
+ source: { kind: 'markdown_table', index: 0 },
+ provenance: fromReply,
+ columns: [
+ { key: 'host', label: 'Host', numeric: false, unit: null, role: 'label' },
+ { key: 'price', label: 'Price per month', numeric: true, unit: 'EUR', role: 'value' },
+ { key: 'minutes', label: 'Build minutes', numeric: true, unit: null, role: 'value' },
+ { key: 'pros', label: 'Pros', numeric: false, unit: null, role: 'pros' },
+ { key: 'cons', label: 'Cons', numeric: false, unit: null, role: 'cons' },
+ ],
+ rows: cmpRows.map((cells, i) => ({ id: `r${i}`, cells })),
+ highlight_row: 'r1',
+ highlight_reason: 'named as the pick in this reply',
+ }),
+};
+
+// chart (line): a time-like first column, numeric series.
+const lineRows = [
+ ['Jul 2026', '1,240', '310'],
+ ['Aug 2026', '1,515', '362'],
+ ['Sep 2026', '1,890', '401'],
+ ['Oct 2026', '2,260', '455'],
+];
+const chartLine: Fixture = {
+ reply: `Signups kept climbing through October.\n\n${table(['Month', 'Signups', 'Paid'], lineRows)}\n\nOctober had 2,260 signups and 455 paid.`,
+ results: set({
+ id: 'b-line',
+ type: 'chart',
+ title: 'Signups by month',
+ source: { kind: 'markdown_table', index: 0 },
+ provenance: fromReply,
+ chart_kind: 'line',
+ x: { label: 'Month', kind: 'time' },
+ series: [
+ { key: 'signups', label: 'Signups', unit: null },
+ { key: 'paid', label: 'Paid', unit: null },
+ ],
+ points: lineRows.map(([x, a, b], i) => ({ id: `p${i}`, x, cells: [a, b], values: [Number(a.replace(/,/g, '')), Number(b)] })),
+ summary: 'October had 2,260 signups and 455 paid.',
+ }),
+};
+
+// chart (bar): categories, one series, no pick.
+const barRows = [
+ ['Search', '4,120'],
+ ['Newsletter', '1,980'],
+ ['Social', '1,310'],
+ ['Referral', '640'],
+];
+const chartBar: Fixture = {
+ reply: `Where October's visits came from:\n\n${table(['Channel', 'Visits'], barRows)}`,
+ results: set({
+ id: 'b-bar',
+ type: 'chart',
+ title: null,
+ source: { kind: 'markdown_table', index: 0 },
+ provenance: fromReply,
+ chart_kind: 'bar',
+ x: { label: 'Channel', kind: 'category' },
+ series: [{ key: 'visits', label: 'Visits', unit: null }],
+ points: barRows.map(([x, v], i) => ({ id: `p${i}`, x, cells: [v], values: [Number(v.replace(/,/g, ''))] })),
+ summary: null,
+ }),
+};
+
+// metrics: "**Label:** value" lines, the rest is the note.
+const metrics: Fixture = {
+ reply: `October in numbers:\n\n- **Revenue:** EUR 18,400, up 8% vs September\n- **Active teams:** 312\n- **Churn:** 2.1%, down from 2.6%`,
+ results: set({
+ id: 'b-metrics',
+ type: 'metrics',
+ title: null,
+ source: { kind: 'markdown_list', index: 0, ordered: false },
+ provenance: fromReply,
+ items: [
+ { id: 'm0', label: 'Revenue', value_text: 'EUR 18,400', value: 18400, unit: 'EUR', note: 'up 8% vs September' },
+ { id: 'm1', label: 'Active teams', value_text: '312', value: 312, unit: null, note: null },
+ { id: 'm2', label: 'Churn', value_text: '2.1%', value: 2.1, unit: '%', note: 'down from 2.6%' },
+ ],
+ }),
+};
+
+// facts: mostly non-numeric "**Label:** value" lines.
+const facts: Fixture = {
+ reply: `Here's the domain as it stands:\n\n- **Registrar:** Porkfish\n- **Renews:** 14 March 2027\n- **DNS host:** Northdeck\n- **Owner contact:** [email protected]`,
+ results: set({
+ id: 'b-facts',
+ type: 'facts',
+ title: 'docs.trailhead.shop',
+ source: { kind: 'markdown_list', index: 0, ordered: false },
+ provenance: fromReply,
+ items: [
+ { id: 'f0', label: 'Registrar', value: 'Porkfish' },
+ { id: 'f1', label: 'Renews', value: '14 March 2027' },
+ { id: 'f2', label: 'DNS host', value: 'Northdeck' },
+ { id: 'f3', label: 'Owner contact', value: '[email protected]' },
+ ],
+ }),
+};
+
+// steps: a numbered list.
+const stepTexts = [
+ 'Lower the TTL on the current `docs` record to 300 seconds, a day ahead.',
+ 'In the new host, add `docs.trailhead.shop` as a custom domain.',
+ 'Copy the CNAME target it shows you.',
+ 'At the registrar, point the `docs` CNAME at that target.',
+ 'Wait for the certificate to show **Active**, then open the site to check.',
+];
+const steps: Fixture = {
+ reply: `Moving DNS takes about 20 minutes.\n\n${stepTexts.map((t, i) => `${i + 1}. ${t}`).join('\n')}\n\nTell me when step 4 is done.`,
+ results: set({
+ id: 'b-steps',
+ type: 'steps',
+ title: null,
+ source: { kind: 'markdown_list', index: 0, ordered: true },
+ provenance: fromReply,
+ variant: 'steps',
+ items: stepTexts.map((text, i) => ({ id: `s${i}`, text, done: null, when: null, owner: null })),
+ }),
+};
+
+// checklist: a task list; `done` comes from the reply's [x].
+const checks: [boolean, string][] = [
+ [true, 'Export the old site as static files'],
+ [true, 'Create the Northdeck project'],
+ [false, 'Move the `docs` CNAME (owner: Sam)'],
+ [false, 'Turn on preview builds'],
+];
+const checklist: Fixture = {
+ reply: `Where the move stands:\n\n${checks.map(([d, t]) => `- [${d ? 'x' : ' '}] ${t}`).join('\n')}`,
+ results: set({
+ id: 'b-check',
+ type: 'steps',
+ title: 'Docs move',
+ source: { kind: 'markdown_list', index: 0, ordered: false },
+ provenance: fromReply,
+ variant: 'checklist',
+ items: checks.map(([done, text], i) => ({ id: `c${i}`, text, done, when: null, owner: text.includes('owner: Sam') ? 'Sam' : null })),
+ }),
+};
+
+// timeline: each item starts with a time-like label and a separator; the label is `when`.
+const events: [string, string][] = [
+ ['Mon 9 Nov', 'Freeze content on the old site'],
+ ['Tue 10 Nov', 'Switch DNS (Owner: Sam)'],
+ ['Wed 11 Nov', 'Check search console for errors'],
+ ['Fri 13 Nov', 'Cancel the old plan'],
+];
+const timeline: Fixture = {
+ reply: `Proposed schedule:\n\n${events.map(([w, t]) => `- ${w}: ${t}`).join('\n')}`,
+ results: set({
+ id: 'b-time',
+ type: 'steps',
+ title: null,
+ source: { kind: 'markdown_list', index: 0, ordered: false },
+ provenance: fromReply,
+ variant: 'timeline',
+ items: events.map(([when, text], i) => ({ id: `t${i}`, text, done: null, when, owner: text.includes('Owner: Sam') ? 'Sam' : null })),
+ }),
+};
+
+// cards: links from the reply, each with a description.
+const links: [string, string, string][] = [
+ ['Northdeck docs hosting', 'https://northdeck.example/docs', 'Preview builds on every pull request and an EU region.'],
+ ['Pagecraft pricing', 'https://pagecraft.example/pricing', 'The cheapest plan, with 500 build minutes a month.'],
+ ['Fernlane security', 'https://fernlane.example/security', 'SSO and audit log, priced for teams past ten people.'],
+];
+const cards: Fixture = {
+ reply: `Worth a read before we decide:\n\n${links.map(([t, u, d]) => `- [${t}](${u}) - ${d}`).join('\n')}`,
+ results: set({
+ id: 'b-cards',
+ type: 'cards',
+ title: null,
+ source: { kind: 'markdown_list', index: 0, ordered: false },
+ provenance: fromReply,
+ items: links.map(([title, url, description], i) => ({ id: `k${i}`, title, url, description, meta: [] })),
+ }),
+};
+
+// findings: severity tokens, refs from code spans.
+const findings: Fixture = {
+ reply: [
+ 'Review of the deploy script:',
+ '',
+ '- **High:** the token is written to the log in `scripts/deploy.sh:42`',
+ '- **Medium:** no timeout on the health check in `scripts/deploy.sh:88`',
+ '- **Nit:** unused variable `RETRIES`',
+ ].join('\n'),
+ results: set({
+ id: 'b-find',
+ type: 'findings',
+ title: null,
+ source: { kind: 'markdown_list', index: 0, ordered: false },
+ provenance: fromReply,
+ items: [
+ { id: 'x0', severity: 'high', severity_text: 'High', title: 'the token is written to the log', detail: 'the token is written to the log in `scripts/deploy.sh:42`', refs: [{ path: 'scripts/deploy.sh', line: 42 }] },
+ { id: 'x1', severity: 'medium', severity_text: 'Medium', title: 'no timeout on the health check', detail: 'no timeout on the health check in `scripts/deploy.sh:88`', refs: [{ path: 'scripts/deploy.sh', line: 88 }] },
+ { id: 'x2', severity: 'info', severity_text: 'Nit', title: 'unused variable', detail: 'unused variable `RETRIES`', refs: [] },
+ ],
+ }),
+};
+
+// verification: from the task's stored check results; drawn after the reply.
+const verification: Fixture = {
+ reply: 'The migration task is done. I ran the outcome checks; one is still failing.',
+ results: set({
+ id: 'b-verify',
+ type: 'verification',
+ title: null,
+ source: { kind: 'slot' },
+ provenance: { kind: 'kwant_data', ref: 'task:7f3a9c' },
+ target: { kind: 'task', id: '7f3a9c', title: 'Move docs to Northdeck' },
+ checks: [
+ { id: 'v0', label: 'docs.trailhead.shop answers 200', kind: 'http', status: 'passed', excerpt: 'HTTP 200 in 182 ms', checked_at: '2026-11-02T21:10:00Z' },
+ { id: 'v1', label: 'Certificate is valid', kind: 'command', status: 'passed', excerpt: 'notAfter=Feb 1 2027', checked_at: '2026-11-02T21:10:02Z' },
+ { id: 'v2', label: 'Old host redirects', kind: 'http', status: 'failed', excerpt: 'HTTP 404, expected 301', checked_at: '2026-11-02T21:10:03Z' },
+ { id: 'v3', label: 'Sitemap lists 120 pages', kind: 'command', status: 'pending', excerpt: null, checked_at: null },
+ ],
+ summary: '2 of 4 checks passed',
+ }),
+};
+
+// files: the message's own attachments; drawn after the reply.
+const files: Fixture = {
+ reply: "Here's the export and the redirect map.",
+ results: set({
+ id: 'b-files',
+ type: 'files',
+ title: null,
+ source: { kind: 'slot' },
+ provenance: { kind: 'kwant_data', ref: 'attachment:att-redirects' },
+ items: [
+ {
+ id: 'a0',
+ attachment_id: 'att-redirects',
+ name: 'redirects.csv',
+ mime: 'text/csv',
+ size_bytes: 2310,
+ preview: { kind: 'table', columns: ['from', 'to'], rows: [['/guide', '/docs/guide'], ['/faq', '/docs/faq']] },
+ },
+ { id: 'a1', attachment_id: 'att-notes', name: 'move-notes.md', mime: 'text/markdown', size_bytes: 840, preview: { kind: 'text', excerpt: '# Move notes\nFreeze content on Monday.' } },
+ { id: 'a2', attachment_id: 'att-shot', name: 'dns.png', mime: 'image/png', size_bytes: 48200, preview: { kind: 'image' } },
+ ],
+ }),
+};
+
+export const FIXTURES = {
+ comparison,
+ chartLine,
+ chartBar,
+ metrics,
+ facts,
+ steps,
+ checklist,
+ timeline,
+ cards,
+ findings,
+ verification,
+ files,
+} satisfies Record<string, Fixture>;
diff --git a/frontend/src/components/results/registry.ts b/frontend/src/components/results/registry.ts
new file mode 100644
index 00000000..4b857202
--- /dev/null
+++ b/frontend/src/components/results/registry.ts
@@ -0,0 +1,91 @@
+// Smart Results registry: block type → { validate, matches?, Component }. A type that isn't here, a block
+// its validator rejects, or one that doesn't match the reply's own table or list renders the reply's
+// markdown instead. Each renderer lives in its own file in this folder and exports its validator.
+//
+// Adding a renderer (plan §A.6):
+// 1. results/<Type>.tsx exports `valid<Type>(raw: unknown): <Type>Block | null` (build it from the
+// helpers in smartResults.ts: parseCommon, isText, optText, inRange, uniqueIds, isNum, isHttpUrl)
+// and a component taking RendererProps<<Type>Block>.
+// 2. Add one line to REGISTRY below.
+// 3. Fixtures for every type are in results/fixtures.ts.
+
+import type React from 'react';
+import type { BlockOf, BlockType, SmartBlock } from '../../smartResults';
+import { matchKey, validComparison, validSteps } from '../../smartResults';
+import { Comparison } from './Comparison';
+import { Steps } from './Steps';
+
+/** One cell or list item of the reply as react-markdown drew it, plus its plain text for matching. */
+export interface ReplyPart {
+ node: React.ReactNode;
+ text: string;
+}
+
+/** The reply's own table or list that a block replaces in place. */
+export type ReplySource =
+ | { kind: 'table'; head: ReplyPart[]; body: ReplyPart[][] }
+ | { kind: 'list'; items: ReplyPart[]; start: number; ordered: boolean; task: boolean };
+
+export interface RendererProps<B extends SmartBlock = SmartBlock> {
+ block: B;
+ messageId: string;
+ /** The table or list this block replaces; null for a `slot` block (drawn after the reply). */
+ reply: ReplySource | null;
+ /** "Ask about this": puts a prefilled question in the composer. It never sends. */
+ ask: (text: string) => void;
+}
+
+export interface Renderer<B extends SmartBlock> {
+ validate: (raw: unknown) => B | null;
+ /** Does the block stand for this table or list? Defaults to the same number of rows or items. */
+ matches?: (block: B, reply: ReplySource) => boolean;
+ Component: React.ComponentType<RendererProps<B>>;
+}
+
+export const sameText = (part: ReplyPart | undefined, text: string) => !!part && matchKey(part.text) === matchKey(text);
+
+const comparisonMatches = (block: BlockOf<'comparison'>, reply: ReplySource) =>
+ reply.kind === 'table' &&
+ reply.head.length === block.columns.length &&
+ reply.body.length === block.rows.length &&
+ reply.head.every((th, j) => sameText(th, block.columns[j].label)) &&
+ reply.body.every((cells, i) => cells.length === block.columns.length && cells.every((td, j) => sameText(td, block.rows[i].cells[j])));
+
+const stepsMatches = (block: BlockOf<'steps'>, reply: ReplySource) => {
+ if (reply.kind !== 'list' || reply.items.length !== block.items.length) return false;
+ // A task list is a checklist and only a checklist; numbered steps need a numbered list.
+ if (reply.task !== (block.variant === 'checklist')) return false;
+ if (block.variant === 'steps' && !reply.ordered) return false;
+ return reply.items.every((li, i) => {
+ const it = block.items[i];
+ return sameText(li, it.text) || (!!it.when && sameText(li, `${it.when} ${it.text}`));
+ });
+};
+
+export const REGISTRY: { [T in BlockType]?: Renderer<BlockOf<T>> } = {
+ comparison: { validate: validComparison, matches: comparisonMatches, Component: Comparison },
+ steps: { validate: validSteps, matches: stepsMatches, Component: Steps },
+ // Iris (smart-results-renderers): chart, metrics, facts, cards, findings, verification, files.
+};
+
+const count = (block: SmartBlock): number | null => {
+ const b = block as { rows?: unknown[]; points?: unknown[]; items?: unknown[] };
+ return (b.points ?? b.rows ?? b.items)?.length ?? null;
+};
+
+/** Same number of rows (table) or items (list) as the block. */
+export const defaultMatches = (block: SmartBlock, reply: ReplySource) =>
+ reply.kind === 'table' ? reply.body.length === count(block) : reply.items.length === count(block);
+
+/** The checked block and its renderer, or null: then the reply shows its markdown. */
+export function resolveBlock(raw: unknown, reply: ReplySource | null): { block: SmartBlock; renderer: Renderer<SmartBlock> } | null {
+ const type = (raw as { type?: unknown } | null)?.type;
+ if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(REGISTRY, type)) return null;
+ const renderer = REGISTRY[type as BlockType] as unknown as Renderer<SmartBlock> | undefined;
+ const block = renderer?.validate(raw);
+ if (!renderer || !block) return null;
+ const src = block.source.kind;
+ if (!reply) return src === 'slot' ? { block, renderer } : null;
+ if ((src === 'markdown_table') !== (reply.kind === 'table') || src === 'slot') return null;
+ return (renderer.matches ?? defaultMatches)(block, reply) ? { block, renderer } : null;
+}
diff --git a/frontend/src/smartResults.ts b/frontend/src/smartResults.ts
new file mode 100644
index 00000000..5100d6c6
--- /dev/null
+++ b/frontend/src/smartResults.ts
@@ -0,0 +1,504 @@
+// Smart Results: a bot reply's own structure (a table, a list, typed kwant data) shown as a block, such
+// as a sortable comparison, a chart or a checklist. The server picks at most one block per reply and
+// copies every value from the reply text or typed kwant data; the client checks the block again before
+// anything renders it (each renderer's `validate`, in results/registry.ts). Anything off, and the reply
+// renders as markdown. Contract: plan.md §A.3 (version 1).
+
+// ---------------------------------------------------------------------------------------------------
+// Contract (plan §A.3)
+
+export type Source =
+ | { kind: 'markdown_table'; index: number }
+ /** `ordered` absent means true (v1). Ordered and unordered lists are counted separately. */
+ | { kind: 'markdown_list'; index: number; ordered?: boolean }
+ /** No source in the text: drawn after the reply. */
+ | { kind: 'slot' };
+
+export type Provenance =
+ | { kind: 'reply_text' }
+ /** Declared by the bot with present_result and grounded against the reply. */
+ | { kind: 'bot_declared'; tool_call_id: string }
+ /** "task:<id>" or "attachment:<id>". */
+ | { kind: 'kwant_data'; ref: string };
+
+export interface BlockCommon<T extends string> {
+ id: string;
+ type: T;
+ title: string | null;
+ source: Source;
+ provenance: Provenance;
+}
+
+export type ColumnRole = 'label' | 'value' | 'pros' | 'cons' | 'note';
+export interface ComparisonColumn {
+ key: string;
+ label: string;
+ numeric: boolean;
+ unit: string | null;
+ /** Absent in v1 payloads: the first column is the label, the rest are values. */
+ role: ColumnRole;
+}
+export interface ComparisonRow {
+ id: string;
+ cells: string[];
+}
+/** 3–50 rows, 2–8 columns. */
+export interface ComparisonBlock extends BlockCommon<'comparison'> {
+ columns: ComparisonColumn[];
+ rows: ComparisonRow[];
+ highlight_row: string | null;
+ highlight_reason: string | null;
+}
+
+export interface ChartSeries {
+ key: string;
+ label: string;
+ unit: string | null;
+}
+export interface ChartPoint {
+ id: string;
+ /** The first cell, verbatim. */
+ x: string;
+ /** The row's other cells, verbatim, one per series. */
+ cells: string[];
+ /** The same cells as numbers; null where a cell has none. */
+ values: (number | null)[];
+}
+/** 3–60 points, 1–4 series. */
+export interface ChartBlock extends BlockCommon<'chart'> {
+ chart_kind: 'line' | 'bar';
+ x: { label: string; kind: 'time' | 'category' };
+ series: ChartSeries[];
+ points: ChartPoint[];
+ /** Quotes cells only; never a computed number. */
+ summary: string | null;
+}
+
+export interface MetricItem {
+ id: string;
+ label: string;
+ value_text: string;
+ value: number;
+ unit: string | null;
+ /** The rest of the item's text, verbatim ("up 8% vs October"). */
+ note: string | null;
+}
+/** 2–6 items. */
+export interface MetricsBlock extends BlockCommon<'metrics'> {
+ items: MetricItem[];
+}
+
+export interface FactItem {
+ id: string;
+ label: string;
+ value: string;
+}
+/** 3–12 items. */
+export interface FactsBlock extends BlockCommon<'facts'> {
+ items: FactItem[];
+}
+
+export type StepsVariant = 'steps' | 'checklist' | 'timeline';
+export interface StepItem {
+ id: string;
+ text: string;
+ /** checklist: ticked in the reply's markdown; null for the other variants. */
+ done: boolean | null;
+ /** timeline: the item's time label ("Mon 3 Nov", "Week 2"). */
+ when: string | null;
+ /** Only from a literal "Owner: X" or "(owner: X)". */
+ owner: string | null;
+}
+/** 3–20 items. */
+export interface StepsBlock extends BlockCommon<'steps'> {
+ /** Absent in v1 payloads: "steps". */
+ variant: StepsVariant;
+ items: StepItem[];
+}
+
+export interface CardItem {
+ id: string;
+ title: string;
+ /** An http(s) link from the reply, or null. */
+ url: string | null;
+ description: string;
+ meta: string[];
+}
+/** 3–12 items. */
+export interface CardsBlock extends BlockCommon<'cards'> {
+ items: CardItem[];
+}
+
+export type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';
+export interface FindingRef {
+ path: string;
+ line: number | null;
+}
+export interface FindingItem {
+ id: string;
+ severity: Severity;
+ /** The reply's own token: "Blocker", "P1", "Nit". */
+ severity_text: string;
+ title: string;
+ detail: string;
+ refs: FindingRef[];
+}
+/** 2–30 items. */
+export interface FindingsBlock extends BlockCommon<'findings'> {
+ items: FindingItem[];
+}
+
+export type CheckStatus = 'passed' | 'failed' | 'error' | 'pending';
+export interface VerificationCheck {
+ id: string;
+ label: string;
+ /** The outcome check kind: command, http, file_exists, file_contains, file_sha256. */
+ kind: string;
+ status: CheckStatus;
+ /** ≤ 300 chars, redacted like check output; untrusted text. */
+ excerpt: string | null;
+ /** ISO time; null while pending. */
+ checked_at: string | null;
+}
+/** 1–20 checks; source is always slot. */
+export interface VerificationBlock extends BlockCommon<'verification'> {
+ target: { kind: 'task'; id: string; title: string };
+ checks: VerificationCheck[];
+ /** "3 of 4 checks passed", counted from typed rows. */
+ summary: string;
+}
+
+export type FilePreview =
+ | { kind: 'table'; columns: string[]; rows: string[][] }
+ | { kind: 'text'; excerpt: string }
+ | { kind: 'image' }
+ | null;
+export interface FileItem {
+ id: string;
+ attachment_id: string;
+ name: string;
+ mime: string;
+ size_bytes: number;
+ preview: FilePreview;
+}
+/** 1–10 files; source is always slot. */
+export interface FilesBlock extends BlockCommon<'files'> {
+ items: FileItem[];
+}
+
+export type SmartBlock =
+ | ComparisonBlock
+ | ChartBlock
+ | MetricsBlock
+ | FactsBlock
+ | StepsBlock
+ | CardsBlock
+ | FindingsBlock
+ | VerificationBlock
+ | FilesBlock;
+export type BlockType = SmartBlock['type'];
+export type BlockOf<T extends BlockType> = Extract<SmartBlock, { type: T }>;
+
+/** `results` on a message: 0 or 1 block in 0.6.5. */
+export interface ResultSet {
+ version: 1;
+ blocks: SmartBlock[];
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Validation helpers, shared by every renderer's `validate`
+
+export const MAX_PAYLOAD = 64 * 1024;
+export const MAX_TEXT = 300;
+const HTML_TAG = /<\/?[a-z][^>]*>/i;
+export const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
+/** A string of at most `max` chars with no HTML tag; blank only when `empty`. */
+export const isText = (v: unknown, max = MAX_TEXT, empty = false): v is string =>
+ typeof v === 'string' && v.length <= max && (empty || v.trim() !== '') && !HTML_TAG.test(v);
+/** isText, or null/absent (returned as null). `undefined` means invalid. */
+export const optText = (v: unknown, max = MAX_TEXT): string | null | undefined => (v === null || v === undefined ? null : isText(v, max) ? v : undefined);
+export const isIndex = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0;
+export const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
+export const inRange = (a: unknown, min: number, max: number): a is unknown[] => Array.isArray(a) && a.length >= min && a.length <= max;
+export const uniqueIds = (items: unknown[]) =>
+ items.every((x) => isObj(x) && typeof x.id === 'string' && x.id !== '') && new Set(items.map((x) => (x as { id: string }).id)).size === items.length;
+/** An http(s) URL, or null. Anything else (javascript:, data:, relative) is not a link a block may show. */
+export const isHttpUrl = (v: unknown): v is string => {
+ if (typeof v !== 'string' || v.length > 2048) return false;
+ try {
+ const u = new URL(v);
+ return u.protocol === 'https:' || u.protocol === 'http:';
+ } catch {
+ return false;
+ }
+};
+
+export function parseSource(v: unknown): Source | null {
+ if (!isObj(v)) return null;
+ if (v.kind === 'slot') return { kind: 'slot' };
+ if (!isIndex(v.index)) return null;
+ if (v.kind === 'markdown_table') return { kind: 'markdown_table', index: v.index };
+ if (v.kind === 'markdown_list') {
+ if (v.ordered !== undefined && typeof v.ordered !== 'boolean') return null;
+ return { kind: 'markdown_list', index: v.index, ordered: v.ordered !== false };
+ }
+ return null;
+}
+
+/** Provenance; absent (v1 payloads) means the reply text. */
+export function parseProvenance(v: unknown): Provenance | null {
+ if (v === undefined || v === null) return { kind: 'reply_text' };
+ if (!isObj(v)) return null;
+ if (v.kind === 'reply_text') return { kind: 'reply_text' };
+ if (v.kind === 'bot_declared' && isText(v.tool_call_id, 200)) return { kind: 'bot_declared', tool_call_id: v.tool_call_id };
+ if (v.kind === 'kwant_data' && typeof v.ref === 'string' && /^(task|attachment):[\w.-]{1,120}$/.test(v.ref)) return { kind: 'kwant_data', ref: v.ref };
+ return null;
+}
+
+/** The fields every block has, checked; null if any is off. `title` absent (v1) means null. */
+export function parseCommon<T extends BlockType>(b: unknown, type: T): (BlockCommon<T> & Record<string, unknown>) | null {
+ if (!isObj(b) || b.type !== type || typeof b.id !== 'string' || b.id === '' || b.id.length > 120) return null;
+ const title = optText(b.title);
+ const source = parseSource(b.source);
+ const provenance = parseProvenance(b.provenance);
+ if (title === undefined || !source || !provenance) return null;
+ return { ...b, id: b.id, type, title, source, provenance };
+}
+
+/** The blocks of a message's `results`, unchecked, or [] when it isn't a v1 result set this client can trust. */
+export function resultBlocks(results: unknown): Record<string, unknown>[] {
+ if (!isObj(results) || results.version !== 1 || !Array.isArray(results.blocks)) return [];
+ try {
+ if (JSON.stringify(results).length > MAX_PAYLOAD) return [];
+ } catch {
+ return [];
+ }
+ const blocks = results.blocks.filter(isObj);
+ return uniqueIds(blocks) ? blocks : [];
+}
+
+/** Where a block sits: a table or list in the reply (as counted by rehypeSmartIndex), or after it. */
+export type Place = { kind: 'table'; index: number } | { kind: 'list'; index: number; ordered: boolean } | { kind: 'slot' };
+
+/** The unchecked block placed at `place`, if any. */
+export function blockAt(results: unknown, place: Place): Record<string, unknown> | null {
+ for (const b of resultBlocks(results)) {
+ const src = parseSource(b.source);
+ if (!src) continue;
+ if (place.kind === 'slot' && src.kind === 'slot') return b;
+ if (place.kind === 'table' && src.kind === 'markdown_table' && src.index === place.index) return b;
+ if (place.kind === 'list' && src.kind === 'markdown_list' && src.index === place.index && src.ordered === place.ordered) return b;
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Comparison and steps (Pixel)
+
+const ROLES: ColumnRole[] = ['label', 'value', 'pros', 'cons', 'note'];
+
+export function validComparison(raw: unknown): ComparisonBlock | null {
+ const b = parseCommon(raw, 'comparison');
+ if (!b || b.source.kind !== 'markdown_table') return null;
+ const cols = b.columns, rows = b.rows;
+ if (!inRange(cols, 2, 8) || !inRange(rows, 3, 50)) return null;
+ const columns: ComparisonColumn[] = [];
+ for (const [j, c] of cols.entries()) {
+ if (!isObj(c) || typeof c.key !== 'string' || !isText(c.label) || typeof c.numeric !== 'boolean') return null;
+ const unit = optText(c.unit, 40);
+ if (unit === undefined) return null;
+ const role = c.role === undefined || c.role === null ? (j === 0 ? 'label' : 'value') : c.role;
+ if (!ROLES.includes(role as ColumnRole)) return null;
+ columns.push({ key: c.key, label: c.label, numeric: c.numeric, unit, role: role as ColumnRole });
+ }
+ if (new Set(columns.map((c) => c.key)).size !== columns.length) return null;
+ const rowsOk = rows.every((r) => isObj(r) && inRange(r.cells, columns.length, columns.length) && r.cells.every((c) => isText(c, MAX_TEXT, true)));
+ if (!rowsOk || !uniqueIds(rows)) return null;
+ const typed = rows as unknown as ComparisonRow[];
+ const labels = typed.map((r) => plainText(r.cells[0]).toLowerCase());
+ if (new Set(labels).size !== labels.length) return null;
+ const hl = b.highlight_row ?? null;
+ if (hl !== null && !typed.some((r) => r.id === hl)) return null;
+ const why = optText(b.highlight_reason);
+ if (why === undefined) return null;
+ return {
+ id: b.id,
+ type: 'comparison',
+ title: b.title,
+ source: b.source,
+ provenance: b.provenance,
+ columns,
+ rows: typed.map((r) => ({ id: r.id, cells: [...r.cells] })),
+ highlight_row: hl as string | null,
+ highlight_reason: hl === null ? null : why,
+ };
+}
+
+const VARIANTS: StepsVariant[] = ['steps', 'checklist', 'timeline'];
+
+export function validSteps(raw: unknown): StepsBlock | null {
+ const b = parseCommon(raw, 'steps');
+ if (!b || b.source.kind !== 'markdown_list') return null;
+ const variant = (b.variant ?? 'steps') as StepsVariant;
+ if (!VARIANTS.includes(variant)) return null;
+ if (!inRange(b.items, 3, 20) || !uniqueIds(b.items)) return null;
+ const items: StepItem[] = [];
+ for (const it of b.items as Record<string, unknown>[]) {
+ const when = optText(it.when, 80), owner = optText(it.owner, 80);
+ const done = it.done ?? null;
+ if (!isText(it.text) || when === undefined || owner === undefined || (done !== null && typeof done !== 'boolean')) return null;
+ items.push({ id: it.id as string, text: it.text, done: variant === 'checklist' ? !!done : null, when, owner });
+ }
+ if (variant === 'timeline' && !items.every((i) => i.when)) return null;
+ return { id: b.id, type: 'steps', title: b.title, source: b.source, provenance: b.provenance, variant, items };
+}
+
+/** A cell's text without inline markdown: what sorting, CSV and matching use. */
+export function plainText(md: string): string {
+ return md
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/`([^`]*)`/g, '$1')
+ .replace(/(\*\*|__)(.+?)\1/g, '$2')
+ .replace(/(\*|_)(.+?)\1/g, '$2')
+ .replace(/~~(.+?)~~/g, '$1')
+ .replace(/\\([\\`*_{}[\]()#+\-.!|~])/g, '$1')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+/** Letters and digits only, so the rendered table and the block can be compared loosely. */
+export const matchKey = (s: string) => plainText(s).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');
+
+/**
+ * The number in a numeric cell: "EUR 1,200", "12 GB", "$9.50", "-3%", "1 200". NaN when there isn't one.
+ * The column's unit and a leading currency sign are dropped first.
+ */
+export function cellNumber(cell: string, unit: string | null): number {
+ let s = plainText(cell);
+ if (unit) s = s.split(unit).join(' ');
+ s = s.replace(/[€$£¥₹]/g, ' ').trim();
+ const m = /^([+-]?)\s*(\d{1,3}(?:[ ,\u00a0\u202f]\d{3})+|\d+)?(?:\.(\d+))?\s*%?$/.exec(s);
+ if (!m || (m[2] === undefined && m[3] === undefined)) return NaN;
+ const whole = (m[2] ?? '0').replace(/[ ,\u00a0\u202f]/g, '');
+ const n = Number(`${whole}.${m[3] ?? '0'}`);
+ return m[1] === '-' ? -n : n;
+}
+
+export type SortDir = 'ascending' | 'descending';
+export interface Sort {
+ col: number;
+ dir: SortDir;
+}
+
+/** Rows in the chosen order; the reply's order when `sort` is null. Cells without a number go last. */
+export function sortRows(block: ComparisonBlock, sort: Sort | null): ComparisonRow[] {
+ if (!sort) return block.rows;
+ const col = block.columns[sort.col];
+ if (!col) return block.rows;
+ const sign = sort.dir === 'ascending' ? 1 : -1;
+ const keyed = block.rows.map((r, i) => ({ r, i, v: r.cells[sort.col] ?? '' }));
+ if (col.numeric) {
+ const num = (v: string) => cellNumber(v, col.unit);
+ keyed.sort((a, b) => {
+ const x = num(a.v), y = num(b.v);
+ if (Number.isNaN(x) || Number.isNaN(y)) return Number.isNaN(x) === Number.isNaN(y) ? a.i - b.i : Number.isNaN(x) ? 1 : -1;
+ return (x - y) * sign || a.i - b.i;
+ });
+ } else {
+ const coll = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
+ keyed.sort((a, b) => coll.compare(plainText(a.v), plainText(b.v)) * sign || a.i - b.i);
+ }
+ return keyed.map((k) => k.r);
+}
+
+/** The next sort when a column header is pressed: ascending, then descending, then the reply's order. */
+export function nextSort(cur: Sort | null, col: number): Sort | null {
+ if (!cur || cur.col !== col) return { col, dir: 'ascending' };
+ return cur.dir === 'ascending' ? { col, dir: 'descending' } : null;
+}
+
+export const csvCell = (s: string) => {
+ // A leading = + - @ would run as a formula in a spreadsheet; a plain signed number is left alone.
+ const v = /^[=+\-@\t\r]/.test(s) && !/^[+-]?\d[\d.,\s]*%?$/.test(s) ? `'${s}` : s;
+ return /[",\n\r]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
+};
+
+/** The comparison as CSV, header first, rows in the order shown. */
+export function comparisonCsv(block: ComparisonBlock, rows: ComparisonRow[] = block.rows): string {
+ const lines = [block.columns.map((c) => plainText(c.label)), ...rows.map((r) => r.cells.map(plainText))];
+ return lines.map((l) => l.map(csvCell).join(',')).join('\n') + '\n';
+}
+
+/** The steps as markdown, as the reply wrote them: numbered, or a task list for a checklist. */
+export const stepsMarkdown = (block: StepsBlock, done?: Set<string>) =>
+ block.items
+ .map((it, i) =>
+ block.variant === 'checklist'
+ ? `- [${(done ? done.has(it.id) : it.done) ? 'x' : ' '}] ${it.text}`
+ : block.variant === 'timeline'
+ ? `- ${it.when}: ${it.text}`
+ : `${i + 1}. ${it.text}`,
+ )
+ .join('\n') + '\n';
+
+export const stepsStorageKey = (messageId: string, blockId: string) => `kwnt:steps:${messageId}:${blockId}`;
+
+/** Ticked step ids for this message's block: what the person ticked here, else what the reply ticked. */
+export function readDoneSteps(messageId: string, block: StepsBlock): Set<string> {
+ const fromReply = new Set(block.items.filter((i) => i.done).map((i) => i.id));
+ try {
+ const stored = localStorage.getItem(stepsStorageKey(messageId, block.id));
+ if (stored === null) return fromReply;
+ const raw = JSON.parse(stored);
+ const ids = new Set(block.items.map((i) => i.id));
+ return new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string' && ids.has(x)) : []);
+ } catch {
+ return fromReply;
+ }
+}
+
+export function saveDoneSteps(messageId: string, block: StepsBlock, done: Set<string>) {
+ try {
+ const key = stepsStorageKey(messageId, block.id);
+ const fromReply = block.items.filter((i) => i.done).map((i) => i.id);
+ if (done.size === fromReply.length && fromReply.every((id) => done.has(id))) localStorage.removeItem(key);
+ else localStorage.setItem(key, JSON.stringify([...done]));
+ } catch {
+ // Private mode or a full store: the ticks just don't outlast the page.
+ }
+}
+
+/** The bits of a parsed (hast) node this file reads. */
+export interface HastNode {
+ type: string;
+ tagName?: string;
+ value?: string;
+ children?: HastNode[];
+ properties?: Record<string, unknown>;
+ data?: Record<string, unknown>;
+}
+
+export const hastText = (n: HastNode | undefined): string =>
+ !n ? '' : n.type === 'text' ? n.value ?? '' : (n.children ?? []).map(hastText).join('');
+
+/**
+ * Numbers the reply's tables, its ordered lists and its unordered lists, each in its own count, in
+ * document order at any depth (pre-order, nested included), the way the server counts `source.index`.
+ * Code fences and raw HTML never become these elements.
+ */
+export function rehypeSmartIndex() {
+ return (tree: HastNode) => {
+ let tables = 0;
+ let ordered = 0;
+ let unordered = 0;
+ const walk = (n: HastNode, parent: HastNode | null) => {
+ if (n.type === 'element' && n.tagName === 'table') n.data = { ...n.data, smartIndex: tables++ };
+ if (n.type === 'element' && (n.tagName === 'ol' || n.tagName === 'ul')) {
+ const isOl = n.tagName === 'ol';
+ n.data = { ...n.data, smartIndex: isOl ? ordered++ : unordered++, smartOrdered: isOl, smartTop: parent?.type === 'root' };
+ }
+ n.children?.forEach((c) => walk(c, n));
+ };
+ walk(tree, null);
+ };
+}
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
index 66b11ff4..3b503185 100644
--- a/frontend/src/styles/modern.css
+++ b/frontend/src/styles/modern.css
@@ -238,3 +238,33 @@
padding-top: 1rem;
}
}
+
+/* Smart results: the "Pick in this reply" label in a table row. It sits in whatever room is left on the
+ first cell's first line and adds no width (inline-size containment), so the table keeps the streamed
+ reply's exact geometry. Short of room it says "Pick"; with almost none, the row's tint and bar show
+ the pick and the full label stays for screen readers. */
+.smart-pick {
+ container-type: inline-size;
+ overflow: clip;
+ white-space: nowrap;
+}
+.smart-pick-short {
+ display: none;
+}
+@container (max-width: 7rem) {
+ .smart-pick-full {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ border-width: 0;
+ }
+}
+@container (min-width: 2.5rem) and (max-width: 7rem) {
+ .smart-pick-short {
+ display: inline-block;
+ }
+}
diff --git a/frontend/tests/decisionsBlock.test.mjs b/frontend/tests/decisionsBlock.test.mjs
index 639c99f0..5e666743 100644
--- a/frontend/tests/decisionsBlock.test.mjs
+++ b/frontend/tests/decisionsBlock.test.mjs
@@ -83,7 +83,7 @@ test('a block being streamed in is hidden, including a half-typed tag', () => {
test('the chat renders the cleaned text and keeps client-read chips read-only', () => {
assert.match(src, /messageDecisions\(msg\.text, msg\.meta\)/);
- assert.match(src, /<MarkdownRenderer content=\{text\} \/>/);
+ assert.match(src, /<MarkdownRenderer content=\{text\} results=\{msg\.results\} messageId=\{msg\.id\} \/>/);
assert.match(src, /onChangeDecision && !shownDecisions\?\.readOnly/);
assert.match(src, /hideStreamingDecisions\(stripDiscussionMarkers\(streamingText\)\)/);
assert.match(src, /handleCopy\(text, msg\.id\)/);
diff --git a/frontend/tests/smartResults.test.mjs b/frontend/tests/smartResults.test.mjs
new file mode 100644
index 00000000..41180295
--- /dev/null
+++ b/frontend/tests/smartResults.test.mjs
@@ -0,0 +1,622 @@
+// Smart Results (0.6.5): a bot reply's table or list shown as a block (a sortable comparison, steps, a
+// checklist, a timeline; Iris adds the other types), from the `results` the server attaches. Always on:
+// there is no setting. Anything the client can't trust, and the reply renders as plain markdown.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+g.matchMedia = g.window.matchMedia;
+g.window.HTMLElement.prototype.scrollIntoView ??= () => {};
+const clipboard = { text: null, writeText: async (t) => void (clipboard.text = t) };
+Object.defineProperty(g.navigator, 'clipboard', { value: clipboard, configurable: true });
+g.fetch = g.window.fetch = async () => new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export * from './src/smartResults';
+ export { MarkdownRenderer } from './src/components/MarkdownRenderer';
+ export { SmartResultBoundary } from './src/components/results/SmartResult';
+ export { SmartActionsSlot } from './src/components/results/SmartActions';
+ export { REGISTRY, resolveBlock } from './src/components/results/registry';
+ export { FIXTURES } from './src/components/results/fixtures';
+ export { blockCsv, blockMarkdown, blockRows } from './src/components/results/exporters';
+ export { COMPOSE_PREFILL_EVENT, evidenceText } from './src/components/results/SmartResult';
+ export { shortList } from './src/components/results/Comparison';
+`);
+const { React, createRoot } = m;
+const h = React.createElement;
+
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mounted = new Set();
+afterEach(() => {
+ for (const v of mounted) v.done();
+ mounted.clear();
+ localStorage.clear();
+});
+async function mount(el) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const v = {
+ host,
+ render: async (e) => {
+ root.render(e);
+ await settle();
+ },
+ done: () => {
+ root.unmount();
+ host.remove();
+ },
+ };
+ mounted.add(v);
+ await v.render(el);
+ return v;
+}
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const md = (content, extra = {}) => m.renderToStaticMarkup(h(m.MarkdownRenderer, { content, ...extra }));
+
+// ---------------------------------------------------------------------------
+// Fixtures that follow plan.md's payload v1 exactly
+
+const REPLY = `Here are the three plans.
+
+| Plan | Price | Seats |
+|---|---|---|
+| A | EUR 12 | 1 |
+| **B** | EUR 100 | 5 |
+| C | EUR 20 | 10 |
+
+I recommend B for a team of five.`;
+
+const comparison = (over = {}) => ({
+ id: 'b0',
+ type: 'comparison',
+ source: { kind: 'markdown_table', index: 0 },
+ columns: [
+ { key: 'c0', label: 'Plan', numeric: false, unit: null },
+ { key: 'c1', label: 'Price', numeric: true, unit: 'EUR' },
+ { key: 'c2', label: 'Seats', numeric: true, unit: null },
+ ],
+ rows: [
+ { id: 'r0', cells: ['A', 'EUR 12', '1'] },
+ { id: 'r1', cells: ['**B**', 'EUR 100', '5'] },
+ { id: 'r2', cells: ['C', 'EUR 20', '10'] },
+ ],
+ highlight_row: 'r1',
+ highlight_reason: 'named as the pick in this reply',
+ provenance: { kind: 'reply_text' },
+ ...over,
+});
+const set = (...blocks) => ({ version: 1, blocks });
+
+const STEPS_REPLY = `To set it up:
+
+1. Open Settings.
+2. Turn on **Smart results**.
+3. Send a reply with a table.
+
+That's it.`;
+const steps = (over = {}) => ({
+ id: 'b1',
+ type: 'steps',
+ source: { kind: 'markdown_list', index: 0 },
+ items: [
+ { id: 's0', text: 'Open Settings.' },
+ { id: 's1', text: 'Turn on **Smart results**.' },
+ { id: 's2', text: 'Send a reply with a table.' },
+ ],
+ provenance: { kind: 'reply_text' },
+ ...over,
+});
+
+const bodyRows = (host) => [...host.querySelectorAll('[data-smart-result="comparison"] tbody tr')].map((tr) => tr.querySelector('td').textContent.replace(/Pick in this reply(Pick)?$/, ''));
+const header = (host, label) => [...host.querySelectorAll('th')].find((th) => th.textContent.includes(label));
+
+// ---------------------------------------------------------------------------
+// Off path: identical to 0.6.4
+
+test('no results, results null or a streaming reply: the exact 0.6.4 markup', () => {
+ const plain = md(REPLY);
+ assert.match(plain, /<table/);
+ assert.doesNotMatch(plain, /data-smart-result/);
+ assert.equal(md(REPLY, { results: null, messageId: 'm1' }), plain);
+ assert.equal(md(REPLY, { results: undefined, messageId: 'm1' }), plain);
+ // Streaming never shows a block, even with one on hand.
+ assert.equal(md(REPLY, { results: set(comparison()), messageId: 'm1', isStreaming: true }), md(REPLY, { isStreaming: true }));
+});
+
+// ---------------------------------------------------------------------------
+// Comparison
+
+test('a valid comparison replaces table #0 and shows the reply’s own cells', async () => {
+ const v = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: 'm1' }));
+ const block = v.host.querySelector('[data-smart-result="comparison"]');
+ assert.ok(block, 'block rendered');
+ assert.equal(v.host.querySelectorAll('table').length, 1, 'one table: the block’s, not the markdown one too');
+ assert.deepEqual(bodyRows(v.host), ['A', 'B', 'C']);
+ // The cell is the reply's rendered markdown: **B** is bold, not asterisks.
+ assert.equal(block.querySelector('tbody tr:nth-child(2) td strong')?.textContent, 'B');
+ assert.doesNotMatch(block.textContent, /\*\*/);
+ // The prose around the table is untouched.
+ assert.match(v.host.textContent, /Here are the three plans\..*I recommend B for a team of five\./s);
+ // Wide view keeps the markdown table's classes, so the swap from the streamed table moves nothing.
+ const wrap = block.querySelector('.overflow-x-auto');
+ assert.equal(wrap.className, 'overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-950/70 shadow-sm');
+ assert.equal(wrap.querySelector('table').className, 'w-full text-left border-collapse text-xs font-sans');
+});
+
+test('the highlighted row carries one “Pick in this reply” label per view', async () => {
+ const v = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: 'm1' }));
+ const picked = [...v.host.querySelectorAll('tr[data-pick]')];
+ assert.equal(picked.length, 1);
+ assert.match(picked[0].textContent, /^B\s*Pick in this reply/);
+ assert.equal(picked[0].querySelectorAll('.smart-pick-full').length, 1, 'one label a screen reader reads, however narrow');
+ assert.equal(picked[0].querySelector('.smart-pick-short')?.getAttribute('aria-hidden'), 'true');
+ const cards = [...v.host.querySelectorAll('li[data-pick]')];
+ assert.equal(cards.length, 1, 'the narrow view marks the same row');
+ assert.equal(v.host.querySelectorAll('tr:not([data-pick])').length, 3, 'header + two plain rows');
+ // No highlight in the block, no label.
+ const w = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison({ highlight_row: null, highlight_reason: null })), messageId: 'm1' }));
+ assert.doesNotMatch(w.host.textContent, /Pick in this reply/);
+});
+
+test('header buttons sort ascending, descending, then back; numbers sort as numbers', async () => {
+ const v = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: 'm1' }));
+ const price = () => header(v.host, 'Price');
+ const seats = () => header(v.host, 'Seats');
+ assert.equal(price().getAttribute('aria-sort'), 'none');
+ assert.equal(price().querySelector('button').textContent, 'Price', 'the button is named by its column');
+ await click(price().querySelector('button'));
+ assert.equal(price().getAttribute('aria-sort'), 'ascending');
+ assert.deepEqual(bodyRows(v.host), ['A', 'C', 'B'], 'EUR 12, EUR 20, EUR 100');
+ await click(price().querySelector('button'));
+ assert.equal(price().getAttribute('aria-sort'), 'descending');
+ assert.deepEqual(bodyRows(v.host), ['B', 'C', 'A']);
+ await click(price().querySelector('button'));
+ assert.equal(price().getAttribute('aria-sort'), 'none');
+ assert.deepEqual(bodyRows(v.host), ['A', 'B', 'C'], 'the reply’s order again');
+ await click(seats().querySelector('button'));
+ assert.deepEqual(bodyRows(v.host), ['A', 'B', 'C'], '1, 5, 10 (not 1, 10, 5)');
+ assert.equal(price().getAttribute('aria-sort'), 'none', 'only the active column says sorted');
+ assert.match(v.host.querySelector('[aria-live]').textContent, /Sorted by Seats, ascending/);
+ // The narrow view's select shares the order.
+ assert.equal(v.host.querySelector('select').value, '2:ascending');
+});
+
+test('sorting helpers: units, separators, signs, text and blanks', () => {
+ assert.equal(m.cellNumber('EUR 1,200', 'EUR'), 1200);
+ assert.equal(m.cellNumber('$9.50', null), 9.5);
+ assert.equal(m.cellNumber('-3%', null), -3);
+ assert.equal(m.cellNumber('1 200', null), 1200);
+ assert.equal(m.cellNumber('12 GB', 'GB'), 12);
+ assert.ok(Number.isNaN(m.cellNumber('n/a', null)));
+ const b = comparison({
+ rows: [
+ { id: 'r0', cells: ['A', 'n/a', '1'] },
+ { id: 'r1', cells: ['b', 'EUR 9', '2'] },
+ { id: 'r2', cells: ['C', 'EUR 10', '3'] },
+ ],
+ highlight_row: null,
+ });
+ assert.deepEqual(m.sortRows(b, { col: 1, dir: 'ascending' }).map((r) => r.id), ['r1', 'r2', 'r0'], 'a cell without a number goes last');
+ assert.deepEqual(m.sortRows(b, { col: 1, dir: 'descending' }).map((r) => r.id), ['r2', 'r1', 'r0'], 'last both ways');
+ assert.deepEqual(m.sortRows(b, { col: 0, dir: 'ascending' }).map((r) => r.id), ['r0', 'r1', 'r2'], 'text ignores case');
+ assert.deepEqual(m.nextSort(null, 1), { col: 1, dir: 'ascending' });
+ assert.deepEqual(m.nextSort({ col: 1, dir: 'ascending' }, 1), { col: 1, dir: 'descending' });
+ assert.equal(m.nextSort({ col: 1, dir: 'descending' }, 1), null);
+ assert.deepEqual(m.nextSort({ col: 1, dir: 'descending' }, 0), { col: 0, dir: 'ascending' });
+});
+
+const copyData = async (host, format) => {
+ // Its label says "Copied" for 2 s after a copy.
+ const button = host.querySelector('button[aria-haspopup="menu"]');
+ assert.ok(button, 'Copy data is there');
+ await click(button);
+ assert.equal(button.getAttribute('aria-expanded'), 'true');
+ const item = [...host.querySelectorAll('[role="menu"] [role="menuitem"]')].find((b) => b.textContent === format);
+ assert.deepEqual([...host.querySelectorAll('[role="menuitem"]')].map((b) => b.textContent), ['Markdown', 'CSV', 'JSON']);
+ await click(item);
+ assert.equal(host.querySelector('[role="menu"]'), null, 'the menu closes after copying');
+ return button;
+};
+
+test('Copy data copies Markdown, CSV or JSON; spreadsheet formulas are neutralised', async () => {
+ const v = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: 'm1' }));
+ assert.equal([...v.host.querySelectorAll('button')].filter((b) => b.textContent.includes('Copy data')).length, 1, 'one button for both views');
+ const button = await copyData(v.host, 'CSV');
+ assert.equal(clipboard.text, 'Plan,Price,Seats\nA,EUR 12,1\nB,EUR 100,5\nC,EUR 20,10\n');
+ assert.match(button.textContent, /Copied/);
+ await copyData(v.host, 'Markdown');
+ assert.equal(clipboard.text, '| Plan | Price | Seats |\n| --- | --- | --- |\n| A | EUR 12 | 1 |\n| B | EUR 100 | 5 |\n| C | EUR 20 | 10 |');
+ await copyData(v.host, 'JSON');
+ const json = JSON.parse(clipboard.text);
+ assert.equal(json.type, 'comparison');
+ assert.deepEqual(json.rows[1].cells, ['**B**', 'EUR 100', '5']);
+ // Escape closes the menu and puts focus back on the button.
+ await click(button);
+ const menu = v.host.querySelector('[role="menu"]');
+ menu.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ assert.equal(v.host.querySelector('[role="menu"]'), null);
+ assert.equal(document.activeElement, button);
+ const risky = comparison({
+ rows: [
+ { id: 'r0', cells: ['=HYPERLINK("x")', '-3', '1'] },
+ { id: 'r1', cells: ['say "hi", ok', '+2', '2'] },
+ { id: 'r2', cells: ['-1+cmd', '@sum', '3'] },
+ ],
+ highlight_row: null,
+ });
+ assert.equal(m.comparisonCsv(risky), `Plan,Price,Seats\n"'=HYPERLINK(""x"")",-3,1\n"say ""hi"", ok",+2,2\n'-1+cmd,'@sum,3\n`);
+});
+
+test('below 640 px the same rows are label: value cards (both views rendered, CSS picks one)', async () => {
+ const v = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: 'm1' }));
+ const wide = v.host.querySelector('[data-smart-result="comparison"] > div.hidden.sm\\:block');
+ const narrow = v.host.querySelector('[data-smart-result="comparison"] > div.sm\\:hidden');
+ assert.ok(wide && narrow);
+ const cards = [...narrow.querySelectorAll('ul > li')];
+ assert.equal(cards.length, 3);
+ assert.deepEqual([...cards[0].querySelectorAll('dt')].map((d) => d.textContent), ['Price', 'Seats']);
+ assert.deepEqual([...cards[0].querySelectorAll('dd')].map((d) => d.textContent), ['EUR 12', '1']);
+ assert.ok(cards.every((c) => /overflow-wrap:anywhere/.test(c.innerHTML)), 'long strings wrap instead of clipping');
+});
+
+test('in a chat, the block’s buttons go in the message’s action row, so the reply keeps its size', async () => {
+ const Message = ({ id, content, results }) =>
+ h('div', null, h('div', { id: 'bubble' }, h(m.MarkdownRenderer, { content, results, messageId: id })), h('div', { id: 'row' }, h('button', null, 'Copy markdown'), h(m.SmartActionsSlot, { messageId: id })));
+ const other = document.createElement('span');
+ other.setAttribute('data-smart-actions', 'm1-other');
+ document.body.append(other);
+ const v = await mount(h('div', null, h(Message, { id: 'm1', content: REPLY, results: set(comparison()) }), h(Message, { id: 'm7', content: STEPS_REPLY, results: set(steps()) })));
+ const rows = [...v.host.querySelectorAll('#row')];
+ for (const row of rows) {
+ assert.deepEqual([...row.querySelectorAll('button')].map((b) => b.textContent.trim()), ['Copy markdown', 'Show as text', 'Copy data']);
+ assert.equal(row.querySelector('[data-evidence]').textContent, 'From this reply');
+ }
+ assert.equal(other.childNodes.length, 0, 'only its own message’s row');
+ const extra = (bubble) => [...bubble.querySelectorAll('button')].filter((b) => !b.closest('th') && !/^Ask about/.test(b.getAttribute('aria-label') ?? b.textContent));
+ for (const bubble of v.host.querySelectorAll('#bubble')) assert.equal(extra(bubble).length, 0, 'nothing but sort and Ask about this inside the reply');
+ other.remove();
+});
+
+test('no setting: ChatView always passes results and adds the action-row spot when a message has them', async () => {
+ const { readFile } = await import('node:fs/promises');
+ const read = (f) => readFile(new URL(`../src/${f}`, import.meta.url), 'utf8');
+ const chat = await read('components/ChatView.tsx');
+ assert.match(chat, /\{msg\.results != null && <SmartActionsSlot messageId=\{msg\.id\} \/>\}/);
+ assert.match(chat, /results=\{msg\.results\} messageId=\{msg\.id\}/);
+ for (const f of ['components/ChatView.tsx', 'components/SettingsModal.tsx', 'smartResults.ts', 'components/MarkdownRenderer.tsx']) assert.doesNotMatch(await read(f), /smart_results|SmartResultsOn|smart-results-label/, f);
+});
+
+test('Show as text swaps the block for the reply’s markdown, per message, and is remembered', async () => {
+ const plain = md(REPLY);
+ const Message = ({ id }) => h('div', null, h('div', { id: 'bubble' }, h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: id })), h('div', { id: 'row' }, h(m.SmartActionsSlot, { messageId: id })));
+ const v = await mount(h(Message, { id: 'm1' }));
+ const toggle = () => [...v.host.querySelectorAll('button')].find((b) => b.textContent === 'Show as text');
+ assert.equal(toggle().getAttribute('aria-pressed'), 'false');
+ await click(toggle());
+ assert.equal(toggle().getAttribute('aria-pressed'), 'true');
+ assert.equal(v.host.querySelector('[data-smart-result]'), null);
+ assert.ok(v.host.querySelector('#bubble table'), 'the reply’s own table');
+ assert.equal(v.host.querySelectorAll('#bubble th button').length, 0, 'no sort buttons');
+ assert.match(plain, /<table/);
+ assert.equal(localStorage.getItem('kwnt:smart-text:m1'), '1');
+ v.done();
+ mounted.delete(v);
+ const again = await mount(h(Message, { id: 'm1' }));
+ assert.equal(again.host.querySelector('[data-smart-result]'), null, 'still text after a reload');
+ const other = await mount(h(Message, { id: 'm2' }));
+ assert.ok(other.host.querySelector('[data-smart-result="comparison"]'), 'other messages keep their block');
+});
+
+test('Ask about this fills in the composer through an event and never sends', async () => {
+ const asked = [];
+ const onAsk = (e) => asked.push(e.detail.text);
+ window.addEventListener(m.COMPOSE_PREFILL_EVENT, onAsk);
+ const sent = [];
+ const fetchBefore = g.fetch;
+ g.fetch = g.window.fetch = async (...a) => (sent.push(a), new Response('{}'));
+ try {
+ const v = await mount(h(m.MarkdownRenderer, { content: REPLY, results: set(comparison()), messageId: 'm1' }));
+ const row = v.host.querySelector('tbody tr:nth-child(2) button[aria-label^="Ask about"]');
+ assert.equal(row.getAttribute('aria-label'), 'Ask about B');
+ await click(row);
+ const card = [...v.host.querySelectorAll('li button')].filter((b) => b.textContent.trim() === 'Ask about this');
+ assert.equal(card.length, 3, 'each stacked card has one');
+ await click(card[2]);
+ assert.deepEqual(asked, ['About B in your Plan table: ', 'About C in your Plan table: ']);
+ assert.equal(sent.length, 0, 'nothing sent');
+ const chat = await (await import('node:fs/promises')).readFile(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
+ const listener = chat.slice(chat.indexOf('const prefill = '), chat.indexOf('window.removeEventListener(COMPOSE_PREFILL_EVENT'));
+ assert.match(listener, /setInputVal/);
+ assert.doesNotMatch(listener, /handleSubmit|onSendMessage/, 'the composer is filled in, not sent');
+ } finally {
+ window.removeEventListener(m.COMPOSE_PREFILL_EVENT, onAsk);
+ g.fetch = g.window.fetch = fetchBefore;
+ }
+});
+
+test('pros and cons columns: tinted headers, and short lists in the stacked cards', async () => {
+ const { reply, results } = m.FIXTURES.comparison;
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results, messageId: 'mc' }));
+ assert.ok(v.host.querySelector('[data-smart-result="comparison"]'), 'the fixture renders');
+ assert.match(header(v.host, 'Pros').querySelector('button').className, /text-emerald-300/);
+ assert.match(header(v.host, 'Cons').querySelector('button').className, /text-rose-300/);
+ const card = v.host.querySelectorAll('[data-smart-result="comparison"] > div.sm\\:hidden > ul > li')[1];
+ assert.deepEqual([...card.querySelectorAll('dd ul li')].map((li) => li.textContent), ['Preview builds', 'EU region', 'chat support']);
+ assert.deepEqual(m.shortList('Cheapest; simple setup'), ['Cheapest', 'simple setup']);
+ assert.deepEqual(m.shortList('Fast, cheap, small'), ['Fast', 'cheap', 'small']);
+ assert.equal(m.shortList('No preview builds'), null);
+ assert.equal(m.shortList('Good if you need SSO, audit logs and a named contact for every team'), null, 'a sentence stays a sentence');
+});
+
+// ---------------------------------------------------------------------------
+// Steps
+
+test('steps: numbered and tickable; ticks stay per message and block; Copy data copies the markdown', async () => {
+ const v = await mount(h(m.MarkdownRenderer, { content: STEPS_REPLY, results: set(steps()), messageId: 'm7' }));
+ const block = v.host.querySelector('[data-smart-result="steps"]');
+ assert.ok(block);
+ const boxes = () => [...v.host.querySelectorAll('input[type="checkbox"]')];
+ assert.equal(boxes().length, 3);
+ assert.ok(boxes().every((b) => b.labels.length === 1), 'each tick is a labelled checkbox');
+ assert.match(boxes()[1].labels[0].textContent, /^2\.\s*Turn on Smart results\.$/);
+ assert.equal(boxes()[1].labels[0].querySelector('strong')?.textContent, 'Smart results', 'the reply’s markdown');
+ assert.match(block.textContent, /0 of 3 done/);
+ await click(boxes()[1]);
+ assert.equal(boxes()[1].checked, true);
+ assert.match(block.textContent, /1 of 3 done/);
+ assert.equal(localStorage.getItem('kwnt:steps:m7:b1'), '["s1"]', 'ids only, no reply text');
+ v.done();
+ mounted.delete(v);
+ const again = await mount(h(m.MarkdownRenderer, { content: STEPS_REPLY, results: set(steps()), messageId: 'm7' }));
+ assert.deepEqual([...again.host.querySelectorAll('input[type="checkbox"]')].map((b) => b.checked), [false, true, false], 'kept after a reload');
+ const other = await mount(h(m.MarkdownRenderer, { content: STEPS_REPLY, results: set(steps()), messageId: 'm8' }));
+ assert.deepEqual([...other.host.querySelectorAll('input[type="checkbox"]')].map((b) => b.checked), [false, false, false], 'another message starts fresh');
+ await copyData(again.host, 'Markdown');
+ assert.equal(clipboard.text, '1. Open Settings.\n2. Turn on **Smart results**.\n3. Send a reply with a table.\n');
+});
+
+test('steps follow the list’s own start number, and a loose list reads as one line per step', async () => {
+ const numbered = STEPS_REPLY.replace('1. Open', '4. Open').replace('2. Turn', '5. Turn').replace('3. Send', '6. Send');
+ const v = await mount(h(m.MarkdownRenderer, { content: numbered, results: set(steps()), messageId: 'm7' }));
+ assert.match(v.host.querySelector('label').textContent, /^4\./);
+ const loose = STEPS_REPLY.replace('\n2.', '\n\n2.').replace('\n3.', '\n\n3.');
+ const w = await mount(h(m.MarkdownRenderer, { content: loose, results: set(steps()), messageId: 'm9' }));
+ assert.ok(w.host.querySelector('[data-smart-result="steps"]'));
+ assert.equal(w.host.querySelector('[data-smart-result="steps"] p'), null, 'no paragraph blocks inside a label');
+});
+
+test('checklist: a task list whose ticks start from the reply’s [x], with the same box in the streamed list', async () => {
+ const { reply, results } = m.FIXTURES.checklist;
+ const streamed = await mount(h(m.MarkdownRenderer, { content: reply, isStreaming: true }));
+ const sBoxes = [...streamed.host.querySelectorAll('input[type="checkbox"]')];
+ assert.deepEqual(sBoxes.map((b) => [b.checked, b.disabled]), [[true, true], [true, true], [false, true], [false, true]], 'read-only while streaming');
+ assert.match(streamed.host.querySelector('ul').className, /list-none pl-1 my-2\.5 space-y-1/);
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results, messageId: 'mk' }));
+ const block = v.host.querySelector('[data-smart-result="steps"][data-variant="checklist"]');
+ assert.ok(block);
+ assert.equal(block.querySelector('ul').getAttribute('role'), 'list', 'an unordered task list stays a ul');
+ const boxes = [...block.querySelectorAll('input[type="checkbox"]')];
+ assert.deepEqual(boxes.map((b) => b.checked), [true, true, false, false]);
+ assert.ok(boxes.every((b) => !b.disabled && b.labels.length === 1));
+ assert.equal(boxes[0].className, sBoxes[0].className.replace(' rounded-sm accent-sky-500', ' cursor-pointer rounded-sm accent-sky-500') + ' focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/70 focus-visible:ring-offset-1 focus-visible:ring-offset-zinc-900', 'the same box, now clickable');
+ assert.doesNotMatch(block.textContent, /^\s*\d\./m, 'no numbers on a checklist');
+ assert.equal(block.querySelector('label code')?.textContent, 'docs', 'the reply’s markdown');
+ assert.deepEqual([...block.querySelectorAll('label')].map((l) => l.textContent), [...streamed.host.querySelectorAll('li > span')].map((s) => s.textContent), 'every item keeps its text');
+ assert.ok([...block.querySelectorAll('label')].every((l) => l.textContent.length > 10));
+ await click(boxes[0]);
+ assert.equal(localStorage.getItem('kwnt:steps:mk:b-check'), '["c1"]');
+ await click(boxes[0]);
+ assert.equal(localStorage.getItem('kwnt:steps:mk:b-check'), null, 'back to the reply’s ticks: nothing stored');
+ await click(boxes[2]);
+ await copyData(v.host, 'Markdown');
+ assert.equal(clipboard.text, '- [x] Export the old site as static files\n- [x] Create the Northdeck project\n- [x] Move the `docs` CNAME (owner: Sam)\n- [ ] Turn on preview builds\n');
+});
+
+test('timeline: a rail in the bullets’ place, the reply’s own items', async () => {
+ const { reply, results } = m.FIXTURES.timeline;
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results, messageId: 'mt' }));
+ const block = v.host.querySelector('[data-smart-result="steps"][data-variant="timeline"]');
+ assert.ok(block);
+ assert.match(block.className, /my-2\.5 space-y-1 pl-5/, 'the list’s own box');
+ assert.deepEqual([...block.querySelectorAll(':scope > li')].map((li) => li.textContent), ['Mon 9 Nov: Freeze content on the old site', 'Tue 10 Nov: Switch DNS (Owner: Sam)', 'Wed 11 Nov: Check search console for errors', 'Fri 13 Nov: Cancel the old plan']);
+ assert.equal(block.querySelectorAll('[aria-hidden="true"].rounded-full').length, 4);
+ assert.equal(block.querySelectorAll('[aria-hidden="true"].w-px').length, 3, 'no line after the last item');
+ assert.equal(m.blockMarkdown(m.validSteps(results.blocks[0])), '- Mon 9 Nov: Freeze content on the old site\n- Tue 10 Nov: Switch DNS (Owner: Sam)\n- Wed 11 Nov: Check search console for errors\n- Fri 13 Nov: Cancel the old plan\n');
+ assert.equal(m.validSteps({ ...results.blocks[0], items: results.blocks[0].items.map((i) => ({ ...i, when: null })) }), null, 'a timeline needs every when');
+});
+
+test('a task list only becomes a checklist; nested or quoted lists stay markdown', () => {
+ const task = STEPS_REPLY.replace('1. Open', '1. [ ] Open').replace('2. Turn', '2. [ ] Turn').replace('3. Send', '3. [ ] Send');
+ assert.equal(md(task, { results: set(steps()), messageId: 'm1' }), md(task), 'numbered steps never take a task list');
+ const bullets = STEPS_REPLY.replace(/^\d\./gm, '-');
+ assert.equal(md(bullets, { results: set(steps({ source: { kind: 'markdown_list', index: 0, ordered: false } })), messageId: 'm1' }), md(bullets), 'numbered steps need a numbered list');
+ assert.equal(md(STEPS_REPLY, { results: set(steps({ variant: 'checklist' })), messageId: 'm1' }), md(STEPS_REPLY), 'a checklist needs a task list');
+ const quoted = STEPS_REPLY.replace(/^(\d\.)/gm, '> $1');
+ assert.equal(md(quoted, { results: set(steps()), messageId: 'm1' }), md(quoted));
+});
+
+// ---------------------------------------------------------------------------
+// Registry, frame, fixtures
+
+test('fixtures: one per block type, every block well formed; Pixel’s types render from them', async () => {
+ const types = new Set(Object.values(m.FIXTURES).map((f) => f.results.blocks[0].type));
+ assert.deepEqual([...types].sort(), ['cards', 'chart', 'comparison', 'facts', 'files', 'findings', 'metrics', 'steps', 'verification']);
+ const strings = (v) => (typeof v === 'string' ? [v] : Array.isArray(v) ? v.flatMap(strings) : v && typeof v === 'object' ? Object.values(v).flatMap(strings) : []);
+ for (const [name, f] of Object.entries(m.FIXTURES)) {
+ assert.equal(m.resultBlocks(f.results).length, 1, name);
+ assert.ok(m.parseCommon(f.results.blocks[0], f.results.blocks[0].type), name);
+ assert.ok(strings(f.results).every((t) => t.length <= 300), `${name}: strings ≤ 300`);
+ if (m.REGISTRY[f.results.blocks[0].type]) {
+ const v = await mount(h(m.MarkdownRenderer, { content: f.reply, results: f.results, messageId: `fx-${name}` }));
+ assert.ok(v.host.querySelector('[data-smart-frame]'), `${name} renders`);
+ }
+ }
+ assert.deepEqual(Object.keys(m.REGISTRY).sort(), ['comparison', 'steps']);
+});
+
+test('a slot block renders after the reply with its title; Show as text gives its data as markdown', async () => {
+ m.REGISTRY.verification = {
+ validate: (raw) => m.parseCommon(raw, 'verification'),
+ Component: ({ block }) => h('div', { 'data-test-verification': '' }, block.summary),
+ };
+ try {
+ const { reply, results } = m.FIXTURES.verification;
+ const titled = { version: 1, blocks: [{ ...results.blocks[0], title: 'Outcome checks' }] };
+ const Message = ({ id }) => h('div', null, h('div', { id: 'bubble' }, h(m.MarkdownRenderer, { content: reply, results: titled, messageId: id })), h('div', { id: 'row' }, h(m.SmartActionsSlot, { messageId: id })));
+ const v = await mount(h(Message, { id: 'mv' }));
+ const bubble = v.host.querySelector('#bubble > div');
+ const frame = bubble.lastElementChild;
+ assert.equal(frame.getAttribute('data-smart-frame'), 'verification', 'after the reply text');
+ assert.equal(frame.getAttribute('role'), 'group');
+ assert.equal(frame.firstElementChild.textContent, 'Outcome checks', 'a slot block shows its title');
+ assert.match(bubble.firstElementChild.textContent, /The migration task is done/);
+ assert.equal(v.host.querySelector('[data-evidence]').textContent, 'From task checks');
+ assert.equal(md(reply, { results: titled, messageId: 'mv', isStreaming: true }), md(reply, { isStreaming: true }), 'nothing while streaming');
+ await click([...v.host.querySelectorAll('button')].find((b) => b.textContent === 'Show as text'));
+ assert.equal(v.host.querySelector('[data-test-verification]'), null);
+ assert.deepEqual([...frame.querySelectorAll('tbody tr td:first-child')].map((td) => td.textContent), ['docs.trailhead.shop answers 200', 'Certificate is valid', 'Old host redirects', 'Sitemap lists 120 pages']);
+ // A slot block with a reply source elsewhere, or a sourced block with no table there, is dropped.
+ assert.equal(m.resolveBlock(results.blocks[0], { kind: 'table', head: [], body: [] }), null);
+ assert.equal(m.resolveBlock(m.FIXTURES.comparison.results.blocks[0], null), null);
+ } finally {
+ delete m.REGISTRY.verification;
+ }
+});
+
+test('evidence wording follows provenance', () => {
+ const ev = (provenance, extra = {}) => m.evidenceText({ ...m.FIXTURES.files.results.blocks[0], provenance, ...extra });
+ assert.equal(ev({ kind: 'reply_text' }), 'From this reply');
+ assert.equal(ev({ kind: 'bot_declared', tool_call_id: 't1' }), 'From this reply');
+ assert.equal(ev({ kind: 'kwant_data', ref: 'task:7f3a9c' }), 'From task checks');
+ assert.equal(ev({ kind: 'kwant_data', ref: 'attachment:att-redirects' }), 'From attachment redirects.csv');
+ assert.equal(ev({ kind: 'kwant_data', ref: 'attachment:gone' }), 'From attachments');
+ assert.equal(m.parseProvenance({ kind: 'kwant_data', ref: '../etc/passwd' }), null);
+});
+
+test('generic Copy data: every fixture exports CSV and Markdown with one row per item', () => {
+ for (const [name, f] of Object.entries(m.FIXTURES)) {
+ const block = f.results.blocks[0];
+ const rows = m.blockRows(block);
+ const n = (block.rows ?? block.points ?? block.checks ?? block.items).length;
+ assert.equal(rows.length, n, name);
+ assert.equal(m.blockCsv(block).trim().split('\n').length, n + 1, `${name}: header + rows`);
+ assert.ok(m.blockMarkdown(block).length > 0, name);
+ }
+ assert.equal(m.blockCsv(m.FIXTURES.chartLine.results.blocks[0]).split('\n')[1], 'Jul 2026,"1,240",310', 'chart cells verbatim');
+});
+
+// ---------------------------------------------------------------------------
+// Fallback: anything off renders the original markdown, seamlessly
+
+test('unknown version or type, or no message id: the original markdown', () => {
+ const plain = md(REPLY);
+ assert.equal(md(REPLY, { results: { version: 2, blocks: [comparison()] }, messageId: 'm1' }), plain);
+ assert.equal(md(REPLY, { results: set(comparison({ type: 'chart' })), messageId: 'm1' }), plain);
+ assert.equal(md(REPLY, { results: set(comparison()) }), plain);
+ assert.equal(md(REPLY, { results: 'nonsense', messageId: 'm1' }), plain);
+});
+
+test('malformed or untrustworthy blocks: the original markdown', () => {
+ const plain = md(REPLY);
+ const two = comparison().rows.slice(0, 2);
+ const bad = {
+ 'two rows': comparison({ rows: two }),
+ 'one column': comparison({ columns: comparison().columns.slice(0, 1), rows: comparison().rows.map((r) => ({ ...r, cells: r.cells.slice(0, 1) })) }),
+ 'ragged row': comparison({ rows: [...two, { id: 'r2', cells: ['C', 'EUR 20'] }] }),
+ 'duplicate row ids': comparison({ rows: [...two, { id: 'r1', cells: ['C', 'EUR 20', '10'] }] }),
+ 'duplicate labels': comparison({ rows: [...two, { id: 'r2', cells: ['a', 'EUR 20', '10'] }] }),
+ 'highlight not a row': comparison({ highlight_row: 'r9' }),
+ 'html in a cell': comparison({ rows: [...two, { id: 'r2', cells: ['<img src=x onerror=alert(1)>', 'EUR 20', '10'] }] }),
+ 'html in a label': comparison({ columns: [{ key: 'c0', label: '<b>Plan</b>', numeric: false, unit: null }, ...comparison().columns.slice(1)] }),
+ 'cell over 300 chars': comparison({ rows: [...two, { id: 'r2', cells: ['C'.repeat(301), 'EUR 20', '10'] }] }),
+ 'index out of range': comparison({ source: { kind: 'markdown_table', index: 3 } }),
+ 'wrong source kind': comparison({ source: { kind: 'markdown_list', index: 0 } }),
+ 'cells differ from the reply': comparison({ rows: [two[0], two[1], { id: 'r2', cells: ['C', 'EUR 19', '10'] }] }),
+ 'header differs from the reply': comparison({ columns: [comparison().columns[0], { ...comparison().columns[1], label: 'Cost' }, comparison().columns[2]] }),
+ 'rows missing': { ...comparison(), rows: undefined },
+ 'not an object': 42,
+ };
+ for (const [why, block] of Object.entries(bad)) assert.equal(md(REPLY, { results: set(block), messageId: 'm1' }), plain, why);
+ assert.equal(md(REPLY, { results: { version: 1, blocks: [comparison(), comparison()] }, messageId: 'm1' }), plain, 'duplicate block ids');
+ const huge = { ...set(comparison()), padding: 'x'.repeat(70 * 1024) };
+ assert.equal(md(REPLY, { results: huge, messageId: 'm1' }), plain, 'over 64 KB');
+ const badSteps = {
+ 'two items': steps({ items: steps().items.slice(0, 2) }),
+ 'item differs': steps({ items: [...steps().items.slice(0, 2), { id: 's2', text: 'Something else.' }] }),
+ 'unknown variant': steps({ variant: 'kanban' }),
+ 'done not a boolean': steps({ variant: 'checklist', items: steps().items.map((i) => ({ ...i, done: 'yes' })) }),
+ 'html in an item': steps({ items: [...steps().items.slice(0, 2), { id: 's2', text: '<script>x</script>' }] }),
+ };
+ const plainSteps = md(STEPS_REPLY);
+ for (const [why, block] of Object.entries(badSteps)) assert.equal(md(STEPS_REPLY, { results: set(block), messageId: 'm1' }), plainSteps, why);
+});
+
+test('a block that throws while rendering shows the fallback; the rest of the reply still renders', async () => {
+ const Boom = () => {
+ throw new Error('boom');
+ };
+ const errors = [];
+ const quiet = [console.error, console.warn];
+ console.error = console.warn = (...a) => errors.push(a);
+ try {
+ const v = await mount(h('div', null, h(m.SmartResultBoundary, { fallback: h('p', { id: 'fb' }, 'the reply’s table') }, h(Boom)), h('p', { id: 'after' }, 'later text')));
+ assert.equal(v.host.querySelector('#fb')?.textContent, 'the reply’s table');
+ assert.ok(v.host.querySelector('#after'));
+ } finally {
+ [console.error, console.warn] = quiet;
+ }
+ assert.ok(errors.length > 0, 'logged, not thrown');
+});
+
+test('indexes count tables and ordered lists in document order; fenced tables don’t count', async () => {
+ const reply = `\`\`\`
+| Fenced | Table |
+|---|---|
+| x | y |
+\`\`\`
+
+| Small | Table |
+|---|---|
+| a | b |
+
+${REPLY.split('\n\n').slice(1).join('\n\n')}`;
+ const plainFirst = md(reply);
+ assert.equal(md(reply, { results: set(comparison()), messageId: 'm1' }), plainFirst, 'index 0 is the 1-row table: mismatch, markdown');
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results: set(comparison({ source: { kind: 'markdown_table', index: 1 } })), messageId: 'm1' }));
+ assert.equal(v.host.querySelectorAll('[data-smart-result="comparison"]').length, 1);
+ assert.deepEqual(bodyRows(v.host), ['A', 'B', 'C'], 'table #1 became the block');
+ assert.match(v.host.textContent, /Small.*Table.*a.*b/s, 'table #0 stays markdown');
+ assert.match(v.host.querySelector('pre, code').textContent, /Fenced/);
+
+ const lists = `First, some context:\n\n1. one\n2. two\n\nThen:\n\n${STEPS_REPLY}`;
+ const w = await mount(h(m.MarkdownRenderer, { content: lists, results: set(steps({ source: { kind: 'markdown_list', index: 1 } })), messageId: 'm2' }));
+ assert.equal(w.host.querySelectorAll('[data-smart-result="steps"]').length, 1);
+ assert.match(w.host.querySelector('ol:not([role])').textContent, /one.*two/s, 'list #0 stays markdown');
+});
+
+test('a reply’s HTML is shown as text, in plain markdown and next to a block', async () => {
+ const reply = `${REPLY}\n\n<img src=x onerror="window.__pwned=1"> and <b>bold</b>`;
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results: set(comparison()), messageId: 'm1' }));
+ assert.equal(v.host.querySelector('img'), null);
+ assert.equal(v.host.querySelector('b'), null);
+ assert.match(v.host.textContent, /<b>bold<\/b>/);
+ assert.equal(window.__pwned, undefined);
+});