@filigran/chatbot 3.12.2 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/utils/index.ts","../../src/utils/feedback.ts","../../src/hooks/protocols/parseRestEvent.ts","../../src/hooks/protocols/parseLegacyEvent.ts","../../src/hooks/protocols/parseAgUiEvent.ts","../../src/hooks/useChat.ts","../../src/hooks/streamDeltas.ts","../../src/hooks/useAgents.ts","../../src/hooks/useConversations.ts","../../src/hooks/useSidebarResize.ts","../../src/hooks/useAwayCompletionNotice.ts","../../src/hooks/useComposerExtras.ts","../../src/utils/quota.ts","../../src/hooks/useAgentSuggestions.ts","../../src/hooks/useStableProps.ts","../../src/components/icons/AlertTriangleIcon.tsx","../../src/components/icons/ArrowRightLeftIcon.tsx","../../src/components/icons/AttachFileIcon.tsx","../../src/components/icons/BotIcon.tsx","../../src/components/icons/BrainIcon.tsx","../../src/components/icons/CheckCircleIcon.tsx","../../src/components/icons/CheckIcon.tsx","../../src/components/icons/ChevronDownIcon.tsx","../../src/components/icons/CloseIcon.tsx","../../src/components/icons/CopyIcon.tsx","../../src/components/icons/DatabaseIcon.tsx","../../src/components/icons/DefaultLogoIcon.tsx","../../src/components/icons/DownloadIcon.tsx","../../src/components/icons/EditIcon.tsx","../../src/components/icons/ExternalLinkIcon.tsx","../../src/components/icons/FileIcon.tsx","../../src/components/icons/FloatingIcon.tsx","../../src/components/icons/FullscreenExitIcon.tsx","../../src/components/icons/FullscreenIcon.tsx","../../src/components/icons/GamepadIcon.tsx","../../src/components/icons/GlobeIcon.tsx","../../src/components/icons/HistoryIcon.tsx","../../src/components/icons/ImageIcon.tsx","../../src/components/icons/InfoIcon.tsx","../../src/components/icons/MailIcon.tsx","../../src/components/icons/MaximizeIcon.tsx","../../src/components/icons/MicIcon.tsx","../../src/components/icons/SearchIcon.tsx","../../src/components/icons/SendIcon.tsx","../../src/components/icons/SidebarIcon.tsx","../../src/components/icons/SparklesIcon.tsx","../../src/components/icons/StopCircleIcon.tsx","../../src/components/icons/TerminalIcon.tsx","../../src/components/icons/ThumbsDownIcon.tsx","../../src/components/icons/ThumbsUpIcon.tsx","../../src/components/icons/TrashIcon.tsx","../../src/components/icons/UserPlusIcon.tsx","../../src/components/icons/VolumeIcon.tsx","../../src/components/icons/WrenchIcon.tsx","../../src/components/icons/XCircleIcon.tsx","../../src/components/Dropdown.tsx","../../src/hooks/useClickOutside.ts","../../src/components/Spinner.tsx","../../src/utils/tooltipPlacement.ts","../../src/components/Tooltip.tsx","../../src/components/ChatHeader.tsx","../../src/hooks/dictationController.ts","../../src/hooks/useDictation.ts","../../src/components/ContextUsageIndicator.tsx","../../src/components/PromptPicker.tsx","../../src/components/QuotaIndicator.tsx","../../src/components/ChatInput.tsx","../../src/hooks/useMessageFeedback.ts","../../src/utils/speech.ts","../../src/hooks/useSpeechReader.ts","../../src/utils/messageTime.ts","../../src/utils/scrollFollow.ts","../../src/components/ChatApprovalPrompt.tsx","../../src/components/ChatImage.tsx","../../src/components/ChatWaitingPanel.tsx","../../src/components/ChatThinking.tsx","../../src/utils/markdownBlocks.ts","../../src/components/MarkdownMessage.tsx","../../src/components/ReasoningDetailsDialog.tsx","../../src/components/ChatMessages.tsx","../../src/components/ChatWelcome.tsx","../../src/components/ConversationSidebar.tsx","../../src/components/ChatPanel.tsx","../../src/components/ChatToggleButton.tsx"],"sourcesContent":["import type { Translate } from '../types';\n\nexport function hexAlpha(hex: string, alpha: number): string {\n const a = Math.round(alpha * 255)\n .toString(16)\n .padStart(2, '0');\n return `${hex}${a}`;\n}\n\n/**\n * Markdown has no native support for nesting fenced code blocks of the same\n * length: per the CommonMark spec, the first inner ``` closes the outer block,\n * so everything after it renders *outside* the code block. LLMs constantly hit\n * this — when an agent shows a prompt or a full markdown document inside a\n * ```markdown … ``` fence, that document's own ``` fences shatter the snippet\n * into alternating code / prose fragments.\n *\n * The robust, spec-compliant fix is to make the *outer* fence longer than any\n * fence it contains: a 4-backtick fence is only closed by a run of ≥4\n * backticks, so all inner 3-backtick fences become literal content and the\n * whole document renders as one clean, copyable code block.\n *\n * We act only on the unambiguous, dominant case — a 3-backtick opener whose\n * info string is a markup language (markdown / md / mdx / markup) that actually\n * contains nested fences — so already-correct markdown is never rewritten\n * (a correctly authored nested block already uses a 4+-backtick opener, which\n * we skip).\n */\nexport function hardenNestedCodeFences(raw: string): string {\n if (!raw) return raw;\n const lines = raw.split('\\n');\n const fenceRe = /^(\\s*)(`{3,})(.*)$/;\n const markupLang = /^(markdown|md|mdx|markup)\\b/i;\n\n let openerIdx = -1;\n for (let i = 0; i < lines.length; i++) {\n const m = lines[i].match(fenceRe);\n if (m && m[2].length === 3 && markupLang.test(m[3].trim())) {\n openerIdx = i;\n break;\n }\n }\n if (openerIdx === -1) return raw;\n\n // Find the outer block's *matching* closer rather than the last bare fence in\n // the message. Same-length fences are ambiguous — an inner ``` looks exactly\n // like the outer closer — so inner fences are paired off with two structural\n // signals:\n // • a labelled fence (```lang) opens a nested block, and the next bare\n // fence closes it (depth tracking); and\n // • two consecutive *bare* fences wrapping a non-blank body form an\n // unlabelled nested code block — a ``` … ``` example inside the document.\n // A bare fence at depth 0 is the outer closer when the next fence is\n // labelled, absent, or bare-but-separated-by-only-blank-lines: that last case\n // is a block boundary (this closer followed by a *separate* block), not\n // nesting, so the separate block is never absorbed.\n //\n // Taking the last bare fence instead swallowed everything up to it — trailing\n // prose and unrelated code blocks alike — whenever a later block followed the\n // markdown one.\n const fences: { idx: number; run: number; bare: boolean }[] = [];\n for (let i = openerIdx + 1; i < lines.length; i++) {\n const m = lines[i].match(fenceRe);\n if (m) fences.push({ idx: i, run: m[2].length, bare: m[3].trim() === '' });\n }\n\n // True when every line strictly between two fence lines is blank — which\n // separates a nested code block (real body) from a mere block boundary.\n const blankBetween = (a: number, b: number): boolean => {\n for (let k = a + 1; k < b; k++) {\n if (lines[k].trim() !== '') return false;\n }\n return true;\n };\n\n let depth = 0;\n let maxRun = 3;\n let nestedCount = 0;\n let closerIdx = -1;\n for (let j = 0; j < fences.length; j++) {\n const f = fences[j];\n if (f.bare && depth === 0) {\n const next = fences[j + 1];\n if (!next || !next.bare || blankBetween(f.idx, next.idx)) {\n closerIdx = f.idx;\n break;\n }\n depth++; // opens an unlabelled nested code block\n } else {\n // A labelled fence opens a nested block; a bare fence at depth > 0 closes\n // the innermost one.\n depth = f.bare ? Math.max(0, depth - 1) : depth + 1;\n }\n nestedCount++;\n maxRun = Math.max(maxRun, f.run);\n }\n\n // Only harden when the block really contains nested fences AND its own closer\n // was found — otherwise leave the text alone rather than extending the block\n // over whatever follows.\n if (closerIdx === -1 || nestedCount === 0) return raw;\n\n const fence = '`'.repeat(Math.max(maxRun + 1, 4));\n const om = lines[openerIdx].match(fenceRe)!;\n lines[openerIdx] = `${om[1]}${fence}${om[3]}`;\n const cm = lines[closerIdx].match(fenceRe)!;\n lines[closerIdx] = `${cm[1]}${fence}`;\n return lines.join('\\n');\n}\n\n/**\n * GFM renders a pipe table only when the delimiter row (`|---|---|`) has the\n * SAME number of columns as the header row. LLMs frequently miscount (e.g. a\n * 4-column header followed by a 3-column delimiter), and a server-side guard can\n * corrupt the delimiter — in either case the whole table silently degrades to\n * raw `| … |` text. This repairs a mismatched delimiter row to the header's\n * column count (preserving any alignment colons) so the table renders.\n *\n * It only rewrites a delimiter that is ACTUALLY mismatched, so already-valid\n * tables are never touched. Fenced code blocks are skipped, and setext headings\n * (underlines with no `|`) are never mistaken for a table.\n */\nexport function normalizeMarkdownTables(raw: string): string {\n if (!raw || raw.indexOf('|') === -1) return raw;\n const lines = raw.split('\\n');\n\n // Splits on unescaped `|` only. A manual walk (rather than a negative\n // lookbehind, which is unsupported on older engines and would throw at parse\n // time in an untranspiled ESNext bundle) keeps `\\|` inside a cell intact.\n const splitCells = (row: string): string[] => {\n let s = row.trim();\n if (s.startsWith('|')) s = s.slice(1);\n if (s.endsWith('|')) s = s.slice(0, -1);\n const cells: string[] = [];\n let current = '';\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (ch === '\\\\' && i + 1 < s.length) {\n current += ch + s[i + 1];\n i++;\n } else if (ch === '|') {\n cells.push(current);\n current = '';\n } else {\n current += ch;\n }\n }\n cells.push(current);\n return cells;\n };\n const isDelimiterRow = (row: string): boolean => row.includes('|') && /^\\s*\\|?\\s*:?-+:?\\s*(\\|\\s*:?-+:?\\s*)*\\|?\\s*$/.test(row);\n // Emit the canonical 3-hyphen delimiter form. remark-gfm accepts a single\n // hyphen, but `---` (with optional alignment colons) is the portable form\n // every Markdown renderer agrees on, so prefer it.\n const alignOf = (cell: string): string => {\n const c = cell.trim();\n const left = c.startsWith(':');\n const right = c.endsWith(':');\n return left && right ? ':---:' : right ? '---:' : left ? ':---' : '---';\n };\n\n // Track both the fence character AND its run length: per CommonMark a closing\n // fence must use the same character and be at least as long as the opener, so\n // a shorter run (```) must not close a longer one (````), and a closing fence\n // carries no info string. Optional blockquote / list-item markers are allowed\n // before the run so fences nested in those containers (e.g. `- ```) are still\n // recognised and the table inside them is left untouched.\n const fenceRe = /^\\s*(?:(?:>\\s?)|(?:[-*+]\\s+)|(?:\\d{1,9}[.)]\\s+))*(`{3,}|~{3,})(.*)$/;\n let fenceChar: string | null = null;\n let fenceLen = 0;\n // A pipe-table header can share its line with a list-item marker (e.g.\n // `- | a | b |`). Strip a leading list marker before counting columns so the\n // count matches the cells GFM sees inside the list item, not the marker.\n const listMarkerRe = /^\\s*(?:[-*+]\\s+|\\d{1,9}[.)]\\s+)/;\n for (let i = 0; i < lines.length - 1; i++) {\n const fenceMatch = lines[i].match(fenceRe);\n if (fenceMatch) {\n const run = fenceMatch[1];\n if (fenceChar === null) {\n fenceChar = run[0];\n fenceLen = run.length;\n } else if (run[0] === fenceChar && run.length >= fenceLen && fenceMatch[2].trim() === '') {\n fenceChar = null;\n fenceLen = 0;\n }\n continue;\n }\n if (fenceChar !== null) continue;\n\n const header = lines[i];\n const delim = lines[i + 1];\n if (!header.includes('|') || isDelimiterRow(header) || !isDelimiterRow(delim)) continue;\n\n // A table can start on a list-item line, so both the cells and the\n // delimiter's alignment live AFTER the marker. Anchor the rewritten\n // delimiter to that content offset (padding the marker width with spaces) so\n // it stays a continuation line of the list item: GFM drops a table whose\n // delimiter dedents away from its header. Without a marker this is just the\n // header's leading whitespace, so top-level tables are emitted unchanged.\n const markerMatch = header.match(listMarkerRe);\n const offset = markerMatch ? markerMatch[0].length : header.length - header.trimStart().length;\n const indent = markerMatch ? ' '.repeat(offset) : header.slice(0, offset);\n\n const headerCols = splitCells(header.slice(offset)).length;\n const delimCells = splitCells(delim);\n if (headerCols < 2 || delimCells.length === headerCols) continue;\n\n const aligns: string[] = [];\n for (let c = 0; c < headerCols; c++) aligns.push(delimCells[c] ? alignOf(delimCells[c]) : '---');\n lines[i + 1] = `${indent}| ${aligns.join(' | ')} |`;\n }\n return lines.join('\\n');\n}\n\n/**\n * When the ENTIRE message is a raw JSON object/array (and not already fenced),\n * wrap it in a ```json fence so it renders as a proper, copyable code block\n * instead of one long line of mangled prose — markdown collapses the newlines\n * and eats the `*`/`_` inside string values otherwise.\n *\n * Deliberately conservative: it parses the payload first, so a message that\n * merely *starts* with `{` (e.g. prose about an object) is left untouched.\n */\nexport function wrapBareJson(raw: string): string {\n const trimmed = raw.trim();\n if ((!trimmed.startsWith('{') && !trimmed.startsWith('[')) || trimmed.startsWith('```')) return raw;\n try {\n JSON.parse(trimmed);\n return '```json\\n' + trimmed + '\\n```';\n } catch {\n return raw;\n }\n}\n\n/**\n * Models routinely emit markdown images whose alt text is the whole generation\n * prompt, spread over several lines. CommonMark has no multi-line `![…](…)`, so\n * the image syntax breaks apart and the prompt renders as literal paragraphs\n * followed by a stray link.\n *\n * This collapses the alt text of such an image onto a single line (whitespace\n * runs → one space) so the parser emits a real `<img>` node. Single-line images\n * are returned byte-identical, and the URL is never rewritten — the URL may\n * contain anything, and only the alt text is at fault.\n *\n * The URL part excludes `)` and whitespace, so a link title\n * (`![alt](url \"title\")`) or a parenthesised URL is left alone rather than\n * mis-parsed.\n */\nexport function normalizeImageMarkdown(raw: string): string {\n if (!raw.includes('![')) return raw;\n return raw.replace(/!\\[([^\\]]*?\\n[^\\]]*?)\\]\\(([^)\\s]+)\\)/g, (_match, alt: string, url: string) => {\n const flat = alt.replace(/\\s+/g, ' ').trim();\n return `![${flat}](${url})`;\n });\n}\n\n/**\n * The text the panel hands to its markdown renderer. Order matters — image\n * alt-text is flattened before anything else looks at line structure, and the\n * JSON wrap must see the raw payload before fences are hardened.\n */\nexport function prepareMarkdown(content: string): string {\n return hardenNestedCodeFences(normalizeMarkdownTables(wrapBareJson(normalizeImageMarkdown(content))));\n}\n\n/** Schemes react-markdown's own sanitizer allows, minus the `data:` special case below. */\nconst SAFE_URL_PROTOCOLS = new Set(['http', 'https', 'mailto', 'tel']);\n\n/**\n * URL sanitizer for react-markdown that additionally preserves `data:image/*`\n * URIs.\n *\n * react-markdown v9+ ships a default `urlTransform` allowing only\n * http / https / mailto / tel. Agents with a code interpreter return charts as\n * `data:image/png;base64,…`, which that default strips — leaving a broken\n * `<img>`. Every other scheme (notably `javascript:` / `vbscript:`) is still\n * blocked, and non-image `data:` URIs are blocked too, so this widens the\n * allow-list by exactly one safe, inert case.\n */\nexport function markdownUrlTransform(url: string): string {\n const colon = url.indexOf(':');\n if (colon < 0) return url; // relative URL — always safe\n\n const slash = url.indexOf('/');\n const question = url.indexOf('?');\n const hash = url.indexOf('#');\n\n // A `/`, `?` or `#` before the colon means this is a path, not a scheme\n // (e.g. `./a:b`), so there is nothing to sanitize.\n if ((slash > -1 && colon > slash) || (question > -1 && colon > question) || (hash > -1 && colon > hash)) {\n return url;\n }\n\n const protocol = url.slice(0, colon).toLowerCase();\n if (SAFE_URL_PROTOCOLS.has(protocol)) return url;\n if (protocol === 'data' && /^data:image\\//i.test(url)) return url;\n return '';\n}\n\nexport const identity: Translate = (key) => key;\n\n/**\n * Translates `key`, then splices `values` into the result's `{name}` slots.\n *\n * The point is that the key stays a whole sentence. Building a phrase out of\n * translated fragments — \"Waiting for\" + count + \"tasks\" — freezes English word\n * order and English plural rules into the layout, and a translator sees each\n * fragment with no sentence around it. Here the locale owns the whole sentence\n * and decides where the number goes; the host's `t` still does nothing but look\n * a key up, so this needs no support from it.\n *\n * Plurals stay two explicit keys (`'1 tool call'` / `'{count} tool calls'`) for\n * the same reason: a lookup cannot select a plural form, so the call site picks\n * the sentence and the locale translates it whole.\n */\nexport function translate(t: Translate, key: string, values: Record<string, string | number>): string {\n // One pass over the sentence rather than one pass per value: a value that\n // happens to contain `{something}` is then never mistaken for a slot of its\n // own. A slot with no value keeps its braces, so a stray one is visible\n // rather than silently blank.\n return t(key).replace(/\\{(\\w+)\\}/g, (slot, name) => (Object.hasOwn(values, name) ? String(values[name] ?? '') : slot));\n}\n\n/**\n * Same as `translate`, but leaves one slot unfilled and returns the text on\n * either side of it — for the case where the value has to be markup (a coloured\n * agent name, a link) and so cannot be spliced into a string.\n *\n * Without this the sentence gets cut into \"How can \" + node + \" help you, \",\n * which is untranslatable in any language that would not put the node in that\n * spot. Here the locale still owns the whole sentence and decides where the slot\n * sits.\n *\n * `hasSlot` is false for a translation that dropped the slot — a locale that\n * reworded the sentence so it no longer names the value. The caller then renders\n * the sentence without the node instead of letting it dangle off the end.\n */\nexport function translateAround(\n t: Translate,\n key: string,\n slot: string,\n values: Record<string, string | number> = {},\n): { before: string; after: string; hasSlot: boolean } {\n const sentence = translate(t, key, values);\n const token = `{${slot}}`;\n const at = sentence.indexOf(token);\n if (at === -1) return { before: sentence, after: '', hasSlot: false };\n return { before: sentence.slice(0, at), after: sentence.slice(at + token.length), hasSlot: true };\n}\n\n/**\n * Nearest chatbot panel root (`.filigran-chatbot`) for portal-based overlays\n * (tooltips, dropdowns, dialogs), so they stay inside the panel's stacking\n * context instead of competing with the host app's z-indexes. Falls back to\n * `document.body` when rendered outside a panel.\n */\nexport function findChatbotRoot(el: HTMLElement | null): HTMLElement {\n let node = el;\n while (node) {\n if (node.classList.contains('filigran-chatbot')) return node;\n node = node.parentElement;\n }\n return document.body;\n}\n\n/**\n * Compact count for the composer's status readouts: 1200 → \"1.2k\", so neither\n * the quota nor the context gauge can widen the toolbar as the numbers grow.\n */\nexport function compactCount(n: number): string {\n if (n < 1000) return `${n}`;\n if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\\.0$/, '')}k`;\n return `${(n / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`;\n}\n\n/**\n * Compact relative-time label for the conversation history menu\n * (\"just now\", \"5m ago\", \"3h ago\", \"2d ago\", then a short date).\n * Returns an empty string for missing/unparseable timestamps so the row\n * simply omits the label instead of showing \"Invalid Date\".\n */\nexport function timeAgo(iso: string | undefined, t: Translate): string {\n if (!iso) return '';\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) return '';\n const diffMs = Date.now() - then;\n const minutes = Math.floor(diffMs / 60_000);\n if (minutes < 1) return t('just now');\n if (minutes < 60) return translate(t, '{count}m ago', { count: minutes });\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return translate(t, '{count}h ago', { count: hours });\n const days = Math.floor(hours / 24);\n if (days < 7) return translate(t, '{count}d ago', { count: days });\n return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n}\n\n/** Matches a complete `[[FILE:<id>]]` deliverable marker agents embed in prose. */\nconst FILE_MARKER_RE = /\\[\\[FILE:[^\\]]+\\]\\]/g;\n\n/**\n * Matches an INCOMPLETE marker at the very end of the string. SSE streams can\n * split a `[[FILE:<id>]]` token before the closing `]]` arrives, so the tail\n * may be `[[FILE`, `[[FILE:`, `[[FILE:abc`, or `[[FILE:abc]` mid-stream. We\n * anchor on the literal `[[FILE` prefix (which is vanishingly unlikely to\n * appear legitimately at the end of prose) so it never clips real content.\n */\nconst PARTIAL_FILE_MARKER_RE = /\\[\\[FILE(?::[^\\]]*)?\\]?$/;\n\n/**\n * Strip the `[[FILE:<id>]]` markers an agent embeds in its reply to point at\n * generated files. The actual files render as separate download chips, so the\n * raw markers must be removed from the prose. Complete markers are removed\n * anywhere; an incomplete marker at the end is also removed so a partially\n * streamed token never flickers as raw `[[FILE:...` text.\n *\n * When no marker is present the content is returned **untouched** — we must\n * not trim or collapse blank lines on ordinary prose, which would clobber\n * intentional leading/trailing whitespace (e.g. indented Markdown / code).\n * Whitespace is only normalized when a marker was actually removed.\n *\n * Applied to assistant content only — user-typed text is never touched, so a\n * user who literally types `[[FILE:x]]` still sees their own text.\n */\nexport function stripFileMarkers(content: string): string {\n if (!content) return content;\n const stripped = content.replace(FILE_MARKER_RE, '').replace(PARTIAL_FILE_MARKER_RE, '');\n if (stripped === content) return content;\n return stripped\n .replace(/[ \\t]+\\n/g, '\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/** An ordered piece of assistant content: prose text or a file marker. */\nexport type FileMarkerPart = { type: 'text'; value: string } | { type: 'file'; fileId: string };\n\n/**\n * Split assistant content into ordered text/file parts around complete\n * `[[FILE:<id>]]` markers, so the renderer can place each download card at the\n * marker's source position (preserving interleaved order). A trailing\n * incomplete marker (an SSE token split mid-stream) is removed from the final\n * text part so it never shows as raw `[[FILE:...` text.\n */\nexport function splitFileMarkers(content: string): FileMarkerPart[] {\n if (!content) return [];\n const parts: FileMarkerPart[] = [];\n const re = /\\[\\[FILE:([^\\]]+)\\]\\]/g;\n let lastIndex = 0;\n let match: RegExpExecArray | null = re.exec(content);\n while (match !== null) {\n if (match.index > lastIndex) {\n parts.push({ type: 'text', value: content.slice(lastIndex, match.index) });\n }\n parts.push({ type: 'file', fileId: match[1] });\n lastIndex = re.lastIndex;\n match = re.exec(content);\n }\n const tail = content.slice(lastIndex).replace(PARTIAL_FILE_MARKER_RE, '');\n if (tail) parts.push({ type: 'text', value: tail });\n return parts;\n}\n\n/**\n * The markdown documents an assistant answer is drawn from, in order: each\n * prose part between its file markers (`splitFileMarkers`), prepared as\n * `MarkdownMessage` prepares it (`prepareMarkdown`). The transcript parses each\n * one as a document of its own, and so must anything that reads the answer\n * (read aloud) to read what the screen shows.\n */\nexport function answerMarkdownSources(content: string): string[] {\n const sources: string[] = [];\n for (const part of splitFileMarkers(content)) {\n if (part.type === 'text' && part.value.trim()) sources.push(prepareMarkdown(part.value));\n }\n return sources;\n}\n","import type { ApiEndpoints, BackendType, ChatMessagePersistedFeedback, MessageFeedback } from '../types';\n\n/**\n * Persisted feedback on an assistant answer: the requests the thumbs send.\n * A stored rating is read back by `parsePersistedFeedback` with the rest of a\n * session restore (`hooks/protocols/parseRestEvent.ts`).\n *\n * Kept free of local runtime imports so `node --test` runs it as is.\n */\n\n/** Longest comment the feedback endpoint stores. */\nexport const FEEDBACK_COMMENT_MAX_LENGTH = 2000;\n\nexport type FeedbackRating = ChatMessagePersistedFeedback['rating'];\n\nexport const ratingOf = (value: MessageFeedback): FeedbackRating => (value === 'up' ? 'positive' : 'negative');\n\nexport const feedbackValueOf = (rating: FeedbackRating): MessageFeedback => (rating === 'positive' ? 'up' : 'down');\n\n/**\n * How the thumbs of one answer work, or null when it shows none:\n * - `persisted`: the panel stores the rating (`ApiEndpoints.feedback`), which\n * needs the conversation and the answer's persisted id - an answer the\n * backend did not identify cannot be rated;\n * - `callback`: the host stores it (`onMessageFeedback` alone).\n */\nexport type FeedbackMode = 'persisted' | 'callback';\n\nexport function feedbackModeOf(\n serverId: string | undefined,\n feedbackUrl: string | null | undefined,\n conversationId: string | null | undefined,\n hasCallback: boolean,\n): FeedbackMode | null {\n if (feedbackUrl) return conversationId && serverId ? 'persisted' : null;\n return hasCallback ? 'callback' : null;\n}\n\n/** The rating shown on an answer, and whether it can still be changed. */\nexport function shownFeedback(\n session: { value: MessageFeedback | null } | undefined,\n stored: ChatMessagePersistedFeedback | undefined,\n): { value: MessageFeedback | null; locked: boolean } {\n // Rated in this session: the session's answer wins, and can be changed.\n if (session) return { value: session.value, locked: false };\n // Rated before the conversation was reopened: shown, and final.\n if (stored) return { value: feedbackValueOf(stored.rating), locked: true };\n return { value: null, locked: false };\n}\n\n/** A comment as the endpoint stores it: trimmed, capped, and null when empty. */\nexport function normalizeFeedbackComment(comment: string | null | undefined): string | null {\n const trimmed = (comment ?? '').trim();\n return trimmed ? trimmed.slice(0, FEEDBACK_COMMENT_MAX_LENGTH) : null;\n}\n\n/**\n * `{apiBaseUrl}{feedback}`, or null when the panel does not store feedback\n * itself: the path is unset (no default, see `ApiEndpoints.feedback`), the\n * backend is not the REST one, or every request goes to one endpoint.\n */\nexport function feedbackBaseUrl(apiBaseUrl: string, apiEndpoints: ApiEndpoints | undefined, backendType: BackendType): string | null {\n if (backendType !== 'rest' || apiEndpoints?.singleEndpoint || !apiEndpoints?.feedback) return null;\n return `${apiBaseUrl}${apiEndpoints.feedback}`;\n}\n\n/**\n * The request that stores (`rating`) or retracts (`null`) the user's rating\n * of one message.\n */\nexport function feedbackRequest(\n baseUrl: string,\n conversationId: string,\n messageId: string,\n rating: { rating: FeedbackRating; comment: string | null } | null,\n requestHeaders?: Record<string, string>,\n): { url: string; init: RequestInit } {\n const url = `${baseUrl}/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(messageId)}/feedback`;\n if (!rating) {\n return { url, init: { method: 'DELETE', credentials: 'include', headers: { ...requestHeaders } } };\n }\n return {\n url,\n init: {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...requestHeaders },\n body: JSON.stringify({ rating: rating.rating, comment: normalizeFeedbackComment(rating.comment) }),\n },\n };\n}\n\n/** The part of `fetch` the feedback request needs. */\nexport type FeedbackFetch = (url: string, init: RequestInit) => Promise<{ ok: boolean }>;\n\n/**\n * Sends one `feedbackRequest` and says whether the backend stored it. A network\n * failure is a refusal like any other status: the caller rolls the thumbs back\n * either way.\n */\nexport async function submitFeedback(\n fetchImpl: FeedbackFetch,\n baseUrl: string,\n conversationId: string,\n messageId: string,\n rating: { rating: FeedbackRating; comment: string | null } | null,\n requestHeaders?: Record<string, string>,\n): Promise<boolean> {\n const { url, init } = feedbackRequest(baseUrl, conversationId, messageId, rating, requestHeaders);\n try {\n return (await fetchImpl(url, init)).ok;\n } catch {\n return false;\n }\n}\n","import type {\n ChatAttachment,\n ChatContextBreakdown,\n ChatContextUsage,\n ChatMessage,\n ChatMessagePersistedFeedback,\n ToolApprovalProposal,\n ToolCallTraceEntry,\n TransferChainEntry,\n} from '../../types';\nimport type { ParsedAction, ProtocolContext } from './types';\n\n/** Wire key → the breakdown field it populates. */\nconst BREAKDOWN_KEYS: ReadonlyArray<[string, keyof ChatContextBreakdown]> = [\n ['system', 'system'],\n ['tools', 'tools'],\n ['dynamic_tools', 'dynamicTools'],\n ['summary', 'summary'],\n ['conversation', 'conversation'],\n ['tool_results', 'toolResults'],\n];\n\n/**\n * Normalize the optional `context_breakdown` object.\n *\n * Only positive numbers for keys we know how to label survive: an unlabelled\n * bucket cannot be rendered, and a zero one is noise in a list meant to show\n * where the context actually went. Returns `undefined` when nothing usable is\n * left, so the gauge keeps its number and simply has no detail to open.\n */\nfunction parseBreakdown(raw: unknown): ChatContextBreakdown | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const src = raw as Record<string, unknown>;\n const out: ChatContextBreakdown = {};\n let any = false;\n for (const [wireKey, field] of BREAKDOWN_KEYS) {\n const value = src[wireKey];\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) {\n out[field] = value;\n any = true;\n }\n }\n return any ? out : undefined;\n}\n\n/**\n * Read the context-window occupancy carried by a progress or `done` frame.\n *\n * Both halves are required and the window must be positive: a token count with\n * no window to measure it against is not a ratio, and a zero window would make\n * one out of a division by zero. Returns `undefined` for anything else, so a\n * backend that reports nothing simply leaves the gauge as it was.\n */\nexport function parseContextUsage(evt: Record<string, unknown>): ChatContextUsage | undefined {\n const used = evt.context_tokens;\n const limit = evt.context_window;\n if (typeof used !== 'number' || typeof limit !== 'number') return undefined;\n if (!Number.isFinite(used) || !Number.isFinite(limit) || limit <= 0 || used < 0) return undefined;\n const breakdown = parseBreakdown(evt.context_breakdown);\n return breakdown ? { used, limit, breakdown } : { used, limit };\n}\n\n/**\n * Normalize the raw `attachments` array from a backend `done` event into\n * typed {@link ChatAttachment} objects. Defensive: skips non-object entries\n * and entries without a `file_id`. Returns `undefined` when there is nothing\n * renderable so the `done` action stays lean for backends without #810.\n */\nexport function parseAttachments(raw: unknown): ChatAttachment[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ChatAttachment[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const a = item as Record<string, unknown>;\n const fileId = a.file_id;\n if (typeof fileId !== 'string' || !fileId) continue;\n out.push({\n fileId,\n filename: typeof a.filename === 'string' ? a.filename : 'file',\n type: typeof a.type === 'string' ? a.type : undefined,\n size: typeof a.size === 'number' ? a.size : undefined,\n contentType: typeof a.content_type === 'string' ? a.content_type : undefined,\n fileTag: a.file_tag === 'working_file' ? 'working_file' : 'download_file',\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the raw `tool_call_trace` array (from a `done` event or restored\n * session metadata) into typed {@link ToolCallTraceEntry} objects. Defensive:\n * skips entries without a `name`. Returns `undefined` when empty so the\n * reasoning-details dialog falls back to the flat tool-name list.\n */\nexport function parseToolCallTrace(raw: unknown): ToolCallTraceEntry[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ToolCallTraceEntry[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const e = item as Record<string, unknown>;\n if (typeof e.name !== 'string' || !e.name) continue;\n out.push({\n name: e.name,\n input: typeof e.input === 'string' ? e.input : undefined,\n output: typeof e.output === 'string' ? e.output : undefined,\n // Only a boolean is honored; a missing/malformed value defaults to\n // success so unknown states never render a false failure icon.\n success: typeof e.success === 'boolean' ? e.success : true,\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the raw `transfer_chain` array (from a `done` event or restored\n * session metadata) into typed {@link TransferChainEntry} objects.\n */\nexport function parseTransferChain(raw: unknown): TransferChainEntry[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: TransferChainEntry[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const e = item as Record<string, unknown>;\n if (typeof e.agent_name !== 'string' || !e.agent_name) continue;\n out.push({\n agentId: typeof e.agent_id === 'string' ? e.agent_id : '',\n agentName: e.agent_name,\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the `proposals` array of an `approval_required` event.\n *\n * Only `tool_call_id` is load-bearing — it is what a decision is keyed on, so\n * an entry without one could never be answered and is dropped. Everything else\n * degrades: a proposal with no name still renders under a placeholder rather\n * than vanishing, because a call silently hidden from the reviewer is a call\n * that stalls the turn with nothing on screen to explain it.\n *\n * Returns `undefined` when nothing decidable is left, so the consumer can treat\n * an unusable pause as one it must not claim to have prompted for.\n */\nexport function parseToolApprovalProposals(raw: unknown): ToolApprovalProposal[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ToolApprovalProposal[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const p = item as Record<string, unknown>;\n const toolCallId = p.tool_call_id;\n if (typeof toolCallId !== 'string' || !toolCallId) continue;\n const args = p.arguments;\n const schema = p.input_schema;\n out.push({\n toolCallId,\n // Left empty for the UI to label: a parser has no `t`, and a placeholder\n // baked in here would reach the reviewer untranslated.\n toolName: typeof p.tool_name === 'string' && p.tool_name ? p.tool_name : '',\n toolDescription: typeof p.tool_description === 'string' ? p.tool_description : undefined,\n arguments: args && typeof args === 'object' && !Array.isArray(args) ? (args as Record<string, unknown>) : {},\n inputSchema: schema && typeof schema === 'object' && !Array.isArray(schema) ? (schema as Record<string, unknown>) : undefined,\n source: typeof p.source === 'string' ? p.source : undefined,\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Parse an XTM One (REST) SSE event into a normalized action.\n */\nexport function parseRestEvent(evt: Record<string, unknown>, ctx: ProtocolContext): ParsedAction {\n const type = evt.type as string | undefined;\n\n if (type === 'error') {\n return { action: 'error', content: (evt.content as string) || '' };\n }\n\n if (type === 'status') {\n const st = evt.status as string;\n if (st === 'tool_done' || st === 'wind_down') {\n return { action: 'noop' };\n }\n if (st === 'streaming') {\n return { action: 'status', status: 'streaming' };\n }\n if (st === 'thinking_text') {\n return { action: 'status', status: 'thinking_text', thinkingContent: evt.content as string };\n }\n if (st === 'tool_start') {\n ctx.hasUsedTools = true;\n return { action: 'status', status: 'tool_start', tools: evt.tools as string[] | undefined };\n }\n if (st === 'tool_heartbeat') {\n // Liveness signal during a long tool execution (background tasks,\n // consults, big integration calls): carries the elapsed seconds but\n // no new semantic state — the consumer must keep its current label.\n return {\n action: 'status',\n status: 'tool_heartbeat',\n tools: evt.tools as string[] | undefined,\n elapsedS: typeof evt.elapsed_s === 'number' ? evt.elapsed_s : undefined,\n };\n }\n // Context occupancy rides on the per-iteration `thinking` frame, so the\n // gauge climbs during a long turn. Read before the `analyzing` relabel\n // below, which rewrites the status but not what the frame carries.\n const contextUsage = parseContextUsage(evt);\n if (st === 'thinking' && ctx.hasUsedTools) {\n return { action: 'status', status: 'analyzing', contextUsage };\n }\n return { action: 'status', status: st, tools: evt.tools as string[] | undefined, contextUsage };\n }\n\n // The turn has paused on a gated tool call. Deliberately NOT terminal: the\n // stream stays open (kept warm by SSE `: keepalive` comment lines, which the\n // reader below drops as non-`data:` lines) and the rest of the turn arrives\n // on it once a decision is POSTed back.\n if (type === 'approval_required') {\n const proposals = parseToolApprovalProposals(evt.proposals);\n if (!proposals) return { action: 'noop' };\n return {\n action: 'approval_required',\n proposals,\n conversationId: typeof evt.conversation_id === 'string' ? evt.conversation_id : undefined,\n };\n }\n\n if (type === 'stream') {\n return { action: 'stream', content: evt.content as string };\n }\n\n if (type === 'done') {\n return {\n action: 'done',\n content: evt.content as string,\n conversationId: evt.conversation_id as string | undefined,\n toolNames: evt.tool_names as string[] | undefined,\n toolCallCount: evt.tool_call_count as number | undefined,\n iterations: evt.iterations as number | undefined,\n transferAgentId: evt.transfer_agent_id as string | undefined,\n transferAgentName: evt.transfer_agent_name as string | undefined,\n attachments: parseAttachments(evt.attachments),\n reasoning: typeof evt.reasoning === 'string' ? evt.reasoning : undefined,\n toolCallTrace: parseToolCallTrace(evt.tool_call_trace),\n transferChain: parseTransferChain(evt.transfer_chain),\n isTruncated: evt.is_truncated === true || undefined,\n contextUsage: parseContextUsage(evt),\n messageId: typeof evt.message_id === 'string' && evt.message_id ? evt.message_id : undefined,\n };\n }\n\n return { action: 'noop' };\n}\n\n/** The `feedback` of a restored entry, or undefined for anything that is not a stored rating. */\nexport function parsePersistedFeedback(raw: unknown): ChatMessagePersistedFeedback | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const { rating, comment } = raw as { rating?: unknown; comment?: unknown };\n if (rating !== 'positive' && rating !== 'negative') return undefined;\n return { rating, comment: typeof comment === 'string' && comment.trim() ? comment : null };\n}\n\n/**\n * The messages of a session restore (`POST {sessions}` with a known\n * `conversation_id`), in order.\n *\n * Rows are keyed `restored-<index>`: the key only has to be stable for the\n * life of the transcript, and a restore replaces the transcript whole. The\n * entry's own `id` is the message's persisted id, kept as `serverId` for what\n * is stored against it (feedback); its `created_at` is when it was sent, and\n * a backend that sends neither still restores - with no time to show\n * (`timestampUnknown`) rather than the time of the restore.\n * Entries that are not a user or an assistant message are skipped.\n */\nexport function parseRestoredMessages(raw: unknown): ChatMessage[] {\n if (!Array.isArray(raw)) return [];\n const out: ChatMessage[] = [];\n raw.forEach((item: unknown, i: number) => {\n if (!item || typeof item !== 'object') return;\n const m = item as Record<string, unknown>;\n if (m.role !== 'user' && m.role !== 'assistant') return;\n const createdAt = typeof m.created_at === 'string' ? new Date(m.created_at) : null;\n const sentAt = createdAt && !Number.isNaN(createdAt.getTime()) ? createdAt : null;\n out.push({\n id: `restored-${i}`,\n serverId: typeof m.id === 'string' && m.id ? m.id : undefined,\n role: m.role,\n content: typeof m.content === 'string' ? m.content : '',\n timestamp: sentAt ?? new Date(),\n timestampUnknown: sentAt ? undefined : true,\n feedback: m.role === 'assistant' ? parsePersistedFeedback(m.feedback) : undefined,\n // Per-message attribution when the backend keeps it — the only way a\n // thread that changed hands mid-way reads correctly. Nothing records it\n // today, so this is normally undefined and the conversation's agent\n // applies to the whole thread.\n agentName: typeof m.agent_name === 'string' ? m.agent_name : undefined,\n // Downloadable file chips on both roles: agent-generated deliverables on\n // assistant messages (their [[FILE:…]] markers are stripped at render\n // time) and user uploads, so an upload stays downloadable after a reload\n // and not only in the live session where it is carried on `files`.\n attachments: parseAttachments(m.attachments),\n // The reasoning-details affordance, from the same fields the live `done`\n // event carries.\n toolNames: Array.isArray(m.tool_names) ? (m.tool_names as string[]) : undefined,\n toolCallCount: typeof m.tool_call_count === 'number' ? m.tool_call_count : undefined,\n iterations: typeof m.iterations === 'number' ? m.iterations : undefined,\n reasoning: typeof m.reasoning === 'string' ? m.reasoning : undefined,\n toolCallTrace: parseToolCallTrace(m.tool_call_trace),\n transferChain: parseTransferChain(m.transfer_chain),\n isTruncated: m.is_truncated === true || undefined,\n });\n });\n return out;\n}\n","import type { ParsedAction, ProtocolContext } from './types';\n\n/**\n * Parse a Flowise-style SSE event into a normalized action.\n */\nexport function parseLegacyEvent(evt: Record<string, unknown>, ctx: ProtocolContext): ParsedAction {\n const eventType = evt.event as string | undefined;\n\n if (eventType === 'nextAgentFlow') {\n const data = evt.data as Record<string, unknown> | undefined;\n const nodeId = data?.nodeId as string | undefined;\n if (data?.status === 'INPROGRESS' && nodeId) {\n ctx.activeNodeId = nodeId;\n }\n return { action: 'noop' };\n }\n\n if (eventType === 'start') {\n return { action: 'noop' };\n }\n\n if (eventType === 'token') {\n const tokenData = ((evt.data as string) ?? '').replace(/<br\\s*\\/?>/g, '\\n');\n return { action: 'stream', content: tokenData };\n }\n\n if (eventType === 'agentReasoning') {\n const reasoning = evt.data as Record<string, unknown> | undefined;\n const usedTools = reasoning?.usedTools as Array<{ tool: string }> | undefined;\n if (usedTools?.length) {\n ctx.hasUsedTools = true;\n return { action: 'status', status: 'tool_start', tools: usedTools.map((t) => t.tool) };\n }\n if (ctx.hasUsedTools) {\n return { action: 'status', status: 'analyzing' };\n }\n return { action: 'status', status: 'thinking' };\n }\n\n if (eventType === 'usedTools') {\n ctx.hasUsedTools = true;\n const data = evt.data as Array<{ tool: string }> | undefined;\n const toolNames = Array.isArray(data) ? data.map((t) => t.tool) : [];\n return { action: 'status', status: 'tool_start', tools: toolNames };\n }\n\n if (eventType === 'metadata') {\n const data = evt.data as Record<string, unknown> | undefined;\n const chatId = data?.chatId as string | undefined;\n if (chatId) {\n return { action: 'set_chat_id', chatId };\n }\n return { action: 'noop' };\n }\n\n if (eventType === 'error') {\n return { action: 'error', content: (evt.data as string) || '' };\n }\n\n if (eventType === 'end') {\n return { action: 'done', content: '' };\n }\n\n return { action: 'noop' };\n}\n","import type { ParsedAction, ProtocolContext } from './types';\n\n/**\n * AG-UI protocol event types.\n * @see https://github.com/ag-ui-protocol/ag-ui\n */\n\n/**\n * Parse an AG-UI protocol SSE event into a normalized action.\n *\n * AG-UI uses a Start/Content/End lifecycle for messages and tool calls.\n * We map these to the same internal actions used by the other protocols.\n */\nexport function parseAgUiEvent(evt: Record<string, unknown>, ctx: ProtocolContext): ParsedAction {\n const type = evt.type as string | undefined;\n\n // --- Run lifecycle ---\n\n if (type === 'RUN_STARTED') {\n return { action: 'status', status: 'thinking' };\n }\n\n if (type === 'RUN_FINISHED') {\n return { action: 'done', content: '' };\n }\n\n if (type === 'RUN_ERROR') {\n // Empty rather than a literal English fallback: the content is rendered as\n // the assistant's message, and the consumer supplies its own translated\n // text when the backend sends none — as the other protocols already do.\n return { action: 'error', content: typeof evt.message === 'string' ? evt.message : '' };\n }\n\n // --- Step lifecycle ---\n\n if (type === 'STEP_STARTED') {\n const stepName = evt.stepName as string | undefined;\n return { action: 'status', status: stepName || 'thinking' };\n }\n\n if (type === 'STEP_FINISHED') {\n return { action: 'noop' };\n }\n\n // --- Text message streaming ---\n\n if (type === 'TEXT_MESSAGE_START') {\n return { action: 'status', status: 'streaming' };\n }\n\n if (type === 'TEXT_MESSAGE_CONTENT') {\n const delta = evt.delta as string;\n if (delta) {\n return { action: 'stream', content: delta };\n }\n return { action: 'noop' };\n }\n\n if (type === 'TEXT_MESSAGE_END') {\n return { action: 'noop' };\n }\n\n // TEXT_MESSAGE_CHUNK is a convenience event that combines Start+Content+End\n if (type === 'TEXT_MESSAGE_CHUNK') {\n const delta = evt.delta as string | undefined;\n if (delta) {\n return { action: 'stream', content: delta };\n }\n return { action: 'noop' };\n }\n\n // --- Tool call lifecycle ---\n\n if (type === 'TOOL_CALL_START') {\n ctx.hasUsedTools = true;\n const toolName = evt.toolCallName as string | undefined;\n return { action: 'status', status: 'tool_start', tools: toolName ? [toolName] : [] };\n }\n\n if (type === 'TOOL_CALL_ARGS') {\n // Tool arguments streaming — no UI equivalent, skip\n return { action: 'noop' };\n }\n\n if (type === 'TOOL_CALL_END') {\n return { action: 'status', status: 'analyzing' };\n }\n\n if (type === 'TOOL_CALL_RESULT') {\n // Tool result — no direct UI mapping, skip\n return { action: 'noop' };\n }\n\n if (type === 'TOOL_CALL_CHUNK') {\n // Convenience form — treat like TOOL_CALL_START if it has a name\n const toolName = evt.toolCallName as string | undefined;\n if (toolName) {\n ctx.hasUsedTools = true;\n return { action: 'status', status: 'tool_start', tools: [toolName] };\n }\n return { action: 'noop' };\n }\n\n // --- Reasoning / thinking ---\n\n if (type === 'REASONING_START' || type === 'REASONING_MESSAGE_START') {\n return { action: 'status', status: 'thinking' };\n }\n\n if (type === 'REASONING_MESSAGE_CONTENT' || type === 'REASONING_MESSAGE_CHUNK') {\n // Reasoning text — surface it in the dedicated thinking pane\n const delta = evt.delta as string | undefined;\n if (delta) {\n return { action: 'status', status: 'thinking_text', thinkingContent: delta };\n }\n return { action: 'status', status: 'thinking' };\n }\n\n if (type === 'REASONING_MESSAGE_END' || type === 'REASONING_END' || type === 'REASONING_ENCRYPTED_VALUE') {\n return { action: 'noop' };\n }\n\n // --- State management ---\n\n if (type === 'STATE_SNAPSHOT' || type === 'STATE_DELTA' || type === 'MESSAGES_SNAPSHOT') {\n // State sync — not mapped to chat UI currently\n return { action: 'noop' };\n }\n\n // --- Activity events ---\n\n if (type === 'ACTIVITY_SNAPSHOT' || type === 'ACTIVITY_DELTA') {\n return { action: 'noop' };\n }\n\n // --- Pass-through / custom ---\n\n if (type === 'RAW' || type === 'CUSTOM') {\n return { action: 'noop' };\n }\n\n return { action: 'noop' };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type {\n AgentStatusState,\n ApiEndpoints,\n BackendType,\n ChatContextUsage,\n ChatFile,\n ChatMessage,\n ToolApprovalDecision,\n ToolApprovalProposal,\n} from '../types';\nimport type { ParsedAction, ProtocolContext } from './protocols';\nimport { parseAgUiEvent, parseLegacyEvent, parseRestEvent } from './protocols';\nimport { parseToolApprovalProposals } from './protocols/parseRestEvent';\nimport { createStreamDeltas, type StreamDeltas } from './streamDeltas';\n\nconst STORAGE_KEY = 'filigranChatConversationId';\nconst LEGACY_CHAT_ID_KEY = 'filigranChatLegacyChatId';\n\n/**\n * Unsent composer text is kept per conversation so closing the panel (hosts\n * unmount `<ChatPanel/>` when it is closed) or switching conversation doesn't\n * discard a half-written question. `sessionStorage`, not `localStorage`: a\n * draft is scoped to the tab and dies with it.\n */\nconst DRAFT_KEY_PREFIX = 'filigranChatDraft:';\n/** Debounce on draft writes so a fast typist doesn't hit storage per keystroke. */\nconst DRAFT_PERSIST_DELAY_MS = 300;\n\nconst draftKey = (conversationId: string | null): string => `${DRAFT_KEY_PREFIX}${conversationId ?? 'new'}`;\n\nfunction loadDraft(conversationId: string | null): string {\n if (typeof window === 'undefined') return '';\n try {\n return sessionStorage.getItem(draftKey(conversationId)) ?? '';\n } catch {\n // Storage can throw in restricted/private browsing contexts — a chat\n // without draft recovery is far better than a chat that fails to mount.\n return '';\n }\n}\n\nfunction persistDraft(conversationId: string | null, value: string): void {\n if (typeof window === 'undefined') return;\n try {\n if (value) sessionStorage.setItem(draftKey(conversationId), value);\n else sessionStorage.removeItem(draftKey(conversationId));\n } catch {\n /* ignore — see loadDraft */\n }\n}\n\n/**\n * How often to check on a turn resumed by a decision made on a recovered\n * (streamless) prompt, and the backstop that ends the watch regardless.\n *\n * Such a turn has no stream left to write to — the backend persists the answer\n * and suppresses the live `done` frame — so the panel watches the pause-recovery\n * route instead, which reports whether the turn is still running. That is a\n * definite stop condition rather than a guess at how long an agent might take,\n * and each poll doubles as the sign of life that keeps the turn from being\n * abandoned. The deadline is only a backstop against a turn-state marker that\n * somehow never clears; the ordinary end is the turn reporting itself idle.\n */\nconst RESUME_POLL_MS = 5000;\nconst RESUME_WATCH_MS = 900000;\n\n/**\n * How often to re-assert that somebody is still here while a recovered prompt\n * is on screen.\n *\n * A paused turn gives up after 30 minutes with no sign of a client, and after a\n * reload the stream that would have vouched for the reviewer is gone for good —\n * so presence is inferred from requests about the conversation instead. A tab\n * left open on the prompt IS a client present, but it makes no requests, so\n * without this the turn would abandon a reviewer who is simply taking their\n * time. Well inside the server's window, since missing it costs the whole turn.\n */\nconst APPROVAL_PRESENCE_INTERVAL_MS = 600000;\n\n/** Maximum number of files that can be attached to a single message. */\nconst DEFAULT_MAX_FILE_COUNT = 10;\n/** Maximum total size of all attached files (50 MB). */\nconst DEFAULT_MAX_TOTAL_SIZE = 50 * 1024 * 1024;\n\ninterface UseChatOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n agentSlug: string | null | undefined;\n requestHeaders?: Record<string, string>;\n /** Arbitrary host page/application context, sent as `context` on the REST message body. */\n pageContext?: Record<string, unknown>;\n t: (key: string) => string;\n maxFileCount?: number;\n maxTotalSize?: number;\n}\n\nexport interface TransferredAgent {\n id: string;\n name: string;\n}\n\ninterface UseChatReturn {\n messages: ChatMessage[];\n inputValue: string;\n setInputValue: (value: string) => void;\n isLoading: boolean;\n agentStatus: AgentStatusState | null;\n attachedFiles: ChatFile[];\n conversationId: string | null;\n /**\n * Context-window occupancy for the active conversation, or `null` while the\n * backend has reported none (a fresh chat, or a backend that does not carry\n * the figures at all). Tracked live off the per-iteration progress frames and\n * finalised on `done`.\n */\n contextUsage: ChatContextUsage | null;\n transferredAgent: TransferredAgent | null;\n /**\n * True while a response is streaming AND the typed text can be dispatched\n * immediately as a mid-run steering message (REST backend with a steer\n * endpoint and a known conversation id). Gates the steering affordances in\n * the composer (accent Send next to Stop, \"Enter to send now\" copy).\n */\n canSteer: boolean;\n /**\n * Tool calls the running turn has stopped on, or `null` when nothing is\n * waiting. While set, the turn is paused mid-answer: the stream is open and\n * silent, and only a decision (or aborting the turn) moves it on.\n */\n pendingApprovals: ToolApprovalProposal[] | null;\n /** True while a decision set is in flight to the approve endpoint. */\n isSubmittingApproval: boolean;\n /**\n * Why the last decision submission failed, or `null`. Kept alongside the\n * still-visible prompt rather than replacing it: the turn is paused either\n * way, so the reviewer needs the retry as much as the explanation.\n */\n approvalError: string | null;\n /**\n * Answer a paused turn. Every proposed call must appear exactly once — the\n * backend refuses a partial set, because resuming with an undecided call\n * leaves a `tool_use` block without its `tool_result`, which the model\n * providers reject outright.\n */\n submitApprovalDecisions: (decisions: ToolApprovalDecision[]) => Promise<void>;\n /**\n * True while waiting for the answer to a decision made on a recovered prompt.\n * The turn resumed without a stream to report on, so the panel shows the\n * working indicator itself and re-reads the conversation until the answer\n * lands.\n */\n isResumingAfterDecision: boolean;\n /**\n * Bumped whenever the conversation must be re-read from the server. The panel\n * owns the restore, so this is how the hook asks for one.\n */\n historyReloadNonce: number;\n historyLoadedRef: React.MutableRefObject<boolean>;\n /**\n * Ref mirror of {@link conversationId}, always current across async\n * boundaries. Exposed so the history-restore effect can tell, when its\n * `/chat/sessions` response arrives, whether the conversation it was issued\n * for is still the active one — and ignore a genuinely superseded response\n * (new chat / agent switch) without discarding a restore that was merely\n * torn down by a benign host re-render or a StrictMode double-invoke.\n */\n conversationIdRef: React.MutableRefObject<string | null>;\n handleFileAdd: (fileList: FileList | null) => void;\n handlePaste: (e: React.ClipboardEvent) => void;\n handleSendMessage: () => Promise<void>;\n handleNewChat: () => void;\n handleStopGenerating: () => void;\n setAttachedFiles: React.Dispatch<React.SetStateAction<ChatFile[]>>;\n setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>;\n /**\n * Seed the context gauge from outside a live turn — the history-restore path,\n * which reads the newest restored assistant message's figures.\n */\n setContextUsage: React.Dispatch<React.SetStateAction<ChatContextUsage | null>>;\n /**\n * Set (or clear) the active conversation id, keeping React state, the\n * cross-async-boundary ref mirror, and localStorage all in sync. Pass\n * `null` to reset. Prefer this over a raw state setter so the id consumed\n * by `handleSendMessage` (which reads the ref) never drifts from what the\n * UI shows.\n */\n updateConversationId: (id: string | null) => void;\n /**\n * Switch to another existing conversation (history menu). Aborts any\n * in-flight request, clears the transcript, and re-arms the history-restore\n * effect so the selected conversation's messages are fetched via the\n * sessions endpoint.\n */\n handleSwitchConversation: (id: string) => void;\n}\n\nfunction getParser(backendType: BackendType): (evt: Record<string, unknown>, ctx: ProtocolContext) => ParsedAction {\n switch (backendType) {\n case 'legacy':\n return parseLegacyEvent;\n case 'ag-ui':\n return parseAgUiEvent;\n default:\n return parseRestEvent;\n }\n}\n\nfunction buildRequestBody(\n backendType: BackendType,\n content: string,\n opts: {\n legacyChatId: string | null;\n conversationId: string | null;\n agentSlug: string | null | undefined;\n pageContext?: Record<string, unknown>;\n /** See {@link ApiEndpoints.approve} — derived, never a prop of its own. */\n supportsToolApproval?: boolean;\n },\n): Record<string, unknown> {\n switch (backendType) {\n case 'legacy':\n return { question: content, chatId: opts.legacyChatId ?? undefined, streaming: true };\n case 'ag-ui':\n return {\n threadId: opts.conversationId ?? crypto.randomUUID(),\n runId: crypto.randomUUID(),\n messages: [{ id: crypto.randomUUID(), role: 'user', content }],\n tools: [],\n context: [],\n state: {},\n forwardedProps: opts.agentSlug ? { agentSlug: opts.agentSlug } : {},\n };\n default: {\n const body: Record<string, unknown> = { content, conversation_id: opts.conversationId, agent_slug: opts.agentSlug };\n // Tell the backend this turn may pause on a gated tool call and that we\n // will answer. Sent only when the host named an approve path, because\n // the flag is a promise: a backend that pauses waits indefinitely, so a\n // client that cannot answer must never claim it can. Omitted rather than\n // sent false, so a proxy that rebuilds the body from a fixed field list\n // drops nothing meaningful.\n if (opts.supportsToolApproval) {\n body.supports_tool_approval = true;\n }\n // Forward arbitrary host page context (e.g. current URL) so the agent\n // knows where the user is. Omitted when empty to keep payloads lean.\n // Guard serialization: the whole body is later JSON.stringify'd, so a\n // non-serializable value (circular reference, BigInt, …) would otherwise\n // throw and break the message send. Drop the context instead — page\n // context is supplementary and must never prevent a message from going out.\n // Decide using the serialized result so values that normalize to an empty\n // object (e.g. `{ url: undefined }`, `{ fn: () => {} }`) are also omitted.\n if (opts.pageContext && Object.keys(opts.pageContext).length > 0) {\n try {\n const serialized = JSON.stringify(opts.pageContext);\n if (serialized && serialized !== '{}') {\n body.context = opts.pageContext;\n }\n } catch {\n // Non-serializable page context — skip it rather than fail the send.\n }\n }\n return body;\n }\n }\n}\n\nexport function useChat({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n agentSlug,\n requestHeaders,\n pageContext,\n t,\n maxFileCount = DEFAULT_MAX_FILE_COUNT,\n maxTotalSize = DEFAULT_MAX_TOTAL_SIZE,\n}: UseChatOptions): UseChatReturn {\n const isLegacy = backendType === 'legacy';\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [agentStatus, setAgentStatus] = useState<AgentStatusState | null>(null);\n const [conversationId, setConversationId] = useState<string | null>(() => {\n if (typeof window === 'undefined') return null;\n return localStorage.getItem(STORAGE_KEY);\n });\n // Seeded from the persisted draft of whichever conversation we mount into,\n // so re-opening the panel restores what the user had typed.\n const [inputValue, setInputValue] = useState(() => loadDraft(typeof window === 'undefined' ? null : localStorage.getItem(STORAGE_KEY)));\n const [attachedFiles, setAttachedFiles] = useState<ChatFile[]>([]);\n const [transferredAgent, setTransferredAgent] = useState<TransferredAgent | null>(null);\n // How full the model's context window is for this conversation. Conversation\n // state rather than per-message: it describes what the NEXT turn will carry,\n // which is the only thing the user can still act on.\n const [contextUsage, setContextUsage] = useState<ChatContextUsage | null>(null);\n // Tool calls the running turn is paused on. Conversation-level rather than\n // per-message: the pause belongs to the turn, not to any one bubble, and the\n // prompt outlives the segment that was streaming when it arrived.\n const [pendingApprovals, setPendingApprovals] = useState<ToolApprovalProposal[] | null>(null);\n const [isSubmittingApproval, setIsSubmittingApproval] = useState(false);\n const [approvalError, setApprovalError] = useState<string | null>(null);\n // A prompt recovered after a reload is answered the same way, but resumes\n // differently: there is no stream left to carry the rest of the turn.\n const [isResumingAfterDecision, setIsResumingAfterDecision] = useState(false);\n const [historyReloadNonce, setHistoryReloadNonce] = useState(0);\n // Drives the resume watch's next poll: each tick re-arms the effect.\n const [resumeTick, setResumeTick] = useState(0);\n const [legacyChatId, setLegacyChatId] = useState<string | null>(() => {\n if (typeof window === 'undefined') return null;\n return localStorage.getItem(LEGACY_CHAT_ID_KEY);\n });\n\n const historyLoadedRef = useRef(false);\n const abortControllerRef = useRef<AbortController | null>(null);\n // The running stream's pending deltas, so stopping it can apply them and a\n // new chat can drop them.\n const streamDeltasRef = useRef<StreamDeltas | null>(null);\n const hasUsedToolsRef = useRef(false);\n // Ref mirror of conversationId — always current across async boundaries\n const conversationIdRef = useRef(conversationId);\n // Ref mirror of isLoading, so the recovery probe can tell at apply time\n // whether a live turn has started owning the prompt since it was issued.\n const isLoadingRef = useRef(isLoading);\n isLoadingRef.current = isLoading;\n // Ref mirror of pageContext so the value sent reflects the page the user is\n // on at send time, regardless of when the send handler closure was created.\n const pageContextRef = useRef(pageContext);\n pageContextRef.current = pageContext;\n // Conversation id as the paused turn itself reported it. The decision POST\n // needs an id, and the first turn of a fresh conversation has none yet —\n // `conversationId` is normally learned from `done`, which a paused turn has\n // by definition not reached. Kept separate from `conversationIdRef` rather\n // than adopted into it: a pause should not quietly switch on the affordances\n // (steering, history) that having an id unlocks.\n const approvalConversationIdRef = useRef<string | null>(null);\n // True when the pending prompt was recovered from the server rather than read\n // off a live stream — the turn is running, but nothing is listening to it.\n const approvalDetachedRef = useRef(false);\n // Conversations already asked about a pause, so the recovery probe runs once\n // per conversation instead of on every render that settles.\n const probedConversationRef = useRef<string | null>(null);\n // When the resume watch stops regardless of what the turn reports.\n const resumeDeadlineRef = useRef(0);\n // Mutex to prevent concurrent session creation\n const creatingSessionRef = useRef<Promise<string | null> | null>(null);\n // Abort controller for in-flight file uploads (cancelled on new chat)\n const uploadAbortRef = useRef<AbortController>(new AbortController());\n\n // Guard invalid consumer values and keep deterministic limits.\n const effectiveMaxFileCount = Number.isFinite(maxFileCount) && maxFileCount > 0 ? Math.floor(maxFileCount) : DEFAULT_MAX_FILE_COUNT;\n const effectiveMaxTotalSize = Number.isFinite(maxTotalSize) && maxTotalSize > 0 ? maxTotalSize : DEFAULT_MAX_TOTAL_SIZE;\n\n // Determine message endpoint URL\n const getMessagesUrl = () => {\n if (isLegacy || apiEndpoints?.singleEndpoint) {\n return apiBaseUrl; // POST directly to base URL\n }\n return `${apiBaseUrl}${apiEndpoints?.messages ?? '/chat/messages'}`;\n };\n\n // Determine mid-run steering endpoint URL (null disables steering)\n const getSteerUrl = (): string | null => {\n if (isLegacy || backendType === 'ag-ui' || apiEndpoints?.singleEndpoint || apiEndpoints?.steer === null) {\n return null;\n }\n return `${apiBaseUrl}${apiEndpoints?.steer ?? '/chat/messages/steer'}`;\n };\n\n /**\n * Determine the tool-approval endpoint URL, or null when this host has not\n * opted in.\n *\n * Unlike its siblings there is no default path — see {@link ApiEndpoints.approve}.\n * Whether this returns a URL is exactly what decides if the widget advertises\n * `supports_tool_approval`, so \"configured\" and \"able to answer\" are the same\n * fact rather than two that can drift apart.\n */\n const getApproveUrl = (): string | null => {\n if (isLegacy || backendType === 'ag-ui' || apiEndpoints?.singleEndpoint) return null;\n const path = apiEndpoints?.approve;\n if (!path) return null;\n return `${apiBaseUrl}${path}`;\n };\n\n /**\n * Determine the pause-recovery URL for one conversation, or null when the\n * host has not exposed the route. See {@link ApiEndpoints.pendingApprovals}.\n */\n const getPendingApprovalsUrl = (convId: string): string | null => {\n if (isLegacy || backendType === 'ag-ui' || apiEndpoints?.singleEndpoint) return null;\n const base = apiEndpoints?.pendingApprovals;\n if (!base) return null;\n return `${apiBaseUrl}${base}/${convId}/pending-approvals`;\n };\n\n /**\n * Read what a conversation is paused on, and whether its turn is still going.\n *\n * One request serves three purposes: recovering a prompt the page never saw,\n * telling a resumed turn's watcher when to stop, and counting as the sign of\n * life that keeps a paused turn from being abandoned. Returns null on any\n * failure — every caller treats that as \"learned nothing\" and tries again or\n * leaves the panel as it was.\n */\n const readPendingApprovals = async (convId: string): Promise<{ proposals?: ToolApprovalProposal[]; turnRunning: boolean } | null> => {\n const url = getPendingApprovalsUrl(convId);\n if (!url) return null;\n try {\n const res = await fetch(url, { headers: { ...(requestHeaders ?? {}) } });\n if (!res.ok) return null;\n const data = await res.json();\n return {\n proposals: parseToolApprovalProposals(data?.proposals),\n // Anything but an explicit `running` ends the watch. A backend that\n // omits the field is one that cannot say, and waiting forever on a\n // turn nobody can report on is the worse failure.\n turnRunning: data?.turn === 'running',\n };\n } catch {\n return null;\n }\n };\n\n /**\n * Ask the panel to re-read the conversation from the server.\n *\n * Clearing the guard alone would not do it — the restore effect lives in the\n * panel and only re-runs when something in its dependencies changes, which is\n * what the nonce is for.\n */\n const reloadHistory = useCallback(() => {\n historyLoadedRef.current = false;\n setHistoryReloadNonce((n) => n + 1);\n }, []);\n\n // Determine upload endpoint URL (null disables file upload proxying)\n const getUploadUrl = (): string | null => {\n if (isLegacy || apiEndpoints?.singleEndpoint || apiEndpoints?.upload === null) {\n return null;\n }\n return `${apiBaseUrl}${apiEndpoints?.upload ?? '/chat/upload'}`;\n };\n\n // Determine sessions endpoint URL\n const getSessionsUrl = (): string | null => {\n if (isLegacy || apiEndpoints?.singleEndpoint || apiEndpoints?.sessions === null) {\n return null;\n }\n return `${apiBaseUrl}${apiEndpoints?.sessions ?? '/chat/sessions'}`;\n };\n\n /**\n * Update conversationId in React state, the ref mirror, and localStorage.\n * Stable identity (useCallback) so it can be used as an effect dependency.\n */\n const updateConversationId = useCallback((id: string | null) => {\n conversationIdRef.current = id;\n setConversationId(id);\n if (id) {\n localStorage.setItem(STORAGE_KEY, id);\n } else {\n localStorage.removeItem(STORAGE_KEY);\n }\n }, []);\n\n /**\n * Ensure a conversation exists. Uses a mutex so concurrent callers\n * (e.g. multiple files selected at once) share a single session creation.\n */\n const ensureConversation = async (slug: string | null | undefined): Promise<string | null> => {\n // Fast path: already have one\n if (conversationIdRef.current) return conversationIdRef.current;\n\n // If another call is already creating, wait for it\n if (creatingSessionRef.current) return creatingSessionRef.current;\n\n const sessionsUrl = getSessionsUrl();\n if (!sessionsUrl) return null;\n\n const promise = (async () => {\n try {\n const res = await fetch(sessionsUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ agent_slug: slug }),\n });\n if (!res.ok) return null;\n const data = await res.json();\n const convId = (data?.conversation_id as string) ?? null;\n if (convId) {\n updateConversationId(convId);\n }\n return convId;\n } catch {\n return null;\n } finally {\n creatingSessionRef.current = null;\n }\n })();\n\n creatingSessionRef.current = promise;\n return promise;\n };\n\n /**\n * Upload a single file to the backend and return its file_id.\n */\n const uploadSingleFile = async (file: File, convId: string, signal: AbortSignal): Promise<string> => {\n const uploadUrl = getUploadUrl()!;\n const formData = new FormData();\n formData.append('conversation_id', convId);\n formData.append('file', file, file.name);\n\n const uploadHeaders = requestHeaders\n ? Object.fromEntries(\n Object.entries(requestHeaders).filter(([k]) => {\n const key = k.toLowerCase();\n return key !== 'content-type';\n }),\n )\n : undefined;\n\n const res = await fetch(uploadUrl, {\n method: 'POST',\n headers: uploadHeaders,\n body: formData,\n signal,\n });\n if (!res.ok) {\n throw new Error(`File upload failed: ${res.status}`);\n }\n const data = await res.json();\n const ids: string[] = data.file_ids ?? [];\n if (ids.length === 0) throw new Error('No file_id returned');\n return ids[0];\n };\n\n /**\n * Handle file selection: validate limits, add files to state immediately,\n * then upload them in the background. Each file chip shows its upload status.\n */\n const handleFileAdd = (fileList: FileList | null) => {\n if (!fileList || fileList.length === 0 || !getUploadUrl()) return;\n\n // Build the list of accepted files outside the state updater (pure logic)\n const incoming = Array.from(fileList);\n\n // We need current state to check limits — use a ref-like approach:\n // read attachedFiles via a one-shot updater that returns prev unchanged,\n // then compute outside. Simpler: just compute optimistically and let the\n // updater do the final gating.\n\n // Pre-generate stable IDs and entries so side effects use the same IDs\n const candidates: { file: File; tempId: string }[] = incoming.map((file) => ({\n file,\n tempId: crypto.randomUUID(),\n }));\n\n // Update state (pure — no side effects)\n let accepted: { file: File; tempId: string }[] = [];\n setAttachedFiles((prev) => {\n const currentCount = prev.length;\n const currentSize = prev.reduce((sum, f) => sum + f.size, 0);\n\n const slotsAvailable = effectiveMaxFileCount - currentCount;\n if (slotsAvailable <= 0) return prev;\n\n let sizeLeft = effectiveMaxTotalSize - currentSize;\n const filtered: { file: File; tempId: string }[] = [];\n for (const c of candidates.slice(0, slotsAvailable)) {\n if (c.file.size <= sizeLeft) {\n filtered.push(c);\n sizeLeft -= c.file.size;\n }\n }\n if (filtered.length === 0) return prev;\n\n accepted = filtered;\n\n const newEntries: ChatFile[] = filtered.map(({ file, tempId }) => ({\n name: file.name,\n type: file.type,\n size: file.size,\n rawFile: file,\n uploadStatus: 'pending' as const,\n fileId: tempId,\n }));\n\n return [...prev, ...newEntries];\n });\n\n // Launch uploads OUTSIDE the state updater (side effects)\n // Use setTimeout(0) to ensure state has settled after the updater\n setTimeout(() => {\n const signal = uploadAbortRef.current.signal;\n for (const { file, tempId } of accepted) {\n (async () => {\n try {\n const convId = await ensureConversation(agentSlug);\n if (!convId) {\n setAttachedFiles((p) => p.map((f) => (f.fileId === tempId ? { ...f, uploadStatus: 'error' } : f)));\n return;\n }\n const fileId = await uploadSingleFile(file, convId, signal);\n setAttachedFiles((p) => p.map((f) => (f.fileId === tempId ? { ...f, fileId, uploadStatus: 'done' } : f)));\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') return;\n setAttachedFiles((p) => p.map((f) => (f.fileId === tempId ? { ...f, uploadStatus: 'error' } : f)));\n }\n })();\n }\n }, 0);\n };\n\n const handlePaste = (e: React.ClipboardEvent) => {\n const { files } = e.clipboardData;\n if (files.length > 0) {\n e.preventDefault();\n handleFileAdd(files);\n }\n };\n\n /**\n * Mid-run steering: dispatch a message while the agent is still generating.\n * The user bubble is added optimistically and the steer endpoint is POSTed;\n * the backend persists the message and injects it into the running agentic\n * loop at the next iteration boundary. On failure (network error, or a\n * backend without steering support answering non-2xx) the optimistic bubble\n * is rolled back and the text is restored into the composer — prepended on\n * its own line if the user already typed something new — so the message is\n * never silently lost and never resets the in-flight run state.\n */\n const steerMessage = async (content: string) => {\n const steerUrl = getSteerUrl();\n const convId = conversationIdRef.current;\n if (!steerUrl || !convId) return;\n\n const optimistic: ChatMessage = {\n id: crypto.randomUUID(),\n role: 'user',\n content,\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, optimistic]);\n\n try {\n const res = await fetch(steerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ conversation_id: convId, content, agent_slug: agentSlug }),\n });\n if (!res.ok) throw new Error(`Steer failed: ${res.status}`);\n } catch {\n setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));\n setInputValue((prev) => (prev ? `${content}\\n${prev}` : content));\n }\n };\n\n /**\n * Answer a turn that paused on a gated tool call.\n *\n * The decision travels the same way a steering message does — a POST beside\n * the open stream — and for the same reason: the turn is still running, so\n * the answer cannot ride on a new one. The paused turn is polling for it and\n * resumes on the stream that is already open, with no lost context.\n *\n * Deliberately not carried on the turn's own AbortController: the two are\n * independent requests, and aborting the turn must not look like a decision.\n *\n * A failure leaves the prompt on screen. The alternative — clearing it —\n * would strand the turn paused with nothing to answer it, which is the exact\n * state this whole opt-in exists to avoid.\n */\n const submitApprovalDecisions = async (decisions: ToolApprovalDecision[]) => {\n const approveUrl = getApproveUrl();\n const convId = approvalConversationIdRef.current ?? conversationIdRef.current;\n // Nothing decided is a no-op, not a failure — the prompt only submits a\n // full set, so this is unreachable from the UI.\n if (decisions.length === 0) return;\n // Missing prerequisites must be VISIBLE. The prompt is on screen, the turn\n // is paused behind it, and a silent return would leave the reviewer\n // clicking a control that does nothing — the exact failure this feature\n // exists to prevent, reintroduced at the last step. Reachable if the host\n // never named an approve path, or if a paused turn arrived without a\n // conversation id on the first turn of a fresh conversation, where the id\n // is otherwise only learned from `done`.\n if (!approveUrl || !convId) {\n setApprovalError(t('This decision could not be sent. Reload the chat and try again.'));\n return;\n }\n\n setApprovalError(null);\n setIsSubmittingApproval(true);\n try {\n const res = await fetch(approveUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({\n conversation_id: convId,\n decisions: decisions.map((d) => ({\n tool_call_id: d.toolCallId,\n decision: d.verdict,\n // Only ever sent with a rejection, and only when the reviewer\n // actually wrote something — an empty string reaches the agent as\n // a reason that says nothing.\n ...(d.verdict === 'reject' && d.rejectionReason ? { rejection_reason: d.rejectionReason } : {}),\n })),\n }),\n });\n if (res.ok) {\n setPendingApprovals(null);\n if (approvalDetachedRef.current) {\n // Answered after a reload: the turn resumes, but the stream it would\n // have reported on died with the old page. The backend persists the\n // answer and suppresses the live `done`, so re-reading the\n // conversation is the only way it can ever appear — and without this\n // the click would look like it did nothing at all.\n approvalDetachedRef.current = false;\n resumeDeadlineRef.current = Date.now() + RESUME_WATCH_MS;\n setIsResumingAfterDecision(true);\n return;\n }\n // The turn is moving again; show that immediately rather than leaving\n // the composer looking idle until the next server event lands.\n setAgentStatus((prev) => (prev ? { ...prev, status: 'thinking' } : { status: 'thinking' }));\n return;\n }\n // 409: nothing is waiting any more — the turn finished, was cancelled, or\n // somebody else answered it. Distinguished from a transient failure\n // because retrying cannot help; the stream ending clears the prompt.\n setApprovalError(\n res.status === 409 ? t('This turn is no longer waiting for a decision.') : t('Could not send your decision. Please try again.'),\n );\n } catch {\n setApprovalError(t('Could not send your decision. Please try again.'));\n } finally {\n setIsSubmittingApproval(false);\n }\n };\n\n const handleSendMessage = async () => {\n const steerText = inputValue.trim();\n if (isLoading) {\n // Mid-run steering — text-only sends while a response is streaming.\n // Attachments keep the legacy wait behavior (the upload + message pair\n // cannot be injected into a running loop).\n if (steerText && attachedFiles.length === 0 && getSteerUrl() && conversationIdRef.current) {\n setInputValue('');\n await steerMessage(steerText);\n }\n return;\n }\n if (!inputValue.trim() && attachedFiles.length === 0) return;\n const content = inputValue.trim();\n\n const userMsg: ChatMessage = {\n id: crypto.randomUUID(),\n role: 'user',\n content,\n timestamp: new Date(),\n files: attachedFiles.length > 0 ? [...attachedFiles] : undefined,\n };\n setMessages((prev) => [...prev, userMsg]);\n setInputValue('');\n // Clear attachment chips after sending so the input returns to a clean state.\n setAttachedFiles([]);\n setIsLoading(true);\n setAgentStatus({ status: 'thinking' });\n hasUsedToolsRef.current = false;\n\n const assistantId = crypto.randomUUID();\n setMessages((prev) => [...prev, { id: assistantId, role: 'assistant', content: '', timestamp: new Date() }]);\n\n // The assistant message currently being streamed into. A steered turn can\n // produce multiple response segments on one SSE stream: the backend\n // completes the current segment (intermediate `done`), then runs a\n // follow-up pass for the steering message (fresh `thinking` + `stream`\n // events). Each segment gets its own assistant bubble. Declared outside\n // the try so the catch below writes the error into the LIVE segment, not\n // an already-completed one.\n let currentAssistantId = assistantId;\n let accumulated = '';\n let doneReceived = false;\n\n const deltas = createStreamDeltas((textChanged, thinking) => {\n if (textChanged) {\n // Snapshot the segment id and text: the state updater runs\n // asynchronously and `currentAssistantId` / `accumulated` may\n // already belong to the NEXT segment by then.\n const segId = currentAssistantId;\n const text = accumulated;\n setAgentStatus((prev) => ({ status: 'streaming', thinkingContent: prev?.thinkingContent }));\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: text } : m)));\n }\n if (thinking) {\n setAgentStatus((prev) => ({\n ...prev,\n status: prev?.status ?? 'thinking',\n thinkingContent: (prev?.thinkingContent ?? '') + thinking,\n }));\n }\n });\n streamDeltasRef.current = deltas;\n\n try {\n const controller = new AbortController();\n abortControllerRef.current = controller;\n\n // Collect file_ids from already-uploaded files (uploaded eagerly on selection)\n const fileIds = (userMsg.files ?? []).filter((f) => f.uploadStatus === 'done' && f.fileId).map((f) => f.fileId!);\n\n // Step 1: Send the message (with file_ids if files were uploaded)\n // Use conversationIdRef to get the latest value (may have been set by eager upload)\n const requestBody = buildRequestBody(backendType, content, {\n legacyChatId,\n conversationId: conversationIdRef.current,\n agentSlug,\n pageContext: pageContextRef.current,\n supportsToolApproval: getApproveUrl() !== null,\n });\n if (fileIds.length > 0) {\n (requestBody as Record<string, unknown>).file_ids = fileIds;\n }\n\n setAgentStatus({ status: 'thinking' });\n\n const res = await fetch(getMessagesUrl(), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify(requestBody),\n signal: controller.signal,\n });\n\n if (!res.ok || !res.body) {\n setMessages((prev) =>\n prev.map((m) => (m.id === assistantId ? { ...m, content: t('Unable to connect. Please check the configuration.') } : m)),\n );\n return;\n }\n\n const parseEvent = getParser(backendType);\n const ctx: ProtocolContext = { hasUsedTools: false, activeNodeId: '' };\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n /**\n * Open a new response segment when events keep flowing after a `done`.\n * Appends a fresh empty assistant message (after any steered user\n * bubble) and resets the per-segment accumulators. The fresh `thinking`\n * status also clears the reasoning window — each segment carries its\n * own reasoning, mirroring the web chat behavior.\n */\n const ensureSegment = () => {\n if (!doneReceived) return;\n // Nothing of the closed segment may land in the new one.\n deltas.flush();\n doneReceived = false;\n accumulated = '';\n currentAssistantId = crypto.randomUUID();\n const segmentId = currentAssistantId;\n setMessages((prev) => [...prev, { id: segmentId, role: 'assistant', content: '', timestamp: new Date() }]);\n setAgentStatus({ status: 'thinking' });\n };\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n for (const rawLine of lines) {\n const line = rawLine.replace(/\\r$/, '');\n if (!line.startsWith('data:')) continue;\n const jsonStr = line.startsWith('data: ') ? line.slice(6) : line.slice(5);\n try {\n const evt = JSON.parse(jsonStr) as Record<string, unknown>;\n const parsed: ParsedAction = parseEvent(evt, ctx);\n\n // Sync ref → context for cross-event tracking\n ctx.hasUsedTools = ctx.hasUsedTools || hasUsedToolsRef.current;\n\n switch (parsed.action) {\n case 'status': {\n ensureSegment();\n const segId = currentAssistantId;\n // Orthogonal to the status label below: a progress frame can\n // carry a fresh context reading whatever phase it announces.\n if (parsed.contextUsage) setContextUsage(parsed.contextUsage);\n if (parsed.status === 'tool_start') hasUsedToolsRef.current = true;\n if (parsed.status === 'thinking_text') {\n deltas.thinking(parsed.thinkingContent ?? '');\n break;\n }\n // Every other status lands after the text and reasoning that\n // arrived before it.\n deltas.flush();\n if (parsed.status === 'stream_retract') {\n // Rare: text that streamed as a provisional answer turned\n // out to precede tool calls — discard the answer bubble\n // (the text re-arrives as thinking_text right after, so it\n // lands in the reasoning window instead).\n accumulated = '';\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: '' } : m)));\n setAgentStatus((prev) => ({\n status: 'analyzing',\n thinkingContent: prev?.thinkingContent,\n }));\n } else if (parsed.status === 'tool_heartbeat') {\n // Liveness signal during a long tool execution: update the\n // elapsed counter but KEEP the current status label/tools —\n // replacing the status would flip e.g. \"Waiting for\n // background task…\" back to \"Thinking…\" mid-execution.\n // Re-anchor the elapsed origin on every beat so the local\n // 1s ticker in ChatThinking stays true to the server clock.\n const elapsedStartMs = typeof parsed.elapsedS === 'number' ? Date.now() - parsed.elapsedS * 1000 : undefined;\n setAgentStatus((prev) =>\n prev\n ? { ...prev, elapsedS: parsed.elapsedS, elapsedStartMs }\n : { status: 'tool_start', tools: parsed.tools, elapsedS: parsed.elapsedS, elapsedStartMs },\n );\n } else {\n setAgentStatus((prev) => ({\n status: parsed.status,\n tools: parsed.tools,\n thinkingContent: prev?.thinkingContent,\n }));\n }\n break;\n }\n\n case 'stream': {\n ensureSegment();\n accumulated += parsed.content;\n deltas.text();\n break;\n }\n\n case 'done': {\n deltas.flush();\n doneReceived = true;\n // A completed segment cannot still be waiting on a decision, so\n // any prompt left standing (a submission that failed against a\n // turn somebody else already answered) is stale.\n setPendingApprovals(null);\n setApprovalError(null);\n if (parsed.conversationId) {\n updateConversationId(parsed.conversationId);\n }\n // Closing reading wins: a turn whose last iteration compacted\n // ends lower than it peaked mid-run.\n if (parsed.contextUsage) setContextUsage(parsed.contextUsage);\n if (parsed.transferAgentId && parsed.transferAgentName) {\n setTransferredAgent({ id: parsed.transferAgentId, name: parsed.transferAgentName });\n }\n const segId = currentAssistantId;\n const finalContent = parsed.content || accumulated;\n // The backend stores a segment when its `done` is sent, and a\n // restore shows that time: stamping the send time instead would\n // change the footer on the next reload.\n const completedAt = new Date();\n setMessages((prev) =>\n prev.map((m) =>\n m.id === segId\n ? {\n ...m,\n content: finalContent,\n timestamp: completedAt,\n toolNames: parsed.toolNames,\n toolCallCount: parsed.toolCallCount,\n iterations: parsed.iterations,\n attachments: parsed.attachments,\n reasoning: parsed.reasoning,\n toolCallTrace: parsed.toolCallTrace,\n transferChain: parsed.transferChain,\n isTruncated: parsed.isTruncated,\n serverId: parsed.messageId ?? m.serverId,\n }\n : m,\n ),\n );\n break;\n }\n\n case 'approval_required': {\n // The turn stops here and the stream goes silent until a\n // decision is POSTed back. Not an end state: no segment is\n // opened or closed, `isLoading` stays true, and the rest of\n // the turn arrives on this same reader afterwards.\n deltas.flush();\n approvalConversationIdRef.current = parsed.conversationId ?? conversationIdRef.current;\n setApprovalError(null);\n setPendingApprovals(parsed.proposals);\n // Keep whatever reasoning the turn had already streamed: the\n // pause interrupts the turn, it does not start a new one, and\n // the prose leading up to the proposed call is exactly the\n // context the reviewer is about to judge it on.\n setAgentStatus((prev) => (prev ? { ...prev, status: 'awaiting_approval' } : { status: 'awaiting_approval' }));\n break;\n }\n\n case 'error': {\n ensureSegment();\n deltas.flush();\n const segId = currentAssistantId;\n setMessages((prev) =>\n prev.map((m) =>\n // The backend reported a failure of its own, so the generic\n // apology rather than \"check the configuration\": the\n // connection plainly worked.\n m.id === segId ? { ...m, content: parsed.content || t('Sorry, an error occurred. Please try again.') } : m,\n ),\n );\n return;\n }\n\n case 'set_chat_id':\n setLegacyChatId(parsed.chatId);\n localStorage.setItem(LEGACY_CHAT_ID_KEY, parsed.chatId);\n break;\n\n case 'noop':\n break;\n }\n\n // Keep ref in sync with context\n hasUsedToolsRef.current = ctx.hasUsedTools;\n } catch {\n /* skip malformed SSE */\n }\n }\n }\n deltas.flush();\n if (accumulated && !doneReceived) {\n const segId = currentAssistantId;\n const text = accumulated;\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: text || t('No response.') } : m)));\n }\n } catch (err) {\n // A frame still pending would land after the error below, or in the\n // chat that replaced an aborted stream.\n deltas.close();\n if (err instanceof DOMException && err.name === 'AbortError') return;\n const segId = currentAssistantId;\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: t('Sorry, an error occurred. Please try again.') } : m)));\n } finally {\n deltas.close();\n if (streamDeltasRef.current === deltas) streamDeltasRef.current = null;\n abortControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n // The stream is gone, so nothing can carry a decision any more —\n // whether the turn finished, errored, or was stopped. Leaving the prompt\n // up would offer an answer to a question nobody is listening for.\n setPendingApprovals(null);\n setApprovalError(null);\n approvalConversationIdRef.current = null;\n approvalDetachedRef.current = false;\n // We watched this turn end, so there is nothing for the recovery probe to\n // find — including on a fresh conversation, whose id only just arrived.\n probedConversationRef.current = conversationIdRef.current;\n }\n };\n\n const handleNewChat = () => {\n // Nothing of the abandoned stream may land in the fresh chat.\n streamDeltasRef.current?.close();\n streamDeltasRef.current = null;\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n // Cancel any in-flight file uploads\n uploadAbortRef.current.abort();\n uploadAbortRef.current = new AbortController();\n creatingSessionRef.current = null;\n setMessages([]);\n setInputValue('');\n setAttachedFiles([]);\n setIsLoading(false);\n setAgentStatus(null);\n setTransferredAgent(null);\n // A fresh (or newly selected) conversation starts with no known occupancy;\n // the restore or the first turn fills it back in. Carrying the previous\n // conversation's reading over would be a plain lie.\n setContextUsage(null);\n setPendingApprovals(null);\n setApprovalError(null);\n setIsResumingAfterDecision(false);\n approvalConversationIdRef.current = null;\n approvalDetachedRef.current = false;\n // Re-arm the probe: the conversation being switched to may well be paused.\n probedConversationRef.current = null;\n hasUsedToolsRef.current = false;\n historyLoadedRef.current = false;\n if (isLegacy) {\n setLegacyChatId(null);\n localStorage.removeItem(LEGACY_CHAT_ID_KEY);\n } else {\n updateConversationId(null);\n }\n };\n\n const handleSwitchConversation = (id: string) => {\n if (!isLegacy && id === conversationIdRef.current) return;\n // Reuse the full new-chat reset (abort in-flight request + uploads,\n // clear transcript/composer/status), then adopt the selected id and\n // re-arm the history-restore effect so the host panel fetches the\n // conversation's messages via the sessions endpoint.\n handleNewChat();\n if (!isLegacy) {\n updateConversationId(id);\n // `handleNewChat` blanked the composer; bring back this conversation's\n // own unsent draft, if any.\n setInputValue(loadDraft(id));\n }\n };\n\n const handleStopGenerating = () => {\n // The text that arrived before the stop stays on screen, including what the\n // next frame would have applied; nothing after it does.\n streamDeltasRef.current?.flush();\n streamDeltasRef.current?.close();\n streamDeltasRef.current = null;\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n // Stopping IS the way out of a pause the reviewer does not want to answer:\n // the backend waits indefinitely by design, so abandoning the stream is\n // the client's only other move.\n setPendingApprovals(null);\n setApprovalError(null);\n setIsResumingAfterDecision(false);\n approvalConversationIdRef.current = null;\n approvalDetachedRef.current = false;\n setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.content)));\n };\n\n // Persist the composer draft against the conversation it belongs to. Writing\n // an empty value removes the entry, so sending (which blanks the composer)\n // also clears the draft — no explicit cleanup needed at the send sites.\n useEffect(() => {\n const id = window.setTimeout(() => persistDraft(conversationId, inputValue), DRAFT_PERSIST_DELAY_MS);\n return () => window.clearTimeout(id);\n }, [inputValue, conversationId]);\n\n // A panel closed mid-stream has no state left for the stream's frames to update.\n useEffect(() => () => streamDeltasRef.current?.close(), []);\n\n // Flush the pending draft on unmount. Hosts unmount the panel the instant it\n // is closed, which would otherwise drop anything typed inside the debounce\n // window — exactly the keystrokes the draft exists to protect.\n const draftFlushRef = useRef({ conversationId, inputValue });\n draftFlushRef.current = { conversationId, inputValue };\n useEffect(\n () => () => {\n const { conversationId: id, inputValue: value } = draftFlushRef.current;\n persistDraft(id, value);\n },\n [],\n );\n\n /**\n * Recover a prompt the page never saw, or lost to a reload.\n *\n * `approval_required` is one event on one stream: reload while it is showing\n * and the panel holds nothing — not even the `tool_call_id`s a decision has\n * to name — while the turn goes on waiting for an answer that can no longer\n * be given. Asked once per conversation; an empty list is the ordinary\n * answer, and the whole probe is best-effort, since a host that has not\n * exposed the route simply keeps the pre-recovery behaviour.\n *\n * Skipped while a turn is live: that prompt arrives on the stream, and the\n * stream is the more current of the two.\n */\n useEffect(() => {\n const convId = conversationId;\n if (!convId || isLoading) return;\n if (probedConversationRef.current === convId) return;\n // Recovering a prompt there is no way to answer would only strand the\n // reviewer differently, so both routes have to be configured.\n const url = getPendingApprovalsUrl(convId);\n if (!url || !getApproveUrl()) return;\n probedConversationRef.current = convId;\n\n (async () => {\n // Best-effort: a failure leaves the panel exactly as it was, which is the\n // pre-recovery behaviour.\n const state = await readPendingApprovals(convId);\n if (!state?.proposals) return;\n // Validate at apply time against the live refs rather than dropping the\n // response on effect teardown — the same reasoning as the panel's\n // history restore. A StrictMode double-invoke or a host re-render tears\n // this effect down while the request is in flight without the\n // conversation having changed, and a teardown flag would discard the\n // recovery in exactly the case it is needed. Only a genuinely superseded\n // response is dropped: another conversation, or a live turn that has\n // since started and will carry its own prompt.\n if (conversationIdRef.current !== convId || isLoadingRef.current) return;\n approvalConversationIdRef.current = convId;\n approvalDetachedRef.current = true;\n setApprovalError(null);\n setPendingApprovals(state.proposals);\n })();\n // Keyed on the conversation and whether a turn is live; the endpoint\n // getters read current props on each run and must not re-trigger a probe.\n }, [conversationId, isLoading]);\n\n /**\n * Keep a recovered prompt answerable for as long as it is displayed.\n *\n * Only for prompts recovered after a reload: a live one is held open by its\n * own stream, which vouches for the reviewer on its own. Re-reading the\n * pending approvals is the lightest request that counts as a sign of life,\n * and its result is deliberately ignored — this is a heartbeat, not a poll,\n * and a prompt that has since gone stale is better answered with the 409 the\n * reviewer can see than made to vanish under them.\n */\n useEffect(() => {\n if (!pendingApprovals?.length || !approvalDetachedRef.current) return;\n const convId = approvalConversationIdRef.current;\n const url = convId ? getPendingApprovalsUrl(convId) : null;\n if (!url) return;\n const id = window.setInterval(() => {\n fetch(url, { headers: { ...(requestHeaders ?? {}) } }).catch(() => {\n /* A missed heartbeat is survivable: the next one is well inside the\n server's window. */\n });\n }, APPROVAL_PRESENCE_INTERVAL_MS);\n return () => window.clearInterval(id);\n // Re-armed whenever the prompt itself changes; the endpoint getter reads\n // current props on each run.\n }, [pendingApprovals]);\n\n /**\n * Watch a turn resumed by a decision made on a recovered prompt.\n *\n * The turn has no stream left to announce itself on, so its state is read\n * from the pause-recovery route: keep watching while it reports `running`,\n * and re-read the conversation once — the answer is there — when it reports\n * idle. Polling that route rather than the transcript is what makes the stop\n * condition definite instead of a guess, and it keeps the turn alive as a\n * side effect.\n *\n * A resumed turn can also pause *again* on a second gated call. With no\n * stream, this poll is the only way that prompt could ever reach the user, so\n * finding proposals puts the panel straight back into deciding.\n */\n useEffect(() => {\n if (!isResumingAfterDecision) return;\n const convId = approvalConversationIdRef.current;\n if (!convId) {\n setIsResumingAfterDecision(false);\n return;\n }\n if (Date.now() >= resumeDeadlineRef.current) {\n // Backstop only, for a turn-state marker that never clears. Re-read once\n // on the way out so a finished answer still lands.\n setIsResumingAfterDecision(false);\n reloadHistory();\n return;\n }\n\n let cancelled = false;\n const id = window.setTimeout(async () => {\n const state = await readPendingApprovals(convId);\n if (cancelled) return;\n if (!state) {\n // Learned nothing — a transient failure. Try again rather than\n // declaring a running turn finished.\n setResumeTick((n) => n + 1);\n return;\n }\n if (state.proposals) {\n approvalDetachedRef.current = true;\n setApprovalError(null);\n setPendingApprovals(state.proposals);\n setIsResumingAfterDecision(false);\n return;\n }\n if (!state.turnRunning) {\n setIsResumingAfterDecision(false);\n reloadHistory();\n return;\n }\n setResumeTick((n) => n + 1);\n }, RESUME_POLL_MS);\n\n return () => {\n cancelled = true;\n window.clearTimeout(id);\n };\n }, [isResumingAfterDecision, resumeTick, reloadHistory]);\n\n // Steering affordances are only advertised when the typed text can actually\n // be dispatched mid-run: a response is streaming (isLoading), the REST steer\n // endpoint is configured, and the conversation already has a server id (the\n // very first turn of a fresh conversation only receives its id on `done`).\n const canSteer = isLoading && getSteerUrl() !== null && conversationId !== null;\n\n return {\n messages,\n inputValue,\n setInputValue,\n isLoading,\n agentStatus,\n attachedFiles,\n conversationId,\n contextUsage,\n transferredAgent,\n canSteer,\n pendingApprovals,\n isSubmittingApproval,\n approvalError,\n submitApprovalDecisions,\n isResumingAfterDecision,\n historyReloadNonce,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\n setContextUsage,\n updateConversationId,\n handleSwitchConversation,\n };\n}\n","/**\n * Streamed answer text and reasoning, applied to React state at most once per\n * animation frame.\n *\n * A backend can emit one event per model delta, dozens a second: applied one by\n * one, each re-renders the panel and re-parses the live answer, far more often\n * than the screen can show. The deltas are gathered here and applied together\n * on the next frame. Every other event is handled after a `flush()`, so state\n * still changes in the order the events arrived.\n *\n * A hidden tab runs no frames, and needs none: what waits is the text itself,\n * not a queue of events, and the first frame once the tab is visible applies\n * it - or, before that, the next event of another kind or the end of the\n * stream.\n */\nexport interface StreamDeltas {\n /** The answer text grew; the applier reads the text itself. */\n text: () => void;\n /** A chunk of reasoning prose arrived. */\n thinking: (chunk: string) => void;\n /** Apply what is pending now. */\n flush: () => void;\n /** Drop what is pending and ignore any later delta: the stream is over or abandoned. */\n close: () => void;\n}\n\nexport function createStreamDeltas(apply: (textChanged: boolean, thinking: string) => void): StreamDeltas {\n let textChanged = false;\n let thinking = '';\n let frame: number | null = null;\n let closed = false;\n\n const cancelFrame = () => {\n if (frame !== null) cancelAnimationFrame(frame);\n frame = null;\n };\n const flush = () => {\n cancelFrame();\n if (!textChanged && !thinking) return;\n const changed = textChanged;\n const chunk = thinking;\n textChanged = false;\n thinking = '';\n apply(changed, chunk);\n };\n const schedule = () => {\n if (frame !== null) return;\n if (typeof requestAnimationFrame !== 'function') {\n flush();\n return;\n }\n frame = requestAnimationFrame(() => {\n frame = null;\n flush();\n });\n };\n\n return {\n text: () => {\n if (closed) return;\n textChanged = true;\n schedule();\n },\n thinking: (chunk) => {\n if (closed) return;\n thinking += chunk;\n schedule();\n },\n flush,\n close: () => {\n closed = true;\n cancelFrame();\n textChanged = false;\n thinking = '';\n },\n };\n}\n","import { useEffect, useState } from 'react';\nimport type { ApiEndpoints, BackendType, XtmAgent } from '../types';\n\nconst STORAGE_AGENT_KEY = 'filigranChatAgentSlug';\n\ninterface UseAgentsOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\ninterface UseAgentsReturn {\n agents: XtmAgent[];\n /** True while the first fetch is in flight. */\n agentsLoading: boolean;\n /**\n * Set when the agent list could not be retrieved — the backend is\n * unreachable, or answered an error. Distinguishes \"still loading\" from\n * \"there is nothing to load\", which an empty array alone cannot.\n */\n agentsError: boolean;\n selectedAgent: XtmAgent | null;\n setSelectedAgent: React.Dispatch<React.SetStateAction<XtmAgent | null>>;\n agentMenuOpen: boolean;\n setAgentMenuOpen: React.Dispatch<React.SetStateAction<boolean>>;\n handleSwitchAgent: (agent: XtmAgent, onSwitch?: () => void) => void;\n}\n\n/**\n * Normalize the raw agents list response.\n * Defensive: the endpoint may answer with something other than a JSON array\n * (an error envelope, an HTML error page that happens to parse), and an\n * `agents.map is not a function` thrown in ChatHeader blanks the whole panel.\n * Accepts both the bare array and the `{ agents: [...] }` envelope, mirroring\n * what useConversations tolerates, and drops entries without an agent id.\n */\nfunction parseAgents(data: unknown): XtmAgent[] {\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.agents)\n ? ((data as Record<string, unknown>).agents as unknown[])\n : [];\n return rawList.filter((raw): raw is XtmAgent => !!raw && typeof raw === 'object' && typeof (raw as XtmAgent).id === 'string');\n}\n\nexport function useAgents({ apiBaseUrl, apiEndpoints, backendType = 'rest', requestHeaders }: UseAgentsOptions): UseAgentsReturn {\n const [agents, setAgents] = useState<XtmAgent[]>([]);\n const [agentsLoading, setAgentsLoading] = useState(false);\n const [agentsError, setAgentsError] = useState(false);\n const [selectedAgent, setSelectedAgent] = useState<XtmAgent | null>(null);\n const [agentMenuOpen, setAgentMenuOpen] = useState(false);\n\n useEffect(() => {\n // Skip agents fetch if disabled, using single endpoint mode, or legacy backend\n if (apiEndpoints?.agents === null || apiEndpoints?.singleEndpoint || backendType === 'legacy') {\n return;\n }\n const agentsUrl = `${apiBaseUrl}${apiEndpoints?.agents ?? '/chat/agents'}`;\n setAgentsLoading(true);\n setAgentsError(false);\n fetch(agentsUrl, { headers: requestHeaders })\n .then((res) => {\n // A non-2xx is a failure, not an empty catalogue. Mapping it to `[]`\n // was why an unreachable backend left the menu spinning forever with\n // nothing to explain it.\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.json();\n })\n .then((data: unknown) => {\n const list = parseAgents(data);\n setAgents(list);\n if (list.length > 0 && !selectedAgent) {\n const savedSlug = localStorage.getItem(STORAGE_AGENT_KEY);\n const match = savedSlug ? list.find((a) => a.slug === savedSlug) : null;\n setSelectedAgent(match || list[0]);\n }\n })\n .catch(() => {\n setAgents([]);\n setAgentsError(true);\n })\n .finally(() => setAgentsLoading(false));\n }, [apiBaseUrl, apiEndpoints, backendType, requestHeaders]);\n\n const handleSwitchAgent = (agent: XtmAgent, onSwitch?: () => void) => {\n if (agent.id === selectedAgent?.id) {\n setAgentMenuOpen(false);\n return;\n }\n setSelectedAgent(agent);\n if (agent.slug) localStorage.setItem(STORAGE_AGENT_KEY, agent.slug);\n setAgentMenuOpen(false);\n onSwitch?.();\n };\n\n return {\n agents,\n agentsLoading,\n agentsError,\n selectedAgent,\n setSelectedAgent,\n agentMenuOpen,\n setAgentMenuOpen,\n handleSwitchAgent,\n };\n}\n","import { useCallback, useState } from 'react';\nimport type { ApiEndpoints, BackendType, ChatConversationSummary } from '../types';\n\ninterface UseConversationsOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\ninterface UseConversationsReturn {\n /** Whether the history feature is available at all (REST backend with a sessions endpoint). */\n historyEnabled: boolean;\n conversations: ChatConversationSummary[];\n conversationsLoading: boolean;\n /** Fetch (or re-fetch) the conversation list. No-ops when history is disabled. */\n refreshConversations: () => Promise<void>;\n /** Delete a conversation server-side. Returns true on success. */\n deleteConversation: (id: string) => Promise<boolean>;\n /** Rename a conversation server-side. Returns true on success. */\n renameConversation: (id: string, title: string) => Promise<boolean>;\n}\n\n/**\n * Normalize one raw conversation entry from the backend list response.\n * Defensive: skips entries without a conversation id, accepts both the\n * snake_case REST shape and a few aliases so older proxies keep working.\n */\nfunction parseConversation(raw: unknown): ChatConversationSummary | null {\n if (!raw || typeof raw !== 'object') return null;\n const c = raw as Record<string, unknown>;\n const id = c.conversation_id ?? c.id;\n if (typeof id !== 'string' || !id) return null;\n // Keep the raw (trimmed) title; the localized \"Untitled conversation\"\n // fallback is applied at render time (ChatHeader) so it goes through the\n // component's translation function instead of being hardcoded in English.\n const title = typeof c.title === 'string' ? c.title.trim() : '';\n const updatedAt = typeof c.updated_at === 'string' ? c.updated_at : typeof c.created_at === 'string' ? c.created_at : undefined;\n const messageCount = typeof c.message_count === 'number' ? c.message_count : undefined;\n const agentName = typeof c.agent_name === 'string' && c.agent_name ? c.agent_name : undefined;\n return { conversationId: id, title, updatedAt, messageCount, agentName };\n}\n\n/**\n * Multi-conversation history for the REST backend (mirrors the XTM One web\n * chat sidebar). The conversation list is fetched lazily — when the history\n * menu opens — via `GET {apiBaseUrl}{sessions}`, and conversations are\n * deleted via `DELETE {apiBaseUrl}{sessions}/{conversation_id}`.\n *\n * Degrades gracefully: a backend that doesn't implement the list endpoint\n * yet (404/405/network error) simply yields an empty list, so the menu shows\n * its empty state instead of breaking the chat.\n */\nexport function useConversations({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n requestHeaders,\n}: UseConversationsOptions): UseConversationsReturn {\n const [conversations, setConversations] = useState<ChatConversationSummary[]>([]);\n const [conversationsLoading, setConversationsLoading] = useState(false);\n\n const historyEnabled = backendType === 'rest' && !apiEndpoints?.singleEndpoint && apiEndpoints?.sessions !== null && apiEndpoints?.history !== null;\n\n const sessionsUrl = `${apiBaseUrl}${apiEndpoints?.history ?? apiEndpoints?.sessions ?? '/chat/sessions'}`;\n\n const refreshConversations = useCallback(async () => {\n if (!historyEnabled) return;\n setConversationsLoading(true);\n try {\n const res = await fetch(sessionsUrl, {\n method: 'GET',\n headers: { ...(requestHeaders ?? {}) },\n });\n if (!res.ok) {\n setConversations([]);\n return;\n }\n const data: unknown = await res.json();\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.conversations)\n ? ((data as Record<string, unknown>).conversations as unknown[])\n : [];\n setConversations(rawList.map(parseConversation).filter((c): c is ChatConversationSummary => c !== null));\n } catch {\n setConversations([]);\n } finally {\n setConversationsLoading(false);\n }\n }, [historyEnabled, sessionsUrl, requestHeaders]);\n\n const deleteConversation = useCallback(\n async (id: string): Promise<boolean> => {\n if (!historyEnabled) return false;\n try {\n const res = await fetch(`${sessionsUrl}/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n headers: { ...(requestHeaders ?? {}) },\n });\n if (!res.ok) return false;\n setConversations((prev) => prev.filter((c) => c.conversationId !== id));\n return true;\n } catch {\n return false;\n }\n },\n [historyEnabled, sessionsUrl, requestHeaders],\n );\n\n const renameConversation = useCallback(\n async (id: string, title: string): Promise<boolean> => {\n const trimmed = title.trim();\n // An empty title is a no-op rather than an error: the backend would name\n // the conversation from its first message anyway, and silently wiping a\n // title because the user cleared the field and hit Enter is worse.\n if (!historyEnabled || !trimmed) return false;\n // Optimistic: the row is being edited in place, so waiting for the\n // round-trip would make it flicker back to the old title first.\n const previous = conversations;\n setConversations((prev) => prev.map((c) => (c.conversationId === id ? { ...c, title: trimmed } : c)));\n try {\n const res = await fetch(`${sessionsUrl}/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ title: trimmed }),\n });\n if (!res.ok) {\n setConversations(previous);\n return false;\n }\n return true;\n } catch {\n setConversations(previous);\n return false;\n }\n },\n [historyEnabled, sessionsUrl, requestHeaders, conversations],\n );\n\n return { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation, renameConversation };\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { ChatMode } from '../types';\n\nconst SIDEBAR_WIDTH = 400;\nconst SIDEBAR_WIDTH_STORAGE_KEY = 'filigranChatSidebarWidth';\nconst MAX_SIDEBAR_RATIO = 0.4;\n\ninterface UseSidebarResizeOptions {\n mode: ChatMode;\n resizable: boolean;\n onWidthChange?: (width: number) => void;\n onResizeStart?: () => void;\n onResizeEnd?: () => void;\n}\n\ninterface UseSidebarResizeReturn {\n sidebarWidth: number;\n handleResizeStart: (e: React.MouseEvent) => void;\n defaultWidth: number;\n isResizing: boolean;\n}\n\nexport function useSidebarResize({ mode, resizable, onWidthChange, onResizeStart, onResizeEnd }: UseSidebarResizeOptions): UseSidebarResizeReturn {\n const [sidebarWidth, setSidebarWidth] = useState<number>(() => {\n if (typeof window === 'undefined') return SIDEBAR_WIDTH;\n const stored = localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY);\n if (stored) {\n const parsed = parseInt(stored, 10);\n if (!Number.isNaN(parsed) && parsed >= SIDEBAR_WIDTH) return parsed;\n }\n return SIDEBAR_WIDTH;\n });\n const [isResizing, setIsResizing] = useState(false);\n\n const isResizingRef = useRef(false);\n const sidebarWidthRef = useRef(sidebarWidth);\n sidebarWidthRef.current = sidebarWidth;\n const onWidthChangeRef = useRef(onWidthChange);\n onWidthChangeRef.current = onWidthChange;\n const onResizeEndRef = useRef(onResizeEnd);\n onResizeEndRef.current = onResizeEnd;\n\n // Notify parent of sidebar width when entering sidebar mode\n useEffect(() => {\n if (mode === 'sidebar' && resizable) {\n onWidthChangeRef.current?.(sidebarWidthRef.current);\n }\n }, [mode, resizable]);\n\n // Resize event handlers\n useEffect(() => {\n if (mode !== 'sidebar' || !resizable) return undefined;\n\n const handleMouseMove = (e: MouseEvent) => {\n if (!isResizingRef.current) return;\n e.preventDefault();\n const newWidth = window.innerWidth - e.clientX;\n const maxWidth = window.innerWidth * MAX_SIDEBAR_RATIO;\n const clamped = Math.min(Math.max(newWidth, SIDEBAR_WIDTH), maxWidth);\n setSidebarWidth(clamped);\n sidebarWidthRef.current = clamped;\n onWidthChangeRef.current?.(clamped);\n };\n\n const handleMouseUp = () => {\n if (!isResizingRef.current) return;\n isResizingRef.current = false;\n setIsResizing(false);\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(sidebarWidthRef.current));\n onResizeEndRef.current?.();\n };\n\n const handleWindowResize = () => {\n const maxWidth = window.innerWidth * MAX_SIDEBAR_RATIO;\n if (sidebarWidthRef.current > maxWidth) {\n const clamped = Math.max(maxWidth, SIDEBAR_WIDTH);\n setSidebarWidth(clamped);\n sidebarWidthRef.current = clamped;\n onWidthChangeRef.current?.(clamped);\n }\n };\n\n document.addEventListener('mousemove', handleMouseMove);\n document.addEventListener('mouseup', handleMouseUp);\n window.addEventListener('resize', handleWindowResize);\n\n return () => {\n document.removeEventListener('mousemove', handleMouseMove);\n document.removeEventListener('mouseup', handleMouseUp);\n window.removeEventListener('resize', handleWindowResize);\n };\n }, [mode, resizable]);\n\n const handleResizeStart = (e: React.MouseEvent) => {\n e.preventDefault();\n isResizingRef.current = true;\n setIsResizing(true);\n document.body.style.cursor = 'col-resize';\n document.body.style.userSelect = 'none';\n onResizeStart?.();\n };\n\n return {\n sidebarWidth,\n handleResizeStart,\n defaultWidth: SIDEBAR_WIDTH,\n isResizing,\n };\n}\n","import { useEffect, useRef } from 'react';\nimport { translate } from '../utils';\n\n/**\n * A turn must run at least this long before its completion is worth a\n * notification — instant replies never raise one.\n */\nconst MIN_NOTICE_MS = 4000;\n/** Document-title flash cadence while the user is away. */\nconst TITLE_FLASH_MS = 1200;\n\n// The document title is a single page-global resource, so the flash is shared\n// across hook instances on purpose (per-hook timers would fight over the one\n// `document.title` and clobber each other's saved title). `activeHooks` ref-\n// counts mounted, enabled instances so one panel unmounting never cancels a\n// flash another panel still owns — only the last one to leave restores it.\nlet flashTimer: number | null = null;\nlet originalTitle: string | null = null;\nlet activeHooks = 0;\n\n/** Stop flashing and restore the page title captured when the flash began. */\nfunction stopTitleFlash(): void {\n if (flashTimer !== null) {\n window.clearInterval(flashTimer);\n flashTimer = null;\n }\n if (originalTitle !== null) {\n document.title = originalTitle;\n originalTitle = null;\n }\n}\n\n/**\n * Flash the document title so a multitasking user notices the answer landed\n * even from another tab or window. The flash is stopped (and the title\n * restored) the moment the tab is visible AND focused again, by the\n * hook-scoped listeners below. Title flashing needs no permission and is the\n * reliable baseline of the completion notification.\n */\nfunction startTitleFlash(message: string): void {\n if (typeof document === 'undefined') return;\n if (originalTitle === null) originalTitle = document.title;\n if (flashTimer !== null) window.clearInterval(flashTimer);\n let showMessage = true;\n document.title = message;\n flashTimer = window.setInterval(() => {\n showMessage = !showMessage;\n document.title = showMessage ? message : (originalTitle ?? message);\n }, TITLE_FLASH_MS);\n}\n\n/**\n * Best-effort OS notification — only fired when the user has already granted\n * permission. We deliberately never call `Notification.requestPermission()`\n * unprompted: the title flash (and the host toast) cover the case where OS\n * notifications are unavailable.\n */\nfunction notifyOS(title: string, body: string): void {\n try {\n if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return;\n new Notification(title, { body, tag: 'filigran-chat-complete' });\n } catch {\n /* Notification constructor can throw on some platforms — ignore. */\n }\n}\n\ninterface UseAwayCompletionNoticeOptions {\n /** True while a response is being generated. */\n isLoading: boolean;\n /** Name of the answering agent, used in the notification body. */\n agentName: string;\n t: (key: string) => string;\n /** Master switch (default true). */\n enabled?: boolean;\n /**\n * Host hook fired when a long turn finishes and the user is not actively\n * watching the chat — either away (tab hidden / another window) or in-app\n * with the chat surface closed/hidden (`isViewingChat` reports not-viewing).\n * Lets the host raise its own in-app toast (the chatbot has no toast surface\n * of its own). Receives the translated strings.\n */\n onComplete?: (title: string, body: string) => void;\n /**\n * Returns true when the chat surface is on screen for the user (the panel is\n * open and visible) — NOT merely whether focus sits inside it. When provided,\n * the notice also fires if the chat surface is hidden/closed while the tab is\n * still focused (e.g. a docked sidebar the host has collapsed). It must NOT\n * key on focus-within: in sidebar/floating mode the user reads a streamed\n * answer while their focus stays in the host app, and pinging them for an\n * answer they can already see is exactly the noise this guards against. When\n * omitted, only the away case (tab hidden / window unfocused) triggers it.\n */\n isViewingChat?: () => boolean;\n}\n\n/**\n * Notify the user when a long-running turn finishes and they are not watching\n * the chat. State is read at completion (never latched mid-turn) so someone who\n * stepped away but returned before the turn finished is not pinged:\n * - **Away** (tab hidden or another window/app focused): document-title flash +\n * OS notification (when granted) + host toast.\n * - **Surface not visible** (window focused & tab visible, but the chat panel\n * is closed/hidden — only when `isViewingChat` reports not-viewing): host\n * toast only.\n * - **Actively watching** (tab visible, window focused, panel on screen):\n * nothing — the streamed answer is itself the feedback.\n */\nexport function useAwayCompletionNotice({\n isLoading,\n agentName,\n t,\n enabled = true,\n onComplete,\n isViewingChat,\n}: UseAwayCompletionNoticeOptions): void {\n const wasLoadingRef = useRef(false);\n const startRef = useRef(0);\n\n // Stop the flash and restore the title as soon as the user returns to a\n // visible, focused tab. Bound only while enabled and torn down on unmount (or\n // when the host disables it), so we never leak listeners or leave the title\n // flashing after the panel is gone.\n useEffect(() => {\n if (!enabled || typeof document === 'undefined') return;\n activeHooks += 1;\n const clearOnReturn = () => {\n if (!document.hidden && document.hasFocus()) stopTitleFlash();\n };\n document.addEventListener('visibilitychange', clearOnReturn);\n window.addEventListener('focus', clearOnReturn);\n return () => {\n document.removeEventListener('visibilitychange', clearOnReturn);\n window.removeEventListener('focus', clearOnReturn);\n activeHooks = Math.max(0, activeHooks - 1);\n // Only restore the title once the last consumer leaves, so unmounting one\n // panel never cancels another panel's in-flight flash.\n if (activeHooks === 0) stopTitleFlash();\n };\n }, [enabled]);\n\n useEffect(() => {\n const wasLoading = wasLoadingRef.current;\n wasLoadingRef.current = isLoading;\n\n if (isLoading && !wasLoading) {\n startRef.current = Date.now();\n return;\n }\n\n if (!isLoading && wasLoading && enabled) {\n const elapsed = Date.now() - startRef.current;\n if (elapsed < MIN_NOTICE_MS) return;\n const hidden = typeof document !== 'undefined' && document.hidden;\n const unfocused = typeof document !== 'undefined' && !document.hasFocus();\n const away = hidden || unfocused;\n const viewingChat = isViewingChat ? isViewingChat() : true;\n // Focused tab + looking at the chat → the streamed answer is the feedback.\n if (!away && viewingChat) return;\n const title = t('Response ready');\n const body = agentName ? translate(t, '{agent} has finished', { agent: agentName }) : t('Your answer is ready');\n if (away) {\n startTitleFlash(title);\n notifyOS(title, body);\n }\n onComplete?.(title, body);\n }\n }, [isLoading, enabled, agentName, t, onComplete, isViewingChat]);\n}\n","import { useCallback, useEffect, useState } from 'react';\nimport type { ApiEndpoints, BackendType, ChatPromptTemplate, ChatQuotaStatus } from '../types';\nimport { parseQuota } from '../utils/quota';\n\ninterface UseComposerExtrasOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\ninterface UseComposerExtrasReturn {\n /** Null while unavailable — the toolbar then omits the affordance entirely. */\n prompts: ChatPromptTemplate[] | null;\n quota: ChatQuotaStatus | null;\n /** Re-read the quota after a turn completes, so the indicator stays honest. */\n refreshQuota: () => void;\n}\n\n/** Defensive parse: an unexpected payload yields no prompts rather than a crash. */\nfunction parsePrompts(data: unknown): ChatPromptTemplate[] {\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.prompts)\n ? ((data as Record<string, unknown>).prompts as unknown[])\n : [];\n const out: ChatPromptTemplate[] = [];\n for (const item of rawList) {\n if (!item || typeof item !== 'object') continue;\n const p = item as Record<string, unknown>;\n const id = typeof p.id === 'string' ? p.id : '';\n const content = typeof p.content === 'string' ? p.content : '';\n // A prompt with nothing to insert is not worth listing.\n if (!id || !content) continue;\n out.push({\n id,\n title: typeof p.title === 'string' && p.title ? p.title : id,\n content,\n description: typeof p.description === 'string' ? p.description : undefined,\n });\n }\n return out;\n}\n\n/**\n * Fetches the two data-driven composer toolbar items: the prompt library and\n * the quota indicator.\n *\n * Both are opt-in by configuration rather than by a mode flag — a host that\n * does not serve the route (or sets it to null) simply gets no affordance, so\n * the UI can never advertise something the backend cannot answer. Neither is\n * available on the legacy / ag-ui backends or in single-endpoint mode, which\n * have no route to carry them.\n */\nexport function useComposerExtras({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n requestHeaders,\n}: UseComposerExtrasOptions): UseComposerExtrasReturn {\n const [prompts, setPrompts] = useState<ChatPromptTemplate[] | null>(null);\n const [quota, setQuota] = useState<ChatQuotaStatus | null>(null);\n\n const restLike = backendType === 'rest' && !apiEndpoints?.singleEndpoint;\n const promptsPath = apiEndpoints?.prompts === undefined ? '/chat/prompts' : apiEndpoints.prompts;\n const quotaPath = apiEndpoints?.quota === undefined ? '/chat/quota' : apiEndpoints.quota;\n const promptsUrl = restLike && promptsPath ? `${apiBaseUrl}${promptsPath}` : null;\n const quotaUrl = restLike && quotaPath ? `${apiBaseUrl}${quotaPath}` : null;\n\n useEffect(() => {\n if (!promptsUrl) {\n setPrompts(null);\n return;\n }\n let cancelled = false;\n fetch(promptsUrl, { credentials: 'include', headers: { ...(requestHeaders ?? {}) } })\n .then((res) => (res.ok ? res.json() : null))\n .then((data) => {\n if (cancelled) return;\n // A failed or empty fetch leaves the affordance hidden rather than\n // showing an empty menu the user cannot act on.\n const parsed = data === null ? [] : parsePrompts(data);\n setPrompts(parsed.length > 0 ? parsed : null);\n })\n .catch(() => {\n if (!cancelled) setPrompts(null);\n });\n return () => {\n cancelled = true;\n };\n }, [promptsUrl, requestHeaders]);\n\n const [quotaNonce, setQuotaNonce] = useState(0);\n const refreshQuota = useCallback(() => setQuotaNonce((n) => n + 1), []);\n\n useEffect(() => {\n if (!quotaUrl) {\n setQuota(null);\n return;\n }\n let cancelled = false;\n fetch(quotaUrl, { credentials: 'include', headers: { ...(requestHeaders ?? {}) } })\n .then((res) => (res.ok ? res.json() : null))\n .then((data) => {\n if (!cancelled) setQuota(parseQuota(data));\n })\n .catch(() => {\n if (!cancelled) setQuota(null);\n });\n return () => {\n cancelled = true;\n };\n }, [quotaUrl, requestHeaders, quotaNonce]);\n\n return { prompts, quota, refreshQuota };\n}\n","import type { ChatQuotaStatus, Translate } from '../types';\n\n/**\n * The quota the composer indicator shows, as the quota route sends it.\n *\n * Kept free of local runtime imports so `node --test` runs it as is.\n */\n\n/** Defensive parse: an unexpected payload shows no indicator rather than a wrong one. */\nexport function parseQuota(data: unknown): ChatQuotaStatus | null {\n if (!data || typeof data !== 'object') return null;\n const q = data as Record<string, unknown>;\n if (typeof q.used !== 'number') return null;\n return {\n used: q.used,\n // Explicitly nullable: absent and null both mean \"no ceiling\".\n limit: typeof q.limit === 'number' ? q.limit : null,\n period: typeof q.period === 'string' ? q.period : '',\n ...(q.scope === 'global' || q.scope === 'user' ? { scope: q.scope } : {}),\n };\n}\n\n/**\n * The period a limit applies to, as the tooltip words it: the periods XTM One\n * sets a quota for are translated, anything else is shown as sent.\n */\nexport function quotaPeriodLabel(period: string, t: Translate): string {\n switch (period) {\n case 'daily':\n return t('today');\n case 'monthly':\n return t('this month');\n case 'yearly':\n return t('this year');\n default:\n return period;\n }\n}\n","import { useEffect, useState } from 'react';\nimport type { ApiEndpoints, BackendType } from '../types';\n\ninterface UseAgentSuggestionsOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n /** Selected agent; suggestions are re-fetched whenever it changes. */\n agentSlug: string | null | undefined;\n}\n\ninterface UseAgentSuggestionsReturn {\n /** Null when unavailable — the caller then falls back to its own list. */\n suggestions: string[] | null;\n loading: boolean;\n}\n\n/** Accepts a bare array or `{ suggestions: [...] }`, and drops non-strings. */\nfunction parseSuggestions(data: unknown): string[] {\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.suggestions)\n ? ((data as Record<string, unknown>).suggestions as unknown[])\n : [];\n return rawList\n .map((s) => {\n if (typeof s === 'string') return s.trim();\n // Tolerate `{ label }` / `{ prompt }` objects: an \"action suggestion\"\n // is likely to grow fields, and a richer payload should not blank the\n // welcome screen for older clients.\n if (s && typeof s === 'object') {\n const o = s as Record<string, unknown>;\n const v = o.prompt ?? o.label ?? o.text;\n if (typeof v === 'string') return v.trim();\n }\n return '';\n })\n .filter((s) => s.length > 0);\n}\n\n/**\n * Suggested opening actions for the selected agent.\n *\n * Fetched per agent so the welcome screen changes when you switch — which is\n * also the confirmation that the switch took effect. Generic today; the\n * endpoint is the seam through which they can become per-user later without\n * touching this package.\n *\n * Returns null (rather than an empty list) whenever the route is unavailable\n * or answers nothing usable, so the caller can fall back to its own\n * `promptSuggestions` instead of rendering an empty section.\n */\nexport function useAgentSuggestions({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n requestHeaders,\n agentSlug,\n}: UseAgentSuggestionsOptions): UseAgentSuggestionsReturn {\n const [suggestions, setSuggestions] = useState<string[] | null>(null);\n const [loading, setLoading] = useState(false);\n\n const restLike = backendType === 'rest' && !apiEndpoints?.singleEndpoint;\n const path = apiEndpoints?.suggestions === undefined ? '/chat/suggestions' : apiEndpoints.suggestions;\n const baseUrl = restLike && path ? `${apiBaseUrl}${path}` : null;\n\n useEffect(() => {\n if (!baseUrl) {\n setSuggestions(null);\n return;\n }\n let cancelled = false;\n setLoading(true);\n // The agent is a query parameter rather than a path segment: a backend\n // that ignores it still answers with its generic set, which is exactly the\n // \"generic today, personalised later\" progression.\n const url = agentSlug ? `${baseUrl}?agent_slug=${encodeURIComponent(agentSlug)}` : baseUrl;\n fetch(url, { credentials: 'include', headers: { ...(requestHeaders ?? {}) } })\n .then((res) => (res.ok ? res.json() : null))\n .then((data) => {\n if (cancelled) return;\n const parsed = data === null ? [] : parseSuggestions(data);\n setSuggestions(parsed.length > 0 ? parsed : null);\n })\n .catch(() => {\n if (!cancelled) setSuggestions(null);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [baseUrl, agentSlug, requestHeaders]);\n\n return { suggestions, loading };\n}\n","import { useCallback, useInsertionEffect, useRef } from 'react';\n\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every(\n (key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\n/**\n * `value`, keeping the previous object while its keys and values are the same.\n *\n * For plain-data props a host builds inline (headers, endpoint paths, page\n * context): a new but equal object on every host render would otherwise break\n * the memoized message rows and re-run every effect keyed on it — refetching\n * agents, prompts, quota and suggestions, and every image fetched with the\n * headers.\n */\nexport function useShallowStable<T>(value: T): T {\n const ref = useRef(value);\n if (!shallowEqual(ref.current, value)) ref.current = value;\n return ref.current;\n}\n\n/**\n * A function with a stable identity that always calls the latest `callback`,\n * or `undefined` while there is none (callers test for presence to decide what\n * to render).\n */\nexport function useLatestCallback<Args extends unknown[], Result>(\n callback: ((...args: Args) => Result) | undefined,\n): ((...args: Args) => Result) | undefined {\n const ref = useRef(callback);\n // Updated before any layout or passive effect runs, so an effect of this\n // render never calls the previous callback.\n useInsertionEffect(() => {\n ref.current = callback;\n });\n const stable = useCallback((...args: Args) => ref.current?.(...args) as Result, []);\n return callback ? stable : undefined;\n}\n","import type { IconProps } from '../../types';\n\nexport const AlertTriangleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ArrowRightLeftIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m16 3 4 4-4 4\" />\n <path d=\"M20 7H4\" />\n <path d=\"m8 21-4-4 4-4\" />\n <path d=\"M4 17h16\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const AttachFileIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const BotIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 8V4H8\" />\n <rect width=\"16\" height=\"12\" x=\"4\" y=\"8\" rx=\"2\" />\n <path d=\"M2 14h2\" />\n <path d=\"M20 14h2\" />\n <path d=\"M15 13v2\" />\n <path d=\"M9 13v2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const BrainIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z\" />\n <path d=\"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z\" />\n <path d=\"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4\" />\n <path d=\"M17.599 6.5a3 3 0 0 0 .399-1.375\" />\n <path d=\"M6.003 5.125A3 3 0 0 0 6.401 6.5\" />\n <path d=\"M3.477 10.896a4 4 0 0 1 .585-.396\" />\n <path d=\"M19.938 10.5a4 4 0 0 1 .585.396\" />\n <path d=\"M6 18a4 4 0 0 1-1.967-.516\" />\n <path d=\"M19.967 17.484A4 4 0 0 1 18 18\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CheckCircleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m9 12 2 2 4-4\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CheckIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ChevronDownIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CloseIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M18 6 6 18\" />\n <path d=\"m6 6 12 12\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CopyIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\" />\n <path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const DatabaseIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\" />\n <path d=\"M3 5V19A9 3 0 0 0 21 19V5\" />\n <path d=\"M3 12A9 3 0 0 0 21 12\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const DefaultLogoIcon = ({ className, size = 24 }: IconProps) => (\n <svg xmlns=\"http://www.w3.org/2000/svg\" width={size} height={size} viewBox=\"0 0 24 24\" fill=\"currentColor\" stroke=\"none\" className={className}>\n <path d=\"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const DownloadIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n <polyline points=\"7 10 12 15 17 10\" />\n <line x1=\"12\" x2=\"12\" y1=\"15\" y2=\"3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const EditIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 20h9\" />\n <path d=\"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ExternalLinkIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 3h6v6\" />\n <path d=\"M10 14 21 3\" />\n <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FileIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FloatingIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7\" />\n <rect width=\"12\" height=\"12\" x=\"10\" y=\"10\" rx=\"2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FullscreenExitIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M8 3v3a2 2 0 0 1-2 2H3\" />\n <path d=\"M21 8h-3a2 2 0 0 1-2-2V3\" />\n <path d=\"M3 16h3a2 2 0 0 0 2 2v3\" />\n <path d=\"M16 21v-3a2 2 0 0 1 2-2h3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FullscreenIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M8 3H5a2 2 0 0 0-2 2v3\" />\n <path d=\"M21 8V5a2 2 0 0 0-2-2h-3\" />\n <path d=\"M3 16v3a2 2 0 0 0 2 2h3\" />\n <path d=\"M16 21h3a2 2 0 0 0 2-2v-3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const GamepadIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <line x1=\"6\" x2=\"10\" y1=\"11\" y2=\"11\" />\n <line x1=\"8\" x2=\"8\" y1=\"9\" y2=\"13\" />\n <line x1=\"15\" x2=\"15.01\" y1=\"12\" y2=\"12\" />\n <line x1=\"18\" x2=\"18.01\" y1=\"10\" y2=\"10\" />\n <path d=\"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const GlobeIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" />\n <path d=\"M2 12h20\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const HistoryIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n <path d=\"M12 7v5l4 2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ImageIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\" />\n <circle cx=\"9\" cy=\"9\" r=\"2\" />\n <path d=\"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const InfoIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 16v-4\" />\n <path d=\"M12 8h.01\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MailIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"20\" height=\"16\" x=\"2\" y=\"4\" rx=\"2\" />\n <path d=\"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MaximizeIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 3h6v6\" />\n <path d=\"M9 21H3v-6\" />\n <path d=\"M21 3l-7 7\" />\n <path d=\"M3 21l7-7\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MicIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 19v3\" />\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n <rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\" />\n </svg>\n);\n\nexport const MicOffIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 19v3\" />\n <path d=\"M19 10v2a7 7 0 0 1-.11 1.23\" />\n <path d=\"M5 10v2a7 7 0 0 0 12 5\" />\n <path d=\"M15 9.34V5a3 3 0 0 0-5.68-1.33\" />\n <path d=\"M9 9v3a3 3 0 0 0 5.12 2.12\" />\n <path d=\"m2 2 20 20\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SearchIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.3-4.3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SendIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m22 2-7 20-4-9-9-4Z\" />\n <path d=\"m22 2-11 11\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SidebarIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M15 3v18\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SparklesIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const StopCircleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <rect width=\"6\" height=\"6\" x=\"9\" y=\"9\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const TerminalIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <polyline points=\"4 17 10 11 4 5\" />\n <line x1=\"12\" x2=\"20\" y1=\"19\" y2=\"19\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ThumbsDownIcon = ({ className, size = 24, filled = false }: IconProps & { filled?: boolean }) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill={filled ? 'currentColor' : 'none'}\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M17 14V2\" />\n <path d=\"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ThumbsUpIcon = ({ className, size = 24, filled = false }: IconProps & { filled?: boolean }) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill={filled ? 'currentColor' : 'none'}\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M7 10v12\" />\n <path d=\"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const TrashIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M3 6h18\" />\n <path d=\"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6\" />\n <path d=\"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2\" />\n <line x1=\"10\" x2=\"10\" y1=\"11\" y2=\"17\" />\n <line x1=\"14\" x2=\"14\" y1=\"11\" y2=\"17\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const UserPlusIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2\" />\n <circle cx=\"9\" cy=\"7\" r=\"4\" />\n <line x1=\"19\" x2=\"19\" y1=\"8\" y2=\"14\" />\n <line x1=\"22\" x2=\"16\" y1=\"11\" y2=\"11\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nconst SPEAKER =\n 'M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z';\n\nexport const VolumeIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d={SPEAKER} />\n <path d=\"M16 9a5 5 0 0 1 0 6\" />\n <path d=\"M19.364 18.364a9 9 0 0 0 0-12.728\" />\n </svg>\n);\n\nexport const VolumeOffIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d={SPEAKER} />\n <path d=\"m22 9-6 6\" />\n <path d=\"m16 9 6 6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const WrenchIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const XCircleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m15 9-6 6\" />\n <path d=\"m9 9 6 6\" />\n </svg>\n);\n","import { useCallback, useLayoutEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useClickOutside } from '../hooks/useClickOutside';\nimport { findChatbotRoot } from '../utils';\n\ninterface DropdownProps {\n open: boolean;\n onClose: () => void;\n anchorRef: React.RefObject<HTMLElement | null>;\n placement?: 'bottom-start' | 'bottom-end';\n width?: number;\n children: React.ReactNode;\n}\n\n/** Breathing room between the anchor and the panel, and from the viewport edge. */\nconst GAP = 4;\nconst EDGE_MARGIN = 8;\n\nexport const Dropdown = ({ open, onClose, anchorRef, placement = 'bottom-start', width = 280, children }: DropdownProps) => {\n const panelRef = useRef<HTMLDivElement>(null);\n const [pos, setPos] = useState({ top: 0, left: 0 });\n\n const stableOnClose = useCallback(() => onClose(), [onClose]);\n useClickOutside(panelRef, stableOnClose, open);\n\n // `useLayoutEffect`, not `useEffect`: the panel is measured after it mounts\n // and then moved, so doing it after paint would show it in the wrong place\n // for a frame.\n useLayoutEffect(() => {\n if (!open || !anchorRef.current) return;\n const rect = anchorRef.current.getBoundingClientRect();\n const panelHeight = panelRef.current?.offsetHeight ?? 0;\n\n // Flip above the anchor when there isn't room below and there is more room\n // above. The composer toolbar sits at the bottom of the panel, so its\n // menus would otherwise open straight off the bottom edge and be\n // unreachable — the anchor's own position decides, so callers don't have\n // to know where they are.\n const spaceBelow = window.innerHeight - rect.bottom - EDGE_MARGIN;\n const spaceAbove = rect.top - EDGE_MARGIN;\n const flipUp = panelHeight > 0 && spaceBelow < panelHeight && spaceAbove > spaceBelow;\n const top = flipUp ? Math.max(EDGE_MARGIN, rect.top - panelHeight - GAP) : rect.bottom + GAP;\n\n // Keep it inside the viewport horizontally too: the floating panel is\n // narrow, so a menu anchored near its right edge would otherwise hang off.\n const preferredLeft = placement === 'bottom-end' ? rect.right - width : rect.left;\n const left = Math.max(EDGE_MARGIN, Math.min(preferredLeft, window.innerWidth - width - EDGE_MARGIN));\n\n setPos({ top, left });\n }, [open, anchorRef, placement, width, children]);\n\n if (!open) return null;\n\n const portalTarget = findChatbotRoot(anchorRef.current);\n\n return createPortal(\n <div\n ref={panelRef}\n className=\"fixed z-[10000] rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl\"\n style={{ top: pos.top, left: pos.left, width }}\n >\n {children}\n </div>,\n portalTarget,\n );\n};\n","import { useEffect, type RefObject } from 'react';\n\nexport function useClickOutside(ref: RefObject<HTMLElement | null>, handler: () => void, active = true) {\n useEffect(() => {\n if (!active) return undefined;\n const listener = (e: MouseEvent | TouchEvent) => {\n if (!ref.current || ref.current.contains(e.target as Node)) return;\n handler();\n };\n document.addEventListener('mousedown', listener);\n document.addEventListener('touchstart', listener);\n return () => {\n document.removeEventListener('mousedown', listener);\n document.removeEventListener('touchstart', listener);\n };\n }, [ref, handler, active]);\n}\n","interface SpinnerProps {\n size?: number;\n className?: string;\n}\n\nexport const Spinner = ({ size = 16, className = '' }: SpinnerProps) => (\n <div\n className={`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${className}`}\n style={{ width: size, height: size }}\n />\n);\n","/**\n * Where a tooltip is drawn.\n *\n * It is centred above its anchor. Near the side of the panel (the time under a\n * message) it would run past it - into the host page, or off the screen - and\n * near the top it would run above it, into the host app's top bar. So its width\n * is capped to the room there is (a long label wraps instead), it is shifted back\n * inside, and it opens below its anchor when there is no room above.\n */\n\n/** Space between a tooltip and its anchor. */\nexport const ANCHOR_GAP = 4;\n\n/** Space kept between a tooltip and the side of the panel it would cross. */\nexport const EDGE_MARGIN = 4;\n\n/** A box in viewport coordinates, as `getBoundingClientRect` returns it. */\nexport interface Box {\n readonly top: number;\n readonly bottom: number;\n readonly left: number;\n readonly right: number;\n}\n\n/** A tooltip's anchor and the room it may take: the part of the panel inside the viewport, less the margins. */\nexport interface TooltipOpening {\n readonly top: number;\n readonly bottom: number;\n readonly center: number;\n readonly minTop: number;\n readonly minLeft: number;\n readonly maxRight: number;\n}\n\nexport interface TooltipPlacement {\n /** Drawn below its anchor instead of above. */\n readonly below: boolean;\n /** Horizontal offset from the anchor's centre that keeps it inside. */\n readonly shift: number;\n}\n\nexport function tooltipOpening(anchor: Box, panel: Box, viewportWidth: number): TooltipOpening {\n return {\n top: anchor.top,\n bottom: anchor.bottom,\n center: (anchor.left + anchor.right) / 2,\n minTop: Math.max(panel.top, 0),\n minLeft: Math.max(panel.left, 0) + EDGE_MARGIN,\n maxRight: Math.min(panel.right, viewportWidth) - EDGE_MARGIN,\n };\n}\n\n/** The widest a tooltip may be drawn: wider than that, it would cross the panel's side whatever its shift. */\nexport function tooltipMaxWidth(opening: TooltipOpening): number {\n return Math.max(opening.maxRight - opening.minLeft, 0);\n}\n\n/** Places a tooltip of the measured size, drawn no wider than `tooltipMaxWidth`. */\nexport function placeTooltip(opening: TooltipOpening, size: { readonly width: number; readonly height: number }): TooltipPlacement {\n const left = opening.center - size.width / 2;\n let shift = 0;\n if (left < opening.minLeft) shift = opening.minLeft - left;\n else if (left + size.width > opening.maxRight) shift = opening.maxRight - (left + size.width);\n return { below: opening.top - ANCHOR_GAP - size.height < opening.minTop, shift };\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { findChatbotRoot } from '../utils';\nimport { ANCHOR_GAP, placeTooltip, tooltipMaxWidth, tooltipOpening, type TooltipOpening } from '../utils/tooltipPlacement';\n\ninterface TooltipProps {\n title: string;\n children: React.ReactElement;\n}\n\nexport const Tooltip = ({ title, children }: TooltipProps) => {\n const ref = useRef<HTMLSpanElement>(null);\n const tipRef = useRef<HTMLSpanElement>(null);\n const [opening, setOpening] = useState<TooltipOpening | null>(null);\n const [placement, setPlacement] = useState({ below: false, shift: 0 });\n\n // Its size is its text's, wrapped to the room there is: measured once shown,\n // before the browser paints it. The tooltip lives inside the panel's stacking\n // context (z-[1200] in sidebar mode), so anything drawn above the panel lands\n // in the host app's top-bar zone and is hidden whenever the host bar stacks\n // higher (e.g. OpenAEV's AppBar at theme.zIndex.drawer + 1).\n useLayoutEffect(() => {\n if (!opening || !tipRef.current) return;\n const { width, height } = tipRef.current.getBoundingClientRect();\n setPlacement(placeTooltip(opening, { width, height }));\n }, [opening, title]);\n\n if (!title) return children;\n\n const open = () => {\n if (!ref.current) return;\n const panel = findChatbotRoot(ref.current).getBoundingClientRect();\n setOpening(tooltipOpening(ref.current.getBoundingClientRect(), panel, window.innerWidth));\n };\n\n // A keyboard user reaches the control without hovering it, so its tooltip\n // opens on focus too - on keyboard focus only: a click also focuses, and the\n // hover has already shown the tooltip then.\n const handleFocus = (event: React.FocusEvent) => {\n const target = event.target as HTMLElement;\n if (typeof target.matches === 'function' && target.matches(':focus-visible')) open();\n };\n\n return (\n <span\n ref={ref}\n className=\"inline-flex\"\n onMouseEnter={open}\n onMouseLeave={() => setOpening(null)}\n onFocus={handleFocus}\n onBlur={() => setOpening(null)}\n >\n {children}\n {opening &&\n createPortal(\n <span\n ref={tipRef}\n className={`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${placement.below ? '' : '-translate-y-full'} whitespace-normal break-words rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`}\n style={{\n top: placement.below ? opening.bottom + ANCHOR_GAP : opening.top - ANCHOR_GAP,\n left: opening.center + placement.shift,\n maxWidth: tooltipMaxWidth(opening),\n }}\n role=\"tooltip\"\n >\n {title}\n </span>,\n findChatbotRoot(ref.current),\n )}\n </span>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport type { ChatConversationSummary, ChatMode, Translate, XtmAgent } from '../types';\nimport { timeAgo, translate } from '../utils';\nimport {\n AlertTriangleIcon,\n ChevronDownIcon,\n CloseIcon,\n EditIcon,\n ExternalLinkIcon,\n FloatingIcon,\n FullscreenExitIcon,\n FullscreenIcon,\n HistoryIcon,\n SearchIcon,\n SidebarIcon,\n TrashIcon,\n UserPlusIcon,\n} from './icons';\nimport { Dropdown } from './Dropdown';\nimport { Spinner } from './Spinner';\nimport { Tooltip } from './Tooltip';\n\ninterface ChatHeaderProps {\n mode: ChatMode;\n agentName: string;\n agents: XtmAgent[];\n agentsLoading?: boolean;\n agentsError?: boolean;\n selectedAgent: XtmAgent | null;\n transferredFrom?: string;\n agentMenuOpen: boolean;\n onAgentMenuToggle: () => void;\n onAgentMenuClose: () => void;\n onSwitchAgent: (agent: XtmAgent) => void;\n modeMenuOpen: boolean;\n onModeMenuToggle: () => void;\n onModeMenuClose: () => void;\n onModeChange: (mode: ChatMode) => void;\n onNewChat: () => void;\n onClose: () => void;\n logoIcon: React.ReactNode;\n agentDashboardUrl?: string;\n /** Multi-conversation history menu (REST backend). Hidden when false. */\n historyEnabled?: boolean;\n historyMenuOpen?: boolean;\n onHistoryMenuToggle?: () => void;\n onHistoryMenuClose?: () => void;\n conversations?: ChatConversationSummary[];\n conversationsLoading?: boolean;\n activeConversationId?: string | null;\n onSelectConversation?: (id: string) => void;\n onDeleteConversation?: (id: string) => void;\n t: Translate;\n}\n\n// Labels are thunks rather than bare strings so each key stays a literal call\n// on the host's translator in the source: a table of plain keys resolved later\n// through a variable works at runtime but is invisible to key extraction, which\n// is how a locale ends up missing exactly the strings nobody typed by hand.\nconst modeOptions: { mode: ChatMode; label: (t: Translate) => string; getIcon: (p: { size: number; className: string }) => React.ReactNode }[] = [\n { mode: 'floating', label: (t) => t('Floating'), getIcon: (p) => <FloatingIcon {...p} /> },\n { mode: 'sidebar', label: (t) => t('Sidebar'), getIcon: (p) => <SidebarIcon {...p} /> },\n { mode: 'fullscreen', label: (t) => t('Full screen'), getIcon: (p) => <FullscreenIcon {...p} /> },\n];\n\nexport const ChatHeader = ({\n mode,\n agentName,\n agents,\n agentsLoading = false,\n agentsError = false,\n selectedAgent,\n transferredFrom,\n agentMenuOpen,\n onAgentMenuToggle,\n onAgentMenuClose,\n onSwitchAgent,\n modeMenuOpen,\n onModeMenuToggle,\n onModeMenuClose,\n onModeChange,\n onNewChat,\n onClose,\n logoIcon,\n agentDashboardUrl,\n historyEnabled = false,\n historyMenuOpen = false,\n onHistoryMenuToggle,\n onHistoryMenuClose,\n conversations = [],\n conversationsLoading = false,\n activeConversationId = null,\n onSelectConversation,\n onDeleteConversation,\n t,\n}: ChatHeaderProps) => {\n const agentAnchorRef = useRef<HTMLButtonElement>(null);\n const modeAnchorRef = useRef<HTMLButtonElement>(null);\n const historyAnchorRef = useRef<HTMLButtonElement>(null);\n\n // Agent filter, mirroring the XTM One web chat's picker. Reset whenever the\n // menu closes so re-opening never starts on a stale query with most agents\n // hidden — which reads as \"my agents disappeared\".\n const [agentQuery, setAgentQuery] = useState('');\n useEffect(() => {\n if (!agentMenuOpen) setAgentQuery('');\n }, [agentMenuOpen]);\n\n // Match on name AND description: descriptions are what distinguish agents\n // whose names are near-identical, and they are already shown on every row.\n const filteredAgents = useMemo(() => {\n const q = agentQuery.trim().toLowerCase();\n if (!q) return agents;\n return agents.filter((a) => a.name.toLowerCase().includes(q) || (a.description ?? '').toLowerCase().includes(q));\n }, [agents, agentQuery]);\n\n // Only worth the vertical space once the list is long enough to scan for.\n const showAgentSearch = agents.length > 5;\n\n const CurrentModeIcon = mode === 'sidebar' ? SidebarIcon : mode === 'fullscreen' ? FullscreenExitIcon : FloatingIcon;\n\n return (\n <div\n className={`flex items-center px-3 py-2 min-h-[48px] border-b border-gray-200 dark:border-white/10 bg-gradient-to-br from-[var(--chat-accent-dark)]/[0.13] to-[var(--chat-accent)]/[0.07] ${mode === 'floating' ? 'rounded-t-xl' : ''}`}\n >\n <div className=\"min-w-0\">\n <button\n ref={agentAnchorRef}\n type=\"button\"\n onClick={onAgentMenuToggle}\n className=\"flex items-center gap-1.5 text-sm font-semibold text-gray-900 dark:text-white px-2 py-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <span className=\"flex items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]\">{logoIcon}</span>\n <span>{agentName}</span>\n <ChevronDownIcon size={16} className=\"text-gray-400 dark:text-white/30\" />\n </button>\n {transferredFrom && (\n <div className=\"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30\">\n {translate(t, 'Transferred from {agent}', { agent: transferredFrom })}\n </div>\n )}\n </div>\n\n <Dropdown open={agentMenuOpen} onClose={onAgentMenuClose} anchorRef={agentAnchorRef} width={280}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">\n {t('Switch to another agent')}\n </span>\n {/* Three distinct states, because an empty array alone cannot tell them\n apart — and treating \"failed\" as \"still loading\" is what left this\n menu spinning forever against an unreachable backend.\n\n The last one is NOT \"the catalogue is empty\": XTM One always seeds\n agents, so a working backend never answers with none. It is reached\n when the fetch is skipped altogether — `apiEndpoints.agents: null`,\n single-endpoint mode (OpenCTI) or the legacy backend — where there\n is simply nothing to switch between. The menu still earns its place\n there: it carries the agent-dashboard links below. */}\n {agents.length === 0 && agentsLoading && (\n <div className=\"px-4 py-2\">\n <Spinner size={16} />\n </div>\n )}\n {agents.length === 0 && !agentsLoading && agentsError && (\n <div className=\"px-4 py-3 flex items-start gap-2\">\n <AlertTriangleIcon size={14} className=\"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400\" />\n <span className=\"text-[0.75rem] leading-5 text-gray-600 dark:text-white/60\">{t('Could not reach the assistant service. Check the connection and try again.')}</span>\n </div>\n )}\n {agents.length === 0 && !agentsLoading && !agentsError && (\n <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('Agent switching is not available here')}</div>\n )}\n {showAgentSearch && (\n <div className=\"px-3 pb-2 pt-1\">\n <div className=\"relative\">\n <SearchIcon size={12} className=\"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40\" />\n <input\n autoFocus\n type=\"text\"\n value={agentQuery}\n onChange={(e) => setAgentQuery(e.target.value)}\n // Escape closes the whole menu rather than only clearing the\n // query — the same key the rest of the panel uses to dismiss.\n onKeyDown={(e) => {\n if (e.key === 'Escape') onAgentMenuClose();\n }}\n placeholder={t('Search agents...')}\n aria-label={t('Search agents...')}\n className=\"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]\"\n />\n </div>\n </div>\n )}\n <div className=\"max-h-[240px] overflow-y-auto filigran-chat-scrollable\">\n {agents.length > 0 && filteredAgents.length === 0 && (\n <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No agent matches')}</div>\n )}\n {filteredAgents.map((agent) => (\n <button\n key={agent.id}\n type=\"button\"\n onClick={() => onSwitchAgent(agent)}\n className={`w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors ${\n agent.id === selectedAgent?.id ? 'bg-[var(--chat-accent)]/10' : ''\n }`}\n >\n <div className=\"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5\">\n <span className=\"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4\">{logoIcon}</span>\n </div>\n <div className=\"min-w-0\">\n <div className=\"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate\">{agent.name}</div>\n {agent.description && <div className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">{agent.description}</div>}\n </div>\n </button>\n ))}\n </div>\n <div className=\"h-px bg-gray-200 dark:bg-white/10 mx-2\" />\n <div>\n {agentDashboardUrl && (\n <button\n type=\"button\"\n onClick={() => {\n onAgentMenuClose();\n window.open(`${agentDashboardUrl}/agents`, '_blank');\n }}\n className=\"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <ExternalLinkIcon size={18} className=\"text-gray-400 dark:text-white/40 shrink-0\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{t('Browse agents')}</span>\n </button>\n )}\n {agentDashboardUrl && (\n <button\n type=\"button\"\n onClick={() => {\n onAgentMenuClose();\n window.open(`${agentDashboardUrl}/agents/new`, '_blank');\n }}\n className=\"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <UserPlusIcon size={18} className=\"text-gray-400 dark:text-white/40 shrink-0\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{t('Create agent')}</span>\n </button>\n )}\n </div>\n </Dropdown>\n\n <div className=\"flex-1\" />\n\n {historyEnabled && (\n <>\n <Tooltip title={t('Conversation history')}>\n <button\n ref={historyAnchorRef}\n type=\"button\"\n onClick={onHistoryMenuToggle}\n aria-label={t('Conversation history')}\n aria-haspopup=\"menu\"\n aria-expanded={historyMenuOpen}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <HistoryIcon size={18} />\n </button>\n </Tooltip>\n\n <Dropdown open={historyMenuOpen} onClose={() => onHistoryMenuClose?.()} anchorRef={historyAnchorRef} placement=\"bottom-end\" width={300}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">\n {t('Conversation history')}\n </span>\n <div className=\"max-h-72 overflow-y-auto filigran-chat-scrollable\">\n {conversationsLoading && conversations.length === 0 && (\n <div className=\"px-4 py-2\">\n <Spinner size={16} />\n </div>\n )}\n {!conversationsLoading && conversations.length === 0 && (\n <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversations yet')}</div>\n )}\n {conversations.map((conv) => {\n const isActive = conv.conversationId === activeConversationId;\n const when = timeAgo(conv.updatedAt, t);\n return (\n <div\n key={conv.conversationId}\n className={`group flex items-center gap-2 px-4 py-1.5 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors ${\n isActive ? 'bg-[var(--chat-accent)]/10' : ''\n }`}\n >\n <button type=\"button\" onClick={() => onSelectConversation?.(conv.conversationId)} className=\"flex-1 min-w-0 text-left\">\n <div className=\"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate\">\n {conv.title || t('Untitled conversation')}\n </div>\n {when && <div className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">{when}</div>}\n </button>\n {onDeleteConversation && (\n <button\n type=\"button\"\n onClick={() => onDeleteConversation(conv.conversationId)}\n title={t('Delete conversation')}\n aria-label={t('Delete conversation')}\n className=\"shrink-0 p-1 rounded-md text-gray-400 dark:text-white/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all\"\n >\n <TrashIcon size={14} />\n </button>\n )}\n </div>\n );\n })}\n </div>\n <div className=\"h-px bg-gray-200 dark:bg-white/10 mx-2\" />\n <button\n type=\"button\"\n onClick={() => {\n onHistoryMenuClose?.();\n onNewChat();\n }}\n className=\"w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <EditIcon size={16} className=\"text-gray-400 dark:text-white/40 shrink-0\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{t('New conversation')}</span>\n </button>\n </Dropdown>\n </>\n )}\n\n <Tooltip title={t('New chat')}>\n <button\n type=\"button\"\n onClick={onNewChat}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <EditIcon size={18} />\n </button>\n </Tooltip>\n\n <Tooltip title={t('Switch view')}>\n <button\n ref={modeAnchorRef}\n type=\"button\"\n onClick={onModeMenuToggle}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <CurrentModeIcon size={18} />\n </button>\n </Tooltip>\n\n <Dropdown open={modeMenuOpen} onClose={onModeMenuClose} anchorRef={modeAnchorRef} placement=\"bottom-end\" width={180}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">{t('Switch to')}</span>\n <div className=\"pb-1\">\n {modeOptions.map((opt) => (\n <button\n key={opt.mode}\n type=\"button\"\n onClick={() => {\n onModeChange(opt.mode);\n onModeMenuClose();\n }}\n className={`w-full flex items-center gap-3 px-4 py-1 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors ${\n mode === opt.mode ? 'bg-[var(--chat-accent)]/10' : ''\n }`}\n >\n {opt.getIcon({ size: 18, className: 'text-gray-400 dark:text-white/40' })}\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{opt.label(t)}</span>\n </button>\n ))}\n </div>\n </Dropdown>\n\n <Tooltip title={t('Close')}>\n <button\n type=\"button\"\n onClick={onClose}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <CloseIcon size={18} />\n </button>\n </Tooltip>\n </div>\n );\n};\n","/**\n * Minimal shape of the Web Speech API surface we use. Typed locally rather\n * than pulled from `lib.dom` - `SpeechRecognition` is still vendor-prefixed and\n * missing from TypeScript's DOM lib, and this package ships no ambient types.\n */\ninterface SpeechRecognitionAlternativeLike {\n transcript: string;\n}\ninterface SpeechRecognitionResultLike {\n isFinal: boolean;\n 0: SpeechRecognitionAlternativeLike;\n}\nexport interface SpeechRecognitionEventLike {\n resultIndex: number;\n results: { length: number; [index: number]: SpeechRecognitionResultLike };\n}\nexport interface SpeechRecognitionLike {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start: () => void;\n stop: () => void;\n abort: () => void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: (() => void) | null;\n onend: (() => void) | null;\n}\n\nexport interface DictationEvents {\n /** A finalised phrase, trimmed, to append to the draft. */\n onFinal: (text: string) => void;\n /** Words heard but not final yet; an empty string clears the preview. */\n onInterim: (text: string) => void;\n onListeningChange: (listening: boolean) => void;\n}\n\nexport interface DictationController {\n /** Start listening, or stop and commit the phrase already heard. */\n toggle: () => void;\n /** Stop listening and drop whatever the session still delivers. */\n cancel: () => void;\n /** Release the recogniser; no event is reported afterwards. */\n dispose: () => void;\n}\n\n/**\n * - `listening`: a session the user wants; the engine ending it after a pause\n * starts it again.\n * - `stopping`: the user stopped it; the phrase in flight is still committed.\n * - `discarding`: cancelled; everything it delivers until its `end` is dropped.\n */\ntype Phase = 'idle' | 'listening' | 'stopping' | 'discarding';\n\n/**\n * Drives one recogniser through successive dictation sessions.\n *\n * A session keeps emitting after `stop()` / `abort()` until its `end` event,\n * and no event says which session it belongs to. The recogniser also refuses\n * `start()` until that `end`, so every event is read against the phase of the\n * one session it can belong to, and a start asked for while the previous\n * session is still ending waits for that `end` instead of failing.\n */\nexport function createDictationController(recognition: SpeechRecognitionLike, events: DictationEvents): DictationController {\n let phase: Phase = 'idle';\n let startQueued = false;\n let disposed = false;\n let reported = false;\n\n const isOn = () => phase === 'listening' || startQueued;\n\n const report = () => {\n if (disposed || isOn() === reported) return;\n reported = isOn();\n events.onListeningChange(reported);\n };\n\n const tryStart = () => {\n try {\n recognition.start();\n return true;\n } catch {\n return false;\n }\n };\n\n const start = () => {\n if (tryStart()) phase = 'listening';\n else if (phase !== 'idle') startQueued = true;\n report();\n };\n\n const stop = () => {\n startQueued = false;\n if (phase === 'listening') {\n phase = 'stopping';\n events.onInterim('');\n try {\n recognition.stop();\n } catch {\n phase = 'idle';\n }\n }\n report();\n };\n\n const cancel = () => {\n if (disposed) return;\n startQueued = false;\n if (phase === 'listening' || phase === 'stopping') {\n phase = 'discarding';\n events.onInterim('');\n try {\n recognition.abort();\n } catch {\n phase = 'idle';\n }\n }\n report();\n };\n\n recognition.onresult = (event) => {\n if (phase !== 'listening' && phase !== 'stopping') return;\n let finalText = '';\n let interimText = '';\n for (let i = event.resultIndex; i < event.results.length; i++) {\n const result = event.results[i];\n if (result.isFinal) finalText += result[0].transcript;\n else interimText += result[0].transcript;\n }\n const phrase = finalText.trim();\n if (phrase) events.onFinal(phrase);\n if (phase === 'listening') events.onInterim(interimText.trim());\n };\n\n recognition.onerror = () => {\n // Permission denied, no microphone, network failure: let the session end\n // rather than restart it into the same failure.\n if (phase === 'listening') {\n phase = 'stopping';\n events.onInterim('');\n }\n report();\n };\n\n recognition.onend = () => {\n events.onInterim('');\n if (phase === 'listening') {\n if (tryStart()) return;\n phase = 'idle';\n } else if (startQueued) {\n startQueued = false;\n phase = tryStart() ? 'listening' : 'idle';\n } else {\n phase = 'idle';\n }\n report();\n };\n\n return {\n toggle: () => {\n if (disposed) return;\n if (isOn()) stop();\n else start();\n },\n cancel,\n dispose: () => {\n if (disposed) return;\n disposed = true;\n recognition.onresult = null;\n recognition.onerror = null;\n recognition.onend = null;\n if (phase !== 'idle') {\n try {\n recognition.abort();\n } catch {\n /* already ended */\n }\n }\n phase = 'idle';\n startQueued = false;\n },\n };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { createDictationController, type DictationController, type SpeechRecognitionLike } from './dictationController';\n\ntype SpeechRecognitionCtor = new () => SpeechRecognitionLike;\n\nfunction getSpeechRecognition(): SpeechRecognitionCtor | null {\n if (typeof window === 'undefined') return null;\n const w = window as unknown as {\n SpeechRecognition?: SpeechRecognitionCtor;\n webkitSpeechRecognition?: SpeechRecognitionCtor;\n };\n return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n}\n\ninterface UseDictationReturn {\n /** False on browsers without the API — the host should render no button. */\n supported: boolean;\n listening: boolean;\n /** Words heard but not yet finalised, for a live preview. */\n interim: string;\n /** Start listening, or stop and still commit the phrase already heard. */\n toggle: () => void;\n /** Stop listening and drop anything still on its way, e.g. once the draft is sent. */\n cancel: () => void;\n}\n\n/**\n * Speech-to-text for the composer, using the browser's own Web Speech API.\n *\n * Entirely client-side: no endpoint, no key, nothing for a host to deploy —\n * which is why it ships regardless of how the backend is configured, unlike the\n * prompt library and quota indicator.\n *\n * Final phrases are appended through `onFinalText`; interim words are returned\n * separately so the composer can preview them without committing.\n */\nexport function useDictation(onFinalText: (text: string) => void): UseDictationReturn {\n const [listening, setListening] = useState(false);\n const [interim, setInterim] = useState('');\n const controllerRef = useRef<DictationController | null>(null);\n // Read through a ref so re-creating the callback each render does not tear\n // down and rebuild the recogniser mid-dictation.\n const onFinalTextRef = useRef(onFinalText);\n onFinalTextRef.current = onFinalText;\n\n const supported = getSpeechRecognition() !== null;\n\n useEffect(() => {\n const Ctor = getSpeechRecognition();\n if (!Ctor) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = typeof navigator !== 'undefined' ? navigator.language || 'en-US' : 'en-US';\n\n const controller = createDictationController(recognition, {\n onFinal: (text) => onFinalTextRef.current(text),\n onInterim: setInterim,\n onListeningChange: setListening,\n });\n controllerRef.current = controller;\n return () => {\n controllerRef.current = null;\n controller.dispose();\n setListening(false);\n setInterim('');\n };\n }, []);\n\n const toggle = useCallback(() => controllerRef.current?.toggle(), []);\n const cancel = useCallback(() => controllerRef.current?.cancel(), []);\n\n return { supported, listening, interim, toggle, cancel };\n}\n","import { useRef, useState } from 'react';\nimport type { ChatContextBreakdown, ChatContextUsage, Translate } from '../types';\nimport { compactCount, translate } from '../utils';\nimport { Dropdown } from './Dropdown';\nimport { Tooltip } from './Tooltip';\n\ninterface ContextUsageIndicatorProps {\n usage: ChatContextUsage;\n t: Translate;\n}\n\n// Thresholds are the agent loop's own gates, not design choices: at 80 %\n// utilization the backend compacts the session (older turns are distilled into\n// a summary), and past 95 % it emergency-prunes. Colouring anywhere else would\n// warn about a moment that never comes, or arrive after it has passed.\nconst COMPACTION_RATIO = 0.8;\nconst PRUNE_RATIO = 0.95;\n\n// Geometry of the ring. Kept at the text's own scale so the gauge reads as part\n// of the label rather than as an icon beside it.\nconst SIZE = 14;\nconst STROKE = 2;\nconst RADIUS = (SIZE - STROKE) / 2;\nconst CIRCUMFERENCE = 2 * Math.PI * RADIUS;\n\n/**\n * Rows of the detail popover, in a FIXED order that mirrors how the prompt is\n * assembled — instructions, then tools, then the conversation and what the\n * backend has done to it. Fixed rather than sorted by size so the same bucket\n * stays in the same place as a chat grows: a legend whose rows reshuffle between\n * two glances cannot be compared against itself.\n *\n * `color` is both the swatch and the stacked-bar segment, so the bar is readable\n * without a legend lookup. Labels name what the user can act on, not the\n * backend's internals: \"Tool results\" rather than \"role=tool messages\".\n */\nconst ROWS: ReadonlyArray<{ field: keyof ChatContextBreakdown; label: (t: Translate) => string; color: string }> = [\n { field: 'system', label: (t) => t('System prompt'), color: '#9ca3af' },\n { field: 'tools', label: (t) => t('Tool definitions'), color: '#a78bfa' },\n { field: 'dynamicTools', label: (t) => t('MCP & dynamic tools'), color: '#f0abfc' },\n { field: 'summary', label: (t) => t('Summarized conversation'), color: '#fb7185' },\n { field: 'toolResults', label: (t) => t('Tool results'), color: '#34d399' },\n { field: 'conversation', label: (t) => t('Conversation'), color: '#a1a1aa' },\n];\n\n/**\n * Context-window occupancy for the current conversation, as a small ring plus\n * percentage — the affordance Cursor popularised — opening a breakdown of where\n * the context went.\n *\n * It answers one question: is this conversation about to get shorter than the\n * user thinks? Long chats do not fail at the window, they get silently\n * summarised, and a user who cannot see that coming reads the summary's gaps as\n * the assistant forgetting. So the gauge is deliberately a *forecast* of the\n * next turn, and its colours are the backend's real thresholds.\n */\nexport const ContextUsageIndicator = ({ usage, t }: ContextUsageIndicatorProps) => {\n const { used, limit, breakdown } = usage;\n const anchorRef = useRef<HTMLButtonElement>(null);\n const [open, setOpen] = useState(false);\n\n // The parser guarantees a positive limit; clamp anyway so a future producer\n // cannot draw a ring past full or a negative arc.\n const ratio = Math.min(Math.max(used / limit, 0), 1);\n const pruning = ratio >= PRUNE_RATIO;\n const compacting = ratio >= COMPACTION_RATIO;\n\n const ringColor = pruning ? 'text-red-500' : compacting ? 'text-amber-500' : 'text-[var(--chat-accent)]';\n const textColor = pruning\n ? 'text-red-500 dark:text-red-400'\n : compacting\n ? 'text-amber-600 dark:text-amber-400'\n : 'text-gray-400 dark:text-white/30';\n\n const percent = Math.round(ratio * 100);\n const counts = `${compactCount(used)}/${compactCount(limit)}`;\n // Naming the consequence beats naming the state: \"80 % full\" leaves the user\n // to guess what happens next, which is the whole reason the gauge exists.\n const headline = pruning\n ? t('Context full — older turns are being dropped')\n : compacting\n ? t('Context nearly full — older turns are being summarized')\n : t('Context used');\n const tokens = translate(t, '{counts} tokens', { counts });\n // Separator only — nothing to translate, so no key of its own: both halves\n // are already whole translated readouts.\n const summary = `${headline} · ${tokens}`;\n\n const rows = breakdown ? ROWS.filter((r) => (breakdown[r.field] ?? 0) > 0) : [];\n // Without a breakdown there is nothing to open, so the readout stays inert\n // rather than offering a click that does nothing.\n const expandable = rows.length > 0;\n\n const gauge = (\n <span className=\"flex items-center gap-1.5\">\n <svg width={SIZE} height={SIZE} viewBox={`0 0 ${SIZE} ${SIZE}`} className={ringColor} aria-hidden=\"true\">\n <circle cx={SIZE / 2} cy={SIZE / 2} r={RADIUS} fill=\"none\" strokeWidth={STROKE} className=\"stroke-gray-200 dark:stroke-white/15\" />\n <circle\n cx={SIZE / 2}\n cy={SIZE / 2}\n r={RADIUS}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={STROKE}\n strokeLinecap=\"round\"\n strokeDasharray={CIRCUMFERENCE}\n strokeDashoffset={CIRCUMFERENCE * (1 - ratio)}\n /* Start at twelve o'clock: a gauge that fills from the side reads\n as a spinner. */\n transform={`rotate(-90 ${SIZE / 2} ${SIZE / 2})`}\n className=\"transition-[stroke-dashoffset] duration-500\"\n />\n </svg>\n <span className={`text-[0.68rem] tabular-nums ${textColor}`}>{percent}%</span>\n </span>\n );\n\n if (!expandable) {\n return (\n <Tooltip title={summary}>\n <span className=\"flex items-center\" role=\"img\" aria-label={`${summary} (${percent}%)`}>\n {gauge}\n </span>\n </Tooltip>\n );\n }\n\n return (\n <>\n <Tooltip title={open ? '' : translate(t, '{summary} — click for details', { summary })}>\n <button\n ref={anchorRef}\n type=\"button\"\n onClick={() => setOpen((prev) => !prev)}\n aria-label={`${summary} (${percent}%)`}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n className=\"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:bg-gray-100 dark:hover:bg-white/10\"\n >\n {gauge}\n </button>\n </Tooltip>\n\n <Dropdown open={open} onClose={() => setOpen(false)} anchorRef={anchorRef} placement=\"bottom-end\" width={296}>\n <div className=\"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3\">\n <span className={`text-[0.8125rem] tabular-nums ${textColor}`}>{translate(t, '{percent}% full', { percent })}</span>\n {/* The tilde is load-bearing: these are char-derived estimates, and a\n bare \"168k/200k\" would read as a measured count. */}\n <span className=\"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0\">~{tokens}</span>\n </div>\n\n {/* One stacked bar over the whole window: the segments are the legend's\n own colours, so proportions are readable without matching numbers to\n rows. The trailing gap is the headroom left. */}\n <div className=\"px-3.5 pb-2.5 pt-1.5\">\n <span className=\"flex h-1.5 w-full gap-px rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden\">\n {rows.map((row) => (\n <span\n key={row.field}\n className=\"h-full first:rounded-l-full\"\n /* Scaled through the clamped total rather than straight over the\n window, so a producer that reports buckets summing past the\n limit fills the track instead of overflowing it. Identical to\n value/limit whenever the two agree, which is the normal case. */\n style={{\n width: `${((breakdown?.[row.field] ?? 0) / Math.max(used, 1)) * Math.min(used / limit, 1) * 100}%`,\n backgroundColor: row.color,\n }}\n />\n ))}\n </span>\n </div>\n\n <div className=\"px-3.5 pb-1\">\n {rows.map((row) => (\n <div key={row.field} className=\"flex items-center gap-2 py-[3px]\">\n {/* Radius set inline: the panel's reset rounds small spans to a\n pill, which turns the swatches into dots that read as bullets\n rather than as keys to the bar's segments. */}\n <span className=\"h-2 w-2 shrink-0\" style={{ backgroundColor: row.color, borderRadius: 2 }} aria-hidden=\"true\" />\n <span className=\"text-[0.75rem] text-gray-700 dark:text-white/70 truncate\">{row.label(t)}</span>\n <span className=\"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0\">\n {compactCount(breakdown?.[row.field] ?? 0)}\n </span>\n </div>\n ))}\n </div>\n\n {compacting && (\n // The one line that turns a readout into something actionable: at this\n // point the backend is already dropping detail from older turns.\n <p className={`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${textColor}`}>{headline}</p>\n )}\n </Dropdown>\n </>\n );\n};\n","import { useRef, useState } from 'react';\nimport type { ChatPromptTemplate } from '../types';\nimport { SparklesIcon } from './icons';\nimport { Dropdown } from './Dropdown';\nimport { Tooltip } from './Tooltip';\n\ninterface PromptPickerProps {\n prompts: ChatPromptTemplate[];\n /** Receives the template body; the composer decides how to place it. */\n onPick: (content: string) => void;\n t: (key: string) => string;\n}\n\n/** Above this many entries the list is worth filtering rather than scrolling. */\nconst SEARCH_THRESHOLD = 5;\n\n/**\n * Inserts a saved prompt template into the composer. Mirrors the XTM One web\n * chat's \"Insert prompt template\" affordance.\n */\nexport const PromptPicker = ({ prompts, onPick, t }: PromptPickerProps) => {\n const anchorRef = useRef<HTMLButtonElement>(null);\n const [open, setOpen] = useState(false);\n const [query, setQuery] = useState('');\n\n const close = () => {\n setOpen(false);\n // Reset on close: re-opening on a stale filter looks like the library\n // lost most of its entries.\n setQuery('');\n };\n\n const q = query.trim().toLowerCase();\n const filtered = q\n ? prompts.filter((p) => p.title.toLowerCase().includes(q) || (p.description ?? '').toLowerCase().includes(q))\n : prompts;\n\n return (\n <>\n <Tooltip title={t('Insert prompt template')}>\n <button\n ref={anchorRef}\n type=\"button\"\n onClick={() => (open ? close() : setOpen(true))}\n aria-label={t('Insert prompt template')}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n className={`w-7 h-7 flex items-center justify-center rounded-lg transition-colors ${\n open\n ? 'text-[var(--chat-accent)] bg-[var(--chat-accent)]/10'\n : 'text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10'\n }`}\n >\n <SparklesIcon size={15} />\n </button>\n </Tooltip>\n\n <Dropdown open={open} onClose={close} anchorRef={anchorRef} width={280}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">\n {t('Insert prompt template')}\n </span>\n\n {prompts.length > SEARCH_THRESHOLD && (\n <div className=\"px-3 pb-2 pt-1\">\n <input\n autoFocus\n type=\"text\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') close();\n }}\n placeholder={t('Search prompts...')}\n aria-label={t('Search prompts...')}\n className=\"w-full h-7 px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]\"\n />\n </div>\n )}\n\n <div className=\"max-h-[240px] overflow-y-auto filigran-chat-scrollable\">\n {filtered.length === 0 && <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No prompt matches')}</div>}\n {filtered.map((p) => (\n <button\n key={p.id}\n type=\"button\"\n onClick={() => {\n onPick(p.content);\n close();\n }}\n className=\"w-full px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <div className=\"text-[0.8125rem] text-gray-900 dark:text-white truncate\">{p.title}</div>\n {p.description && <div className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">{p.description}</div>}\n </button>\n ))}\n </div>\n </Dropdown>\n </>\n );\n};\n","import type { ChatQuotaStatus } from '../types';\nimport { compactCount as compact, translate } from '../utils';\nimport { quotaPeriodLabel } from '../utils/quota';\nimport { Tooltip } from './Tooltip';\n\ninterface QuotaIndicatorProps {\n quota: ChatQuotaStatus;\n t: (key: string) => string;\n}\n\n/**\n * Agentic quota headroom, as a small bar plus counts.\n *\n * Colour is earned, not decorative: neutral until 75%, amber past it, red once\n * the allowance is spent — the point is to warn before a turn is refused, not\n * to decorate the composer.\n */\nexport const QuotaIndicator = ({ quota, t }: QuotaIndicatorProps) => {\n const { used, limit } = quota;\n const period = quotaPeriodLabel(quota.period, t);\n // One allowance for the whole platform: say so, or a user reads colleagues'\n // consumption as their own.\n const withScope = (title: string) => (quota.scope === 'global' ? translate(t, '{quota} (shared across all users)', { quota: title }) : title);\n\n // No ceiling: report consumption without implying a limit that isn't there.\n if (limit === null) {\n const title = withScope(period ? translate(t, 'Usage · {period}', { period }) : t('Usage'));\n return (\n <Tooltip title={title}>\n <span className=\"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30\" role=\"img\" aria-label={`${title} ${compact(used)}`}>\n {compact(used)}\n </span>\n </Tooltip>\n );\n }\n\n // Guard a zero/negative limit rather than dividing by it.\n const ratio = limit > 0 ? Math.min(used / limit, 1) : 1;\n const exhausted = limit > 0 ? used >= limit : true;\n const nearLimit = ratio >= 0.75;\n\n const barColor = exhausted ? 'bg-red-500' : nearLimit ? 'bg-amber-500' : 'bg-[var(--chat-accent)]/60';\n const textColor = exhausted\n ? 'text-red-500 dark:text-red-400'\n : nearLimit\n ? 'text-amber-600 dark:text-amber-400'\n : 'text-gray-400 dark:text-white/30';\n\n const label = `${compact(used)}/${compact(limit)}`;\n const headline = exhausted ? t('Quota reached') : t('Quota');\n const title = withScope(period ? `${headline} · ${period}` : headline);\n\n return (\n <Tooltip title={title}>\n <span className=\"flex items-center gap-1.5\" role=\"img\" aria-label={`${title} ${label}`}>\n <span className=\"h-1 w-10 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden\">\n <span className={`block h-full rounded-full transition-[width] duration-300 ${barColor}`} style={{ width: `${ratio * 100}%` }} />\n </span>\n <span className={`text-[0.68rem] tabular-nums ${textColor}`}>{label}</span>\n </span>\n </Tooltip>\n );\n};\n","import { useLayoutEffect, useRef, type KeyboardEvent } from 'react';\nimport type { ChatContextUsage, ChatFile, ChatMode, ChatPromptTemplate, ChatQuotaStatus } from '../types';\nimport { AttachFileIcon, FileIcon, MicIcon, MicOffIcon, SendIcon, StopCircleIcon } from './icons';\nimport { useDictation } from '../hooks/useDictation';\nimport { ContextUsageIndicator } from './ContextUsageIndicator';\nimport { PromptPicker } from './PromptPicker';\nimport { QuotaIndicator } from './QuotaIndicator';\nimport { Tooltip } from './Tooltip';\n\ninterface ChatInputProps {\n inputValue: string;\n onInputChange: (value: string) => void;\n onSend: () => void;\n onStop: () => void;\n isLoading: boolean;\n /**\n * Mid-run steering availability: while the agent is generating, the typed\n * text can be dispatched immediately (Enter / accent Send button) and is\n * injected into the running run instead of waiting for it to finish.\n * Attachments keep the legacy wait behavior.\n */\n canSteer?: boolean;\n attachedFiles?: ChatFile[];\n onFileAdd?: (files: FileList | null) => void;\n onFileRemove?: (index: number) => void;\n onPaste?: (e: React.ClipboardEvent) => void;\n t: (key: string) => string;\n mode?: ChatMode;\n separatorColor?: string;\n /** Saved prompt templates; omitted entirely when the host serves none. */\n prompts?: ChatPromptTemplate[] | null;\n /** Agentic quota headroom; omitted entirely when the host serves none. */\n quota?: ChatQuotaStatus | null;\n /** Context-window occupancy; omitted until the backend reports it. */\n contextUsage?: ChatContextUsage | null;\n /** Host-supplied controls appended to the toolbar (see `composerToolbar`). */\n composerToolbar?: React.ReactNode;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 120;\n\nexport const ChatInput = ({\n inputValue,\n onInputChange,\n onSend,\n onStop,\n isLoading,\n canSteer = false,\n attachedFiles = [],\n onFileAdd,\n onFileRemove,\n onPaste,\n t,\n mode,\n separatorColor,\n prompts,\n quota,\n contextUsage,\n composerToolbar,\n}: ChatInputProps) => {\n const fileInputRef = useRef<HTMLInputElement>(null);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n // A dictated phrase lands at the end of the draft while the focus is on the\n // mic, so nothing scrolls the field to it once the text outgrows the cap.\n const revealEndRef = useRef(false);\n\n // Dictation appends each finalised phrase, so speaking continues a draft\n // rather than replacing it — same contract as picking a template.\n const dictation = useDictation((finalText) => {\n revealEndRef.current = true;\n onInputChange(inputValue.trim() ? `${inputValue.trimEnd()} ${finalText}` : finalText);\n });\n\n // Sized from the value rather than from the textarea's own change event:\n // dictation, template picks, draft restores and the clear after a send all\n // change the text without one.\n useLayoutEffect(() => {\n const el = textareaRef.current;\n if (!el) return;\n el.style.height = 'auto';\n el.style.height = `${Math.min(el.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n if (revealEndRef.current) {\n revealEndRef.current = false;\n el.scrollTop = el.scrollHeight;\n }\n }, [inputValue]);\n\n // Append rather than replace: a user who has already started typing must not\n // lose it to a template pick. The blank line keeps the two blocks distinct.\n const handlePromptPick = (content: string) => {\n onInputChange(inputValue.trim() ? `${inputValue.trimEnd()}\\n\\n${content}` : content);\n textareaRef.current?.focus();\n };\n\n // The toolbar row costs vertical space, so it only exists when something\n // actually occupies it. Dictation is not among them: it acts on the text\n // field, so it lives inside it, next to Send.\n const hasToolbar = Boolean((prompts && prompts.length > 0) || quota || contextUsage || composerToolbar);\n\n const isFileManagementEnabled = Boolean(onFileAdd && onFileRemove && onPaste);\n const hasContent = inputValue.trim() || (isFileManagementEnabled && attachedFiles.length > 0);\n const hasFilesUploading = isFileManagementEnabled && attachedFiles.some((f) => f.uploadStatus === 'pending');\n const canSend = hasContent && !hasFilesUploading;\n const hasAttachments = isFileManagementEnabled && attachedFiles.length > 0;\n // Show the accent Send button NEXT to Stop while generating: text-only\n // sends can steer the running agent. With attachments selected the send\n // must wait for the current response, so only Stop is shown.\n const showSteerSend = isLoading && canSteer && Boolean(inputValue.trim()) && !hasAttachments;\n\n // Every way of sending goes through here, and only when the matching button\n // would be enabled: Enter must not send while files upload, nor end a\n // dictation that nothing was sent from. Dictation is cancelled, not stopped:\n // a phrase still being recognised would land in the composer just emptied.\n const send = () => {\n if (!(isLoading ? showSteerSend : canSend)) return;\n dictation.cancel();\n onSend();\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n send();\n }\n if (e.key === 'Escape' && isLoading) {\n e.preventDefault();\n onStop();\n }\n };\n\n const footerText =\n isLoading && canSteer && !hasAttachments\n ? t('Enter to send now · Esc to stop')\n : isLoading && hasAttachments\n ? t('Attachments wait for the current response')\n : t('Uses AI. Verify results.');\n\n return (\n <div\n className={`px-4 py-3 border-t border-gray-200 dark:border-white/10 ${mode === 'floating' ? 'rounded-b-xl' : ''}`}\n style={separatorColor ? { borderTopColor: separatorColor, borderTopWidth: 1 } : undefined}\n >\n {isFileManagementEnabled && attachedFiles.length > 0 && (\n <div className=\"flex gap-1.5 flex-wrap mb-2\">\n {attachedFiles.map((f, i) => (\n <span\n key={i}\n className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] ${\n f.uploadStatus === 'error'\n ? 'border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400'\n : f.uploadStatus === 'pending'\n ? 'border-gray-200 dark:border-white/10 text-gray-400 dark:text-white/40'\n : 'border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60'\n }`}\n >\n {f.uploadStatus === 'pending' ? (\n <span className=\"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin\" />\n ) : (\n <FileIcon size={14} />\n )}\n {f.name}\n {f.uploadStatus === 'error' && <span className=\"text-red-400 text-[0.6rem]\">✕</span>}\n <button\n type=\"button\"\n onClick={() => onFileRemove?.(i)}\n className=\"ml-0.5 text-gray-400 dark:text-white/30 hover:text-gray-600 dark:hover:text-white/60\"\n >\n ×\n </button>\n </span>\n ))}\n </div>\n )}\n\n {/* items-end keeps the buttons on the last line once the field grows. */}\n <div\n className={`flex items-end border rounded-xl px-2 py-1 transition-colors ${\n dictation.listening ? 'border-red-500/50' : 'border-gray-200 dark:border-white/10 focus-within:border-[var(--chat-accent)]'\n }`}\n >\n {isFileManagementEnabled && (\n <>\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n hidden\n onChange={(e) => {\n onFileAdd?.(e.target.files);\n e.target.value = '';\n }}\n />\n <button\n type=\"button\"\n onClick={() => fileInputRef.current?.click()}\n className=\"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 mr-0.5 transition-colors\"\n >\n <AttachFileIcon size={18} />\n </button>\n </>\n )}\n <textarea\n ref={textareaRef}\n placeholder={dictation.listening ? t('Listening...') : t('Ask a question...')}\n value={inputValue}\n onChange={(e) => onInputChange(e.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={onPaste}\n rows={1}\n className=\"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 filigran-chat-scrollable\"\n style={{ maxHeight: MAX_TEXTAREA_HEIGHT }}\n />\n {dictation.supported && (\n <Tooltip title={dictation.listening ? t('Stop dictation') : t('Dictate a message')}>\n <button\n type=\"button\"\n onClick={dictation.toggle}\n aria-label={t('Dictate a message')}\n aria-pressed={dictation.listening}\n className={`relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors ${\n dictation.listening\n ? 'text-red-500 bg-red-500/10 hover:bg-red-500/20'\n : 'text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10'\n }`}\n >\n {dictation.listening ? <MicOffIcon size={18} /> : <MicIcon size={18} />}\n {dictation.listening && <span className=\"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse\" />}\n </button>\n </Tooltip>\n )}\n {showSteerSend && (\n <Tooltip title={t('Send now')}>\n <button\n type=\"button\"\n onClick={send}\n aria-label={t('Send now')}\n className=\"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20\"\n >\n <SendIcon size={18} />\n </button>\n </Tooltip>\n )}\n <Tooltip title={isLoading ? t('Stop generating') : hasFilesUploading ? t('Files uploading...') : ''}>\n <button\n type=\"button\"\n onClick={isLoading ? onStop : send}\n disabled={!isLoading && !canSend}\n className={`p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 ${\n isLoading\n ? 'text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5'\n : canSend\n ? 'text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20'\n : 'text-gray-300 dark:text-white/20 cursor-not-allowed'\n }`}\n >\n {isLoading ? <StopCircleIcon size={18} /> : <SendIcon size={18} />}\n </button>\n </Tooltip>\n </div>\n\n {hasToolbar && (\n <div className=\"flex items-center gap-1.5 mt-1.5 px-0.5\">\n {prompts && prompts.length > 0 && <PromptPicker prompts={prompts} onPick={handlePromptPick} t={t} />}\n {composerToolbar}\n {/* Status readouts sit last and pushed right, together: they are not\n controls, so neither should ever land between two clickable\n things. Context before quota — \"how full is this chat\" is the one\n the user can still act on by starting a new one. */}\n {(contextUsage || quota) && (\n <span className=\"ml-auto flex items-center gap-2.5\">\n {contextUsage && <ContextUsageIndicator usage={contextUsage} t={t} />}\n {quota && <QuotaIndicator quota={quota} t={t} />}\n </span>\n )}\n </div>\n )}\n\n {/* Words heard but not yet final take the footer's place, so the preview\n never shifts the composer's height. */}\n {dictation.interim ? (\n <p className=\"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5\">\n <span className=\"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse\" />\n <span className=\"truncate\">{dictation.interim}</span>\n </p>\n ) : (\n <p className=\"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70\">{footerText}</p>\n )}\n </div>\n );\n};\n","import { useCallback, useInsertionEffect, useRef, useState } from 'react';\nimport type { ChatMessage, MessageFeedback, Translate } from '../types';\nimport { normalizeFeedbackComment, ratingOf, submitFeedback } from '../utils/feedback';\n\n/** What the user did to one answer's rating in this session. */\nexport interface FeedbackEntry {\n /** Identifies the last change: a request answered after a newer one is ignored. */\n seq: number;\n value: MessageFeedback | null;\n comment: string | null;\n /** A request is on its way; the thumbs wait for it. */\n pending: boolean;\n /** The translated reason the last request failed, shown under the answer. */\n error: string | null;\n /** The optional comment asked for after a thumbs down. */\n commentOpen: boolean;\n}\n\n/**\n * The key an answer's rating is kept under. Not `id` alone: a restore renames\n * every row (`restored-<n>`), and one runs right after the first turn of a new\n * conversation - the persisted id is what stays the same.\n */\nexport const feedbackKeyOf = (msg: ChatMessage): string => msg.serverId ?? msg.id;\n\ninterface Options {\n /** `{apiBaseUrl}{feedback}` when the panel stores ratings itself (`feedbackBaseUrl`). */\n feedbackUrl?: string | null;\n conversationId?: string | null;\n requestHeaders?: Record<string, string>;\n onMessageFeedback?: (messageId: string, feedback: MessageFeedback | null, message: ChatMessage) => void;\n t: Translate;\n}\n\n/**\n * The thumbs of every answer in the transcript. A rating shows at once and is\n * taken back if the backend refuses it; the callbacks keep their identity, so\n * the memoized rows do not re-render when the panel does.\n *\n * Every action is handed the answer's current entry by its row: a click is a\n * discrete event, so the row has rendered the previous one's outcome by then.\n */\nexport function useMessageFeedback({ feedbackUrl, conversationId, requestHeaders, onMessageFeedback, t }: Options) {\n const [state, setState] = useState<{ scope: string | null | undefined; entries: Record<string, FeedbackEntry> }>(() => ({\n scope: conversationId,\n entries: {},\n }));\n // Ratings belong to one conversation: another one starts from none, and a\n // request of the previous one answering late finds no entry to update.\n let entries = state.entries;\n if (state.scope !== conversationId) {\n entries = {};\n setState({ scope: conversationId, entries });\n }\n\n const latest = useRef({ feedbackUrl, conversationId, requestHeaders, onMessageFeedback, t });\n useInsertionEffect(() => {\n latest.current = { feedbackUrl, conversationId, requestHeaders, onMessageFeedback, t };\n });\n const seqRef = useRef(0);\n\n const put = useCallback((key: string, entry: FeedbackEntry) => setState((s) => ({ ...s, entries: { ...s.entries, [key]: entry } })), []);\n const patch = useCallback(\n (key: string, seq: number, change: (entry: FeedbackEntry) => FeedbackEntry) =>\n setState((s) => {\n const entry = s.entries[key];\n if (!entry || entry.seq !== seq) return s;\n return { ...s, entries: { ...s.entries, [key]: change(entry) } };\n }),\n [],\n );\n\n const rate = useCallback(\n async (msg: ChatMessage, next: MessageFeedback | null, current: FeedbackEntry | undefined) => {\n const { feedbackUrl: url, conversationId: convId, requestHeaders: headers, onMessageFeedback: notify, t: tr } = latest.current;\n const key = feedbackKeyOf(msg);\n const seq = ++seqRef.current;\n if (!url) {\n // The host stores it: nothing to wait for.\n put(key, { seq, value: next, comment: null, pending: false, error: null, commentOpen: false });\n notify?.(key, next, msg);\n return;\n }\n if (!convId || !msg.serverId) return;\n put(key, { seq, value: next, comment: null, pending: true, error: null, commentOpen: false });\n const stored = await submitFeedback(fetch, url, convId, msg.serverId, next ? { rating: ratingOf(next), comment: null } : null, headers);\n if (!stored) {\n const error = tr(next ? 'Could not submit feedback.' : 'Could not retract feedback.');\n patch(key, seq, () =>\n current\n ? { ...current, seq, pending: false, commentOpen: false, error }\n : { seq, value: null, comment: null, pending: false, error, commentOpen: false },\n );\n return;\n }\n // A thumbs down is worth a word on what went wrong - asked once it is\n // stored, so skipping the question loses nothing.\n patch(key, seq, (entry) => ({ ...entry, pending: false, commentOpen: next === 'down' }));\n latest.current.onMessageFeedback?.(key, next, msg);\n },\n [put, patch],\n );\n\n const saveComment = useCallback(\n async (msg: ChatMessage, text: string, current: FeedbackEntry) => {\n const { feedbackUrl: url, conversationId: convId, requestHeaders: headers, t: tr } = latest.current;\n const key = feedbackKeyOf(msg);\n const comment = normalizeFeedbackComment(text);\n if (!url || !convId || !msg.serverId || !comment) {\n put(key, { ...current, commentOpen: false, error: null });\n return;\n }\n const seq = ++seqRef.current;\n put(key, { ...current, seq, pending: true, error: null });\n const stored = await submitFeedback(fetch, url, convId, msg.serverId, { rating: 'negative', comment }, headers);\n patch(key, seq, (entry) =>\n stored\n ? { ...entry, comment, pending: false, commentOpen: false }\n : // The question stays open with what was typed, to try again.\n { ...entry, pending: false, error: tr('Could not submit feedback.') },\n );\n },\n [put, patch],\n );\n\n const skipComment = useCallback(\n (msg: ChatMessage, current: FeedbackEntry) => put(feedbackKeyOf(msg), { ...current, commentOpen: false, error: null }),\n [put],\n );\n\n return { entries, rate, saveComment, skipComment };\n}\n","import remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport { unified } from 'unified';\n\n/**\n * Reading an answer aloud through the browser's speech synthesis.\n *\n * What is spoken is the text a reader sees, never the markdown that draws it:\n * no `**`, no `#`, no table pipes, no code block, no image, and no bare URL\n * spelled out character by character. The text is parsed with the parser the\n * panel renders with (remark-parse + remark-gfm), so what counts as a heading,\n * a list or a link is what the screen shows. It reads the documents the\n * transcript renders (`answerMarkdownSources`), never the raw answer: the\n * renderer splits it at its file markers and repairs it first (`prepareMarkdown`).\n *\n * Kept free of local imports so `node --test` runs it as is.\n */\n\nconst parser = unified().use(remarkParse).use(remarkGfm).freeze();\n\ntype MdNode = { type: string; value?: string; url?: string; children?: MdNode[] };\n\n/** Blocks and inline nodes a listener has nothing to hear in. */\nconst SILENT = new Set(['code', 'html', 'image', 'imageReference', 'definition', 'footnoteDefinition', 'footnoteReference', 'thematicBreak']);\n\nfunction inlineText(node: MdNode): string {\n if (SILENT.has(node.type)) return '';\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? '';\n if (node.type === 'break') return ' ';\n const text = (node.children ?? []).map(inlineText).join('');\n // A link written as its own address (a bare URL, an autolink) is noise when\n // read out; a link with words says those words.\n if (node.type === 'link' && node.url && (text === node.url || `mailto:${text}` === node.url)) return '';\n return text;\n}\n\nfunction collectLines(node: MdNode, lines: string[]): void {\n if (SILENT.has(node.type)) return;\n switch (node.type) {\n case 'paragraph':\n case 'heading':\n lines.push(inlineText(node));\n return;\n case 'tableRow':\n lines.push(\n (node.children ?? [])\n .map(inlineText)\n .map((cell) => cell.trim())\n .filter(Boolean)\n .join(', '),\n );\n return;\n default:\n for (const child of node.children ?? []) collectLines(child, lines);\n }\n}\n\n/**\n * The words of an answer's markdown documents, one sentence-ending line per\n * block: a heading or a list item without its own punctuation gets a full\n * stop, so the voice pauses where the eye does. Each document is parsed on its own.\n */\nexport function speakableText(documents: readonly string[]): string {\n const lines: string[] = [];\n for (const markdown of documents) {\n if (markdown.trim()) collectLines(parser.parse(markdown) as MdNode, lines);\n }\n return lines\n .map((line) =>\n line\n .replace(/\\s+/g, ' ')\n .replace(/ ([.,!?;:])/g, '$1')\n .trim(),\n )\n .filter((line) => /[\\p{L}\\p{N}]/u.test(line))\n .map((line) => (/[.!?;:\\u3002\\uff01\\uff1f]$/.test(line) ? line : `${line}.`))\n .join('\\n');\n}\n\n/**\n * A fenced code block: a run of 3+ backticks or tildes, closed by a bare run of\n * the same character at least as long (`prepareMarkdown` lengthens the fence\n * around nested ones), or by the end of an answer cut short.\n */\nconst FENCED_BLOCK_RE = /^[ \\t]*((`|~)\\2{2,})[\\s\\S]*?(?:^[ \\t]*\\1\\2*[ \\t]*$|(?![\\s\\S]))/gm;\n\n/**\n * Whether an answer's markdown documents have words to read outside their code\n * blocks - what decides that it gets a \"Read aloud\" button. A cheap look rather\n * than `speakableText`: it runs for every message on screen, the full parse only on a click.\n */\nexport function hasSpeakableWords(documents: readonly string[]): boolean {\n return documents.some((markdown) => /[\\p{L}\\p{N}]/u.test(markdown.replace(FENCED_BLOCK_RE, '')));\n}\n\n/**\n * Longest utterance handed to the synthesiser. Chrome stops a single utterance\n * after roughly fifteen seconds without firing `end`, so a long answer is\n * queued as a series of short ones, cut between sentences.\n */\nexport const SPEECH_CHUNK_MAX_LENGTH = 220;\n\n/** `text` cut into utterances of at most `maxLength` characters, between sentences first, then between words. */\nexport function chunkSpeech(text: string, maxLength: number = SPEECH_CHUNK_MAX_LENGTH): string[] {\n const sentences = text\n .split(/\\n+|(?<=[.!?;:\\u3002\\uff01\\uff1f])\\s+/)\n .map((s) => s.trim())\n .filter(Boolean);\n const pieces: string[] = [];\n for (const sentence of sentences) {\n if (sentence.length <= maxLength) {\n pieces.push(sentence);\n continue;\n }\n let current = '';\n for (const word of sentence.split(' ')) {\n for (let start = 0; start < word.length; start += maxLength) {\n const part = word.slice(start, start + maxLength);\n if (!current) current = part;\n else if (current.length + 1 + part.length <= maxLength) current = `${current} ${part}`;\n else {\n pieces.push(current);\n current = part;\n }\n }\n }\n if (current) pieces.push(current);\n }\n const chunks: string[] = [];\n for (const piece of pieces) {\n const last = chunks.length - 1;\n if (last >= 0 && chunks[last].length + 1 + piece.length <= maxLength) chunks[last] = `${chunks[last]} ${piece}`;\n else chunks.push(piece);\n }\n return chunks;\n}\n\n/** The part of `window.speechSynthesis` the controller uses. */\nexport interface SpeechSynthesisLike<U> {\n speak(utterance: U): void;\n cancel(): void;\n}\n\n/** Builds one utterance; `window.SpeechSynthesisUtterance` in the browser. */\nexport type CreateUtterance<U> = (text: string, options: { lang?: string; onEnd: () => void; onError: () => void }) => U;\n\nexport interface SpeechController {\n /**\n * Reads `chunks` as the message `id`, stopping whatever was being read.\n * Returns false, and reads nothing, when there is nothing to read.\n */\n speak(id: string, chunks: string[], lang?: string): boolean;\n /** Stops reading. A no-op when nothing is being read. */\n stop(): void;\n /** The message being read, or null. */\n readonly speakingId: string | null;\n}\n\n/**\n * One reader for the whole transcript: starting a message stops the previous\n * one, and `onChange` reports which message is being read (null once it ended,\n * failed or was stopped). The synthesiser reports the end of an utterance\n * asynchronously and, on `cancel()`, fails every queued one: each reading\n * carries a generation, and only the current one's events count.\n */\nexport function createSpeechController<U>(\n synth: SpeechSynthesisLike<U>,\n createUtterance: CreateUtterance<U>,\n onChange: (id: string | null) => void,\n): SpeechController {\n let generation = 0;\n let speakingId: string | null = null;\n\n const finish = (gen: number) => {\n if (gen !== generation || speakingId === null) return;\n generation += 1;\n speakingId = null;\n onChange(null);\n };\n\n // Nothing of ours being read, nothing is cancelled: the synthesiser is the\n // page's, and the host may be using it.\n const stop = () => {\n if (speakingId === null) return;\n generation += 1;\n speakingId = null;\n synth.cancel();\n onChange(null);\n };\n\n const speak = (id: string, chunks: string[], lang?: string) => {\n stop();\n const parts = chunks.filter((c) => c.trim());\n if (!parts.length) return false;\n const gen = generation;\n speakingId = id;\n onChange(id);\n parts.forEach((part, index) => {\n const last = index === parts.length - 1;\n const utterance = createUtterance(part, {\n lang,\n onEnd: () => {\n if (last) finish(gen);\n },\n onError: () => {\n if (gen !== generation) return;\n // Ends the reading before cancelling the rest of its queue, whose\n // failures then belong to a past generation.\n finish(gen);\n synth.cancel();\n },\n });\n synth.speak(utterance);\n });\n return true;\n };\n\n return {\n speak,\n stop,\n get speakingId() {\n return speakingId;\n },\n };\n}\n","import { useCallback, useEffect, useInsertionEffect, useRef, useState } from 'react';\nimport { chunkSpeech, createSpeechController, speakableText, type SpeechController } from '../utils/speech';\n\nconst speechSupported = (): boolean =>\n typeof window !== 'undefined' && !!window.speechSynthesis && typeof window.SpeechSynthesisUtterance === 'function';\n\n/**\n * Reads answers aloud through the browser's speech synthesis, one at a time,\n * in `locale` (the browser's voice when unset). `supported` is false where the\n * browser has no synthesiser: the panel then offers no button at all.\n *\n * Whatever is being read stops when the transcript unmounts.\n */\nexport function useSpeechReader(locale?: string) {\n const [supported] = useState(speechSupported);\n const [speakingId, setSpeakingId] = useState<string | null>(null);\n const controllerRef = useRef<SpeechController | null>(null);\n const localeRef = useRef(locale);\n useInsertionEffect(() => {\n localeRef.current = locale;\n });\n\n const controller = useCallback((): SpeechController | null => {\n if (!supported) return null;\n controllerRef.current ??= createSpeechController<SpeechSynthesisUtterance>(\n window.speechSynthesis,\n (text, { lang, onEnd, onError }) => {\n const utterance = new SpeechSynthesisUtterance(text);\n if (lang) utterance.lang = lang;\n utterance.onend = onEnd;\n utterance.onerror = onError;\n return utterance;\n },\n setSpeakingId,\n );\n return controllerRef.current;\n }, [supported]);\n\n /**\n * Reads the message `id` from the markdown documents the transcript renders it\n * from (`answerMarkdownSources`), or stops it when it is the one being read.\n */\n const toggle = useCallback(\n (id: string, documents: readonly string[]) => {\n const reader = controller();\n if (!reader) return;\n if (reader.speakingId === id) reader.stop();\n else reader.speak(id, chunkSpeech(speakableText(documents)), localeRef.current);\n },\n [controller],\n );\n\n const stop = useCallback(() => controllerRef.current?.stop(), []);\n\n useEffect(() => () => controllerRef.current?.stop(), []);\n\n return { supported, speakingId, toggle, stop };\n}\n","/**\n * The time shown under a chat message.\n *\n * A message from today reads as its time alone (`14:05`); an older one leads\n * with a short date (`29 Sept, 14:05`), and one from another year carries the\n * year, so a restored conversation says when each answer was given without\n * anyone having to hover. The tooltip spells the whole date out.\n *\n * Kept free of local imports so `node --test` runs it as is.\n */\n\nexport interface MessageTime {\n /** What the footer shows. */\n label: string;\n /** The complete date and time, for the tooltip. */\n full: string;\n /** Machine-readable, for the `dateTime` attribute of a `<time>` element. */\n iso: string;\n}\n\ntype FormatKind = 'time' | 'date' | 'dateWithYear' | 'full';\n\nconst FORMAT_OPTIONS: Record<FormatKind, Intl.DateTimeFormatOptions> = {\n time: { hour: '2-digit', minute: '2-digit' },\n date: { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' },\n dateWithYear: { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' },\n full: { dateStyle: 'full', timeStyle: 'short' },\n};\n\n// Every row of a transcript formats with the same few formatters, and building\n// one costs far more than using it.\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction formatter(locale: string | undefined, kind: FormatKind): Intl.DateTimeFormat {\n const key = `${locale ?? ''}|${kind}`;\n let cached = formatters.get(key);\n if (!cached) {\n try {\n cached = new Intl.DateTimeFormat(locale || undefined, FORMAT_OPTIONS[kind]);\n } catch {\n // A malformed tag throws a RangeError: fall back to the browser's own\n // language rather than losing the time.\n cached = new Intl.DateTimeFormat(undefined, FORMAT_OPTIONS[kind]);\n }\n formatters.set(key, cached);\n }\n return cached;\n}\n\nfunction sameDay(a: Date, b: Date): boolean {\n return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();\n}\n\n/**\n * The footer time of a message sent at `date`, in `locale` (browser default\n * when absent), read against `now`. `null` for a date that is not one, so a\n * backend sending an unparseable `created_at` loses the time, not the row.\n */\nexport function formatMessageTime(date: Date, locale?: string, now: Date = new Date()): MessageTime | null {\n if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;\n const kind: FormatKind = sameDay(date, now) ? 'time' : date.getFullYear() === now.getFullYear() ? 'date' : 'dateWithYear';\n return {\n label: formatter(locale, kind).format(date),\n full: formatter(locale, 'full').format(date),\n iso: date.toISOString(),\n };\n}\n","/**\n * How the thread keeps the end of the conversation in view as it grows.\n *\n * The view follows the conversation while the reader is at the bottom, stops\n * once they scroll up to read back, and follows again when they come back down\n * or send a message. While following, each streamed frame jumps to the end at\n * once: a smooth scroll restarted on every frame lags behind the text. A\n * message just sent and a conversation just opened are scrolled to smoothly,\n * and since any other scroll aborts a smooth one, the frames streamed in the\n * meantime wait for it to arrive and the view then catches up with them.\n *\n * The reader's gestures toward the top (a wheel, a swipe, a key, a press on\n * the scrollbar) stop the follow before the scroll they cause, read by the\n * predicates below. A scroll event that moved nothing changes nothing: it is\n * the event of a jump of ours, delivered a frame late, and right after such a\n * gesture it would re-arm the follow the gesture just ended. Each move is read\n * against the last position that moved more than 1 px, so a slow drift of\n * sub-pixel steps adds up to a move instead of reading as none at every step.\n */\n\n/** How near the bottom a reader scrolling down must come for the view to follow again. */\nexport const FOLLOW_THRESHOLD_PX = 100;\n\n/** How far (px) a finger must travel down the screen before the swipe counts as scrolling up. */\nexport const TOUCH_SLOP_PX = 4;\n\n/**\n * The longest a smooth scroll of ours is waited for. Browsers finish one well\n * within it; past it the view catches up anyway, since a smooth scroll cut\n * short by another one (a prompt scrolling itself into view) never reaches\n * where it was going.\n */\nconst SMOOTH_SCROLL_TIMEOUT_MS = 1000;\n\n/** The scroll container, as far as following the conversation needs it. */\nexport interface ScrollBox {\n readonly scrollTop: number;\n readonly scrollHeight: number;\n readonly clientHeight: number;\n scrollTo(options: ScrollToOptions): void;\n}\n\nexport interface ScrollFollowTimers {\n set: (callback: () => void, ms: number) => unknown;\n clear: (handle: unknown) => void;\n}\n\nexport interface ScrollFollower {\n /** Whether the view follows the conversation as it grows. */\n readonly following: boolean;\n /** Scroll smoothly to the end and follow again: a message just sent, a conversation just opened. */\n reveal: () => void;\n /** The conversation grew: keep its end in view while the view follows. */\n keepUp: () => void;\n /** The container scrolled. */\n onScroll: () => void;\n /**\n * The reader is scrolling toward the top (a wheel, a swipe, a key, the scrollbar). Stops the follow\n * at once: the scroll event only comes with the next frame, and a streamed\n * frame committed before it would pull the view back down first.\n */\n leave: () => void;\n}\n\nconst browserTimers: ScrollFollowTimers = {\n set: (callback, ms) => setTimeout(callback, ms),\n clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n\nexport function createScrollFollower(getBox: () => ScrollBox | null, timers: ScrollFollowTimers = browserTimers): ScrollFollower {\n let following = true;\n // Where the view was last seen, which tells the reader scrolling up apart\n // from the view being moved down by a scroll of ours.\n let lastTop = 0;\n // A smooth scroll of ours still running: where it lands, and the timer that\n // stops waiting for it.\n let smooth: { target: number; timer: unknown } | null = null;\n\n // 'instant' rather than 'auto': a `scroll-behavior: smooth` stylesheet would\n // turn 'auto' smooth again.\n const jumpToEnd = (box: ScrollBox) => {\n box.scrollTo({ top: box.scrollHeight, behavior: 'instant' });\n lastTop = box.scrollTop;\n };\n\n const stopWaiting = () => {\n if (!smooth) return;\n timers.clear(smooth.timer);\n smooth = null;\n };\n\n // The smooth scroll is over: catch up with what streamed in while it ran.\n const arrived = () => {\n stopWaiting();\n const box = getBox();\n if (box && following) jumpToEnd(box);\n };\n\n return {\n get following() {\n return following;\n },\n reveal: () => {\n const box = getBox();\n if (!box) return;\n following = true;\n stopWaiting();\n const target = Math.max(0, box.scrollHeight - box.clientHeight);\n box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });\n lastTop = box.scrollTop;\n // Already at the end, or moved there at once (smooth scrolling turned off).\n if (lastTop >= target - 1) return;\n smooth = { target, timer: timers.set(arrived, SMOOTH_SCROLL_TIMEOUT_MS) };\n },\n keepUp: () => {\n const box = getBox();\n // A jump now would cut the smooth scroll short: it catches up on arrival.\n if (box && following && !smooth) jumpToEnd(box);\n },\n onScroll: () => {\n const box = getBox();\n if (!box) return;\n const top = box.scrollTop;\n const movedUp = top < lastTop - 1;\n const movedDown = top > lastTop + 1;\n if (movedUp || movedDown) lastTop = top;\n const distance = box.scrollHeight - top - box.clientHeight;\n if (movedUp) {\n // The reader scrolled up — or the browser moved the view to the new end\n // of a list that got shorter, which leaves it at the bottom.\n following = distance <= 1;\n } else if (movedDown && distance <= FOLLOW_THRESHOLD_PX) {\n following = true;\n }\n // Ours only goes down: it is over once the view reaches where it was sent\n // or the end, and a move up is the reader taking over.\n if (smooth && (movedUp || top >= smooth.target - 1 || distance <= 1)) arrived();\n },\n leave: () => {\n const box = getBox();\n // With nothing above to scroll to (a thread that fits), the reader is\n // still at the end whatever the gesture.\n if (!box || box.scrollTop <= 0) return;\n following = false;\n stopWaiting();\n },\n };\n}\n\n/** A wheel turned toward the top. A pinch (ctrl + wheel) zooms, and a mostly sideways one pans a code block or a table. */\nexport function wheelScrollsUp(event: { deltaX: number; deltaY: number; ctrlKey: boolean }): boolean {\n return !event.ctrlKey && event.deltaY < 0 && Math.abs(event.deltaY) > Math.abs(event.deltaX);\n}\n\nconst KEYS_TOWARD_TOP = new Set(['ArrowUp', 'PageUp', 'Home']);\n\n/** A key that scrolls a focused thread toward its top. */\nexport function keyScrollsUp(event: { key: string; shiftKey: boolean; altKey: boolean }): boolean {\n if (event.altKey) return false;\n return KEYS_TOWARD_TOP.has(event.key) || (event.key === ' ' && event.shiftKey);\n}\n\n/**\n * A finger moving DOWN the screen (the content follows it toward the top),\n * measured from the highest point of the touch so far, so a tap's jitter is\n * not a swipe.\n */\nexport function swipeScrollsUp(anchorY: number, y: number): boolean {\n return y - anchorY > TOUCH_SLOP_PX;\n}\n\n/**\n * Where the one finger on the screen is. `null` while two or more are down: a\n * pinch zooms and a first finger can travel down past the slop without the\n * thread scrolling at all.\n */\nexport function singleTouchY(touches: ArrayLike<{ clientY: number }>): number | null {\n return touches.length === 1 ? touches[0].clientY : null;\n}\n\n/**\n * The swipe anchor after a `touchmove` that found the finger at `y`: none\n * during a pinch, the finger's own position on its first move after one (no\n * `touchstart` marks the finger left on the screen), else the highest point.\n */\nexport function nextTouchAnchor(anchor: number | null, y: number | null): number | null {\n if (y === null) return null;\n return anchor === null ? y : Math.min(anchor, y);\n}\n\n/** A pointer press on the thread, `x` / `y` measured from its padding box. */\nexport interface ScrollPress {\n button: number;\n /** The press landed on the container itself, not on its content. */\n onContainer: boolean;\n /** The press landed on a link, a button or a field. */\n onControl: boolean;\n x: number;\n y: number;\n clientWidth: number;\n clientHeight: number;\n scrollTop: number;\n scrollHeight: number;\n}\n\n/**\n * A press that hands the view to the reader: the middle button away from a\n * control, which starts the browser's autoscroll on Windows and Linux (on a\n * link it opens a tab), or the thread's own scrollbar (`x` past its content\n * box) on the thumb or above it. The track below the thumb pages DOWN, toward\n * the end the view follows.\n */\nexport function pressTakesScrollbar(press: ScrollPress): boolean {\n if (press.button === 1) return !press.onControl;\n if (press.button !== 0 || !press.onContainer || press.x < press.clientWidth) return false;\n const thumbBottom = ((press.scrollTop + press.clientHeight) / press.scrollHeight) * press.clientHeight;\n return press.y <= thumbBottom;\n}\n\n/** What `innerBoxScrollsUp` reads of an element. */\nexport interface ScrollNode {\n readonly scrollTop: number;\n readonly scrollHeight: number;\n readonly clientHeight: number;\n}\n\nconst SCROLLING_OVERFLOW = new Set(['auto', 'scroll', 'overlay']);\n\n/**\n * Whether a gesture toward the top at `target` scrolls a box INSIDE the thread\n * instead of the thread: the browser moves the innermost box under it that can\n * still go up, and the thread only once that box is at its top. A box that\n * only clips (`overflow: hidden` — the reasoning window, pinned to its own\n * end) is not one: the gesture goes through it.\n */\nexport function innerBoxScrollsUp<T extends ScrollNode>(\n target: T | null,\n container: T,\n parentOf: (node: T) => T | null,\n overflowY: (node: T) => string,\n): boolean {\n for (let node = target; node && node !== container; node = parentOf(node)) {\n if (node.scrollTop > 0 && node.scrollHeight > node.clientHeight && SCROLLING_OVERFLOW.has(overflowY(node))) {\n return true;\n }\n }\n return false;\n}\n","import { useEffect, useId, useRef, useState } from 'react';\nimport type { ToolApprovalDecision, ToolApprovalProposal, ToolApprovalVerdict } from '../types';\nimport { translate } from '../utils';\nimport { AlertTriangleIcon, CheckIcon, WrenchIcon, XCircleIcon } from './icons';\n\ninterface ChatApprovalPromptProps {\n proposals: ToolApprovalProposal[];\n /** Sends one decision per proposal — the backend refuses a partial set. */\n onSubmit: (decisions: ToolApprovalDecision[]) => void;\n isSubmitting?: boolean;\n /** Why the last submission failed. Non-null re-arms the controls for a retry. */\n error?: string | null;\n t: (key: string) => string;\n}\n\n/** Shape of one argument as described by the tool's own JSON Schema. */\ninterface ArgumentSchema {\n description?: string;\n type?: string;\n}\n\n/**\n * Pull `{ description, type }` for one argument out of a JSON Schema, tolerating\n * a schema that is absent or shaped unexpectedly — an unlabelled argument still\n * renders, it just carries less.\n */\nfunction argumentSchema(inputSchema: Record<string, unknown> | undefined, name: string): ArgumentSchema {\n const properties = inputSchema?.properties;\n if (!properties || typeof properties !== 'object') return {};\n const entry = (properties as Record<string, unknown>)[name];\n if (!entry || typeof entry !== 'object') return {};\n const e = entry as Record<string, unknown>;\n return {\n description: typeof e.description === 'string' ? e.description : undefined,\n type: typeof e.type === 'string' ? e.type : undefined,\n };\n}\n\n/** Render an argument value as something a person can read. */\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n // Cyclic or otherwise unstringifiable — the reviewer still needs to see\n // that the argument is there, so degrade rather than blank the card.\n return String(value);\n }\n}\n\n/**\n * Scroll `ref` into view when `active` becomes true, and on each later\n * transition into it.\n *\n * Every control here is revealed rather than always present: the prompt itself\n * arrives at the bottom of a thread that has just grown by a whole turn, \"No\"\n * opens a reason box under the card, and \"Yes, always\" opens a warning under the\n * list. In each case the click can look like it did nothing — and on a *paused*\n * turn a stalled reviewer stalls the agent too. rAF because the revealed node\n * must be laid out before it can be scrolled to.\n */\nfunction useRevealIntoView<T extends HTMLElement>(active: boolean) {\n const ref = useRef<T>(null);\n useEffect(() => {\n if (!active) return;\n const raf = requestAnimationFrame(() => {\n ref.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });\n });\n return () => cancelAnimationFrame(raf);\n }, [active]);\n return ref;\n}\n\nconst BUTTON_BASE =\n 'inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50';\n\ninterface ApprovalCardProps {\n proposal: ToolApprovalProposal;\n decision: ToolApprovalDecision | undefined;\n onDecide: (decision: ToolApprovalDecision) => void;\n disabled?: boolean;\n t: (key: string) => string;\n}\n\n/**\n * One proposed call: what the agent wants to run, what it does, and every\n * argument labelled with the tool's own description of it.\n *\n * Those descriptions are the difference between a control and a rubber stamp.\n * `cascade: true` is unjudgeable; \"cascade — also delete linked entities\" is a\n * decision someone can actually make.\n */\nconst ApprovalCard = ({ proposal, decision, onDecide, disabled, t }: ApprovalCardProps) => {\n // Declining asks why before it sends. With argument editing deliberately\n // absent, a rejection IS the correction channel — it is the agent's only\n // signal to adapt. Optional, so a reviewer with nothing to add just confirms.\n const [rejecting, setRejecting] = useState(false);\n const [reason, setReason] = useState('');\n // Every proposal in a batch renders its own reason box, so the association\n // needs an id unique to this card rather than a constant.\n const reasonId = useId();\n const rejectPanelRef = useRevealIntoView<HTMLDivElement>(rejecting);\n\n const verdict = decision?.verdict;\n const argumentNames = Object.keys(proposal.arguments ?? {});\n\n const decide = (next: ToolApprovalVerdict) => {\n onDecide({\n toolCallId: proposal.toolCallId,\n verdict: next,\n ...(next === 'reject' && reason.trim() ? { rejectionReason: reason.trim() } : {}),\n });\n };\n\n return (\n <div className=\"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2\">\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"min-w-0 flex items-start gap-2\">\n <WrenchIcon size={13} className=\"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400\" />\n <div className=\"min-w-0\">\n {/* An unnamed tool is a malformed proposal, not a tool called\n \"unknown tool\": the placeholder is the package's own text and\n therefore translated here, not in the parser. */}\n <p className=\"truncate font-mono text-xs text-gray-800 dark:text-white/85\">{proposal.toolName || t('unknown tool')}</p>\n {proposal.toolDescription && <p className=\"mt-0.5 text-[0.7rem] text-gray-600 dark:text-white/60\">{proposal.toolDescription}</p>}\n {proposal.source && <p className=\"mt-0.5 text-[0.65rem] text-gray-400 dark:text-white/35\">{proposal.source}</p>}\n </div>\n </div>\n {verdict && (\n <span\n className={\n 'shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium ' +\n (verdict === 'reject' ? 'bg-red-500/15 text-red-600 dark:text-red-300' : 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300')\n }\n >\n {verdict === 'reject' ? t('Declined') : verdict === 'approve_always' ? t('Always allowed') : t('Approved')}\n </span>\n )}\n </div>\n\n {argumentNames.length > 0 && (\n <div className=\"flex flex-col gap-1.5\">\n {argumentNames.map((name) => {\n const schema = argumentSchema(proposal.inputSchema, name);\n return (\n <div key={name} className=\"text-[0.7rem]\">\n <div className=\"flex flex-wrap items-baseline gap-1.5\">\n <span className=\"font-mono text-gray-700 dark:text-white/75\">{name}</span>\n {schema.description && <span className=\"text-gray-500 dark:text-white/45\">— {schema.description}</span>}\n </div>\n <pre className=\"mt-0.5 whitespace-pre-wrap break-all font-mono text-gray-600 dark:text-white/60\">\n {formatValue(proposal.arguments?.[name])}\n </pre>\n </div>\n );\n })}\n </div>\n )}\n\n {!verdict && rejecting && (\n <div ref={rejectPanelRef} className=\"flex flex-col gap-1.5\">\n <label htmlFor={reasonId} className=\"text-[0.7rem] text-gray-500 dark:text-white/45\">\n {t('Why not? The agent sees this and can adapt (optional)')}\n </label>\n <textarea\n id={reasonId}\n autoFocus\n rows={2}\n value={reason}\n onChange={(e) => setReason(e.target.value)}\n placeholder={t('e.g. wrong environment — use staging instead')}\n className=\"w-full resize-none rounded-md border border-gray-200 bg-white px-2 py-1 text-[0.7rem] text-gray-800 outline-none focus:border-[var(--chat-accent)]/50 dark:border-white/10 dark:bg-white/[0.03] dark:text-white/85\"\n />\n <div className=\"flex items-center gap-1.5\">\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => decide('reject')}\n className={`${BUTTON_BASE} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`}\n >\n <XCircleIcon size={13} />\n {t('Decline this call')}\n </button>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => {\n setRejecting(false);\n setReason('');\n }}\n className={`${BUTTON_BASE} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`}\n >\n {t('Back')}\n </button>\n </div>\n </div>\n )}\n\n {!verdict && !rejecting && (\n <div className=\"flex flex-wrap items-center gap-1.5\">\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => setRejecting(true)}\n className={`${BUTTON_BASE} text-red-600 hover:bg-red-500/10 dark:text-red-300`}\n >\n <XCircleIcon size={13} />\n {t('No')}\n </button>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => decide('approve')}\n className={`${BUTTON_BASE} bg-[var(--chat-accent)] text-white hover:opacity-90`}\n >\n <CheckIcon size={13} />\n {t('Yes')}\n </button>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => decide('approve_always')}\n /* Disclosed on the control itself rather than buried in a tooltip:\n this is the one verdict whose effect outlives the turn. */\n title={t('Also applies to your scheduled runs, until you revoke it')}\n className={`${BUTTON_BASE} border border-gray-200 text-gray-700 hover:bg-gray-100 dark:border-white/15 dark:text-white/70 dark:hover:bg-white/5`}\n >\n {t('Yes, always')}\n </button>\n </div>\n )}\n </div>\n );\n};\n\n/**\n * Collects a verdict for every call a paused turn is waiting on.\n *\n * Submission is all-or-nothing because the backend requires it: resuming with\n * an undecided call would leave its `tool_use` block without a `tool_result`,\n * which the model providers reject outright. That condition is met the moment\n * the last card is decided, so the set submits itself there — a verdict is\n * final once clicked (a decided card shows a badge, not buttons), so a separate\n * confirm would gate work already committed to.\n *\n * \"Yes, always\" is the exception and the only click that earns a confirm step:\n * it saves a standing preference for this user that applies to unattended runs\n * too, and that has to be read before it is committed.\n */\nexport const ChatApprovalPrompt = ({ proposals, onSubmit, isSubmitting, error, t }: ChatApprovalPromptProps) => {\n const [decisions, setDecisions] = useState<Record<string, ToolApprovalDecision>>({});\n // Guards the auto-submit against a double fire: React may re-render between\n // the last verdict and the parent flipping `isSubmitting`, and answering the\n // same pause twice would decide a turn that is already resuming.\n const submitted = useRef(false);\n // The same fact as state, because a ref cannot re-render the footer button.\n const [sent, setSent] = useState(false);\n\n // A failed submission is the one case where the prompt survives its own send:\n // the turn is still paused, so the controls have to come back for a retry.\n useEffect(() => {\n if (!error) return;\n submitted.current = false;\n setSent(false);\n }, [error]);\n\n const busy = isSubmitting || sent;\n\n const submit = (all: ToolApprovalDecision[]) => {\n if (submitted.current || isSubmitting) return;\n submitted.current = true;\n setSent(true);\n onSubmit(all);\n };\n\n const decidedCount = proposals.filter((p) => decisions[p.toolCallId]).length;\n const allDecided = decidedCount === proposals.length && proposals.length > 0;\n const willRunAlways = Object.values(decisions).some((d) => d.verdict === 'approve_always');\n\n // The warning and the confirm sit *below* the cards, so an \"always\" click can\n // push them past the fold — exactly what must be read before confirming.\n const footerRef = useRevealIntoView<HTMLDivElement>(willRunAlways);\n // The prompt arrives at the bottom of a thread that just grew by a whole\n // turn. Always true: the mount is the reveal.\n const rootRef = useRevealIntoView<HTMLDivElement>(true);\n\n return (\n <div ref={rootRef} className=\"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3\">\n <p className=\"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300\">\n <AlertTriangleIcon size={13} className=\"mt-0.5 shrink-0\" />\n {proposals.length === 1 ? t('The agent needs your approval to run a tool:') : t('The agent needs your approval to run these tools:')}\n </p>\n\n {proposals.map((proposal) => (\n <ApprovalCard\n key={proposal.toolCallId}\n proposal={proposal}\n decision={decisions[proposal.toolCallId]}\n disabled={busy}\n t={t}\n onDecide={(decision) => {\n const next = { ...decisions, [decision.toolCallId]: decision };\n setDecisions(next);\n // Safe to read `decisions` from the closure: each verdict is its\n // own click, so this handler always sees the state the previous\n // one set.\n const all = proposals.map((p) => next[p.toolCallId]);\n if (all.every(Boolean) && !all.some((d) => d.verdict === 'approve_always')) {\n submit(all);\n }\n }}\n />\n ))}\n\n {willRunAlways && (\n <p className=\"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90\">\n <AlertTriangleIcon size={13} className=\"mt-0.5 shrink-0\" />\n {t(\n '“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.',\n )}\n </p>\n )}\n\n {error && <p className=\"text-[0.7rem] text-red-600 dark:text-red-300\">{error}</p>}\n\n <div ref={footerRef} className=\"flex items-center justify-between gap-2\">\n {/* The counter earns its place only when there is more than one thing\n to count; on a single proposal it reads as a progress bar for a\n one-step process. */}\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40\">\n {proposals.length > 1 ? translate(t, '{decided}/{total} decided', { decided: decidedCount, total: proposals.length }) : ''}\n </span>\n <button\n type=\"button\"\n disabled={!allDecided || busy}\n onClick={() => submit(proposals.map((p) => decisions[p.toolCallId]))}\n className={`${BUTTON_BASE} bg-[var(--chat-accent)] text-white hover:opacity-90`}\n >\n {busy ? t('Sending…') : t('Confirm')}\n </button>\n </div>\n </div>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CloseIcon, ImageIcon, MaximizeIcon } from './icons';\nimport { findChatbotRoot } from '../utils';\n\ninterface ImageLightboxProps {\n src: string;\n alt: string;\n onClose: () => void;\n t: (key: string) => string;\n}\n\n/**\n * Full-panel image viewer. Portalled into the chatbot root (not `document.body`)\n * so it inherits the panel's stacking context and can never be painted under —\n * or over — unrelated host chrome, matching the reasoning-details dialog.\n */\nconst ImageLightbox = ({ src, alt, onClose, t }: ImageLightboxProps) => {\n const hostRef = useRef<HTMLSpanElement>(null);\n const closeButtonRef = useRef<HTMLButtonElement>(null);\n const [root, setRoot] = useState<HTMLElement | null>(null);\n\n useEffect(() => {\n setRoot(findChatbotRoot(hostRef.current));\n }, []);\n\n useEffect(() => {\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose();\n };\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [onClose]);\n\n // The overlay is the only interactive surface while open, so focus moves to\n // its close button and returns to the thumbnail on dismiss.\n useEffect(() => {\n if (!root) return;\n const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n closeButtonRef.current?.focus({ preventScroll: true });\n return () => previouslyFocused?.focus({ preventScroll: true });\n }, [root]);\n\n return (\n <span ref={hostRef} className=\"hidden\">\n {root &&\n createPortal(\n <div\n className=\"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4\"\n onClick={onClose}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={t('Image preview')}\n >\n <button\n ref={closeButtonRef}\n type=\"button\"\n onClick={onClose}\n aria-label={t('Close')}\n className=\"absolute top-4 right-4 rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20\"\n >\n <CloseIcon size={20} />\n </button>\n <img src={src} alt={alt} className=\"max-h-[90%] max-w-[90%] rounded-lg object-contain\" onClick={(e) => e.stopPropagation()} />\n </div>,\n root,\n )}\n </span>\n );\n};\n\n/**\n * True for a URL with no scheme — a host-relative path such as\n * `/api/v1/platform/chat/files/<id>/download`. Protocol-relative URLs (`//host`)\n * are excluded: they resolve to a different origin, so the host's auth headers\n * must not be attached to them.\n */\nconst isRelativeUrl = (src: string): boolean => !src.startsWith('//') && !/^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(src);\n\ninterface ChatImageProps {\n src: string;\n alt: string;\n /**\n * Auth headers the host attaches to chatbot API calls. When present and the\n * image is host-relative, the image is fetched as a blob with these headers\n * instead of being handed to `<img src>` — a browser never sends custom\n * headers on an `<img>` request, so a bearer-authenticated image endpoint\n * would otherwise return 401 and render as a broken image.\n */\n requestHeaders?: Record<string, string>;\n /** Cap the inline thumbnail height. Full size is always available via the lightbox. */\n maxHeightClass?: string;\n t: (key: string) => string;\n}\n\n/**\n * An image inside a chat message: click (or the hover affordance) opens a\n * full-panel lightbox. Handles the three shapes an agent produces — inline\n * `data:image/*` charts from a code interpreter, host-relative API-served\n * images needing auth headers, and ordinary absolute URLs.\n */\nexport const ChatImage = ({ src, alt, requestHeaders, maxHeightClass = 'max-h-[400px]', t }: ChatImageProps) => {\n const needsAuth = !!requestHeaders && Object.keys(requestHeaders).length > 0 && isRelativeUrl(src);\n const [blobUrl, setBlobUrl] = useState<string | null>(null);\n const [errored, setErrored] = useState(false);\n const [expanded, setExpanded] = useState(false);\n\n useEffect(() => {\n if (!needsAuth) return;\n let cancelled = false;\n let objectUrl: string | null = null;\n\n fetch(src, { credentials: 'include', headers: { ...requestHeaders } })\n .then((res) => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.blob();\n })\n .then((blob) => {\n if (cancelled) return;\n objectUrl = URL.createObjectURL(blob);\n setBlobUrl(objectUrl);\n })\n .catch(() => {\n if (!cancelled) setErrored(true);\n });\n\n return () => {\n cancelled = true;\n // Revoking on teardown (rather than on unmount only) keeps a src change\n // from leaking the previous blob.\n if (objectUrl) URL.revokeObjectURL(objectUrl);\n };\n }, [needsAuth, src, requestHeaders]);\n\n const displaySrc = needsAuth ? blobUrl : src;\n\n if (errored) {\n return <p className=\"my-2 text-[0.75rem] italic text-gray-400 dark:text-white/40\">{t('Image could not be loaded')}</p>;\n }\n\n if (!displaySrc) {\n return (\n <span className=\"my-3 inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 dark:border-white/10\">\n <ImageIcon size={14} className=\"shrink-0 animate-pulse text-[var(--chat-accent)]\" />\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40\">{t('Loading image…')}</span>\n </span>\n );\n }\n\n return (\n <>\n <span className=\"group/img relative my-3 inline-block max-w-full rounded-lg border border-gray-200 p-1 transition-colors hover:border-[var(--chat-accent)]/40 dark:border-white/10\">\n <img\n src={displaySrc}\n alt={alt}\n loading=\"lazy\"\n onClick={() => setExpanded(true)}\n onError={() => setErrored(true)}\n className={`max-w-full cursor-zoom-in rounded-md object-contain ${maxHeightClass}`}\n />\n <button\n type=\"button\"\n onClick={() => setExpanded(true)}\n aria-label={t('Expand image')}\n className=\"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100\"\n >\n <MaximizeIcon size={14} />\n </button>\n </span>\n {expanded && <ImageLightbox src={displaySrc} alt={alt} onClose={() => setExpanded(false)} t={t} />}\n </>\n );\n};\n","import { useEffect, useMemo, useState } from 'react';\nimport type { Translate } from '../types';\nimport { ExternalLinkIcon, GamepadIcon } from './icons';\n\n/**\n * Playful, rotating \"still working on it\" messages shown below the status\n * bubble during longer waits. Kept short and upbeat so they fit on one line in\n * the narrow floating panel and read as a sense of progress rather than noise.\n */\nconst defaultMessages = (t: Translate) => [\n t('Crunching the data'),\n t('Connecting the dots'),\n t('Consulting the sources'),\n t('Thinking it through'),\n t('Reticulating splines'),\n t('Analyzing the details'),\n t('Almost there'),\n t('Putting it together'),\n t('Polishing the answer'),\n t('Wrapping things up'),\n];\n\n/** Message rotation cadence. */\nconst ROTATE_MS = 2600;\n\n/**\n * Where the waiting game is played: XTM One's arcade, which `?arcade=play`\n * opens on any XTM One page, the chat being where it lives. `xtmOneUrl` is\n * host input that ends up in an href, so only an http(s) base is linked.\n */\nexport function waitingGameUrl(xtmOneUrl: string | undefined): string | null {\n const base = xtmOneUrl?.trim().replace(/\\/+$/, '');\n if (!base || !/^https?:\\/\\//i.test(base)) return null;\n return `${base}/chat?arcade=play`;\n}\n\nfunction usePrefersReducedMotion(): boolean {\n const [reduced, setReduced] = useState(() => {\n if (typeof window === 'undefined' || !window.matchMedia) return false;\n return window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n });\n useEffect(() => {\n if (typeof window === 'undefined' || !window.matchMedia) return;\n const mql = window.matchMedia('(prefers-reduced-motion: reduce)');\n const onChange = () => setReduced(mql.matches);\n // Older Safari/WebKit only expose the deprecated addListener/removeListener.\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', onChange);\n return () => mql.removeEventListener('change', onChange);\n }\n mql.addListener(onChange);\n return () => mql.removeListener(onChange);\n }, []);\n return reduced;\n}\n\ninterface ChatWaitingPanelProps {\n t: Translate;\n /** Host-level override; when false the panel is hidden entirely. */\n enabled?: boolean;\n /** Opens the arcade in place, for a host that runs it itself. Wins over `playUrl`. */\n onPlay?: () => void;\n /** Where the arcade is played, opened in a new tab. */\n playUrl?: string | null;\n /** The thread's follower: keeps its end in view while the reader is there. */\n keepEndInView: () => void;\n}\n\nconst PLAY_CLASS =\n 'inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100';\n\n/**\n * Waiting experience shown below the status bubble during longer waits:\n * rotating messages, and an invitation to play XTM One's Space Invaders arcade\n * while the agent works. The package ships no game of its own; without a way\n * to reach the arcade the messages stand alone.\n */\nexport const ChatWaitingPanel = ({ t, enabled = true, onPlay, playUrl, keepEndInView }: ChatWaitingPanelProps) => {\n const messages = useMemo(() => defaultMessages(t), [t]);\n const reducedMotion = usePrefersReducedMotion();\n const [msgIndex, setMsgIndex] = useState(0);\n\n // The panel mounts below the last message but, unlike streamed reasoning or\n // answer text (which auto-scrolls on length change), nothing else triggers a\n // scroll - so at the bottom it lands under the fold. It is revealed through\n // the thread's follower, which only moves a reader still following the end:\n // one who scrolled up stays where they went, however near the end.\n useEffect(() => {\n if (enabled) keepEndInView();\n }, [enabled, keepEndInView]);\n\n // A disabled host arms no timer; `enabled` is a dep so toggling it cleans up.\n useEffect(() => {\n if (!enabled) return;\n const id = window.setInterval(() => setMsgIndex((i) => (i + 1) % messages.length), ROTATE_MS);\n return () => window.clearInterval(id);\n }, [enabled, messages.length]);\n\n if (!enabled) return null;\n\n const current = messages[msgIndex % messages.length];\n\n return (\n <div className=\"ml-11 mt-2.5 max-w-[78%]\">\n {/* Keep the live region scoped to the announced text only: wrapping the\n play link too would re-announce it alongside each message change. */}\n <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {current}\n </span>\n {/* Every non-essential animation (fade-ins, the blinking caret) stops\n under prefers-reduced-motion; only the dimmed text rotates. */}\n <div\n className=\"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5\"\n style={reducedMotion ? undefined : { animation: 'chat-fade-in 0.5s ease-out' }}\n >\n <span\n key={current}\n aria-hidden\n className=\"text-xs text-gray-500 dark:text-white/45\"\n style={reducedMotion ? undefined : { animation: 'chat-fade-in 0.4s ease-out' }}\n >\n {current}\n <span className={`ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 ${reducedMotion ? '' : 'animate-pulse'}`} />\n </span>\n {onPlay ? (\n <button type=\"button\" onClick={onPlay} className={PLAY_CLASS}>\n <span aria-hidden className=\"inline-flex\">\n <GamepadIcon size={13} />\n </span>\n {t('Play Space Invaders')}\n </button>\n ) : playUrl ? (\n <a href={playUrl} target=\"_blank\" rel=\"noopener noreferrer\" className={PLAY_CLASS}>\n <span aria-hidden className=\"inline-flex\">\n <GamepadIcon size={13} />\n </span>\n {t('Play Space Invaders in XTM One')}\n <span aria-hidden className=\"inline-flex\">\n <ExternalLinkIcon size={11} />\n </span>\n </a>\n ) : null}\n </div>\n </div>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport type { AgentStatusState, IconProps, Translate } from '../types';\nimport {\n AlertTriangleIcon,\n BrainIcon,\n DatabaseIcon,\n ExternalLinkIcon,\n GlobeIcon,\n MailIcon,\n SearchIcon,\n SparklesIcon,\n TerminalIcon,\n UserPlusIcon,\n WrenchIcon,\n} from './icons';\nimport { translate } from '../utils';\nimport { ChatWaitingPanel } from './ChatWaitingPanel';\n\ninterface ChatThinkingProps {\n agentStatus: AgentStatusState | null;\n logoIcon?: React.ReactNode;\n t: Translate;\n /** Host-level override for the waiting panel (messages and the invitation to play). */\n miniGameEnabled?: boolean;\n /** Opens the XTM One arcade in place; wins over `waitingGameUrl`. */\n onPlayWaitingGame?: () => void;\n /** Where the XTM One arcade is played, opened in a new tab. */\n waitingGameUrl?: string | null;\n /** The thread's follower: keeps its end in view while the reader is there. */\n keepEndInView: () => void;\n}\n\ntype IconComponent = (props: IconProps) => React.JSX.Element;\n\ninterface StatusVisual {\n label: string;\n StatusIcon: IconComponent;\n showDots: boolean;\n}\n\n/**\n * Whole-sentence keys, one per plural branch: a lookup-only `t` cannot select a\n * plural form, so the branch is chosen here and the locale translates the\n * finished sentence — including where the count sits in it.\n */\nfunction delegatingLabel(count: number, t: Translate): string {\n return count > 1 ? translate(t, 'Delegating {count} tasks…', { count }) : t('Delegating one task…');\n}\n\nfunction pollingLabel(count: number, t: Translate): string {\n return count > 1 ? translate(t, 'Waiting for {count} background tasks…', { count }) : t('Waiting for one background task…');\n}\n\nfunction collectingLabel(count: number, t: Translate): string {\n return count > 1 ? translate(t, 'Collecting results from {count} tasks…', { count }) : t('Collecting results from one task…');\n}\n\nfunction resolveStatusVisual(agentStatus: AgentStatusState | null, t: Translate): StatusVisual {\n if (!agentStatus) {\n return { label: t('Thinking...'), StatusIcon: BrainIcon, showDots: false };\n }\n switch (agentStatus.status) {\n case 'tool_start': {\n const rawNames = agentStatus.tools ?? [];\n const lower = rawNames.map((n) => n.toLowerCase());\n\n // Delegation tools have dedicated statuses\n if (lower.some((n) => n === 'spawn_background_task')) {\n const count = rawNames.filter((n) => n === 'spawn_background_task').length;\n return { label: delegatingLabel(count, t), StatusIcon: UserPlusIcon, showDots: false };\n }\n if (lower.some((n) => n === 'check_task_status')) {\n const count = rawNames.filter((n) => n === 'check_task_status').length;\n return { label: pollingLabel(count, t), StatusIcon: SparklesIcon, showDots: false };\n }\n if (lower.some((n) => n === 'get_task_result')) {\n const count = rawNames.filter((n) => n === 'get_task_result').length;\n return { label: collectingLabel(count, t), StatusIcon: SparklesIcon, showDots: false };\n }\n\n let StatusIcon: IconComponent = WrenchIcon;\n if (lower.some((n) => n.includes('search') || n.includes('list'))) {\n StatusIcon = SearchIcon;\n } else if (lower.some((n) => n.includes('read') || n.includes('get') || n.includes('query'))) {\n StatusIcon = DatabaseIcon;\n } else if (lower.some((n) => n.includes('send') || n.includes('create') || n.includes('draft') || n.includes('reply') || n.includes('flag'))) {\n StatusIcon = MailIcon;\n } else if (lower.some((n) => n.includes('code') || n.includes('execute'))) {\n StatusIcon = TerminalIcon;\n } else if (lower.some((n) => n.includes('web') || n.includes('browse'))) {\n StatusIcon = GlobeIcon;\n }\n let label: string;\n if (rawNames.length > 0) {\n const display = rawNames.map((n) => n.replace(/_/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase()));\n const unique = Array.from(new Set(display));\n label = unique.length === 1 ? `${unique[0]}…` : translate(t, '{tool} (+{count} more)…', { tool: unique[0], count: unique.length - 1 });\n } else {\n label = t('Using tools…');\n }\n return { label, StatusIcon, showDots: false };\n }\n case 'awaiting_approval':\n // Not progress: the turn has stopped and the stream is held open while a\n // person decides. Shown only when the prompt itself is not rendered (a\n // host wiring `ChatMessages` without a decision handler) — otherwise the\n // prompt replaces this bubble entirely.\n return { label: t('Waiting for your approval…'), StatusIcon: AlertTriangleIcon, showDots: false };\n case 'analyzing':\n return { label: t('Analyzing results…'), StatusIcon: SparklesIcon, showDots: false };\n case 'steering':\n return { label: t('Incorporating your message…'), StatusIcon: SparklesIcon, showDots: true };\n case 'composing':\n return { label: t('Composing answer…'), StatusIcon: BrainIcon, showDots: true };\n case 'consulting': {\n const consultName = agentStatus.tools?.[0] ?? t('the agent');\n return { label: translate(t, 'Consulting {agent}…', { agent: consultName }), StatusIcon: UserPlusIcon, showDots: false };\n }\n case 'delegating': {\n const count = agentStatus.tools?.filter((n) => n === 'spawn_background_task').length ?? 0;\n return { label: delegatingLabel(count, t), StatusIcon: UserPlusIcon, showDots: false };\n }\n case 'polling': {\n const checkCount = agentStatus.tools?.filter((n) => n === 'check_task_status').length ?? 0;\n return { label: pollingLabel(checkCount, t), StatusIcon: SparklesIcon, showDots: false };\n }\n case 'collecting': {\n const fetchCount = agentStatus.tools?.filter((n) => n === 'get_task_result').length ?? 0;\n return { label: collectingLabel(fetchCount, t), StatusIcon: SparklesIcon, showDots: false };\n }\n case 'transferring': {\n const targetName = agentStatus.tools?.[0] ?? t('the agent');\n return { label: translate(t, 'Transferring to {agent}…', { agent: targetName }), StatusIcon: ExternalLinkIcon, showDots: false };\n }\n case 'thinking':\n default:\n return { label: t('Thinking...'), StatusIcon: BrainIcon, showDots: false };\n }\n}\n\n/**\n * Light markdown cleanup for reasoning prose. Preserves paragraph breaks so\n * multi-step reasoning stays readable inside the small scrolling window\n * instead of collapsing into one unbroken blob.\n */\nexport function cleanReasoningText(text: string): string {\n return text\n .replace(/```[\\s\\S]*?```/g, ' ')\n .replace(/`([^`]+)`/g, '$1')\n .replace(/\\*\\*(.+?)\\*\\*/g, '$1')\n .replace(/__(.+?)__/g, '$1')\n .replace(/#{1,6}\\s+/g, '')\n .replace(/^[ \\t]*[-*>]+[ \\t]*/gm, '')\n .replace(/[ \\t]+/g, ' ')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/**\n * Most characters of the turn's reasoning the window renders. The window is\n * pinned to its newest line and shows about eight lines, while a long turn\n * accumulates hundreds of KB: laying all of it out again on every streamed\n * chunk only re-flows text nobody can see.\n */\nconst REASONING_WINDOW_MAX_CHARS = 6000;\n\n/** Fewer visible characters than this is no reasoning to show. */\nconst MIN_REASONING_CHARS = 3;\n\n/**\n * The text the reasoning window shows: the cleaned tail of the prose between\n * the turn's fenced blocks, opened at a paragraph break when one is near.\n * Fences pair up from the start of the whole text, as `cleanReasoningText`\n * pairs them: paired inside a cut tail instead, a block the cut split or a\n * block still streaming shifts every pair and strips the newest prose.\n */\nfunction reasoningWindowText(content: string): string {\n if (content.length <= REASONING_WINDOW_MAX_CHARS) return cleanReasoningText(content);\n // [start, end) of the prose around each fenced block; an unclosed fence\n // stays prose, as `cleanReasoningText` leaves it.\n const prose: [number, number][] = [];\n let from = 0;\n for (let open = content.indexOf('```'); open !== -1; open = content.indexOf('```', from)) {\n const close = content.indexOf('```', open + 3);\n if (close === -1) break;\n prose.push([from, open]);\n from = close + 3;\n }\n prose.push([from, content.length]);\n const parts: string[] = [];\n let budget = REASONING_WINDOW_MAX_CHARS;\n for (let i = prose.length - 1; i >= 0 && budget > 0; i--) {\n const [start, end] = prose[i];\n const cut = Math.max(start, end - budget);\n parts.push(content.slice(cut, end));\n // + 1: each dropped block leaves a space, as in `cleanReasoningText`.\n budget -= end - cut + 1;\n }\n let tail = parts.reverse().join(' ');\n if (budget <= 0) {\n const paragraph = tail.indexOf('\\n\\n');\n if (paragraph !== -1 && paragraph < tail.length / 2) tail = tail.slice(paragraph + 2);\n }\n return cleanReasoningText(tail);\n}\n\n/**\n * Reasoning window — the model's reasoning prose rendered below the status\n * bubble while the agent works: smaller, dimmed text inside a capped-height\n * (max-h-40) window always pinned to the newest line, with a Cursor-style\n * top dissolve once full (soft gradient fade at the top only — the text reads\n * as scrolling up and dissolving; the bottom stays sharp) — framed by the\n * breathing accent left-border glow. The window is intentionally NOT\n * user-scrollable (overflow-hidden, no scrollbar): the prose is ambient\n * feedback that scrolls up and dissolves; the full accumulated reasoning\n * stays readable afterwards via the message's reasoning details. The window\n * (and the status bubble above it) disappears the moment the final answer\n * starts flowing. `text` comes cleaned and tail-bounded from\n * `reasoningWindowText`; the glow lives on `.filigran-chat-reasoning` so\n * reduced motion can stop it.\n */\nfunction ThinkingTextBubble({ text }: { text: string }) {\n const ref = useRef<HTMLDivElement>(null);\n const [isOverflowing, setIsOverflowing] = useState(false);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return;\n el.scrollTop = el.scrollHeight;\n setIsOverflowing(el.scrollHeight > el.clientHeight + 1);\n }, [text]);\n\n return (\n <div className=\"filigran-chat-reasoning ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3\">\n <div\n ref={ref}\n className={`max-h-40 overflow-hidden${\n isOverflowing\n ? // -webkit- twin first: Safari/WebKit ignores unprefixed mask-image\n // on older versions, which would silently drop the top dissolve.\n ' [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]' +\n ' [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]'\n : ''\n }`}\n >\n <p className=\"m-0 whitespace-pre-wrap break-words text-xs leading-5 text-gray-500 dark:text-white/45\">{text}</p>\n </div>\n </div>\n );\n}\n\n/** Render seconds as a compact elapsed label (e.g. `45s`, `3m 20s`). */\nfunction formatElapsed(seconds: number): string {\n // Floor at the boundary: `elapsed_s` comes from the backend and may be a\n // float, which would otherwise render as \"45.3s\" / \"3m 20.5s\".\n const total = Math.floor(seconds);\n if (total < 60) return `${total}s`;\n const m = Math.floor(total / 60);\n const s = total % 60;\n return s > 0 ? `${m}m ${s}s` : `${m}m`;\n}\n\n/**\n * Elapsed time is only surfaced once the current operation has been\n * running long enough that the user could wonder whether it is stuck.\n */\nconst ELAPSED_DISPLAY_THRESHOLD_S = 15;\n\n/**\n * How long a working turn with no reasoning to show waits before the waiting\n * panel fills the space, so a quick reply never flashes it.\n */\nconst WAITING_GAME_DELAY_MS = 5000;\n\n/**\n * How long reasoning already on screen must go without a new chunk before the\n * waiting panel takes its place: long enough to outlast an ordinary tool call,\n * so the window only gives way on a genuinely long wait.\n */\nconst QUIET_REASONING_GAME_DELAY_MS = 10_000;\n\n/**\n * True once `active` has held for `delayMs` with the same `key`; false the\n * moment either changes, in that very render (the timer that fired carries\n * the key it saw). Arms no timer while `active` is false, so a host that\n * disables the waiting panel schedules no timeouts or re-renders for it.\n */\nfunction useSustained(active: boolean, delayMs: number, key = 0): boolean {\n const [firedKey, setFiredKey] = useState<number | null>(null);\n useEffect(() => {\n setFiredKey(null);\n if (!active) return;\n const id = window.setTimeout(() => setFiredKey(key), delayMs);\n return () => window.clearTimeout(id);\n }, [active, delayMs, key]);\n return active && firedKey === key;\n}\n\nexport const ChatThinking = ({\n agentStatus,\n logoIcon,\n t,\n miniGameEnabled = true,\n onPlayWaitingGame,\n waitingGameUrl,\n keepEndInView,\n}: ChatThinkingProps) => {\n const { label, StatusIcon, showDots } = resolveStatusVisual(agentStatus, t);\n const thinkingContent = agentStatus?.thinkingContent;\n\n // Tick the elapsed counter every second. The backend only reports a fresh\n // value once every ~10s (`tool_heartbeat`), so rendering that integer\n // directly makes the timer sit still and then jump ~10s at a time. Each\n // heartbeat re-anchors `elapsedStartMs` (the instant elapsed was zero); the\n // displayed seconds are derived from that anchor plus a local 1s ticker, so\n // the number moves smoothly and self-corrects on every beat. The interval\n // only runs while an anchor is present, and this state is local to the\n // indicator so the tick never re-renders the surrounding message list.\n const elapsedStartMs = agentStatus?.elapsedStartMs;\n const [nowMs, setNowMs] = useState(() => Date.now());\n useEffect(() => {\n if (elapsedStartMs == null) return;\n setNowMs(Date.now());\n const id = window.setInterval(() => setNowMs(Date.now()), 1000);\n return () => window.clearInterval(id);\n }, [elapsedStartMs]);\n\n // Fall back to the raw heartbeat value for backends/protocols that report\n // `elapsedS` without an anchor.\n const elapsedS = elapsedStartMs != null ? Math.max(0, (nowMs - elapsedStartMs) / 1000) : agentStatus?.elapsedS;\n const showElapsed = typeof elapsedS === 'number' && elapsedS >= ELAPSED_DISPLAY_THRESHOLD_S;\n // Reasoning wins over the waiting panel: once the turn has reasoning to show,\n // the window stays through tool calls and short silences until the answer\n // streams. The panel fills a wait with no reasoning after 5 s, and takes over\n // from reasoning that has gone 10 s without a new chunk, until the next one.\n const reasoningText = useMemo(() => reasoningWindowText(thinkingContent ?? ''), [thinkingContent]);\n const showReasoning = reasoningText.length >= MIN_REASONING_CHARS;\n const waitedWithoutReasoning = useSustained(miniGameEnabled && !showReasoning, WAITING_GAME_DELAY_MS);\n const reasoningWentQuiet = useSustained(miniGameEnabled && showReasoning, QUIET_REASONING_GAME_DELAY_MS, thinkingContent?.length ?? 0);\n const showWaiting = showReasoning ? reasoningWentQuiet : waitedWithoutReasoning;\n\n return (\n <>\n <div className=\"flex gap-3 items-center justify-start\">\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5\">\n <span className=\"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4\">{logoIcon}</span>\n </div>\n <div className=\"rounded-lg bg-gray-50 dark:bg-white/[0.03] px-4 py-3 relative overflow-hidden\">\n <div className=\"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none\" />\n <div className=\"relative flex items-center gap-2.5\">\n {showDots ? (\n <div className=\"flex gap-[3px] items-center h-3.5 w-3.5 justify-center\">\n {[0, 0.15, 0.3].map((delay, i) => (\n <span\n key={i}\n className=\"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50\"\n style={{ animation: `chat-dot 1s ease-in-out infinite ${delay}s` }}\n />\n ))}\n </div>\n ) : (\n <StatusIcon size={14} className=\"text-[var(--chat-accent)] animate-pulse transition-all duration-300\" />\n )}\n <span className=\"text-sm text-gray-500 dark:text-white/50 transition-all duration-300\">{label}</span>\n {showElapsed && <span className=\"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0\">{formatElapsed(elapsedS)}</span>}\n </div>\n </div>\n </div>\n {showWaiting ? (\n <ChatWaitingPanel t={t} enabled={miniGameEnabled} onPlay={onPlayWaitingGame} playUrl={waitingGameUrl} keepEndInView={keepEndInView} />\n ) : showReasoning ? (\n <ThinkingTextBubble text={reasoningText} />\n ) : null}\n </>\n );\n};\n","import remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport { unified } from 'unified';\n\n/**\n * The top-level blocks of a streamed markdown answer.\n *\n * The live answer is re-rendered every time the stream delivers text, and\n * parsing it whole costs ~14 ms at 8K characters and ~75 ms at 40K, on the\n * host application's main thread: past a few thousand characters its frames\n * go to re-parsing text that is already on screen. Rendered block by block\n * with a memoized renderer per block, only the blocks that can still change\n * are parsed again.\n *\n * The boundaries come from the parser the panel renders with (remark-parse +\n * remark-gfm; remark-breaks only rewrites line breaks inside a block), so\n * rendering the blocks one after the other produces what one parse of the\n * whole text produces. A block is final once a later top-level block starts\n * after a blank line with a complete first line: a blank line closes a\n * paragraph, and a written line after one cannot rejoin a list, a quote or an\n * indented block, whatever is appended to it. A block that starts without a\n * blank line before it stays open with its predecessor (`#` alone is a heading\n * that interrupts the paragraph above; `#x` is that paragraph's next line).\n * Link reference definitions and footnote definitions resolve across the whole\n * document, from a quote or a list item too, so a text holding one renders as\n * one block. They are read off the tree the split parses anyway rather than\n * matched by a line pattern: a pattern misses a label spanning lines, and\n * keeps whole a text that only looks like a definition (a TypeScript index\n * signature in a code block, a regex's `[^a-z]`).\n *\n * XTM One's web chat splits its streaming answer by the same rules; a fix to\n * one belongs in the other.\n */\n\nconst blockParser = unified().use(remarkParse).use(remarkGfm).freeze();\n\ntype BlockNode = ReturnType<typeof blockParser.parse>['children'][number];\n\nexport interface MarkdownBlocks {\n /** The text the blocks cover; `blocks.join('') === source`. */\n source: string;\n /** What to render: the top-level blocks, or the whole text when it holds a definition. */\n blocks: string[];\n /** Offset of each top-level block in `source`, kept when the text renders whole. */\n starts: number[];\n /** Top-level blocks `[0, settled)` are final while text is appended to `source`. */\n settled: number;\n /** The first top-level block holding a link reference or footnote definition, `-1` for none. */\n firstDefinition: number;\n}\n\n/** Whether *node* is or contains a link reference or footnote definition. */\nfunction holdsDefinition(node: BlockNode): boolean {\n switch (node.type) {\n case 'definition':\n case 'footnoteDefinition':\n return true;\n case 'blockquote':\n case 'list':\n case 'listItem':\n return node.children.some(holdsDefinition);\n default:\n return false;\n }\n}\n\nfunction lineStart(text: string, offset: number): number {\n return text.lastIndexOf('\\n', offset - 1) + 1;\n}\n\n/**\n * Whether the blocks before the one at *start* are final: it starts after a\n * blank line, and its first line is complete - while that line is still being\n * written it can turn into a continuation of the block above (`1` is a\n * paragraph, `10.` the next item of the ordered list before it).\n */\nfunction settlesBefore(text: string, start: number): boolean {\n if (start < 2 || text.indexOf('\\n', start) === -1) return false;\n const previousLine = text.slice(lineStart(text, start - 1), start - 1);\n return previousLine.trim() === '';\n}\n\n/**\n * Whether the region ends on an indented line (4 spaces or a tab). micromark\n * keeps an indented code block open across the blank lines after it and parses\n * the next line as if it interrupted it - `2. two` is text there and an ordered\n * list on its own - so the next block is rendered with it.\n */\nfunction endsIndented(text: string, start: number, end: number): boolean {\n const lines = text.slice(start, end).split('\\n');\n for (let index = lines.length - 1; index >= 0; index--) {\n if (lines[index].trim()) return /^(?: {4}|\\t)/.test(lines[index]);\n }\n return false;\n}\n\nfunction single(text: string): MarkdownBlocks {\n return { source: text, blocks: text ? [text] : [], starts: text ? [0] : [], settled: 0, firstDefinition: -1 };\n}\n\n/**\n * Split *text* into top-level markdown blocks.\n *\n * With *previous* - the split of a text that *text* extends - the settled\n * blocks are reused and only the rest is parsed again. Any other *previous* (a\n * retracted answer, a normalizer that rewrote earlier lines) is ignored.\n */\nexport function splitMarkdownBlocks(text: string, previous?: MarkdownBlocks | null): MarkdownBlocks {\n if (!text.trim()) return single(text);\n\n const reuse = previous && previous.settled > 0 && text.startsWith(previous.source) ? previous.settled : 0;\n const from = reuse ? previous!.starts[reuse] : 0;\n const tail = text.slice(from);\n\n const starts = previous && reuse ? previous.starts.slice(0, reuse) : [];\n // A definition in a settled block stays one; none there means the first one,\n // if any, is in the part parsed now.\n let firstDefinition = previous && reuse && previous.firstDefinition < reuse ? previous.firstDefinition : -1;\n starts.push(from);\n for (const node of blockParser.parse(tail).children) {\n const offset = node.position?.start.offset;\n if (offset !== undefined) {\n const start = from + lineStart(tail, offset);\n const last = starts[starts.length - 1];\n if (start > last && !endsIndented(text, last, start)) starts.push(start);\n }\n if (firstDefinition < 0 && holdsDefinition(node)) firstDefinition = starts.length - 1;\n }\n\n let settled = reuse;\n for (let index = starts.length - 1; index > reuse; index--) {\n if (settlesBefore(text, starts[index])) {\n settled = index;\n break;\n }\n }\n\n const blocks = firstDefinition < 0 ? starts.map((start, index) => text.slice(start, starts[index + 1] ?? text.length)) : [text];\n return { source: text, blocks, starts, settled, firstDefinition };\n}\n\n/**\n * {@link splitMarkdownBlocks} with the previous split kept between calls, so a\n * text that grows by a few characters per call is re-parsed from its last open\n * block only. Correctness never depends on the kept split: a text that does not\n * extend it is split from the start.\n */\nexport class MarkdownBlockSplitter {\n private last: MarkdownBlocks | null = null;\n\n split(text: string): string[] {\n if (this.last?.source !== text) this.last = splitMarkdownBlocks(text, this.last);\n return this.last.blocks;\n }\n}\n","import { createContext, memo, useCallback, useContext, useMemo, useState } from 'react';\nimport Markdown, { type Components } from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport remarkBreaks from 'remark-breaks';\nimport { CheckIcon, CopyIcon } from './icons';\nimport { ChatImage } from './ChatImage';\nimport { identity, markdownUrlTransform, prepareMarkdown } from '../utils';\nimport { MarkdownBlockSplitter } from '../utils/markdownBlocks';\n\ninterface MarkdownMessageProps {\n content: string;\n /**\n * True while the message is still streaming: it is then rendered one\n * top-level block at a time, so a new chunk only re-parses the blocks it can\n * still change, and stays so once the stream ends. The markup is the one a\n * single parse of the finished message renders.\n */\n streaming?: boolean;\n onRelativeLinkClick?: (href: string) => void;\n /** Auth headers used to fetch host-relative images (see `ChatImage`). */\n requestHeaders?: Record<string, string>;\n t?: (key: string) => string;\n}\n\nconst isRelativeHref = (href?: string) => {\n if (!href) return false;\n if (href.startsWith('//')) return false;\n const hasAbsoluteScheme = /^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(href);\n return !hasAbsoluteScheme;\n};\n\n/**\n * Resolve an href to its host-app-internal form, or null when it points\n * elsewhere.\n *\n * Internal links must route through the host application's router\n * (`onRelativeLinkClick`) instead of a full page load / new tab. Two shapes\n * qualify:\n *\n * 1. Relative hrefs (`/dashboard/...`) — kept as-is.\n * 2. Absolute http(s) hrefs on the SAME origin as the embedding page\n * (e.g. `https://octi.example.com/dashboard/id/<uuid>`) — reduced to\n * `pathname + search + hash`. Backends intentionally emit absolute links\n * (so links work from any chat surface); when the chatbot is embedded in\n * that very platform the link must still navigate in-app.\n *\n * Anything else (other origins, non-http schemes, malformed URLs) returns\n * null and falls back to a regular new-tab anchor.\n */\nconst toInternalHref = (href?: string): string | null => {\n if (!href) return null;\n if (isRelativeHref(href)) return href;\n if (typeof window === 'undefined') return null;\n try {\n const url = new URL(href, window.location.href);\n if ((url.protocol === 'http:' || url.protocol === 'https:') && url.origin === window.location.origin) {\n return `${url.pathname}${url.search}${url.hash}` || '/';\n }\n } catch {\n /* malformed URL — treat as external */\n }\n return null;\n};\n\n/**\n * What the element renderers need from the message they render.\n *\n * react-markdown uses each renderer as an element TYPE, so a renderer must keep\n * its identity across renders: a new function is a new type, and React remounts\n * everything rendered with it. The renderers are therefore module-level and\n * read what varies per message from here — with renderers recreated on every\n * render, the streaming answer's DOM was rebuilt on every chunk, a selection in\n * it was lost, and each image in it was fetched again.\n */\ninterface MarkdownRenderContextValue {\n copiedBlock: string | null;\n onCopyCode: (code: string) => void;\n onRelativeLinkClick?: (href: string) => void;\n requestHeaders?: Record<string, string>;\n t: (key: string) => string;\n}\n\nconst MarkdownRenderContext = createContext<MarkdownRenderContextValue>({ copiedBlock: null, onCopyCode: () => undefined, t: identity });\n\nconst MarkdownCode = ({ className, children }: { className?: string; children?: React.ReactNode }) => {\n const { copiedBlock, onCopyCode, t } = useContext(MarkdownRenderContext);\n const match = /language-(\\w+)/.exec(className || '');\n const codeStr = String(children).replace(/\\n$/, '');\n // A fence with no info string (```\\n…\\n```) carries no `language-*`\n // class. Falling back to the multi-line test keeps it a block instead\n // of collapsing it into a single run of inline code.\n if (match || codeStr.includes('\\n')) {\n return (\n <div className=\"my-3 rounded-lg border border-gray-200 dark:border-white/10 overflow-hidden bg-gray-50 dark:bg-white/[0.03]\">\n <div className=\"flex items-center justify-between px-3 py-1.5 border-b border-gray-200 dark:border-white/10 bg-gray-100 dark:bg-white/[0.03]\">\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40 font-mono\">{match?.[1] ?? 'plaintext'}</span>\n <button\n type=\"button\"\n onClick={() => onCopyCode(codeStr)}\n aria-label={copiedBlock === codeStr ? t('Copied') : t('Copy code')}\n className=\"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors\"\n >\n {copiedBlock === codeStr ? (\n <CheckIcon size={14} className=\"text-green-500\" />\n ) : (\n <CopyIcon size={14} className=\"text-gray-400 dark:text-white/40\" />\n )}\n </button>\n </div>\n <pre className=\"m-0 px-3 py-2 overflow-x-auto\">\n <code className=\"font-mono text-xs leading-[1.7] text-gray-800 dark:text-white/90 whitespace-pre\">{codeStr}</code>\n </pre>\n </div>\n );\n }\n return <code className=\"bg-gray-100 dark:bg-white/[0.08] px-1.5 py-0.5 rounded-sm font-mono text-xs text-[var(--chat-accent)]\">{children}</code>;\n};\n\nconst MarkdownLink = ({ href, children }: { href?: string; children?: React.ReactNode }) => {\n const { onRelativeLinkClick } = useContext(MarkdownRenderContext);\n const internalHref = toInternalHref(href);\n const routeInternally = internalHref !== null && !!onRelativeLinkClick;\n const openInNewTab = !routeInternally && !isRelativeHref(href);\n const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {\n if (!routeInternally) return;\n event.preventDefault();\n onRelativeLinkClick!(internalHref!);\n };\n\n return (\n <a\n href={href}\n onClick={handleClick}\n target={openInNewTab ? '_blank' : undefined}\n rel={openInNewTab ? 'noopener noreferrer' : undefined}\n className=\"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125\"\n >\n {children}\n </a>\n );\n};\n\nconst MarkdownImage = ({ src, alt }: { src?: unknown; alt?: string }) => {\n const { requestHeaders, t } = useContext(MarkdownRenderContext);\n if (typeof src !== 'string' || !src) return null;\n // Keyed by its source: the image at a given place can change while the\n // message streams (a reference-style image resolves to each partial URL of\n // its definition as that line arrives), and a new source must not inherit the\n // previous one's fetched blob or its load error.\n return <ChatImage key={src} src={src} alt={alt || ''} requestHeaders={requestHeaders} t={t} />;\n};\n\nconst MARKDOWN_COMPONENTS: Components = {\n p: ({ children }) => <p className=\"mb-3 last:mb-0 leading-7 break-words text-[0.8125rem] text-gray-900 dark:text-white/90\">{children}</p>,\n // A fenced block renders as `<pre><code>`; the `code` override below\n // returns a `<div>` wrapper, which is not valid inside `<pre>`. Passing\n // the children straight through keeps the markup well-formed.\n pre: ({ children }) => <>{children}</>,\n code: MarkdownCode,\n // `list-disc` / `list-decimal` are required, not decorative: the\n // package's scoped preflight resets `list-style` inside the panel, so\n // without them every list renders as unmarked, indented prose.\n ul: ({ children }) => (\n <ul className=\"list-disc pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">\n {children}\n </ul>\n ),\n ol: ({ children }) => (\n <ol className=\"list-decimal pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">\n {children}\n </ol>\n ),\n li: ({ children }) => <li className=\"leading-7 break-words\">{children}</li>,\n strong: ({ children }) => <strong className=\"font-semibold text-gray-900 dark:text-white\">{children}</strong>,\n em: ({ children }) => <em className=\"italic\">{children}</em>,\n hr: () => <hr className=\"my-4 border-gray-200 dark:border-white/10\" />,\n blockquote: ({ children }) => (\n <blockquote className=\"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic text-gray-500 dark:text-white/60\">\n {children}\n </blockquote>\n ),\n a: MarkdownLink,\n img: MarkdownImage,\n h1: ({ children }) => <h1 className=\"mt-4 first:mt-0 mb-2 font-bold text-base text-gray-900 dark:text-white\">{children}</h1>,\n h2: ({ children }) => <h2 className=\"mt-3 first:mt-0 mb-2 font-bold text-[0.9rem] text-gray-900 dark:text-white\">{children}</h2>,\n h3: ({ children }) => <h3 className=\"mt-3 first:mt-0 mb-1.5 font-semibold text-[0.85rem] text-gray-900 dark:text-white\">{children}</h3>,\n table: ({ children }) => (\n <div className=\"my-3 overflow-x-auto rounded-lg border border-gray-200 dark:border-white/10\">\n <table className=\"w-full border-collapse text-xs\">{children}</table>\n </div>\n ),\n tr: ({ children }) => <tr className=\"transition-colors hover:bg-gray-50 dark:hover:bg-white/[0.02]\">{children}</tr>,\n th: ({ children }) => (\n <th className=\"px-3 py-2 text-left font-semibold bg-gray-50 dark:bg-white/[0.04] border-b border-gray-200 dark:border-white/10 text-gray-900 dark:text-white\">\n {children}\n </th>\n ),\n td: ({ children }) => <td className=\"px-3 py-2 border-b border-gray-200 dark:border-white/10 text-gray-700 dark:text-white/80\">{children}</td>,\n};\n\nconst REMARK_PLUGINS = [remarkGfm, remarkBreaks];\n\n/** One parse of `source`, run again only when the text itself changes. */\nconst MarkdownBody = memo(({ source }: { source: string }) => (\n <Markdown remarkPlugins={REMARK_PLUGINS} urlTransform={markdownUrlTransform} components={MARKDOWN_COMPONENTS}>\n {source}\n </Markdown>\n));\n\nMarkdownBody.displayName = 'MarkdownBody';\n\n/**\n * A streamed message, one top-level block per parse: a settled block keeps its\n * rendering, and a new chunk re-parses only the blocks it can still change.\n * The blocks render as siblings, which is the markup one parse of the whole\n * text produces.\n */\nconst StreamedMarkdownBody = ({ source }: { source: string }) => {\n const [splitter] = useState(() => new MarkdownBlockSplitter());\n const blocks = useMemo(() => splitter.split(source), [splitter, source]);\n return (\n <>\n {blocks.map((block, index) => (\n <MarkdownBody key={index} source={block} />\n ))}\n </>\n );\n};\n\n/**\n * Assistant prose renderer.\n *\n * Memoized because the message list re-renders on every streamed frame: without\n * it, each settled message in the thread would re-run the full remark parse on\n * every frame, which is the dominant source of streaming jank in long threads.\n * With it, only the live bubble re-parses — and only the blocks of it that can\n * still change.\n */\nexport const MarkdownMessage = memo(({ content, streaming = false, onRelativeLinkClick, requestHeaders, t = identity }: MarkdownMessageProps) => {\n const [copiedBlock, setCopiedBlock] = useState<string | null>(null);\n\n // Rendered by blocks once it has streamed: switching to one parse when the\n // stream ends would rebuild the whole message to produce the same markup,\n // fetching its images again behind their placeholders and dropping a\n // selection in it. A message first rendered finished (a restored thread, the\n // panel reopened) takes one parse.\n const [byBlocks, setByBlocks] = useState(streaming);\n if (streaming && !byBlocks) setByBlocks(true);\n\n // Preprocess once per `content`: every pass scans the whole message, so\n // memoizing keeps that work off the hot path for large messages.\n const processedContent = useMemo(() => prepareMarkdown(content), [content]);\n\n const onCopyCode = useCallback((code: string) => {\n navigator.clipboard.writeText(code);\n setCopiedBlock(code);\n setTimeout(() => setCopiedBlock(null), 2000);\n }, []);\n\n const renderContext = useMemo(\n () => ({ copiedBlock, onCopyCode, onRelativeLinkClick, requestHeaders, t }),\n [copiedBlock, onCopyCode, onRelativeLinkClick, requestHeaders, t],\n );\n\n return (\n <MarkdownRenderContext.Provider value={renderContext}>\n {byBlocks ? <StreamedMarkdownBody source={processedContent} /> : <MarkdownBody source={processedContent} />}\n </MarkdownRenderContext.Provider>\n );\n});\n\nMarkdownMessage.displayName = 'MarkdownMessage';\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { ChatMessage, ToolCallTraceEntry } from '../types';\nimport {\n AlertTriangleIcon,\n ArrowRightLeftIcon,\n BotIcon,\n BrainIcon,\n CheckCircleIcon,\n ChevronDownIcon,\n CloseIcon,\n WrenchIcon,\n XCircleIcon,\n} from './icons';\nimport { cleanReasoningText } from './ChatThinking';\nimport { findChatbotRoot, translate } from '../utils';\n\n/** Trace values longer than this are shown raw instead of pretty-printed JSON. */\nconst TRACE_PRETTY_LIMIT = 10_000;\n\n/**\n * Pretty-print a tool-call input/output when it is compact JSON; anything\n * else (plain text, oversized payloads, malformed JSON) is shown raw.\n */\nfunction prettyTraceValue(raw: string | undefined): string {\n if (!raw) return '';\n if (raw.length > TRACE_PRETTY_LIMIT) return raw;\n try {\n return JSON.stringify(JSON.parse(raw), null, 2);\n } catch {\n return raw;\n }\n}\n\nfunction toolDisplayName(name: string): string {\n return name.replace(/_/g, ' ');\n}\n\n/** Expandable row for a single tool call in the reasoning-details dialog. */\nconst ToolCallRow = ({ entry, index, t }: { entry: ToolCallTraceEntry; index: number; t: (key: string) => string }) => {\n const [expanded, setExpanded] = useState(false);\n\n const inputDisplay = useMemo(() => prettyTraceValue(entry.input), [entry.input]);\n const outputDisplay = useMemo(() => prettyTraceValue(entry.output), [entry.output]);\n const hasInput = !!inputDisplay && inputDisplay !== '{}';\n\n return (\n <div className=\"border border-gray-200 dark:border-white/[0.06] rounded-md overflow-hidden\">\n <button\n type=\"button\"\n onClick={() => setExpanded((v) => !v)}\n aria-expanded={expanded}\n className=\"w-full flex items-center gap-2.5 px-3 py-2 hover:bg-gray-50 dark:hover:bg-white/[0.03] transition-colors text-left\"\n >\n <span className=\"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]\">\n {index + 1}\n </span>\n {entry.success ? (\n <CheckCircleIcon size={12} className=\"shrink-0 text-emerald-500 dark:text-emerald-400\" />\n ) : (\n <XCircleIcon size={12} className=\"shrink-0 text-red-500 dark:text-red-400\" />\n )}\n <span className=\"flex-1 min-w-0 text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono\">{toolDisplayName(entry.name)}</span>\n <ChevronDownIcon\n size={14}\n className={`shrink-0 text-gray-400 dark:text-white/50 transition-transform duration-200 ${expanded ? 'rotate-180' : ''}`}\n />\n </button>\n\n {expanded && (\n <div className=\"border-t border-gray-200 dark:border-white/[0.06]\">\n {hasInput && (\n <div className=\"px-3 py-2 border-b border-gray-100 dark:border-white/[0.04] bg-gray-50/50 dark:bg-white/[0.01]\">\n <p className=\"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium\">{t('Input')}</p>\n <pre className=\"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable\">\n {inputDisplay}\n </pre>\n </div>\n )}\n <div className=\"px-3 py-2 bg-gray-50/50 dark:bg-white/[0.01]\">\n <p className=\"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium\">{t('Output')}</p>\n <pre className=\"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable\">\n {outputDisplay || t('(no output)')}\n </pre>\n </div>\n </div>\n )}\n </div>\n );\n};\n\ninterface ReasoningDetailsDialogProps {\n msg: ChatMessage;\n onClose: () => void;\n t: (key: string) => string;\n}\n\n/**\n * Modal dialog with the full reasoning details of an assistant message —\n * mirrors the XTM One web chat dialog (truncation warning, model reasoning,\n * expandable per-tool-call trace, transfer chain). Rendered as an overlay\n * covering the chatbot panel so it works in every mode and host without\n * depending on the host app's stacking order.\n */\nexport const ReasoningDetailsDialog = ({ msg, onClose, t }: ReasoningDetailsDialogProps) => {\n const hostRef = useRef<HTMLSpanElement>(null);\n const closeButtonRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n const [root, setRoot] = useState<HTMLElement | null>(null);\n\n useEffect(() => {\n setRoot(findChatbotRoot(hostRef.current));\n }, []);\n\n useEffect(() => {\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n onClose();\n return;\n }\n // Focus trap: aria-modal promises focus stays inside the dialog, so\n // Tab/Shift+Tab cycle within it instead of escaping to the panel.\n if (e.key !== 'Tab') return;\n const dialog = dialogRef.current;\n if (!dialog) return;\n const focusable = dialog.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])');\n if (focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = document.activeElement;\n if (e.shiftKey) {\n if (active === first || !dialog.contains(active)) {\n e.preventDefault();\n last.focus();\n }\n } else if (active === last || !dialog.contains(active)) {\n e.preventDefault();\n first.focus();\n }\n };\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [onClose]);\n\n // Move initial keyboard focus into the modal (aria-modal) once the portal\n // is mounted, and hand it back to the trigger when the dialog closes.\n useEffect(() => {\n if (!root) return;\n const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n closeButtonRef.current?.focus({ preventScroll: true });\n return () => previouslyFocused?.focus({ preventScroll: true });\n }, [root]);\n\n // Prefer the backend's explicit count, then the detailed trace (what the\n // dialog body actually renders), then the flat tool-name list — keeps the\n // header summary consistent with the rows below.\n const totalCalls = msg.toolCallCount ?? msg.toolCallTrace?.length ?? msg.toolNames?.length ?? 0;\n const tools = msg.toolNames ?? [];\n const iterations = msg.iterations ?? 1;\n const transfers = msg.transferChain ?? [];\n const trace = msg.toolCallTrace ?? [];\n const reasoning = (msg.reasoning ?? '').trim();\n\n const summaryParts = [\n iterations > 1 ? translate(t, '{count} iterations', { count: iterations }) : '',\n totalCalls === 1 ? t('1 tool call') : translate(t, '{count} tool calls', { count: totalCalls }),\n transfers.length === 1 ? t('1 transfer') : transfers.length > 1 ? translate(t, '{count} transfers', { count: transfers.length }) : '',\n ].filter(Boolean);\n\n return (\n <span ref={hostRef} className=\"hidden\">\n {root &&\n createPortal(\n <div\n className=\"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4\"\n onClick={onClose}\n role=\"presentation\"\n >\n <div\n ref={dialogRef}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={t('Reasoning details')}\n onClick={(e) => e.stopPropagation()}\n className=\"w-full max-w-md max-h-full flex flex-col rounded-xl border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1e1e2e] shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]\"\n >\n <div className=\"px-4 pt-3.5 pb-2.5 border-b border-gray-200 dark:border-white/10\">\n <div className=\"flex items-center gap-2\">\n <WrenchIcon size={15} className=\"text-[var(--chat-accent)]\" />\n <span className=\"flex-1 text-[0.875rem] font-semibold text-gray-900 dark:text-white\">{t('Reasoning details')}</span>\n <button\n ref={closeButtonRef}\n type=\"button\"\n onClick={onClose}\n aria-label={t('Close')}\n className=\"w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <CloseIcon size={16} />\n </button>\n </div>\n <p className=\"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40\">{summaryParts.join(' · ')}</p>\n </div>\n\n <div className=\"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3\">\n {msg.isTruncated && (\n <div className=\"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90\">\n <AlertTriangleIcon size={14} className=\"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400\" />\n <span>\n <span className=\"font-semibold\">{t('Turn limit reached.')}</span>{' '}\n {t(\n \"The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.\",\n )}\n </span>\n </div>\n )}\n\n {reasoning && (\n <div>\n <div className=\"flex items-center gap-1.5 mb-1.5\">\n <BrainIcon size={13} className=\"text-[var(--chat-accent)]/70\" />\n <span className=\"text-[0.72rem] font-medium text-gray-500 dark:text-white/50\">{t('Model reasoning')}</span>\n </div>\n <div className=\"rounded-md border border-gray-200 dark:border-white/[0.06] bg-gray-50/50 dark:bg-white/[0.01] px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable\">\n <p className=\"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 text-gray-500 dark:text-white/45\">\n {cleanReasoningText(reasoning)}\n </p>\n </div>\n </div>\n )}\n\n {trace.length > 0 ? (\n <div className=\"flex flex-col gap-1.5\">\n {trace.map((entry, i) => (\n <ToolCallRow key={`${entry.name}-${i}`} entry={entry} index={i} t={t} />\n ))}\n </div>\n ) : (\n tools.length > 0 && (\n // Fallback when no detailed trace is available (legacy\n // messages / backends without trace support).\n <div>\n {tools.map((tn, i) => (\n <div\n key={`${tn}-${i}`}\n className=\"flex items-center gap-3 py-2 border-b border-gray-100 dark:border-white/[0.04] last:border-0\"\n >\n <span className=\"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]\">\n {i + 1}\n </span>\n <WrenchIcon size={12} className=\"shrink-0 text-gray-400 dark:text-white/50\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono\">{toolDisplayName(tn)}</span>\n </div>\n ))}\n </div>\n )\n )}\n\n {transfers.length > 0 && (\n <div>\n <div className=\"flex items-center gap-1.5 mb-1.5\">\n <ArrowRightLeftIcon size={13} className=\"text-[var(--chat-accent)]/70\" />\n <span className=\"text-[0.72rem] font-medium text-gray-500 dark:text-white/50\">{t('Transfer chain')}</span>\n </div>\n <div className=\"flex items-center gap-1.5 flex-wrap\">\n {transfers.map((tr, i) => (\n // Composite key: the same agent can appear twice in a\n // chain (A -> B -> A) and older payloads have no id.\n <div key={`${tr.agentId}-${i}`} className=\"flex items-center gap-1.5\">\n {i > 0 && <span className=\"text-gray-300 dark:text-white/30 text-[0.72rem]\">→</span>}\n <span className=\"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]\">\n <BotIcon size={12} />\n {tr.agentName}\n </span>\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n </div>\n </div>,\n root,\n )}\n </span>\n );\n};\n","import { memo, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { AgentStatusState, ChatAttachment, ChatMessage, MessageFeedback, ToolApprovalDecision, ToolApprovalProposal } from '../types';\nimport { feedbackKeyOf, useMessageFeedback, type FeedbackEntry } from '../hooks/useMessageFeedback';\nimport { useSpeechReader } from '../hooks/useSpeechReader';\nimport { answerMarkdownSources, splitFileMarkers, stripFileMarkers } from '../utils';\nimport { FEEDBACK_COMMENT_MAX_LENGTH, feedbackModeOf, shownFeedback, type FeedbackMode } from '../utils/feedback';\nimport { formatMessageTime } from '../utils/messageTime';\nimport {\n createScrollFollower,\n innerBoxScrollsUp,\n keyScrollsUp,\n nextTouchAnchor,\n pressTakesScrollbar,\n singleTouchY,\n swipeScrollsUp,\n wheelScrollsUp,\n} from '../utils/scrollFollow';\nimport { hasSpeakableWords } from '../utils/speech';\nimport {\n AlertTriangleIcon,\n CheckIcon,\n ChevronDownIcon,\n CopyIcon,\n DownloadIcon,\n FileIcon,\n InfoIcon,\n ThumbsDownIcon,\n ThumbsUpIcon,\n VolumeIcon,\n VolumeOffIcon,\n} from './icons';\nimport { ChatApprovalPrompt } from './ChatApprovalPrompt';\nimport { ChatImage } from './ChatImage';\nimport { ChatThinking } from './ChatThinking';\nimport { MarkdownMessage } from './MarkdownMessage';\nimport { ReasoningDetailsDialog } from './ReasoningDetailsDialog';\nimport { Tooltip } from './Tooltip';\n\n/**\n * Windowed thread rendering: only the most recent slice of the thread is\n * mounted, and \"Load earlier messages\" walks the window back a step at a time.\n * A long restored conversation would otherwise mount hundreds of markdown\n * subtrees at once, which stalls the panel on open and on every streamed frame.\n */\nconst INITIAL_RENDER_WINDOW = 150;\nconst RENDER_WINDOW_STEP = 50;\n\n/** How long the copy affordance stays in its confirmed state. */\nconst COPY_FEEDBACK_DELAY = 2000;\n\nconst parentOf = (node: Element) => node.parentElement;\nconst overflowYOf = (node: Element) => getComputedStyle(node).overflowY;\n\n/** Arrows and Page Up move the caret of a field (the feedback comment), not the thread. */\nfunction isTypingTarget(target: EventTarget): boolean {\n return target instanceof HTMLElement && (target.isContentEditable || !!target.closest('input, textarea, select'));\n}\n\nconst CONTROLS = 'a[href], button, summary, label, input, textarea, select, [role=\"button\"], [role=\"link\"]';\n\n/** A link, a button or a field: a middle click opens it, Shift+Space presses it. */\nfunction isControl(target: EventTarget): boolean {\n return target instanceof Element && !!target.closest(CONTROLS);\n}\n\ninterface ChatMessagesProps {\n messages: ChatMessage[];\n isLoading: boolean;\n agentStatus: AgentStatusState | null;\n agentName: string;\n logoIcon: React.ReactNode;\n onRelativeLinkClick?: (href: string) => void;\n /** Download an agent-generated file via the host app's backend proxy. */\n onDownloadFile?: (attachment: ChatAttachment) => void;\n /**\n * Resolve the host-proxied URL of an attachment, used to preview image\n * attachments inline. Attachments stay chips/cards when omitted.\n */\n resolveAttachmentUrl?: (attachment: ChatAttachment) => string | undefined;\n /** Auth headers used when fetching previewed images (see `ChatImage`). */\n requestHeaders?: Record<string, string>;\n /** Host-level override for the waiting panel (messages and the invitation to play). */\n miniGameEnabled?: boolean;\n /** Opens the XTM One arcade in place; wins over `waitingGameUrl`. */\n onPlayWaitingGame?: () => void;\n /** Where the XTM One arcade is played, opened in a new tab. */\n waitingGameUrl?: string | null;\n /** Enables the 👍/👎 affordance on completed assistant messages (see `feedbackUrl`). */\n onMessageFeedback?: (messageId: string, feedback: MessageFeedback | null, message: ChatMessage) => void;\n /**\n * Where the panel stores ratings itself (`feedbackBaseUrl`): shows the thumbs\n * on every answer the backend identified, whether or not `onMessageFeedback`\n * is passed.\n */\n feedbackUrl?: string | null;\n /** The conversation on screen; its ratings are stored against it. */\n conversationId?: string | null;\n /** BCP 47 tag the times are formatted in and answers are read aloud in. */\n locale?: string;\n /**\n * True while a turn answered after a reload is finishing without a stream.\n * Rendered as the ordinary working indicator: from the user's side nothing\n * about it is unusual, and a decision that visibly leads nowhere reads as a\n * broken button.\n */\n isResumingAfterDecision?: boolean;\n /**\n * Tool calls the running turn has paused on, awaiting a decision. Rendered\n * below the transcript, since the pause belongs to the turn rather than to\n * any one bubble.\n */\n pendingApprovals?: ToolApprovalProposal[] | null;\n onSubmitApprovalDecisions?: (decisions: ToolApprovalDecision[]) => void;\n isSubmittingApproval?: boolean;\n approvalError?: string | null;\n t: (key: string) => string;\n}\n\nfunction formatFileSize(bytes?: number): string {\n if (!bytes || bytes <= 0) return '';\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Short uppercase extension label for a file chip (e.g. `report.pdf` → `PDF`). */\nfunction fileExtensionLabel(filename: string): string | undefined {\n const dot = filename.lastIndexOf('.');\n if (dot <= 0 || dot === filename.length - 1) return undefined;\n const ext = filename.slice(dot + 1);\n return ext.length <= 8 ? ext.toUpperCase() : undefined;\n}\n\nconst IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif']);\n\n/**\n * True when an attachment is worth previewing inline rather than showing as a\n * download card. The MIME type is authoritative; the short `type` label and the\n * filename extension are fallbacks for backends that omit it.\n */\nfunction isImageAttachment(att: ChatAttachment): boolean {\n if (att.contentType?.toLowerCase().startsWith('image/')) return true;\n const label = att.type?.toLowerCase();\n if (label && IMAGE_EXTENSIONS.has(label)) return true;\n const dot = att.filename.lastIndexOf('.');\n return dot > 0 && IMAGE_EXTENSIONS.has(att.filename.slice(dot + 1).toLowerCase());\n}\n\n/**\n * The footer's secondary controls show while the message is hovered or holds\n * the focus, and always where nothing hovers (a touch screen). A keyboard user\n * tabbing onto one sees it through `focus-visible` / `focus-within`.\n */\nconst SHOWN_ON_HOVER = 'group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100';\nconst FOOTER_BUTTON = 'p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]';\nconst ACCENT_ON_HOVER = 'hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]';\nconst REVEALED_BUTTON = `opacity-0 ${SHOWN_ON_HOVER} ${ACCENT_ON_HOVER}`;\n/**\n * The reasoning details button stays dimly in view, so a turn that reasoned is\n * noticed, and reads like its neighbours once they show.\n */\nconst DIMMED_BUTTON = `opacity-50 ${SHOWN_ON_HOVER} ${ACCENT_ON_HOVER}`;\n/** A control in its \"on\" state (the given rating, the message being read) stays in view. */\nconst ACTIVE_BUTTON = 'opacity-100 text-[var(--chat-accent)]';\n\n/** When the message was sent; the tooltip spells the date out. */\nconst MessageTime = ({ timestamp, locale }: { timestamp: Date; locale?: string }) => {\n const time = formatMessageTime(timestamp, locale);\n if (!time) return null;\n return (\n <Tooltip title={time.full}>\n <time dateTime={time.iso} className=\"px-1 text-[0.65rem] tabular-nums text-gray-400 dark:text-white/40 select-none\">\n <span aria-hidden=\"true\">{time.label}</span>\n <span className=\"sr-only\">{time.full}</span>\n </time>\n </Tooltip>\n );\n};\n\n/** Copies a message as plain text. Revealed on message hover. */\nconst MessageCopyButton = ({ text, label, t }: { text: string; label: string; t: (key: string) => string }) => {\n const [copied, setCopied] = useState(false);\n\n const handleCopy = async () => {\n try {\n await navigator.clipboard.writeText(text || '');\n setCopied(true);\n setTimeout(() => setCopied(false), COPY_FEEDBACK_DELAY);\n } catch {\n /* Clipboard unavailable (insecure context / denied permission) — the\n button simply doesn't confirm rather than throwing at the user. */\n }\n };\n\n const name = copied ? t('Copied!') : label;\n return (\n <Tooltip title={name}>\n <button\n type=\"button\"\n onClick={handleCopy}\n aria-label={name}\n className={`${FOOTER_BUTTON} ${copied ? 'opacity-100 text-green-500 dark:text-green-400' : REVEALED_BUTTON}`}\n >\n {copied ? <CheckIcon size={14} /> : <CopyIcon size={14} />}\n </button>\n </Tooltip>\n );\n};\n\n/**\n * 👍/👎 on a completed answer. Clicking the active value clears it. A rating\n * given before the conversation was reopened is final: only it is shown.\n */\nconst MessageFeedbackButtons = ({\n value,\n locked,\n pending,\n onChange,\n downRef,\n t,\n}: {\n value: MessageFeedback | null;\n locked: boolean;\n pending: boolean;\n onChange: (next: MessageFeedback | null) => void;\n downRef: React.RefObject<HTMLButtonElement | null>;\n t: (key: string) => string;\n}) => {\n const lockedId = useId();\n const inert = locked || pending;\n\n const button = (target: MessageFeedback, label: string) => {\n const active = value === target;\n if (locked && !active) return null;\n const Icon = target === 'up' ? ThumbsUpIcon : ThumbsDownIcon;\n return (\n <Tooltip title={locked ? t('Feedback already submitted') : label}>\n <button\n ref={target === 'down' ? downRef : undefined}\n type=\"button\"\n onClick={() => {\n if (!inert) onChange(active ? null : target);\n }}\n aria-label={label}\n aria-pressed={active}\n // Not `disabled`: a disabled button takes no focus and no hover, so\n // it could not say why it does not answer.\n aria-disabled={inert || undefined}\n aria-describedby={locked ? lockedId : undefined}\n className={`${FOOTER_BUTTON} ${active ? ACTIVE_BUTTON : REVEALED_BUTTON} ${inert ? 'cursor-default' : ''}`}\n >\n <Icon size={14} filled={active} />\n </button>\n </Tooltip>\n );\n };\n\n return (\n <>\n {button('up', t('Good response'))}\n {button('down', t('Bad response'))}\n {locked && (\n <span id={lockedId} className=\"sr-only\">\n {t('Feedback already submitted')}\n </span>\n )}\n </>\n );\n};\n\n/** The optional word on what went wrong, asked once a thumbs down is stored. */\nconst FeedbackComment = ({\n pending,\n onSave,\n onSkip,\n t,\n}: {\n pending: boolean;\n onSave: (text: string) => void;\n onSkip: () => void;\n t: (key: string) => string;\n}) => {\n const [text, setText] = useState('');\n const id = useId();\n const canSave = !pending && !!text.trim();\n\n return (\n <div className=\"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] p-2\">\n <label htmlFor={id} className=\"text-[0.7rem] text-gray-600 dark:text-white/60\">\n {t('Tell us what went wrong (optional)')}\n </label>\n <textarea\n id={id}\n // Opened by the user's own thumbs down, to be typed into.\n autoFocus\n rows={2}\n maxLength={FEEDBACK_COMMENT_MAX_LENGTH}\n value={text}\n // Read-only rather than disabled while saving, so the focus stays here.\n readOnly={pending}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n if (!pending) onSkip();\n } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {\n e.preventDefault();\n if (canSave) onSave(text);\n }\n }}\n placeholder={t('What could be improved?')}\n className=\"w-full resize-y rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-transparent px-2 py-1 text-[0.75rem] leading-5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]\"\n />\n <div className=\"flex justify-end gap-1.5\">\n <button\n type=\"button\"\n onClick={() => {\n if (!pending) onSkip();\n }}\n aria-disabled={pending || undefined}\n className=\"rounded-md px-2 py-0.5 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]\"\n >\n {t('Skip')}\n </button>\n <button\n type=\"button\"\n onClick={() => {\n if (canSave) onSave(text);\n }}\n aria-disabled={!canSave || undefined}\n className={`rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] ${canSave ? 'hover:opacity-90' : 'opacity-50 cursor-default'}`}\n >\n {t('Save')}\n </button>\n </div>\n </div>\n );\n};\n\n/** Reads the answer aloud; the same button stops it. */\nconst ReadAloudButton = ({ speaking, onToggle, t }: { speaking: boolean; onToggle: () => void; t: (key: string) => string }) => {\n const name = speaking ? t('Stop reading') : t('Read aloud');\n return (\n <Tooltip title={name}>\n <button type=\"button\" onClick={onToggle} aria-label={name} className={`${FOOTER_BUTTON} ${speaking ? ACTIVE_BUTTON : REVEALED_BUTTON}`}>\n {speaking ? <VolumeOffIcon size={14} /> : <VolumeIcon size={14} />}\n </button>\n </Tooltip>\n );\n};\n\ninterface MessageRowProps {\n msg: ChatMessage;\n /** True only for the message currently being streamed. */\n isStreaming: boolean;\n agentName: string;\n logoIcon: React.ReactNode;\n onRelativeLinkClick?: (href: string) => void;\n onDownloadFile?: (attachment: ChatAttachment) => void;\n resolveAttachmentUrl?: (attachment: ChatAttachment) => string | undefined;\n requestHeaders?: Record<string, string>;\n /** How this answer's thumbs work, or null for none (`feedbackModeOf`). */\n feedbackMode: FeedbackMode | null;\n /** What the user did to its rating in this session. */\n feedback: FeedbackEntry | undefined;\n onRate: (msg: ChatMessage, next: MessageFeedback | null, current: FeedbackEntry | undefined) => void;\n onSaveComment: (msg: ChatMessage, text: string, current: FeedbackEntry) => void;\n onSkipComment: (msg: ChatMessage, current: FeedbackEntry) => void;\n locale?: string;\n /** The browser can read aloud. */\n canSpeak: boolean;\n /** This message is being read aloud. */\n isSpeaking: boolean;\n onToggleSpeech: (id: string, documents: readonly string[]) => void;\n t: (key: string) => string;\n}\n\n/**\n * One message in the thread.\n *\n * Memoized: the parent re-renders on every streamed frame, and without this\n * every settled message would re-run its markdown parse and re-mount its\n * attachment cards on each frame.\n */\nconst MessageRow = memo(\n ({\n msg,\n isStreaming,\n agentName,\n logoIcon,\n onRelativeLinkClick,\n onDownloadFile,\n resolveAttachmentUrl,\n requestHeaders,\n feedbackMode,\n feedback,\n onRate,\n onSaveComment,\n onSkipComment,\n locale,\n canSpeak,\n isSpeaking,\n onToggleSpeech,\n t,\n }: MessageRowProps) => {\n const [showReasoning, setShowReasoning] = useState(false);\n const isAssistant = msg.role === 'assistant';\n const isEmpty = !msg.content;\n const downRef = useRef<HTMLButtonElement>(null);\n\n // The comment question takes the focus when it opens; when it closes with\n // the focus still in it (the element is gone, so the page lost it), the\n // focus goes back to the thumb that opened it rather than to the page.\n const commentOpen = !!feedback?.commentOpen;\n const wasCommentOpen = useRef(commentOpen);\n useLayoutEffect(() => {\n const closed = wasCommentOpen.current && !commentOpen;\n wasCommentOpen.current = commentOpen;\n if (closed && (!document.activeElement || document.activeElement === document.body)) downRef.current?.focus();\n }, [commentOpen]);\n\n const renderAttachmentCard = (att: ChatAttachment, key: string) => {\n // An image the host can resolve a URL for is shown, not filed away.\n const previewUrl = resolveAttachmentUrl && isImageAttachment(att) ? resolveAttachmentUrl(att) : undefined;\n if (previewUrl) {\n return <ChatImage key={key} src={previewUrl} alt={att.filename} requestHeaders={requestHeaders} maxHeightClass=\"max-h-[200px]\" t={t} />;\n }\n\n const isWorking = att.fileTag === 'working_file';\n const sizeLabel = formatFileSize(att.size);\n return (\n <button\n key={key}\n type=\"button\"\n onClick={() => onDownloadFile?.(att)}\n title={t('Download')}\n className={`group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] ${\n isWorking\n ? 'border-gray-200 dark:border-white/10 bg-transparent'\n : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5'\n }`}\n >\n <span className={`shrink-0 ${isWorking ? 'text-gray-400 dark:text-white/40' : 'text-[var(--chat-accent)]'}`}>\n <FileIcon size={16} />\n </span>\n <span className=\"flex flex-col min-w-0 flex-1\">\n <span className=\"truncate text-[0.75rem] text-gray-900 dark:text-white\">{att.filename}</span>\n {(att.type || sizeLabel) && (\n <span className=\"text-[0.65rem] text-gray-400 dark:text-white/40 uppercase\">{[att.type, sizeLabel].filter(Boolean).join(' · ')}</span>\n )}\n </span>\n <span className=\"shrink-0 text-gray-400 dark:text-white/30 group-hover:text-[var(--chat-accent)]\">\n <DownloadIcon size={15} />\n </span>\n </button>\n );\n };\n\n // A user-uploaded file shown as a non-clickable chip — used while the upload\n // is still in flight (no server `fileId` yet) or when no download handler is\n // wired by the host.\n const renderFileChip = (name: string, key: string) => (\n <span\n key={key}\n className=\"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-white/60\"\n >\n <FileIcon size={14} />\n {name}\n </span>\n );\n\n // Render assistant content as an ordered interleave of prose segments and\n // download cards, so a reply with markers like\n // `text [[FILE:a]] more text [[FILE:b]]` keeps the cards at their source\n // position. Cards only render when a download handler is wired\n // (`onDownloadFile`); attachments whose marker isn't found in the prose are\n // appended as a fallback. During streaming the attachments aren't hydrated\n // yet, so only prose (markers stripped) renders.\n const buildAssistantBlocks = (): React.ReactNode[] => {\n const parts = splitFileMarkers(msg.content);\n const attByFileId = new Map((msg.attachments ?? []).map((a) => [a.fileId, a] as const));\n const used = new Set<string>();\n const blocks: React.ReactNode[] = [];\n\n parts.forEach((part, i) => {\n if (part.type === 'text') {\n if (part.value.trim()) {\n blocks.push(\n <div key={`t-${i}`} className=\"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7\">\n <MarkdownMessage\n content={part.value}\n streaming={isStreaming}\n onRelativeLinkClick={onRelativeLinkClick}\n requestHeaders={requestHeaders}\n t={t}\n />\n </div>,\n );\n }\n } else if (onDownloadFile) {\n const att = attByFileId.get(part.fileId);\n if (att) {\n used.add(part.fileId);\n blocks.push(renderAttachmentCard(att, `f-${part.fileId}-${i}`));\n }\n }\n });\n\n if (onDownloadFile) {\n (msg.attachments ?? []).forEach((att) => {\n if (!used.has(att.fileId)) {\n blocks.push(renderAttachmentCard(att, `orphan-${att.fileId}`));\n }\n });\n }\n\n // An assistant reply that is *only* a file marker leaves no prose; show a\n // subtle ellipsis (not an empty padded bubble) when nothing else rendered\n // and we're not still streaming.\n if (blocks.length === 0 && !isStreaming) {\n blocks.push(\n <span key=\"empty\" className=\"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic\">\n ...\n </span>,\n );\n }\n\n return blocks;\n };\n\n // Build the file cards shown on a user message. A successfully-uploaded file\n // carries a server `fileId`, so it renders as the same download card as an\n // agent-generated attachment (re-using the host download proxy via\n // `onDownloadFile`) — uploaded files must stay downloadable, not just\n // displayed. Files still uploading (no `fileId` / not `done`) or hosts\n // without a download handler fall back to a static chip. On conversation\n // restore the backend re-surfaces user uploads as `attachments` (there are\n // no live `files`), so those are rendered too.\n const buildUserFileBlocks = (): React.ReactNode[] => {\n const blocks: React.ReactNode[] = [];\n const seen = new Set<string>();\n\n (msg.files ?? []).forEach((f, i) => {\n const downloadable = !!(onDownloadFile && f.fileId && f.uploadStatus === 'done');\n if (downloadable && f.fileId) {\n seen.add(f.fileId);\n blocks.push(\n renderAttachmentCard(\n { fileId: f.fileId, filename: f.name, type: fileExtensionLabel(f.name), size: f.size, contentType: f.type },\n `file-${f.fileId}-${i}`,\n ),\n );\n } else {\n blocks.push(renderFileChip(f.name, `file-${i}`));\n }\n });\n\n (msg.attachments ?? []).forEach((att, i) => {\n if (seen.has(att.fileId)) return;\n seen.add(att.fileId);\n blocks.push(onDownloadFile ? renderAttachmentCard(att, `att-${att.fileId}-${i}`) : renderFileChip(att.filename, `att-${i}`));\n });\n\n return blocks;\n };\n\n const hasReasoningDetails =\n (msg.toolNames && msg.toolNames.length > 0) ||\n !!(msg.reasoning ?? '').trim() ||\n (msg.toolCallTrace && msg.toolCallTrace.length > 0) ||\n (msg.transferChain && msg.transferChain.length > 0) ||\n msg.isTruncated;\n\n // Actions only make sense on a finished answer, so they stay hidden while\n // the message is still streaming.\n const showActions = isAssistant && !isEmpty && !isStreaming;\n const plainText = stripFileMarkers(msg.content);\n const speechDocuments = useMemo(\n () => (showActions && canSpeak ? answerMarkdownSources(msg.content) : null),\n [showActions, canSpeak, msg.content],\n );\n const shown = shownFeedback(feedback, msg.feedback);\n const speechKey = feedbackKeyOf(msg);\n\n return (\n <div className={`group/msg flex flex-col ${isAssistant ? 'items-start' : 'items-end'}`}>\n {isAssistant && (\n <div className=\"flex items-center gap-1.5 mb-1\">\n <div className=\"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5\">\n <span className=\"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3\">{logoIcon}</span>\n </div>\n {/*\n The message's own agent wins over the panel-wide one. That name is\n whoever is selected right now, which is simply wrong for history —\n a thread that changed hands mid-way must keep each answer under\n the agent that wrote it.\n */}\n <span className=\"font-semibold text-xs text-gray-900 dark:text-white\">{msg.agentName ?? agentName}</span>\n </div>\n )}\n\n {!isAssistant && ((msg.files?.length ?? 0) > 0 || (msg.attachments?.length ?? 0) > 0) && (\n <div className=\"flex gap-1.5 flex-wrap mb-1.5 justify-end\">{buildUserFileBlocks()}</div>\n )}\n\n {isAssistant ? (\n <div className=\"flex flex-col gap-1.5 w-full items-start\">\n {buildAssistantBlocks()}\n {!isEmpty && isStreaming && <span className=\"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse\" />}\n </div>\n ) : (\n <div className=\"max-w-[90%] px-3.5 py-2 rounded-[14px_14px_4px_14px] bg-[var(--chat-accent-dark)] text-white text-[0.8125rem] leading-6\">\n {msg.content}\n </div>\n )}\n\n {/* The user's side mirrors the answer's: the time hugs the bubble's edge. */}\n {!isAssistant && (\n <div className=\"mt-0.5 flex items-center justify-end gap-0.5 text-gray-400 dark:text-white/40\">\n {!!msg.content.trim() && <MessageCopyButton text={msg.content} label={t('Copy message')} t={t} />}\n {!msg.timestampUnknown && <MessageTime timestamp={msg.timestamp} locale={locale} />}\n </div>\n )}\n\n {showActions && (\n <div className=\"mt-0.5 flex flex-wrap items-center gap-0.5 text-gray-400 dark:text-white/40\">\n {!msg.timestampUnknown && <MessageTime timestamp={msg.timestamp} locale={locale} />}\n {hasReasoningDetails && (\n <Tooltip title={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}>\n <button\n type=\"button\"\n onClick={() => setShowReasoning((v) => !v)}\n className={`${FOOTER_BUTTON} ${\n msg.isTruncated\n ? // A truncated turn must be visible at a glance (not gated\n // on hover) so the user notices the warning — mirrors the\n // XTM One web chat affordance.\n 'opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300'\n : DIMMED_BUTTON\n }`}\n aria-label={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}\n aria-haspopup=\"dialog\"\n aria-expanded={showReasoning}\n >\n {msg.isTruncated ? <AlertTriangleIcon size={14} /> : <InfoIcon size={14} />}\n </button>\n </Tooltip>\n )}\n <MessageCopyButton text={plainText} label={t('Copy response')} t={t} />\n {feedbackMode && (\n <MessageFeedbackButtons\n value={shown.value}\n locked={shown.locked}\n pending={!!feedback?.pending}\n onChange={(next) => onRate(msg, next, feedback)}\n downRef={downRef}\n t={t}\n />\n )}\n {speechDocuments && hasSpeakableWords(speechDocuments) && (\n <ReadAloudButton speaking={isSpeaking} onToggle={() => onToggleSpeech(speechKey, speechDocuments)} t={t} />\n )}\n </div>\n )}\n {showActions && feedback?.commentOpen && (\n <FeedbackComment\n pending={feedback.pending}\n onSave={(text) => onSaveComment(msg, text, feedback)}\n onSkip={() => onSkipComment(msg, feedback)}\n t={t}\n />\n )}\n {showActions && feedback?.error && (\n <p role=\"alert\" className=\"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400\">\n {feedback.error}\n </p>\n )}\n {showReasoning && <ReasoningDetailsDialog msg={msg} onClose={() => setShowReasoning(false)} t={t} />}\n </div>\n );\n },\n);\n\nMessageRow.displayName = 'MessageRow';\n\nexport const ChatMessages = ({\n messages,\n isLoading,\n agentStatus,\n agentName,\n logoIcon,\n onRelativeLinkClick,\n onDownloadFile,\n resolveAttachmentUrl,\n requestHeaders,\n miniGameEnabled = true,\n onPlayWaitingGame,\n waitingGameUrl,\n onMessageFeedback,\n isResumingAfterDecision,\n pendingApprovals,\n onSubmitApprovalDecisions,\n isSubmittingApproval,\n approvalError,\n feedbackUrl,\n conversationId,\n locale,\n t,\n}: ChatMessagesProps) => {\n const scrollRef = useRef<HTMLDivElement>(null);\n const [renderWindow, setRenderWindow] = useState(INITIAL_RENDER_WINDOW);\n const {\n entries: feedbackEntries,\n rate,\n saveComment,\n skipComment,\n } = useMessageFeedback({\n feedbackUrl,\n conversationId,\n requestHeaders,\n onMessageFeedback,\n t,\n });\n const speech = useSpeechReader(locale);\n\n // Keeps the end of the conversation in view while the reader is at the\n // bottom (see `createScrollFollower`). It holds no React state: its timer\n // firing after unmount finds no container and does nothing.\n const [follower] = useState(() => createScrollFollower(() => scrollRef.current));\n // The highest point of the touch in progress: a swipe is measured from it,\n // so a finger that turns back down counts from where it turned.\n const touchAnchorRef = useRef<number | null>(null);\n\n // A gesture toward the top is the reader leaving the bottom — but only where\n // it moves the thread itself: an overlay portalled out of it (the image\n // lightbox) still bubbles its events here through React and scrolls nothing\n // of ours, and a box inside it that can still go up takes the gesture first.\n const leaveFrom = (container: HTMLDivElement, target: EventTarget) => {\n if (!(target instanceof Element) || !container.contains(target)) return;\n if (innerBoxScrollsUp<Element>(target, container, parentOf, overflowYOf)) return;\n follower.leave();\n };\n const handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {\n if (wheelScrollsUp(event)) leaveFrom(event.currentTarget, event.target);\n };\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.defaultPrevented || !keyScrollsUp(event) || isTypingTarget(event.target)) return;\n if (event.key === ' ' && isControl(event.target)) return;\n leaveFrom(event.currentTarget, event.target);\n };\n const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n const container = event.currentTarget;\n const rect = container.getBoundingClientRect();\n const press = {\n button: event.button,\n onContainer: event.target === container,\n onControl: isControl(event.target),\n x: event.clientX - rect.left - container.clientLeft,\n y: event.clientY - rect.top - container.clientTop,\n clientWidth: container.clientWidth,\n clientHeight: container.clientHeight,\n scrollTop: container.scrollTop,\n scrollHeight: container.scrollHeight,\n };\n if (pressTakesScrollbar(press)) leaveFrom(container, event.target);\n };\n // A second finger ends the swipe: a pinch is no scroll, and the swipe of\n // the finger left on the screen is measured afresh from its next move.\n const handleTouchStart = (event: React.TouchEvent) => {\n touchAnchorRef.current = singleTouchY(event.touches);\n };\n const handleTouchMove = (event: React.TouchEvent<HTMLDivElement>) => {\n const y = singleTouchY(event.touches);\n const anchor = touchAnchorRef.current;\n if (y !== null && anchor !== null && swipeScrollsUp(anchor, y)) leaveFrom(event.currentTarget, event.target);\n touchAnchorRef.current = nextTouchAnchor(anchor, y);\n };\n\n // Switching conversation (restore / new chat) replaces the whole array, so\n // the window must snap back to the tail instead of keeping a widened one.\n const firstMessageId = messages[0]?.id;\n useEffect(() => {\n setRenderWindow(INITIAL_RENDER_WINDOW);\n }, [firstMessageId]);\n\n // A message the user just sent (a steer included) and a conversation just\n // opened are scrolled into view smoothly, and the view follows again.\n // Anything else — mostly the streamed answer, which changes `messages` on\n // every frame — keeps the bottom in view only while the view follows, so a\n // reader who scrolled up stays where they are.\n let userMessageCount = 0;\n for (const m of messages) if (m.role === 'user') userMessageCount += 1;\n const seenRef = useRef<{ firstMessageId?: string; userMessageCount: number } | null>(null);\n useLayoutEffect(() => {\n const seen = seenRef.current;\n seenRef.current = { firstMessageId, userMessageCount };\n if (!seen || seen.firstMessageId !== firstMessageId || userMessageCount > seen.userMessageCount) {\n follower.reveal();\n } else {\n follower.keepUp();\n }\n }, [messages, firstMessageId, userMessageCount, follower]);\n\n // Keep the bottom in view while the reasoning window below the status\n // bubble grows: thinking prose streams in without any `messages` change,\n // so without this the growing window slides under the fold and the user\n // stops seeing the live reasoning.\n const thinkingLen = agentStatus?.thinkingContent?.length ?? 0;\n useLayoutEffect(() => {\n if (thinkingLen) follower.keepUp();\n }, [thinkingLen, follower]);\n\n const hasEarlierMessages = messages.length > renderWindow;\n const visibleMessages = useMemo(\n () => (hasEarlierMessages ? messages.slice(messages.length - renderWindow) : messages),\n [messages, renderWindow, hasEarlierMessages],\n );\n\n // Reading aloud is about the message on screen: it stops when the user\n // sends a new one, opens another conversation, or the message goes away.\n const { speakingId, stop: stopSpeech } = speech;\n const spokenStillShown = speakingId === null || messages.some((m) => feedbackKeyOf(m) === speakingId);\n const speechScope = useRef({ conversationId, userMessageCount });\n useEffect(() => {\n const previous = speechScope.current;\n speechScope.current = { conversationId, userMessageCount };\n if (previous.conversationId !== conversationId || userMessageCount > previous.userMessageCount || !spokenStillShown) stopSpeech();\n }, [conversationId, userMessageCount, spokenStillShown, stopSpeech]);\n\n // The streaming response is the LAST ASSISTANT message — not necessarily\n // the last message overall: a mid-run steering send appends an optimistic\n // user bubble after the assistant message that is still streaming. Gating\n // on `messages.length - 1` would then drop the live cursor / ChatThinking\n // state the moment the user steers.\n let streamingMessageId: string | null = null;\n if (isLoading) {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n streamingMessageId = messages[i].id;\n break;\n }\n }\n }\n\n // Only a prompt something can actually answer counts: without a submit\n // handler the controls would collect verdicts with nowhere to send them.\n const awaitingApproval = !!pendingApprovals?.length && !!onSubmitApprovalDecisions;\n\n // A tab stop of its own, so the keys scroll the thread (and are read as\n // leaving the bottom) without first focusing something inside it.\n return (\n <div\n ref={scrollRef}\n role=\"region\"\n aria-label={t('Conversation transcript')}\n tabIndex={0}\n onScroll={follower.onScroll}\n onWheel={handleWheel}\n onKeyDown={handleKeyDown}\n onPointerDown={handlePointerDown}\n onTouchStart={handleTouchStart}\n onTouchMove={handleTouchMove}\n className=\"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]\"\n >\n {hasEarlierMessages && (\n <div className=\"flex justify-center\">\n <button\n type=\"button\"\n onClick={() => setRenderWindow((w) => w + RENDER_WINDOW_STEP)}\n className=\"flex items-center gap-1.5 rounded-full border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]\"\n >\n <ChevronDownIcon size={13} className=\"rotate-180\" />\n {t('Load earlier messages')}\n </button>\n </div>\n )}\n\n {visibleMessages.map((msg) => {\n const isStreamingMessage = msg.id === streamingMessageId;\n // An assistant message with no content yet is the \"agent is working\"\n // placeholder, replaced by the live status bubble.\n if (msg.role === 'assistant' && !msg.content && isStreamingMessage) {\n // A turn paused for approval is not working, it is waiting on the\n // person reading it — so the progress bubble (and the waiting game\n // it grows into) gives way to the prompt rendered below.\n if (awaitingApproval) return null;\n return (\n <div key={msg.id}>\n <ChatThinking\n agentStatus={agentStatus}\n logoIcon={logoIcon}\n t={t}\n miniGameEnabled={miniGameEnabled}\n onPlayWaitingGame={onPlayWaitingGame}\n waitingGameUrl={waitingGameUrl}\n keepEndInView={follower.keepUp}\n />\n </div>\n );\n }\n\n return (\n <MessageRow\n key={msg.id}\n msg={msg}\n isStreaming={isStreamingMessage}\n agentName={agentName}\n logoIcon={logoIcon}\n onRelativeLinkClick={onRelativeLinkClick}\n onDownloadFile={onDownloadFile}\n resolveAttachmentUrl={resolveAttachmentUrl}\n requestHeaders={requestHeaders}\n feedbackMode={msg.role === 'assistant' ? feedbackModeOf(msg.serverId, feedbackUrl, conversationId, !!onMessageFeedback) : null}\n feedback={feedbackEntries[feedbackKeyOf(msg)]}\n onRate={rate}\n onSaveComment={saveComment}\n onSkipComment={skipComment}\n locale={locale}\n canSpeak={speech.supported}\n isSpeaking={speakingId === feedbackKeyOf(msg)}\n onToggleSpeech={speech.toggle}\n t={t}\n />\n );\n })}\n {/* Not tied to a placeholder message like the streaming indicator: a\n restore replaces the whole transcript on every poll, so there is no\n bubble of ours left to hang it on. */}\n {isResumingAfterDecision && !awaitingApproval && (\n <ChatThinking\n agentStatus={agentStatus}\n logoIcon={logoIcon}\n t={t}\n miniGameEnabled={miniGameEnabled}\n onPlayWaitingGame={onPlayWaitingGame}\n waitingGameUrl={waitingGameUrl}\n keepEndInView={follower.keepUp}\n />\n )}\n {awaitingApproval && (\n <ChatApprovalPrompt\n // A second pause in the same turn is a new question, not a continuation\n // of the answered one: remounting drops the verdicts and the\n // already-submitted guard the previous set left behind.\n key={pendingApprovals!.map((p) => p.toolCallId).join('|')}\n proposals={pendingApprovals!}\n onSubmit={onSubmitApprovalDecisions!}\n isSubmitting={isSubmittingApproval}\n error={approvalError}\n t={t}\n />\n )}\n {/* Holds the list's gap below its last item. */}\n <div />\n </div>\n );\n};\n","import type { Translate } from '../types';\nimport { translate, translateAround } from '../utils';\n\n/**\n * The greeting, as one sentence the locale owns end to end. The agent's name is\n * markup (it carries the accent colour), so it cannot be spliced into a string —\n * hence the split around its slot rather than three separate fragments.\n */\nconst Greeting = ({ firstName, agentName, t }: { firstName: string; agentName?: string; t: Translate }) => {\n if (!agentName) return <>{translate(t, 'How can I help you, {name}?', { name: firstName })}</>;\n const { before, after, hasSlot } = translateAround(t, 'How can {agent} help you, {name}?', 'agent', { name: firstName });\n return (\n <>\n {before}\n {hasSlot && <span className=\"text-[var(--chat-accent)]\">{agentName}</span>}\n {after}\n </>\n );\n};\n\ninterface ChatWelcomeProps {\n firstName: string;\n logoIcon: React.ReactNode;\n /** Already translated by the caller — see `ChatPanel`. */\n promptSuggestions: string[];\n onPromptClick: (prompt: string) => void;\n /** Selected agent, so the screen says who is about to answer. */\n agentName?: string;\n agentDescription?: string | null;\n /** True while agent-specific suggestions are being fetched. */\n suggestionsLoading?: boolean;\n t: Translate;\n}\n\nexport const ChatWelcome = ({\n firstName,\n logoIcon,\n promptSuggestions,\n onPromptClick,\n agentName,\n agentDescription,\n suggestionsLoading = false,\n t,\n}: ChatWelcomeProps) => (\n <div className=\"flex-1 flex flex-col items-center justify-center px-6 pb-8\">\n <span className=\"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]\">{logoIcon}</span>\n\n {/*\n Naming the agent here is the only confirmation that switching in the\n header actually took effect: the thread resets to this screen, so without\n it nothing tells you which agent the next message will reach.\n `key` on the heading restarts the fade whenever the agent changes, so the\n switch is visible rather than a silent text swap.\n */}\n <h2\n key={agentName ?? 'default'}\n className=\"text-xl font-medium mb-1 text-center text-gray-900 dark:text-white\"\n style={{ fontFamily: '\"Geologica\", sans-serif', animation: 'chat-fade-in 0.35s ease-out' }}\n >\n <Greeting firstName={firstName} agentName={agentName} t={t} />\n </h2>\n\n {agentDescription && (\n <p className=\"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 text-gray-500 dark:text-white/40\">{agentDescription}</p>\n )}\n {!agentDescription && <span className=\"mb-5\" />}\n\n {/* A host that passes no suggestions gets no section: the heading on its own\n used to sit above an empty gap. */}\n {(suggestionsLoading || promptSuggestions.length > 0) && (\n <div className=\"w-full max-w-[320px]\">\n <span className=\"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold\">\n {t('Suggestions')}\n </span>\n {suggestionsLoading ? (\n // Placeholder rows rather than an empty gap: the list is about to be\n // replaced by the new agent's own suggestions.\n <div aria-hidden className=\"space-y-1\">\n {[0, 1, 2].map((i) => (\n <div key={i} className=\"h-8 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-100/50 dark:bg-white/[0.03] animate-pulse\" />\n ))}\n </div>\n ) : (\n promptSuggestions.map((prompt) => (\n <button\n key={prompt}\n type=\"button\"\n onClick={() => onPromptClick(prompt)}\n className=\"w-full text-left text-[0.8125rem] text-gray-800 dark:text-white py-1.5 px-3 mb-1 rounded-lg border border-gray-200 dark:border-white/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]\"\n >\n {prompt}\n </button>\n ))\n )}\n </div>\n )}\n </div>\n);\n","import { useMemo, useRef, useState } from 'react';\nimport type { ChatConversationSummary } from '../types';\nimport { timeAgo } from '../utils';\nimport { BotIcon, EditIcon, SearchIcon, SidebarIcon, TrashIcon } from './icons';\nimport { Spinner } from './Spinner';\nimport { Tooltip } from './Tooltip';\n\ninterface ConversationSidebarProps {\n conversations: ChatConversationSummary[];\n loading: boolean;\n activeConversationId: string | null;\n collapsed: boolean;\n onToggleCollapsed: () => void;\n onSelect: (id: string) => void;\n onDelete: (id: string) => void;\n /** Omit to hide the rename affordance (backend without the route). */\n onRename?: (id: string, title: string) => void;\n onNewChat: () => void;\n t: (key: string) => string;\n}\n\n/** Below this many conversations the list is quicker to scan than to filter. */\nconst SEARCH_THRESHOLD = 7;\n\n/**\n * Persistent conversation list for fullscreen mode, mirroring the XTM One web\n * chat's sidebar.\n *\n * Fullscreen is the only mode with room for it: in floating and sidebar modes\n * the header's history menu remains the way in, since a permanent column there\n * would eat most of the panel.\n */\nexport const ConversationSidebar = ({\n conversations,\n loading,\n activeConversationId,\n collapsed,\n onToggleCollapsed,\n onSelect,\n onDelete,\n onRename,\n onNewChat,\n t,\n}: ConversationSidebarProps) => {\n const [query, setQuery] = useState('');\n const [editingId, setEditingId] = useState<string | null>(null);\n const [draftTitle, setDraftTitle] = useState('');\n // Guards the input's onBlur: committing and then blurring would fire the\n // commit twice, and cancelling via Escape blurs too.\n const settledRef = useRef(false);\n\n const startRename = (id: string, current: string) => {\n settledRef.current = false;\n setEditingId(id);\n setDraftTitle(current);\n };\n\n const commitRename = () => {\n if (settledRef.current) return;\n settledRef.current = true;\n const id = editingId;\n const next = draftTitle.trim();\n setEditingId(null);\n // Unchanged or emptied: leave the conversation alone rather than issuing a\n // request that would either no-op or wipe the title.\n if (id && next) onRename?.(id, next);\n };\n\n const cancelRename = () => {\n settledRef.current = true;\n setEditingId(null);\n };\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase();\n if (!q) return conversations;\n return conversations.filter((c) => (c.title || '').toLowerCase().includes(q));\n }, [conversations, query]);\n\n if (collapsed) {\n return (\n <div className=\"flex flex-col items-center gap-1 border-r border-gray-200 dark:border-white/10 px-2 py-3 shrink-0\">\n <Tooltip title={t('Show conversations')}>\n <button\n type=\"button\"\n onClick={onToggleCollapsed}\n aria-label={t('Show conversations')}\n aria-expanded={false}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <SidebarIcon size={17} />\n </button>\n </Tooltip>\n <Tooltip title={t('New conversation')}>\n <button\n type=\"button\"\n onClick={onNewChat}\n aria-label={t('New conversation')}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <EditIcon size={17} />\n </button>\n </Tooltip>\n </div>\n );\n }\n\n return (\n <div className=\"w-64 shrink-0 flex flex-col border-r border-gray-200 dark:border-white/10\">\n <div className=\"flex items-center gap-1 px-3 py-3\">\n <button\n type=\"button\"\n onClick={onNewChat}\n className=\"flex-1 flex items-center gap-2 rounded-lg border border-gray-200 dark:border-white/10 px-3 py-1.5 text-[0.8125rem] text-gray-700 dark:text-white/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors\"\n >\n <EditIcon size={15} />\n {t('New conversation')}\n </button>\n <Tooltip title={t('Hide conversations')}>\n <button\n type=\"button\"\n onClick={onToggleCollapsed}\n aria-label={t('Hide conversations')}\n aria-expanded\n className=\"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <SidebarIcon size={17} />\n </button>\n </Tooltip>\n </div>\n\n {conversations.length > SEARCH_THRESHOLD && (\n <div className=\"px-3 pb-2\">\n <div className=\"relative\">\n <SearchIcon size={12} className=\"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40\" />\n <input\n type=\"text\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') setQuery('');\n }}\n placeholder={t('Search conversations...')}\n aria-label={t('Search conversations...')}\n className=\"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]\"\n />\n </div>\n </div>\n )}\n\n <div className=\"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable\">\n {loading && conversations.length === 0 && (\n <div className=\"px-3 py-2\">\n <Spinner size={16} />\n </div>\n )}\n {!loading && conversations.length === 0 && (\n <p className=\"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversations yet')}</p>\n )}\n {conversations.length > 0 && filtered.length === 0 && (\n <p className=\"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversation matches')}</p>\n )}\n\n {filtered.map((c) => {\n const isActive = c.conversationId === activeConversationId;\n const isEditing = c.conversationId === editingId;\n return (\n <div\n key={c.conversationId}\n role=\"button\"\n tabIndex={0}\n aria-current={isActive}\n onClick={() => onSelect(c.conversationId)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n onSelect(c.conversationId);\n }\n }}\n className={`group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors ${\n isActive ? 'bg-[var(--chat-accent)]/10' : 'hover:bg-gray-100 dark:hover:bg-white/[0.06]'\n }`}\n >\n <span\n className={`mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg ${\n isActive ? 'bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]' : 'bg-gray-100 dark:bg-white/[0.06] text-gray-400 dark:text-white/30'\n }`}\n >\n <BotIcon size={13} />\n </span>\n <span className=\"min-w-0 flex-1\">\n {isEditing ? (\n <input\n autoFocus\n value={draftTitle}\n onChange={(e) => setDraftTitle(e.target.value)}\n // The row selects on click and on Enter/Space; while editing\n // those belong to the field, not to navigation.\n onClick={(e) => e.stopPropagation()}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === 'Enter') commitRename();\n if (e.key === 'Escape') cancelRename();\n }}\n onBlur={commitRename}\n aria-label={t('Conversation title')}\n className=\"w-full rounded-md bg-white dark:bg-white/10 px-1.5 py-0.5 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]\"\n />\n ) : (\n <span className={`block truncate text-[0.8125rem] ${isActive ? 'text-gray-900 dark:text-white' : 'text-gray-700 dark:text-white/70'}`}>\n {c.title || t('Untitled conversation')}\n </span>\n )}\n {/*\n Agent before time, on one line: which agent a thread is with\n is what tells two similarly-titled conversations apart, and\n knowing it before opening one is the point. Omitted entirely\n when the backend does not report it, rather than padded with\n a placeholder.\n */}\n {(c.agentName || c.updatedAt) && !isEditing && (\n <span className=\"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate\">\n {c.agentName}\n {c.agentName && c.updatedAt ? ' · ' : ''}\n {c.updatedAt ? timeAgo(c.updatedAt, t) : ''}\n </span>\n )}\n </span>\n {!isEditing && (\n <span className=\"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity\">\n {onRename && (\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n startRename(c.conversationId, c.title || '');\n }}\n aria-label={t('Rename conversation')}\n title={t('Rename conversation')}\n className=\"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]\"\n >\n <EditIcon size={13} />\n </button>\n )}\n <button\n type=\"button\"\n onClick={(e) => {\n // The row is the click target for selection, so deleting\n // must not also open the conversation on its way out.\n e.stopPropagation();\n onDelete(c.conversationId);\n }}\n aria-label={t('Delete conversation')}\n title={t('Delete conversation')}\n className=\"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-red-500 dark:hover:text-red-400\"\n >\n <TrashIcon size={13} />\n </button>\n </span>\n )}\n </div>\n );\n })}\n </div>\n </div>\n );\n};\n","import { type FunctionComponent, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ChatAttachment, ChatPanelProps, Translate } from '../types';\nimport { hexAlpha, identity } from '../utils';\nimport { feedbackBaseUrl } from '../utils/feedback';\nimport { parseContextUsage, parseRestoredMessages } from '../hooks/protocols/parseRestEvent';\nimport { useChat } from '../hooks/useChat';\nimport { useAgents } from '../hooks/useAgents';\nimport { useConversations } from '../hooks/useConversations';\nimport { useSidebarResize } from '../hooks/useSidebarResize';\nimport { useAwayCompletionNotice } from '../hooks/useAwayCompletionNotice';\nimport { useComposerExtras } from '../hooks/useComposerExtras';\nimport { useAgentSuggestions } from '../hooks/useAgentSuggestions';\nimport { useLatestCallback, useShallowStable } from '../hooks/useStableProps';\nimport { DefaultLogoIcon } from './icons';\nimport { ChatHeader } from './ChatHeader';\nimport { ChatInput } from './ChatInput';\nimport { ChatMessages } from './ChatMessages';\nimport { waitingGameUrl } from './ChatWaitingPanel';\nimport { ChatWelcome } from './ChatWelcome';\nimport { ConversationSidebar } from './ConversationSidebar';\n\nconst FLOATING_WIDTH = 380;\nconst FLOATING_HEIGHT = 560;\nconst SIDEBAR_GAP = 6;\n\n/**\n * Fallback suggestions, translated where they are written so extraction sees\n * the keys — the host's own list and the backend's are translated too (they may\n * be keys), but only these belong to the package.\n */\nconst defaultSuggestions = (t: Translate) => [\n t('Help me create a new simulation scenario'),\n t('What are the latest attack patterns?'),\n t('How do I configure detection rules?'),\n t('Summarize my recent findings'),\n];\n\nexport const ChatPanel: FunctionComponent<ChatPanelProps> = ({\n mode,\n onClose,\n onModeChange,\n topOffset = 0,\n apiBaseUrl,\n apiEndpoints: apiEndpointsProp,\n agentDashboardUrl,\n user,\n t = identity,\n accentColor = '#7b5cff',\n logoIcon,\n promptSuggestions: promptSuggestionsProp,\n draftBorderColor,\n resizable = false,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n disableFileManagement = false,\n onRelativeLinkClick: onRelativeLinkClickProp,\n onDownloadError: onDownloadErrorProp,\n maxFileCount,\n maxTotalSize,\n requestHeaders: requestHeadersProp,\n pageContext: pageContextProp,\n pushContentSelector,\n backendType = 'rest',\n miniGameEnabled = true,\n onPlayWaitingGame: onPlayWaitingGameProp,\n notifyOnComplete = true,\n onTaskComplete: onTaskCompleteProp,\n onMessageFeedback: onMessageFeedbackProp,\n locale,\n disableImagePreviews = false,\n contextUsageEnabled = true,\n composerToolbar,\n}) => {\n // Hosts tend to build these inline, so each host render hands the panel new\n // objects and functions with the same content. Held stable here, a host\n // render no longer re-renders every memoized message row, re-runs the effects\n // keyed on them (agent list, prompts, quota, suggestions, conversation list)\n // or refetches the images fetched with the headers. `t` passes through as is,\n // since a new one means new translations, and so do ReactNode props, which\n // cannot be compared.\n const apiEndpoints = useShallowStable(apiEndpointsProp);\n const requestHeaders = useShallowStable(requestHeadersProp);\n const pageContext = useShallowStable(pageContextProp);\n const promptSuggestions = useShallowStable(promptSuggestionsProp);\n const onRelativeLinkClick = useLatestCallback(onRelativeLinkClickProp);\n const onDownloadError = useLatestCallback(onDownloadErrorProp);\n const onPlayWaitingGame = useLatestCallback(onPlayWaitingGameProp);\n const onTaskComplete = useLatestCallback(onTaskCompleteProp);\n const onMessageFeedback = useLatestCallback(onMessageFeedbackProp);\n\n const [modeMenuOpen, setModeMenuOpen] = useState(false);\n\n const { agents, agentsLoading, agentsError, selectedAgent, agentMenuOpen, setAgentMenuOpen, handleSwitchAgent } = useAgents({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n\n const {\n messages,\n inputValue,\n setInputValue,\n isLoading,\n agentStatus,\n attachedFiles,\n conversationId,\n contextUsage,\n transferredAgent,\n canSteer,\n pendingApprovals,\n isSubmittingApproval,\n approvalError,\n submitApprovalDecisions,\n isResumingAfterDecision,\n historyReloadNonce,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\n setContextUsage,\n updateConversationId,\n handleSwitchConversation,\n } = useChat({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n agentSlug: selectedAgent?.slug,\n requestHeaders,\n pageContext,\n t,\n maxFileCount,\n maxTotalSize,\n });\n\n const { suggestions: agentSuggestions, loading: suggestionsLoading } = useAgentSuggestions({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n agentSlug: selectedAgent?.slug,\n });\n\n /**\n * Suggestions shown on the welcome screen, resolved to final text here rather\n * than in `ChatWelcome`: the backend's and the host's lists still go through\n * `t` (a host may well pass keys), while the package's own fallback is\n * translated at its definition so the keys stay extractable.\n */\n const suggestions = useMemo(\n () => (agentSuggestions ?? promptSuggestions)?.map((s) => t(s)) ?? defaultSuggestions(t),\n [agentSuggestions, promptSuggestions, t],\n );\n\n const { prompts, quota, refreshQuota } = useComposerExtras({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n\n const { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation, renameConversation } = useConversations({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n const [historyMenuOpen, setHistoryMenuOpen] = useState(false);\n\n // Fullscreen shows the conversation list permanently, so it has to be\n // fetched on entry rather than lazily when a menu opens. Kept collapsible:\n // fullscreen is also the mode people use to read a long answer.\n const [sidebarCollapsed, setSidebarCollapsed] = useState(false);\n const showConversationSidebar = mode === 'fullscreen' && historyEnabled;\n\n // Re-read on entry AND whenever the active conversation changes, so a chat\n // created by the first send appears in the list. The header menu could fetch\n // lazily on open; a permanent list has no such moment, and a stale sidebar\n // that never shows the conversation you are in is worse than no sidebar.\n useEffect(() => {\n if (showConversationSidebar) void refreshConversations();\n }, [showConversationSidebar, conversationId, refreshConversations]);\n\n // A finished turn has consumed allowance and may have retitled the chat.\n const wasLoadingRef = useRef(false);\n useEffect(() => {\n if (wasLoadingRef.current && !isLoading) {\n refreshQuota();\n // The backend titles a conversation from its first message, so the row\n // stays \"New conversation\" until the turn is read back.\n if (showConversationSidebar) void refreshConversations();\n }\n wasLoadingRef.current = isLoading;\n }, [isLoading, refreshQuota, showConversationSidebar, refreshConversations]);\n\n const handleHistoryMenuToggle = () => {\n // Computed from the committed state in the event handler — NOT inside the\n // state updater, which must stay pure (StrictMode/concurrent rendering may\n // invoke updaters more than once, which would duplicate the fetch).\n const next = !historyMenuOpen;\n if (next) {\n // Fetch lazily on open so the list reflects the latest server state\n // (titles are rewritten by the backend after the first message).\n void refreshConversations();\n }\n setHistoryMenuOpen(next);\n };\n\n const handleSelectConversation = (id: string) => {\n setHistoryMenuOpen(false);\n handleSwitchConversation(id);\n };\n\n const handleDeleteConversation = async (id: string) => {\n const deleted = await deleteConversation(id);\n // Deleting the active conversation resets to a fresh chat so the next\n // message doesn't target a dead conversation id.\n if (deleted && id === conversationIdRef.current) {\n handleNewChat();\n }\n };\n\n const { sidebarWidth, handleResizeStart, defaultWidth, isResizing } = useSidebarResize({\n mode,\n resizable,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n });\n\n // Push content when sidebar mode is active using CSS variable\n useEffect(() => {\n const width = mode === 'sidebar' ? (resizable ? sidebarWidth : defaultWidth) : 0;\n const pushWidth = width > 0 ? width + SIDEBAR_GAP : 0;\n\n // Set CSS variable on :root for any component to use\n document.documentElement.style.setProperty('--chatbot-sidebar-width', `${pushWidth}px`);\n document.documentElement.style.setProperty('--chatbot-transition', isResizing ? 'none' : 'all 225ms cubic-bezier(0.4, 0, 0.2, 1)');\n\n // Also apply to pushContentSelector if provided (for simple cases)\n if (pushContentSelector) {\n const contentElement = document.querySelector<HTMLElement>(pushContentSelector);\n if (contentElement) {\n const originalPaddingRight = contentElement.style.paddingRight;\n const originalTransition = contentElement.style.transition;\n\n contentElement.style.paddingRight = pushWidth > 0 ? `${pushWidth}px` : '';\n contentElement.style.transition = isResizing ? 'none' : 'padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)';\n\n return () => {\n contentElement.style.paddingRight = originalPaddingRight;\n contentElement.style.transition = originalTransition;\n document.documentElement.style.setProperty('--chatbot-sidebar-width', '0px');\n };\n }\n }\n\n return () => {\n document.documentElement.style.setProperty('--chatbot-sidebar-width', '0px');\n };\n }, [pushContentSelector, mode, sidebarWidth, defaultWidth, resizable, isResizing]);\n\n // Stable across renders so the memoized message rows (which take it as a\n // prop) aren't invalidated on every streamed frame.\n const resolvedLogo = useMemo(() => logoIcon ?? <DefaultLogoIcon size={24} />, [logoIcon]);\n const playUrl = useMemo(() => waitingGameUrl(agentDashboardUrl), [agentDashboardUrl]);\n const firstName = user.firstName;\n /**\n * The agent a *restored* conversation belongs to, as the backend reports it.\n *\n * Sits between the live transfer and the menu selection on purpose. Reopening\n * a past thread used to relabel it — and its new replies — with whichever\n * agent was selected, while the backend went on routing the conversation to\n * its own stored agent. The label named someone who had not spoken. This is\n * the same agent that will answer, so the two now agree.\n */\n const [conversationAgentName, setConversationAgentName] = useState<string | null>(null);\n const agentName = transferredAgent?.name || conversationAgentName || selectedAgent?.name || t('Assistant');\n\n // \"Viewing the chat\" must mean the panel is on screen in the active tab —\n // NOT that an element inside it currently holds focus. In sidebar (and\n // floating) mode the user routinely reads a streamed answer while their focus\n // stays in the host app, so the previous focus-within test\n // (`document.activeElement.closest('.filigran-chatbot.fixed')`) wrongly\n // classified them as \"not viewing\" and fired a redundant completion toast for\n // an answer sitting right in front of them. The host mounts `<ChatPanel/>`\n // only while the widget is open, so a mounted + visible panel root means the\n // answer is visible to the user; the notifier still treats a hidden tab or an\n // unfocused window as \"away\" and notifies there. A host that keeps the panel\n // mounted but `display:none` while \"closed\" is likewise reported as not\n // viewing (checkVisibility() === false), so completion still notifies. The\n // `.fixed` qualifier targets the panel root, never the toggle button (which\n // carries `.filigran-chatbot` alone). Stable reference (useCallback) so the\n // notifier's effect doesn't re-run on every render — the panel re-renders\n // frequently while a response streams; the DOM is queried live on each call.\n const isViewingChat = useCallback(() => {\n if (typeof document === 'undefined') return false;\n const panel = document.querySelector('.filigran-chatbot.fixed') as (HTMLElement & { checkVisibility?: () => boolean }) | null;\n if (!panel) return false;\n if (typeof panel.checkVisibility === 'function') return panel.checkVisibility();\n // Fallback for browsers without Element.checkVisibility(): a display:none\n // panel generates no layout box, so an empty client-rect list means hidden\n // (works for the position:fixed root, whose offsetParent is null even when\n // shown). Erring toward \"not viewing\" keeps the documented closed/hidden\n // path notifying instead of silently swallowing the notice on older engines.\n return panel.getClientRects().length > 0;\n }, []);\n\n // Notify when a long turn finishes and the user is not watching the chat —\n // away (tab hidden / another window / panel closed-or-hidden). An open,\n // on-screen panel in the focused tab counts as watching, so no toast fires\n // for an answer the user can already see.\n useAwayCompletionNotice({\n isLoading,\n agentName,\n t,\n enabled: notifyOnComplete,\n onComplete: onTaskComplete,\n isViewingChat,\n });\n\n // Download an agent-generated file. The URL is resolved against the host\n // app's own backend proxy (apiBaseUrl), NOT the upstream chat service:\n // the proxy mints any upstream token server-side, so the user stays\n // authenticated to the host platform (e.g. OpenCTI / OpenAEV) only and\n // never logs in to the upstream service. Same-origin cookies +\n // requestHeaders (CSRF / draft context) carry the host-app auth.\n // Downloads need a path to build the URL from. Enabled for the REST\n // backend unless explicitly disabled (`download === null`). In\n // single-endpoint mode there is no per-path routing, so a download path\n // must be provided explicitly (e.g. an OpenCTI-style proxy route);\n // otherwise the default REST `/chat/files` path is used.\n const downloadPathProvided = apiEndpoints?.download !== null && apiEndpoints?.download !== undefined;\n const canDownload = backendType === 'rest' && apiEndpoints?.download !== null && (!apiEndpoints?.singleEndpoint || downloadPathProvided);\n\n // The host-proxied URL of an attachment. Shared by the download action and\n // the inline image preview so both resolve against the same proxy route.\n const resolveAttachmentUrl = useCallback(\n (att: ChatAttachment) => {\n const base = apiEndpoints?.download ?? '/chat/files';\n return `${apiBaseUrl}${base}/${encodeURIComponent(att.fileId)}/download`;\n },\n [apiBaseUrl, apiEndpoints],\n );\n\n const handleDownloadFile = useCallback(\n async (att: ChatAttachment) => {\n const url = resolveAttachmentUrl(att);\n try {\n const res = await fetch(url, {\n method: 'GET',\n credentials: 'include',\n headers: { ...(requestHeaders ?? {}) },\n });\n if (!res.ok) throw new Error(`Download failed: ${res.status}`);\n const blob = await res.blob();\n const objectUrl = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = objectUrl;\n link.download = att.filename || 'download';\n document.body.appendChild(link);\n link.click();\n link.remove();\n URL.revokeObjectURL(objectUrl);\n } catch (err) {\n // Surface the failure (403/404/5xx/network) to the host so it can\n // notify the user — the chatbot has no toast surface of its own.\n // If the host doesn't provide a handler the error is intentionally\n // not thrown further (a rejected click handler has nowhere to go).\n onDownloadError?.(err, att);\n }\n },\n [resolveAttachmentUrl, requestHeaders, onDownloadError],\n );\n\n const cssVars = {\n '--chat-accent': accentColor,\n '--chat-accent-10': hexAlpha(accentColor, 0.1),\n '--chat-accent-40': hexAlpha(accentColor, 0.25),\n '--chat-accent-50': hexAlpha(accentColor, 0.5),\n '--chat-accent-dark': accentColor,\n } as React.CSSProperties;\n\n // Tracks whether this panel is still mounted. Flipped to false ONLY on a\n // real unmount (empty-deps cleanup) — never on the benign teardowns that an\n // inline `apiEndpoints` / `requestHeaders` prop churn or a StrictMode\n // double-invoke trigger. The restore effect below reads it so an in-flight\n // `/chat/sessions` response that outlives the panel — the host renders\n // `<ChatPanel />` conditionally and the user closes it mid-request — can't\n // call `setMessages` / `updateConversationId` after unmount, while a restore\n // merely interrupted by a re-render still lands. Re-set to true on setup so\n // StrictMode's mount → unmount → remount of the same instance leaves it true.\n const isMountedRef = useRef(true);\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n // Load conversation history when agent is selected\n useEffect(() => {\n // Skip session history if disabled, using single endpoint mode, or non-REST backend\n if (apiEndpoints?.sessions === null || apiEndpoints?.singleEndpoint || backendType === 'legacy' || backendType === 'ag-ui') return;\n // No conversation means a fresh chat — \"New conversation\", or an agent\n // switch, both of which null the id. Drop the restored thread's agent with\n // it, or the new chat would keep wearing the old one's name.\n if (!conversationId) {\n setConversationAgentName(null);\n return;\n }\n if (historyLoadedRef.current || !selectedAgent) return;\n historyLoadedRef.current = true;\n const sessionsUrl = `${apiBaseUrl}${apiEndpoints?.sessions ?? '/chat/sessions'}`;\n\n // The conversation this restore is being issued for. A host re-render that\n // churns an inline `apiEndpoints` / `requestHeaders` prop, or a React\n // StrictMode double-invoke, tears this effect down and re-runs it while the\n // request is still in flight — but the conversation itself hasn't changed.\n // We must NOT drop the restore in those benign cases (doing so left the\n // panel looking like a brand-new chat, randomly, on reload). Only a real\n // change — the user starting a new chat or switching agent, both of which\n // reset the id via `handleNewChat()` — should abandon the response, so it\n // can't resurrect a dead id or overwrite the freshly-started conversation.\n // Compare the live ref at apply time (not a blanket teardown flag) so the\n // legitimate restore always lands while a superseded one is still ignored —\n // and bail out entirely once the panel has actually unmounted, so a late\n // response can't write to localStorage / state after the panel is gone.\n const requestedConversationId = conversationId;\n const isStale = () => !isMountedRef.current || conversationIdRef.current !== requestedConversationId;\n\n fetch(sessionsUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({\n conversation_id: conversationId,\n agent_slug: selectedAgent.slug,\n }),\n })\n .then((res) => {\n if (isStale()) return null;\n if (!res.ok) {\n // Stale or invalid stored id (e.g. the platform was reset but the\n // browser kept an old id) — silently reset so a fresh conversation\n // is created on the next message instead of surfacing an error and\n // forcing the user to click \"New conversation\".\n updateConversationId(null);\n return null;\n }\n return res.json();\n })\n .then((data) => {\n if (!data || isStale()) return;\n // The backend resolves the session: it returns the same id when the\n // conversation still exists, or transparently creates a fresh one and\n // returns its NEW id when the stored id is stale. Adopt whatever id it\n // returns (and persist it) so we never send subsequent messages\n // against a dead conversation — which would 404 with\n // \"conversation does not exist\".\n if (typeof data.conversation_id === 'string' && data.conversation_id && data.conversation_id !== requestedConversationId) {\n updateConversationId(data.conversation_id);\n }\n // Null is meaningful and different from absent: it says the backend\n // knows this conversation has no agent (one predating per-conversation\n // routing), where a missing key means an older backend that cannot\n // tell us. Both land on the selected-agent fallback, but only the\n // first is a deliberate answer.\n setConversationAgentName(typeof data.agent_name === 'string' ? data.agent_name : null);\n if (!data.messages?.length) return;\n setMessages(parseRestoredMessages(data.messages));\n // The context gauge is conversation state, not per-message: the NEWEST\n // entry that carries a reading is the current occupancy. Scanned from\n // the end so a turn that predates the field (or a user message) falls\n // through to the last one that has it, rather than blanking the gauge.\n for (let i = data.messages.length - 1; i >= 0; i -= 1) {\n const usage = parseContextUsage(data.messages[i] as Record<string, unknown>);\n if (usage) {\n setContextUsage(usage);\n break;\n }\n }\n })\n .catch(() => {\n if (isStale()) return;\n updateConversationId(null);\n });\n }, [\n conversationId,\n selectedAgent,\n apiBaseUrl,\n apiEndpoints,\n backendType,\n // Re-runs the restore when the hook asks for one — the only way a turn\n // resumed without a stream can ever show its answer.\n historyReloadNonce,\n historyLoadedRef,\n conversationIdRef,\n isMountedRef,\n requestHeaders,\n setMessages,\n setContextUsage,\n updateConversationId,\n ]);\n\n const onSwitchAgent = (agent: typeof selectedAgent) => {\n if (!agent) return;\n handleSwitchAgent(agent, () => {\n handleNewChat();\n });\n };\n\n const containerClasses = (() => {\n const base = 'filigran-chatbot';\n switch (mode) {\n case 'sidebar':\n return `${base} fixed right-0 bottom-0 flex flex-col bg-white dark:bg-[#1e1e2e] border-l border-gray-200 dark:border-white/10 z-[1200]`;\n case 'floating':\n return `${base} fixed bottom-5 right-5 flex flex-col bg-white dark:bg-[#1e1e2e] rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border border-gray-200 dark:border-white/10`;\n case 'fullscreen':\n return `${base} fixed right-0 bottom-0 left-0 flex flex-col bg-gray-50 dark:bg-[#161622] z-[1400]`;\n default:\n return base;\n }\n })();\n\n const containerStyle: React.CSSProperties = {\n ...cssVars,\n ...(mode === 'sidebar'\n ? { top: topOffset, width: resizable ? sidebarWidth : defaultWidth }\n : mode === 'floating'\n ? { width: FLOATING_WIDTH, height: FLOATING_HEIGHT }\n : { top: topOffset }),\n };\n\n return (\n <div className={containerClasses} style={containerStyle}>\n {mode === 'sidebar' && resizable && (\n <div onMouseDown={handleResizeStart} className=\"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group\">\n <div className=\"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100\" />\n </div>\n )}\n <ChatHeader\n mode={mode}\n agentName={agentName}\n agents={agents}\n agentsLoading={agentsLoading}\n agentsError={agentsError}\n selectedAgent={selectedAgent}\n transferredFrom={transferredAgent ? selectedAgent?.name : undefined}\n agentMenuOpen={agentMenuOpen}\n onAgentMenuToggle={() => setAgentMenuOpen((p) => !p)}\n onAgentMenuClose={() => setAgentMenuOpen(false)}\n onSwitchAgent={onSwitchAgent}\n modeMenuOpen={modeMenuOpen}\n onModeMenuToggle={() => setModeMenuOpen((p) => !p)}\n onModeMenuClose={() => setModeMenuOpen(false)}\n onModeChange={onModeChange}\n onNewChat={handleNewChat}\n onClose={onClose}\n logoIcon={resolvedLogo}\n agentDashboardUrl={agentDashboardUrl}\n historyEnabled={historyEnabled && !showConversationSidebar}\n historyMenuOpen={historyMenuOpen}\n onHistoryMenuToggle={handleHistoryMenuToggle}\n onHistoryMenuClose={() => setHistoryMenuOpen(false)}\n conversations={conversations}\n conversationsLoading={conversationsLoading}\n activeConversationId={conversationId}\n onSelectConversation={handleSelectConversation}\n onDeleteConversation={(id) => void handleDeleteConversation(id)}\n t={t}\n />\n {/* Fullscreen puts the conversation list beside the thread. The header\n stays full width above both: it carries the agent picker, the mode\n switcher and close, which belong to the panel rather than to either\n column. `min-h-0` lets the thread scroll instead of growing the row. */}\n <div className={showConversationSidebar ? 'flex flex-1 min-h-0' : 'contents'}>\n {showConversationSidebar && (\n <ConversationSidebar\n conversations={conversations}\n loading={conversationsLoading}\n activeConversationId={conversationId}\n collapsed={sidebarCollapsed}\n onToggleCollapsed={() => setSidebarCollapsed((v) => !v)}\n onSelect={handleSelectConversation}\n onDelete={(id) => void handleDeleteConversation(id)}\n onRename={(id, title) => void renameConversation(id, title)}\n onNewChat={handleNewChat}\n t={t}\n />\n )}\n <div className={showConversationSidebar ? 'flex flex-1 flex-col min-w-0' : 'contents'}>\n {messages.length === 0 ? (\n <ChatWelcome\n firstName={firstName}\n logoIcon={resolvedLogo}\n // The agent's own suggestions when the backend serves them, the\n // host's list otherwise, this package's list when there is neither —\n // never an empty section.\n promptSuggestions={suggestions}\n suggestionsLoading={suggestionsLoading}\n agentName={selectedAgent?.name}\n agentDescription={selectedAgent?.description}\n onPromptClick={setInputValue}\n t={t}\n />\n ) : (\n <ChatMessages\n messages={messages}\n isLoading={isLoading}\n agentStatus={agentStatus}\n agentName={agentName}\n logoIcon={resolvedLogo}\n onRelativeLinkClick={onRelativeLinkClick}\n onDownloadFile={canDownload ? handleDownloadFile : undefined}\n resolveAttachmentUrl={canDownload && !disableImagePreviews ? resolveAttachmentUrl : undefined}\n requestHeaders={requestHeaders}\n miniGameEnabled={miniGameEnabled}\n onPlayWaitingGame={onPlayWaitingGame}\n waitingGameUrl={playUrl}\n onMessageFeedback={onMessageFeedback}\n feedbackUrl={feedbackBaseUrl(apiBaseUrl, apiEndpoints, backendType)}\n conversationId={conversationId}\n locale={locale}\n isResumingAfterDecision={isResumingAfterDecision}\n pendingApprovals={pendingApprovals}\n onSubmitApprovalDecisions={submitApprovalDecisions}\n isSubmittingApproval={isSubmittingApproval}\n approvalError={approvalError}\n t={t}\n />\n )}\n <ChatInput\n inputValue={inputValue}\n onInputChange={setInputValue}\n onSend={handleSendMessage}\n onStop={handleStopGenerating}\n isLoading={isLoading}\n canSteer={canSteer}\n attachedFiles={disableFileManagement ? [] : attachedFiles}\n onFileAdd={disableFileManagement ? undefined : handleFileAdd}\n onFileRemove={disableFileManagement ? undefined : (i) => setAttachedFiles((prev) => prev.filter((_, j) => j !== i))}\n onPaste={disableFileManagement ? undefined : handlePaste}\n t={t}\n mode={mode}\n separatorColor={draftBorderColor}\n prompts={prompts}\n quota={quota}\n contextUsage={contextUsageEnabled ? contextUsage : null}\n composerToolbar={composerToolbar}\n />\n </div>\n </div>\n </div>\n );\n};\n","import type { FunctionComponent } from 'react';\nimport type { ChatToggleButtonProps } from '../types';\nimport { hexAlpha, identity } from '../utils';\nimport { DefaultLogoIcon } from './icons';\n\nexport const ChatToggleButton: FunctionComponent<ChatToggleButtonProps> = ({\n isOpen,\n onToggle,\n label,\n accentColor = '#7b5cff',\n icon,\n t = identity,\n}) => {\n const resolvedIcon = icon ?? <DefaultLogoIcon size={16} />;\n\n return (\n <button\n type=\"button\"\n onClick={onToggle}\n className=\"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors\"\n style={{\n borderColor: isOpen ? accentColor : hexAlpha(accentColor, 0.5),\n color: accentColor,\n backgroundColor: isOpen ? hexAlpha(accentColor, 0.1) : 'transparent',\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.borderColor = accentColor;\n e.currentTarget.style.backgroundColor = hexAlpha(accentColor, 0.1);\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.borderColor = isOpen ? accentColor : hexAlpha(accentColor, 0.5);\n e.currentTarget.style.backgroundColor = isOpen ? hexAlpha(accentColor, 0.1) : 'transparent';\n }}\n >\n <span className=\"[&>svg]:w-4 [&>svg]:h-4\">{resolvedIcon}</span>\n {label ?? t('Ask Assistant')}\n </button>\n );\n};\n"],"names":["hexAlpha","hex","alpha","Math","round","toString","padStart","prepareMarkdown","content","raw","lines","split","fenceRe","markupLang","openerIdx","i","length","m","match","test","trim","fences","push","idx","run","bare","blankBetween","a","b","k","depth","maxRun","nestedCount","closerIdx","j","f","next","max","fence","repeat","om","cm","join","hardenNestedCodeFences","indexOf","splitCells","row","s","startsWith","slice","endsWith","cells","current","ch","isDelimiterRow","includes","alignOf","cell","c","left","right","fenceChar","fenceLen","listMarkerRe","fenceMatch","header","delim","markerMatch","offset","trimStart","indent","headerCols","delimCells","aligns","normalizeMarkdownTables","trimmed","JSON","parse","wrapBareJson","replace","_match","alt","url","SAFE_URL_PROTOCOLS","Set","markdownUrlTransform","colon","slash","question","hash","protocol","toLowerCase","has","identity","key","translate","t","values","slot","name","Object","hasOwn","String","findChatbotRoot","el","node","classList","contains","parentElement","document","body","compactCount","n","toFixed","timeAgo","iso","then","Date","getTime","Number","isNaN","diffMs","now","minutes","floor","count","hours","days","toLocaleDateString","undefined","month","day","FILE_MARKER_RE","PARTIAL_FILE_MARKER_RE","splitFileMarkers","parts","re","lastIndex","exec","index","type","value","fileId","tail","feedbackModeOf","serverId","feedbackUrl","conversationId","hasCallback","normalizeFeedbackComment","comment","feedbackBaseUrl","apiBaseUrl","apiEndpoints","backendType","singleEndpoint","feedback","async","submitFeedback","fetchImpl","baseUrl","messageId","rating","requestHeaders","init","encodeURIComponent","method","credentials","headers","stringify","feedbackRequest","ok","BREAKDOWN_KEYS","parseContextUsage","evt","used","context_tokens","limit","context_window","isFinite","breakdown","src","out","any","wireKey","field","parseBreakdown","context_breakdown","parseAttachments","Array","isArray","item","file_id","filename","size","contentType","content_type","fileTag","file_tag","parseToolCallTrace","e","input","output","success","parseTransferChain","agent_name","agentId","agent_id","agentName","parseToolApprovalProposals","p","toolCallId","tool_call_id","args","arguments","schema","input_schema","toolName","tool_name","toolDescription","tool_description","inputSchema","source","parseRestEvent","ctx","action","st","status","thinkingContent","hasUsedTools","tools","elapsedS","elapsed_s","contextUsage","proposals","conversation_id","toolNames","tool_names","toolCallCount","tool_call_count","iterations","transferAgentId","transfer_agent_id","transferAgentName","transfer_agent_name","attachments","reasoning","toolCallTrace","tool_call_trace","transferChain","transfer_chain","isTruncated","is_truncated","message_id","parsePersistedFeedback","parseLegacyEvent","eventType","event","data","nodeId","activeNodeId","usedTools","map","tool","chatId","parseAgUiEvent","message","stepName","delta","toolCallName","STORAGE_KEY","LEGACY_CHAT_ID_KEY","draftKey","loadDraft","window","sessionStorage","getItem","persistDraft","setItem","removeItem","DEFAULT_MAX_TOTAL_SIZE","useChat","agentSlug","pageContext","maxFileCount","maxTotalSize","isLegacy","messages","setMessages","useState","isLoading","setIsLoading","agentStatus","setAgentStatus","setConversationId","localStorage","inputValue","setInputValue","attachedFiles","setAttachedFiles","transferredAgent","setTransferredAgent","setContextUsage","pendingApprovals","setPendingApprovals","isSubmittingApproval","setIsSubmittingApproval","approvalError","setApprovalError","isResumingAfterDecision","setIsResumingAfterDecision","historyReloadNonce","setHistoryReloadNonce","resumeTick","setResumeTick","legacyChatId","setLegacyChatId","historyLoadedRef","useRef","abortControllerRef","streamDeltasRef","hasUsedToolsRef","conversationIdRef","isLoadingRef","pageContextRef","approvalConversationIdRef","approvalDetachedRef","probedConversationRef","resumeDeadlineRef","creatingSessionRef","uploadAbortRef","AbortController","effectiveMaxFileCount","effectiveMaxTotalSize","getSteerUrl","steer","getApproveUrl","path","approve","getPendingApprovalsUrl","convId","base","readPendingApprovals","res","fetch","json","turnRunning","turn","reloadHistory","useCallback","getUploadUrl","upload","updateConversationId","id","ensureConversation","slug","sessionsUrl","sessions","promise","agent_slug","uploadSingleFile","file","signal","uploadUrl","formData","FormData","append","uploadHeaders","fromEntries","entries","filter","Error","ids","file_ids","handleFileAdd","fileList","candidates","from","tempId","crypto","randomUUID","accepted","prev","currentCount","currentSize","reduce","sum","slotsAvailable","sizeLeft","filtered","newEntries","rawFile","uploadStatus","setTimeout","err","DOMException","handleNewChat","close","abort","useEffect","clearTimeout","draftFlushRef","state","setInterval","catch","clearInterval","cancelled","canSteer","submitApprovalDecisions","decisions","approveUrl","d","decision","verdict","rejectionReason","rejection_reason","handlePaste","files","clipboardData","preventDefault","handleSendMessage","steerText","steerUrl","optimistic","role","timestamp","steerMessage","userMsg","assistantId","currentAssistantId","accumulated","doneReceived","deltas","apply","textChanged","thinking","frame","closed","cancelFrame","cancelAnimationFrame","flush","changed","chunk","schedule","requestAnimationFrame","text","createStreamDeltas","segId","controller","fileIds","requestBody","opts","streaming","threadId","runId","context","forwardedProps","supportsToolApproval","supports_tool_approval","keys","serialized","buildRequestBody","parseEvent","getParser","reader","getReader","decoder","TextDecoder","buffer","ensureSegment","segmentId","done","read","decode","stream","pop","rawLine","line","jsonStr","parsed","elapsedStartMs","finalContent","completedAt","handleStopGenerating","handleSwitchConversation","STORAGE_AGENT_KEY","useAgents","agents","setAgents","agentsLoading","setAgentsLoading","agentsError","setAgentsError","selectedAgent","setSelectedAgent","agentMenuOpen","setAgentMenuOpen","agentsUrl","list","parseAgents","savedSlug","find","finally","handleSwitchAgent","agent","onSwitch","parseConversation","title","updatedAt","updated_at","created_at","messageCount","message_count","SIDEBAR_WIDTH","SIDEBAR_WIDTH_STORAGE_KEY","flashTimer","originalTitle","activeHooks","stopTitleFlash","useAwayCompletionNotice","enabled","onComplete","isViewingChat","wasLoadingRef","startRef","clearOnReturn","hidden","hasFocus","addEventListener","removeEventListener","wasLoading","unfocused","away","viewingChat","showMessage","startTitleFlash","Notification","permission","tag","notifyOS","useComposerExtras","prompts","setPrompts","quota","setQuota","restLike","promptsPath","quotaPath","promptsUrl","quotaUrl","rawList","description","parsePrompts","quotaNonce","setQuotaNonce","refreshQuota","q","period","scope","parseQuota","useAgentSuggestions","suggestions","setSuggestions","loading","setLoading","o","v","prompt","label","parseSuggestions","useShallowStable","ref","is","every","prototype","hasOwnProperty","call","shallowEqual","useLatestCallback","callback","useInsertionEffect","stable","AlertTriangleIcon","className","_jsxs","xmlns","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","children","_jsx","ArrowRightLeftIcon","AttachFileIcon","BotIcon","x","y","rx","BrainIcon","CheckCircleIcon","cx","cy","r","CheckIcon","ChevronDownIcon","CloseIcon","CopyIcon","ry","DatabaseIcon","DefaultLogoIcon","DownloadIcon","points","x1","x2","y1","y2","EditIcon","ExternalLinkIcon","FileIcon","FloatingIcon","FullscreenExitIcon","FullscreenIcon","GamepadIcon","GlobeIcon","HistoryIcon","ImageIcon","InfoIcon","MailIcon","MaximizeIcon","MicIcon","MicOffIcon","SearchIcon","SendIcon","SidebarIcon","SparklesIcon","StopCircleIcon","TerminalIcon","ThumbsDownIcon","filled","ThumbsUpIcon","TrashIcon","UserPlusIcon","SPEAKER","VolumeIcon","VolumeOffIcon","WrenchIcon","XCircleIcon","Dropdown","open","onClose","anchorRef","placement","panelRef","pos","setPos","top","stableOnClose","handler","active","listener","target","useClickOutside","useLayoutEffect","rect","getBoundingClientRect","panelHeight","offsetHeight","spaceBelow","innerHeight","bottom","spaceAbove","preferredLeft","min","innerWidth","portalTarget","createPortal","style","Spinner","tooltipMaxWidth","opening","maxRight","minLeft","Tooltip","tipRef","setOpening","setPlacement","below","shift","center","minTop","placeTooltip","panel","anchor","viewportWidth","tooltipOpening","onMouseEnter","onMouseLeave","onFocus","matches","onBlur","maxWidth","modeOptions","mode","getIcon","ChatHeader","transferredFrom","onAgentMenuToggle","onAgentMenuClose","onSwitchAgent","modeMenuOpen","onModeMenuToggle","onModeMenuClose","onModeChange","onNewChat","logoIcon","agentDashboardUrl","historyEnabled","historyMenuOpen","onHistoryMenuToggle","onHistoryMenuClose","conversations","conversationsLoading","activeConversationId","onSelectConversation","onDeleteConversation","agentAnchorRef","modeAnchorRef","historyAnchorRef","agentQuery","setAgentQuery","filteredAgents","useMemo","showAgentSearch","CurrentModeIcon","onClick","autoFocus","onChange","onKeyDown","placeholder","_Fragment","conv","isActive","when","opt","createDictationController","recognition","events","phase","startQueued","disposed","reported","isOn","report","onListeningChange","tryStart","start","onresult","finalText","interimText","resultIndex","results","result","isFinal","transcript","phrase","onFinal","onInterim","onerror","onend","toggle","stop","cancel","dispose","getSpeechRecognition","w","SpeechRecognition","webkitSpeechRecognition","SIZE","CIRCUMFERENCE","PI","ROWS","color","ContextUsageIndicator","usage","setOpen","ratio","pruning","compacting","ringColor","textColor","percent","counts","headline","tokens","summary","rows","expandable","gauge","strokeDasharray","strokeDashoffset","transform","backgroundColor","borderRadius","PromptPicker","onPick","query","setQuery","QuotaIndicator","quotaPeriodLabel","withScope","compact","exhausted","nearLimit","barColor","ChatInput","onInputChange","onSend","onStop","onFileAdd","onFileRemove","onPaste","separatorColor","composerToolbar","fileInputRef","textareaRef","revealEndRef","dictation","onFinalText","listening","setListening","interim","setInterim","controllerRef","onFinalTextRef","supported","Ctor","continuous","interimResults","lang","navigator","language","useDictation","trimEnd","scrollHeight","scrollTop","hasToolbar","Boolean","isFileManagementEnabled","hasContent","hasFilesUploading","some","canSend","hasAttachments","showSteerSend","send","footerText","borderTopColor","borderTopWidth","multiple","click","shiftKey","maxHeight","disabled","focus","feedbackKeyOf","msg","parser","unified","use","remarkParse","remarkGfm","freeze","SILENT","inlineText","collectLines","child","FENCED_BLOCK_RE","speechSupported","speechSynthesis","SpeechSynthesisUtterance","useSpeechReader","locale","speakingId","setSpeakingId","localeRef","synth","createUtterance","generation","finish","gen","speak","chunks","forEach","part","last","utterance","onEnd","onError","createSpeechController","documents","maxLength","sentences","pieces","sentence","word","piece","chunkSpeech","markdown","speakableText","FORMAT_OPTIONS","time","hour","minute","date","dateWithYear","year","full","dateStyle","timeStyle","formatters","Map","formatter","kind","cached","get","Intl","DateTimeFormat","set","browserTimers","ms","clear","handle","KEYS_TOWARD_TOP","singleTouchY","touches","clientY","SCROLLING_OVERFLOW","formatValue","useRevealIntoView","raf","scrollIntoView","behavior","block","inline","BUTTON_BASE","ApprovalCard","proposal","onDecide","rejecting","setRejecting","reason","setReason","reasonId","useId","rejectPanelRef","argumentNames","decide","properties","entry","argumentSchema","htmlFor","ChatApprovalPrompt","onSubmit","isSubmitting","error","setDecisions","submitted","sent","setSent","busy","submit","all","decidedCount","allDecided","willRunAlways","footerRef","rootRef","decided","total","ImageLightbox","hostRef","closeButtonRef","root","setRoot","previouslyFocused","activeElement","HTMLElement","preventScroll","stopPropagation","ChatImage","maxHeightClass","needsAuth","isRelativeUrl","blobUrl","setBlobUrl","errored","setErrored","expanded","setExpanded","objectUrl","blob","URL","createObjectURL","revokeObjectURL","displaySrc","PLAY_CLASS","ChatWaitingPanel","onPlay","playUrl","keepEndInView","defaultMessages","reducedMotion","reduced","setReduced","matchMedia","mql","addListener","removeListener","usePrefersReducedMotion","msgIndex","setMsgIndex","animation","href","rel","delegatingLabel","pollingLabel","collectingLabel","cleanReasoningText","ThinkingTextBubble","isOverflowing","setIsOverflowing","clientHeight","formatElapsed","seconds","useSustained","delayMs","firedKey","setFiredKey","ChatThinking","miniGameEnabled","onPlayWaitingGame","waitingGameUrl","StatusIcon","showDots","rawNames","lower","display","toUpperCase","unique","consultName","targetName","resolveStatusVisual","nowMs","setNowMs","showElapsed","reasoningText","prose","budget","end","cut","reverse","paragraph","reasoningWindowText","showReasoning","waitedWithoutReasoning","reasoningWentQuiet","showWaiting","delay","blockParser","holdsDefinition","lineStart","lastIndexOf","settlesBefore","endsIndented","MarkdownBlockSplitter","this","previous","blocks","starts","settled","firstDefinition","single","reuse","position","splitMarkdownBlocks","isRelativeHref","MarkdownRenderContext","createContext","copiedBlock","onCopyCode","MARKDOWN_COMPONENTS","pre","code","useContext","codeStr","ul","ol","li","strong","em","hr","blockquote","onRelativeLinkClick","internalHref","location","origin","pathname","search","toInternalHref","routeInternally","openInNewTab","img","h1","h2","h3","table","tr","th","td","REMARK_PLUGINS","remarkBreaks","MarkdownBody","memo","Markdown","remarkPlugins","urlTransform","components","displayName","StreamedMarkdownBody","splitter","MarkdownMessage","setCopiedBlock","byBlocks","setByBlocks","processedContent","clipboard","writeText","renderContext","Provider","prettyTraceValue","toolDisplayName","ToolCallRow","inputDisplay","outputDisplay","hasInput","ReasoningDetailsDialog","dialogRef","dialog","focusable","querySelectorAll","first","totalCalls","transfers","trace","summaryParts","tn","parentOf","overflowYOf","getComputedStyle","overflowY","isControl","Element","closest","fileExtensionLabel","dot","ext","IMAGE_EXTENSIONS","SHOWN_ON_HOVER","FOOTER_BUTTON","ACCENT_ON_HOVER","REVEALED_BUTTON","DIMMED_BUTTON","ACTIVE_BUTTON","MessageTime","getFullYear","getMonth","getDate","format","toISOString","formatMessageTime","dateTime","MessageCopyButton","copied","setCopied","MessageFeedbackButtons","locked","pending","downRef","lockedId","inert","button","Icon","FeedbackComment","onSave","onSkip","setText","canSave","readOnly","ctrlKey","metaKey","ReadAloudButton","speaking","onToggle","MessageRow","isStreaming","onDownloadFile","resolveAttachmentUrl","feedbackMode","onRate","onSaveComment","onSkipComment","canSpeak","isSpeaking","onToggleSpeech","setShowReasoning","isAssistant","isEmpty","commentOpen","wasCommentOpen","renderAttachmentCard","att","previewUrl","isImageAttachment","isWorking","sizeLabel","bytes","renderFileChip","hasReasoningDetails","showActions","plainText","stripped","stripFileMarkers","speechDocuments","sources","answerMarkdownSources","shown","session","stored","speechKey","seen","add","buildUserFileBlocks","attByFileId","buildAssistantBlocks","timestampUnknown","ChatMessages","onMessageFeedback","onSubmitApprovalDecisions","scrollRef","renderWindow","setRenderWindow","feedbackEntries","rate","saveComment","skipComment","setState","latest","seqRef","put","patch","seq","change","notify","useMessageFeedback","speech","follower","getBox","timers","following","lastTop","smooth","jumpToEnd","box","scrollTo","stopWaiting","timer","arrived","reveal","keepUp","onScroll","movedUp","movedDown","distance","leave","createScrollFollower","touchAnchorRef","leaveFrom","container","innerBoxScrollsUp","firstMessageId","userMessageCount","seenRef","thinkingLen","hasEarlierMessages","visibleMessages","stopSpeech","spokenStillShown","speechScope","streamingMessageId","awaitingApproval","tabIndex","onWheel","deltaY","abs","deltaX","wheelScrollsUp","currentTarget","defaultPrevented","altKey","keyScrollsUp","isContentEditable","onPointerDown","press","onControl","onContainer","clientWidth","thumbBottom","pressTakesScrollbar","clientX","clientLeft","clientTop","onTouchStart","onTouchMove","anchorY","swipeScrollsUp","nextTouchAnchor","isStreamingMessage","Greeting","firstName","before","after","hasSlot","token","at","translateAround","ChatWelcome","promptSuggestions","onPromptClick","agentDescription","suggestionsLoading","fontFamily","ConversationSidebar","collapsed","onToggleCollapsed","onSelect","onDelete","onRename","editingId","setEditingId","draftTitle","setDraftTitle","settledRef","commitRename","isEditing","ChatPanel","topOffset","apiEndpointsProp","user","accentColor","promptSuggestionsProp","draftBorderColor","resizable","onWidthChange","onResizeStart","onResizeEnd","disableFileManagement","onRelativeLinkClickProp","onDownloadError","onDownloadErrorProp","requestHeadersProp","pageContextProp","pushContentSelector","onPlayWaitingGameProp","notifyOnComplete","onTaskComplete","onTaskCompleteProp","onMessageFeedbackProp","disableImagePreviews","contextUsageEnabled","setModeMenuOpen","agentSuggestions","defaultSuggestions","refreshConversations","deleteConversation","renameConversation","setConversations","setConversationsLoading","history","useConversations","setHistoryMenuOpen","sidebarCollapsed","setSidebarCollapsed","showConversationSidebar","handleSelectConversation","handleDeleteConversation","sidebarWidth","handleResizeStart","defaultWidth","isResizing","setSidebarWidth","parseInt","setIsResizing","isResizingRef","sidebarWidthRef","onWidthChangeRef","onResizeEndRef","handleMouseMove","newWidth","clamped","handleMouseUp","cursor","userSelect","handleWindowResize","useSidebarResize","pushWidth","documentElement","setProperty","contentElement","querySelector","originalPaddingRight","paddingRight","originalTransition","transition","resolvedLogo","xtmOneUrl","conversationAgentName","setConversationAgentName","checkVisibility","getClientRects","downloadPathProvided","download","canDownload","handleDownloadFile","link","createElement","appendChild","remove","cssVars","isMountedRef","requestedConversationId","isStale","createdAt","sentAt","parseRestoredMessages","containerClasses","containerStyle","onMouseDown","_","ChatToggleButton","isOpen","icon","resolvedIcon","borderColor"],"mappings":"2bAEM,SAAUA,EAASC,EAAaC,GAIpC,MAAO,GAAGD,IAHAE,KAAKC,MAAc,IAARF,GAClBG,SAAS,IACTC,SAAS,EAAG,MAEjB,CA+PM,SAAUC,EAAgBC,GAC9B,OA3OI,SAAiCC,GACrC,IAAKA,EAAK,OAAOA,EACjB,MAAMC,EAAQD,EAAIE,MAAM,MAClBC,EAAU,qBACVC,EAAa,+BAEnB,IAAIC,GAAY,EAChB,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAMM,OAAQD,IAAK,CACrC,MAAME,EAAIP,EAAMK,GAAGG,MAAMN,GACzB,GAAIK,GAAqB,IAAhBA,EAAE,GAAGD,QAAgBH,EAAWM,KAAKF,EAAE,GAAGG,QAAS,CAC1DN,EAAYC,EACZ,KACF,CACF,CACA,IAAkB,IAAdD,EAAkB,OAAOL,EAkB7B,MAAMY,EAAwD,GAC9D,IAAK,IAAIN,EAAID,EAAY,EAAGC,EAAIL,EAAMM,OAAQD,IAAK,CACjD,MAAME,EAAIP,EAAM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["../../src/utils/index.ts","../../src/utils/feedback.ts","../../src/utils/conversationRefs.ts","../../src/utils/workspaces.ts","../../src/hooks/protocols/parseRestEvent.ts","../../src/hooks/protocols/parseLegacyEvent.ts","../../src/hooks/protocols/parseAgUiEvent.ts","../../src/utils/sessionGate.ts","../../src/utils/pageActions.ts","../../src/utils/pageSnapshot.ts","../../src/hooks/useChat.ts","../../src/hooks/streamDeltas.ts","../../src/hooks/useAgents.ts","../../src/hooks/useConversations.ts","../../src/hooks/useSidebarResize.ts","../../src/hooks/useAwayCompletionNotice.ts","../../src/hooks/useComposerExtras.ts","../../src/utils/quota.ts","../../src/hooks/useAgentSuggestions.ts","../../src/hooks/useStableProps.ts","../../src/components/icons/AlertTriangleIcon.tsx","../../src/components/icons/ArrowRightLeftIcon.tsx","../../src/components/icons/AttachFileIcon.tsx","../../src/components/icons/BotIcon.tsx","../../src/components/icons/BrainIcon.tsx","../../src/components/icons/CheckCircleIcon.tsx","../../src/components/icons/CheckIcon.tsx","../../src/components/icons/ChevronDownIcon.tsx","../../src/components/icons/ChevronRightIcon.tsx","../../src/components/icons/CloseIcon.tsx","../../src/components/icons/CopyIcon.tsx","../../src/components/icons/DatabaseIcon.tsx","../../src/components/icons/DefaultLogoIcon.tsx","../../src/components/icons/DownloadIcon.tsx","../../src/components/icons/EditIcon.tsx","../../src/components/icons/ExternalLinkIcon.tsx","../../src/components/icons/FileIcon.tsx","../../src/components/icons/FloatingIcon.tsx","../../src/components/icons/FolderIcon.tsx","../../src/components/icons/FolderInputIcon.tsx","../../src/components/icons/FolderPlusIcon.tsx","../../src/components/icons/FullscreenExitIcon.tsx","../../src/components/icons/FullscreenIcon.tsx","../../src/components/icons/GamepadIcon.tsx","../../src/components/icons/GlobeIcon.tsx","../../src/components/icons/HistoryIcon.tsx","../../src/components/icons/ImageIcon.tsx","../../src/components/icons/InfoIcon.tsx","../../src/components/icons/MailIcon.tsx","../../src/components/icons/MaximizeIcon.tsx","../../src/components/icons/MessageSquareIcon.tsx","../../src/components/icons/MicIcon.tsx","../../src/components/icons/PencilIcon.tsx","../../src/components/icons/SearchIcon.tsx","../../src/components/icons/SendIcon.tsx","../../src/components/icons/SidebarIcon.tsx","../../src/components/icons/SparklesIcon.tsx","../../src/components/icons/StopCircleIcon.tsx","../../src/components/icons/TerminalIcon.tsx","../../src/components/icons/ThumbsDownIcon.tsx","../../src/components/icons/ThumbsUpIcon.tsx","../../src/components/icons/TrashIcon.tsx","../../src/components/icons/UserPlusIcon.tsx","../../src/components/icons/VolumeIcon.tsx","../../src/components/icons/WrenchIcon.tsx","../../src/components/icons/XCircleIcon.tsx","../../src/components/Dropdown.tsx","../../src/hooks/useClickOutside.ts","../../src/components/Spinner.tsx","../../src/utils/tooltipPlacement.ts","../../src/components/Tooltip.tsx","../../src/components/ChatHeader.tsx","../../src/hooks/useConversationReferenceSearch.ts","../../src/hooks/useConversationReferenceMenu.ts","../../src/hooks/dictationController.ts","../../src/hooks/useDictation.ts","../../src/components/ContextUsageIndicator.tsx","../../src/components/ConversationReferenceMenu.tsx","../../src/components/PromptPicker.tsx","../../src/components/QuotaIndicator.tsx","../../src/components/ChatInput.tsx","../../src/hooks/useMessageFeedback.ts","../../src/utils/speech.ts","../../src/hooks/useSpeechReader.ts","../../src/utils/messageTime.ts","../../src/utils/scrollFollow.ts","../../src/components/ArtifactCard.tsx","../../src/components/icons/PresentationIcon.tsx","../../src/components/icons/FileTextIcon.tsx","../../src/components/icons/ClapperboardIcon.tsx","../../src/utils/polling.ts","../../src/components/ChatApprovalPrompt.tsx","../../src/components/ChatImage.tsx","../../src/components/ChatWaitingPanel.tsx","../../src/components/ChatThinking.tsx","../../src/utils/markdownBlocks.ts","../../src/components/MarkdownMessage.tsx","../../src/components/ReasoningDetailsDialog.tsx","../../src/components/ChatMessages.tsx","../../src/components/ChatWelcome.tsx","../../src/components/ConversationSidebar.tsx","../../src/components/ChatPanel.tsx","../../src/hooks/useWorkspaces.ts","../../src/components/ChatToggleButton.tsx"],"sourcesContent":["import type { ChatArtifact, ChatArtifactKind, Translate } from '../types';\n\nexport function hexAlpha(hex: string, alpha: number): string {\n const a = Math.round(alpha * 255)\n .toString(16)\n .padStart(2, '0');\n return `${hex}${a}`;\n}\n\n/**\n * Markdown has no native support for nesting fenced code blocks of the same\n * length: per the CommonMark spec, the first inner ``` closes the outer block,\n * so everything after it renders *outside* the code block. LLMs constantly hit\n * this — when an agent shows a prompt or a full markdown document inside a\n * ```markdown … ``` fence, that document's own ``` fences shatter the snippet\n * into alternating code / prose fragments.\n *\n * The robust, spec-compliant fix is to make the *outer* fence longer than any\n * fence it contains: a 4-backtick fence is only closed by a run of ≥4\n * backticks, so all inner 3-backtick fences become literal content and the\n * whole document renders as one clean, copyable code block.\n *\n * We act only on the unambiguous, dominant case — a 3-backtick opener whose\n * info string is a markup language (markdown / md / mdx / markup) that actually\n * contains nested fences — so already-correct markdown is never rewritten\n * (a correctly authored nested block already uses a 4+-backtick opener, which\n * we skip).\n */\nexport function hardenNestedCodeFences(raw: string): string {\n if (!raw) return raw;\n const lines = raw.split('\\n');\n const fenceRe = /^(\\s*)(`{3,})(.*)$/;\n const markupLang = /^(markdown|md|mdx|markup)\\b/i;\n\n let openerIdx = -1;\n for (let i = 0; i < lines.length; i++) {\n const m = lines[i].match(fenceRe);\n if (m && m[2].length === 3 && markupLang.test(m[3].trim())) {\n openerIdx = i;\n break;\n }\n }\n if (openerIdx === -1) return raw;\n\n // Find the outer block's *matching* closer rather than the last bare fence in\n // the message. Same-length fences are ambiguous — an inner ``` looks exactly\n // like the outer closer — so inner fences are paired off with two structural\n // signals:\n // • a labelled fence (```lang) opens a nested block, and the next bare\n // fence closes it (depth tracking); and\n // • two consecutive *bare* fences wrapping a non-blank body form an\n // unlabelled nested code block — a ``` … ``` example inside the document.\n // A bare fence at depth 0 is the outer closer when the next fence is\n // labelled, absent, or bare-but-separated-by-only-blank-lines: that last case\n // is a block boundary (this closer followed by a *separate* block), not\n // nesting, so the separate block is never absorbed.\n //\n // Taking the last bare fence instead swallowed everything up to it — trailing\n // prose and unrelated code blocks alike — whenever a later block followed the\n // markdown one.\n const fences: { idx: number; run: number; bare: boolean }[] = [];\n for (let i = openerIdx + 1; i < lines.length; i++) {\n const m = lines[i].match(fenceRe);\n if (m) fences.push({ idx: i, run: m[2].length, bare: m[3].trim() === '' });\n }\n\n // True when every line strictly between two fence lines is blank — which\n // separates a nested code block (real body) from a mere block boundary.\n const blankBetween = (a: number, b: number): boolean => {\n for (let k = a + 1; k < b; k++) {\n if (lines[k].trim() !== '') return false;\n }\n return true;\n };\n\n let depth = 0;\n let maxRun = 3;\n let nestedCount = 0;\n let closerIdx = -1;\n for (let j = 0; j < fences.length; j++) {\n const f = fences[j];\n if (f.bare && depth === 0) {\n const next = fences[j + 1];\n if (!next || !next.bare || blankBetween(f.idx, next.idx)) {\n closerIdx = f.idx;\n break;\n }\n depth++; // opens an unlabelled nested code block\n } else {\n // A labelled fence opens a nested block; a bare fence at depth > 0 closes\n // the innermost one.\n depth = f.bare ? Math.max(0, depth - 1) : depth + 1;\n }\n nestedCount++;\n maxRun = Math.max(maxRun, f.run);\n }\n\n // Only harden when the block really contains nested fences AND its own closer\n // was found — otherwise leave the text alone rather than extending the block\n // over whatever follows.\n if (closerIdx === -1 || nestedCount === 0) return raw;\n\n const fence = '`'.repeat(Math.max(maxRun + 1, 4));\n const om = lines[openerIdx].match(fenceRe)!;\n lines[openerIdx] = `${om[1]}${fence}${om[3]}`;\n const cm = lines[closerIdx].match(fenceRe)!;\n lines[closerIdx] = `${cm[1]}${fence}`;\n return lines.join('\\n');\n}\n\n/**\n * GFM renders a pipe table only when the delimiter row (`|---|---|`) has the\n * SAME number of columns as the header row. LLMs frequently miscount (e.g. a\n * 4-column header followed by a 3-column delimiter), and a server-side guard can\n * corrupt the delimiter — in either case the whole table silently degrades to\n * raw `| … |` text. This repairs a mismatched delimiter row to the header's\n * column count (preserving any alignment colons) so the table renders.\n *\n * It only rewrites a delimiter that is ACTUALLY mismatched, so already-valid\n * tables are never touched. Fenced code blocks are skipped, and setext headings\n * (underlines with no `|`) are never mistaken for a table.\n */\nexport function normalizeMarkdownTables(raw: string): string {\n if (!raw || raw.indexOf('|') === -1) return raw;\n const lines = raw.split('\\n');\n\n // Splits on unescaped `|` only. A manual walk (rather than a negative\n // lookbehind, which is unsupported on older engines and would throw at parse\n // time in an untranspiled ESNext bundle) keeps `\\|` inside a cell intact.\n const splitCells = (row: string): string[] => {\n let s = row.trim();\n if (s.startsWith('|')) s = s.slice(1);\n if (s.endsWith('|')) s = s.slice(0, -1);\n const cells: string[] = [];\n let current = '';\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (ch === '\\\\' && i + 1 < s.length) {\n current += ch + s[i + 1];\n i++;\n } else if (ch === '|') {\n cells.push(current);\n current = '';\n } else {\n current += ch;\n }\n }\n cells.push(current);\n return cells;\n };\n const isDelimiterRow = (row: string): boolean => row.includes('|') && /^\\s*\\|?\\s*:?-+:?\\s*(\\|\\s*:?-+:?\\s*)*\\|?\\s*$/.test(row);\n // Emit the canonical 3-hyphen delimiter form. remark-gfm accepts a single\n // hyphen, but `---` (with optional alignment colons) is the portable form\n // every Markdown renderer agrees on, so prefer it.\n const alignOf = (cell: string): string => {\n const c = cell.trim();\n const left = c.startsWith(':');\n const right = c.endsWith(':');\n return left && right ? ':---:' : right ? '---:' : left ? ':---' : '---';\n };\n\n // Track both the fence character AND its run length: per CommonMark a closing\n // fence must use the same character and be at least as long as the opener, so\n // a shorter run (```) must not close a longer one (````), and a closing fence\n // carries no info string. Optional blockquote / list-item markers are allowed\n // before the run so fences nested in those containers (e.g. `- ```) are still\n // recognised and the table inside them is left untouched.\n const fenceRe = /^\\s*(?:(?:>\\s?)|(?:[-*+]\\s+)|(?:\\d{1,9}[.)]\\s+))*(`{3,}|~{3,})(.*)$/;\n let fenceChar: string | null = null;\n let fenceLen = 0;\n // A pipe-table header can share its line with a list-item marker (e.g.\n // `- | a | b |`). Strip a leading list marker before counting columns so the\n // count matches the cells GFM sees inside the list item, not the marker.\n const listMarkerRe = /^\\s*(?:[-*+]\\s+|\\d{1,9}[.)]\\s+)/;\n for (let i = 0; i < lines.length - 1; i++) {\n const fenceMatch = lines[i].match(fenceRe);\n if (fenceMatch) {\n const run = fenceMatch[1];\n if (fenceChar === null) {\n fenceChar = run[0];\n fenceLen = run.length;\n } else if (run[0] === fenceChar && run.length >= fenceLen && fenceMatch[2].trim() === '') {\n fenceChar = null;\n fenceLen = 0;\n }\n continue;\n }\n if (fenceChar !== null) continue;\n\n const header = lines[i];\n const delim = lines[i + 1];\n if (!header.includes('|') || isDelimiterRow(header) || !isDelimiterRow(delim)) continue;\n\n // A table can start on a list-item line, so both the cells and the\n // delimiter's alignment live AFTER the marker. Anchor the rewritten\n // delimiter to that content offset (padding the marker width with spaces) so\n // it stays a continuation line of the list item: GFM drops a table whose\n // delimiter dedents away from its header. Without a marker this is just the\n // header's leading whitespace, so top-level tables are emitted unchanged.\n const markerMatch = header.match(listMarkerRe);\n const offset = markerMatch ? markerMatch[0].length : header.length - header.trimStart().length;\n const indent = markerMatch ? ' '.repeat(offset) : header.slice(0, offset);\n\n const headerCols = splitCells(header.slice(offset)).length;\n const delimCells = splitCells(delim);\n if (headerCols < 2 || delimCells.length === headerCols) continue;\n\n const aligns: string[] = [];\n for (let c = 0; c < headerCols; c++) aligns.push(delimCells[c] ? alignOf(delimCells[c]) : '---');\n lines[i + 1] = `${indent}| ${aligns.join(' | ')} |`;\n }\n return lines.join('\\n');\n}\n\n/**\n * When the ENTIRE message is a raw JSON object/array (and not already fenced),\n * wrap it in a ```json fence so it renders as a proper, copyable code block\n * instead of one long line of mangled prose — markdown collapses the newlines\n * and eats the `*`/`_` inside string values otherwise.\n *\n * Deliberately conservative: it parses the payload first, so a message that\n * merely *starts* with `{` (e.g. prose about an object) is left untouched.\n */\nexport function wrapBareJson(raw: string): string {\n const trimmed = raw.trim();\n if ((!trimmed.startsWith('{') && !trimmed.startsWith('[')) || trimmed.startsWith('```')) return raw;\n try {\n JSON.parse(trimmed);\n return '```json\\n' + trimmed + '\\n```';\n } catch {\n return raw;\n }\n}\n\n/**\n * Models routinely emit markdown images whose alt text is the whole generation\n * prompt, spread over several lines. CommonMark has no multi-line `![…](…)`, so\n * the image syntax breaks apart and the prompt renders as literal paragraphs\n * followed by a stray link.\n *\n * This collapses the alt text of such an image onto a single line (whitespace\n * runs → one space) so the parser emits a real `<img>` node. Single-line images\n * are returned byte-identical, and the URL is never rewritten — the URL may\n * contain anything, and only the alt text is at fault.\n *\n * The URL part excludes `)` and whitespace, so a link title\n * (`![alt](url \"title\")`) or a parenthesised URL is left alone rather than\n * mis-parsed.\n */\nexport function normalizeImageMarkdown(raw: string): string {\n if (!raw.includes('![')) return raw;\n return raw.replace(/!\\[([^\\]]*?\\n[^\\]]*?)\\]\\(([^)\\s]+)\\)/g, (_match, alt: string, url: string) => {\n const flat = alt.replace(/\\s+/g, ' ').trim();\n return `![${flat}](${url})`;\n });\n}\n\n/**\n * The text the panel hands to its markdown renderer. Order matters — image\n * alt-text is flattened before anything else looks at line structure, and the\n * JSON wrap must see the raw payload before fences are hardened.\n */\nexport function prepareMarkdown(content: string): string {\n return hardenNestedCodeFences(normalizeMarkdownTables(wrapBareJson(normalizeImageMarkdown(content))));\n}\n\n/** Schemes react-markdown's own sanitizer allows, minus the `data:` special case below. */\nconst SAFE_URL_PROTOCOLS = new Set(['http', 'https', 'mailto', 'tel']);\n\n/**\n * URL sanitizer for react-markdown that additionally preserves `data:image/*`\n * URIs.\n *\n * react-markdown v9+ ships a default `urlTransform` allowing only\n * http / https / mailto / tel. Agents with a code interpreter return charts as\n * `data:image/png;base64,…`, which that default strips — leaving a broken\n * `<img>`. Every other scheme (notably `javascript:` / `vbscript:`) is still\n * blocked, and non-image `data:` URIs are blocked too, so this widens the\n * allow-list by exactly one safe, inert case.\n */\nexport function markdownUrlTransform(url: string): string {\n const colon = url.indexOf(':');\n if (colon < 0) return url; // relative URL — always safe\n\n const slash = url.indexOf('/');\n const question = url.indexOf('?');\n const hash = url.indexOf('#');\n\n // A `/`, `?` or `#` before the colon means this is a path, not a scheme\n // (e.g. `./a:b`), so there is nothing to sanitize.\n if ((slash > -1 && colon > slash) || (question > -1 && colon > question) || (hash > -1 && colon > hash)) {\n return url;\n }\n\n const protocol = url.slice(0, colon).toLowerCase();\n if (SAFE_URL_PROTOCOLS.has(protocol)) return url;\n if (protocol === 'data' && /^data:image\\//i.test(url)) return url;\n return '';\n}\n\nexport const identity: Translate = (key) => key;\n\n/**\n * Translates `key`, then splices `values` into the result's `{name}` slots.\n *\n * The point is that the key stays a whole sentence. Building a phrase out of\n * translated fragments — \"Waiting for\" + count + \"tasks\" — freezes English word\n * order and English plural rules into the layout, and a translator sees each\n * fragment with no sentence around it. Here the locale owns the whole sentence\n * and decides where the number goes; the host's `t` still does nothing but look\n * a key up, so this needs no support from it.\n *\n * Plurals stay two explicit keys (`'1 tool call'` / `'{count} tool calls'`) for\n * the same reason: a lookup cannot select a plural form, so the call site picks\n * the sentence and the locale translates it whole.\n */\nexport function translate(t: Translate, key: string, values: Record<string, string | number>): string {\n // One pass over the sentence rather than one pass per value: a value that\n // happens to contain `{something}` is then never mistaken for a slot of its\n // own. A slot with no value keeps its braces, so a stray one is visible\n // rather than silently blank.\n return t(key).replace(/\\{(\\w+)\\}/g, (slot, name) => (Object.hasOwn(values, name) ? String(values[name] ?? '') : slot));\n}\n\n/**\n * Same as `translate`, but leaves one slot unfilled and returns the text on\n * either side of it — for the case where the value has to be markup (a coloured\n * agent name, a link) and so cannot be spliced into a string.\n *\n * Without this the sentence gets cut into \"How can \" + node + \" help you, \",\n * which is untranslatable in any language that would not put the node in that\n * spot. Here the locale still owns the whole sentence and decides where the slot\n * sits.\n *\n * `hasSlot` is false for a translation that dropped the slot — a locale that\n * reworded the sentence so it no longer names the value. The caller then renders\n * the sentence without the node instead of letting it dangle off the end.\n */\nexport function translateAround(\n t: Translate,\n key: string,\n slot: string,\n values: Record<string, string | number> = {},\n): { before: string; after: string; hasSlot: boolean } {\n const sentence = translate(t, key, values);\n const token = `{${slot}}`;\n const at = sentence.indexOf(token);\n if (at === -1) return { before: sentence, after: '', hasSlot: false };\n return { before: sentence.slice(0, at), after: sentence.slice(at + token.length), hasSlot: true };\n}\n\n/**\n * Nearest chatbot panel root (`.filigran-chatbot`) for portal-based overlays\n * (tooltips, dropdowns, dialogs), so they stay inside the panel's stacking\n * context instead of competing with the host app's z-indexes. Falls back to\n * `document.body` when rendered outside a panel.\n */\nexport function findChatbotRoot(el: HTMLElement | null): HTMLElement {\n let node = el;\n while (node) {\n if (node.classList.contains('filigran-chatbot')) return node;\n node = node.parentElement;\n }\n return document.body;\n}\n\n/**\n * Compact count for the composer's status readouts: 1200 → \"1.2k\", so neither\n * the quota nor the context gauge can widen the toolbar as the numbers grow.\n */\nexport function compactCount(n: number): string {\n if (n < 1000) return `${n}`;\n if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\\.0$/, '')}k`;\n return `${(n / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`;\n}\n\n/**\n * Compact relative-time label for the conversation history menu\n * (\"just now\", \"5m ago\", \"3h ago\", \"2d ago\", then a short date).\n * Returns an empty string for missing/unparseable timestamps so the row\n * simply omits the label instead of showing \"Invalid Date\".\n */\nexport function timeAgo(iso: string | undefined, t: Translate): string {\n if (!iso) return '';\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) return '';\n const diffMs = Date.now() - then;\n const minutes = Math.floor(diffMs / 60_000);\n if (minutes < 1) return t('just now');\n if (minutes < 60) return translate(t, '{count}m ago', { count: minutes });\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return translate(t, '{count}h ago', { count: hours });\n const days = Math.floor(hours / 24);\n if (days < 7) return translate(t, '{count}d ago', { count: days });\n return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n}\n\n/**\n * A complete marker an agent embeds in prose: a file (`[[FILE:<id>]]`), or a\n * deck, report or video it made (`[[PRESENTATION:<id>]]`, optionally naming a\n * slide as `#/<slide id>`, `[[REPORT:<id>]]`, `[[VIDEO:<id>]]`). The backend\n * matches the names case-insensitively, and so does this.\n */\nconst ANSWER_MARKER_RE = /\\[\\[(FILE|PRESENTATION|REPORT|VIDEO):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?\\]\\]/gi;\n\n/**\n * Matches an INCOMPLETE marker at the very end of the string. SSE streams can\n * split a marker before the closing `]]` arrives, so the tail may be `[[FILE`,\n * `[[VIDEO:`, `[[REPORT:abc` or `[[FILE:abc]` mid-stream. We anchor on a whole\n * marker name (vanishingly unlikely to end real prose) so it never clips real\n * content.\n */\nconst PARTIAL_ANSWER_MARKER_RE = /\\[\\[(?:FILE|PRESENTATION|REPORT|VIDEO)(?::[^\\]]*)?\\]?$/i;\n\nconst ANSWER_MARKER_HEADS = ['[[FILE:', '[[PRESENTATION:', '[[REPORT:', '[[VIDEO:'];\nconst LONGEST_MARKER_HEAD = Math.max(...ANSWER_MARKER_HEADS.map((head) => head.length));\n\n/**\n * *text* without a trailing start of a marker name (`[`, `[[`, `[[PRES`). Only\n * for an answer still streaming, where the next chunk may complete it: once\n * the answer is done, the same text is prose.\n */\nfunction withoutMarkerHead(text: string): string {\n for (let i = Math.max(0, text.length - LONGEST_MARKER_HEAD); i < text.length; i++) {\n if (text[i] !== '[') continue;\n const tail = text.slice(i).toUpperCase();\n if (ANSWER_MARKER_HEADS.some((head) => head.startsWith(tail))) return text.slice(0, i);\n }\n return text;\n}\n\n/**\n * Strip the markers an agent embeds in its reply to point at the files, decks,\n * reports and videos it made. They render as cards of their own, so the raw\n * markers must be removed from the prose. Complete markers are removed\n * anywhere; an incomplete marker at the end is also removed so a partially\n * streamed token never flickers as raw `[[FILE:...` text.\n *\n * When no marker is present the content is returned **untouched** — we must\n * not trim or collapse blank lines on ordinary prose, which would clobber\n * intentional leading/trailing whitespace (e.g. indented Markdown / code).\n * Whitespace is only normalized when a marker was actually removed.\n *\n * Applied to assistant content only — user-typed text is never touched, so a\n * user who literally types `[[FILE:x]]` still sees their own text.\n */\nexport function stripAnswerMarkers(content: string): string {\n if (!content) return content;\n const stripped = content.replace(ANSWER_MARKER_RE, '').replace(PARTIAL_ANSWER_MARKER_RE, '');\n if (stripped === content) return content;\n return stripped\n .replace(/[ \\t]+\\n/g, '\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/** An ordered piece of assistant content: prose text, a file marker or an artifact marker. */\nexport type AnswerPart =\n | { type: 'text'; value: string }\n | { type: 'file'; fileId: string }\n | { type: 'artifact'; kind: ChatArtifactKind; id: string; slideRef?: string };\n\n/**\n * Split assistant content into ordered parts around complete markers, so the\n * renderer can place each file or artifact card at its marker's source\n * position (preserving interleaved order). An artifact id is lowercased, the\n * form the backend describes it in. A trailing incomplete marker (an SSE token\n * split mid-stream) is removed from the final text part so it never shows as\n * raw `[[FILE:...` text, and so is, while *streaming*, a chunk that stopped\n * inside a marker's name (`[[PRES`).\n */\nexport function splitAnswerMarkers(content: string, streaming = false): AnswerPart[] {\n if (!content) return [];\n const parts: AnswerPart[] = [];\n const re = new RegExp(ANSWER_MARKER_RE.source, 'gi');\n let lastIndex = 0;\n let match: RegExpExecArray | null = re.exec(content);\n while (match !== null) {\n if (match.index > lastIndex) {\n parts.push({ type: 'text', value: content.slice(lastIndex, match.index) });\n }\n const name = match[1].toLowerCase();\n if (name === 'file') {\n parts.push({ type: 'file', fileId: match[2] });\n } else {\n parts.push({ type: 'artifact', kind: name as ChatArtifactKind, id: match[2].toLowerCase(), slideRef: match[3] || undefined });\n }\n lastIndex = re.lastIndex;\n match = re.exec(content);\n }\n const rest = content.slice(lastIndex).replace(PARTIAL_ANSWER_MARKER_RE, '');\n const tail = streaming ? withoutMarkerHead(rest) : rest;\n if (tail) parts.push({ type: 'text', value: tail });\n return parts;\n}\n\n/**\n * The markdown documents an assistant answer is drawn from, in order: each\n * prose part between its markers (`splitAnswerMarkers`), prepared as\n * `MarkdownMessage` prepares it (`prepareMarkdown`). The transcript parses each\n * one as a document of its own, and so must anything that reads the answer\n * (read aloud) to read what the screen shows.\n */\nexport function answerMarkdownSources(content: string): string[] {\n const sources: string[] = [];\n for (const part of splitAnswerMarkers(content)) {\n if (part.type === 'text' && part.value.trim()) sources.push(prepareMarkdown(part.value));\n }\n return sources;\n}\n\n/** `kind:id`, how an artifact marker finds the descriptor it renders. */\nexport const artifactKey = (kind: string, id: string): string => `${kind}:${id.toLowerCase()}`;\n\n/** A video whose newest render has not finished: its card follows it. */\nexport const isRenderInProgress = (artifact: ChatArtifact): boolean =>\n artifact.kind === 'video' && (artifact.status === 'pending' || artifact.status === 'running');\n\n/** The kind's name, for a card with no title and for its accessible label. */\nexport function artifactKindLabel(kind: ChatArtifactKind, t: Translate): string {\n if (kind === 'presentation') return t('Presentation');\n if (kind === 'report') return t('Report');\n return t('Video');\n}\n\n/** The facts line under a card's title: its slides, its sections, or its scenes and length. */\nexport function artifactFacts(artifact: ChatArtifact, t: Translate): string {\n const parts: string[] = [];\n if (artifact.kind === 'presentation' && artifact.slideCount !== undefined) {\n parts.push(translate(t, '{count} slides', { count: artifact.slideCount }));\n }\n if (artifact.kind === 'report' && artifact.sectionCount !== undefined) {\n parts.push(translate(t, '{count} sections', { count: artifact.sectionCount }));\n }\n if (artifact.kind === 'video') {\n if (artifact.sceneCount !== undefined) parts.push(translate(t, '{count} scenes', { count: artifact.sceneCount }));\n const duration = formatVideoDuration(artifact.durationMs);\n if (duration) parts.push(duration);\n }\n return parts.join(' · ');\n}\n\n/** What a video's render is doing, when the card has something to say about it. */\nexport function videoRenderLabel(artifact: ChatArtifact, t: Translate): string | undefined {\n if (artifact.kind !== 'video') return undefined;\n if (artifact.status === 'running') {\n return translate(t, 'Rendering {progress}%', { progress: Math.round(artifact.progress ?? 0) });\n }\n if (artifact.status === 'pending') return t('Waiting to render');\n if (artifact.downloads.length > 0) return undefined;\n if (artifact.status === 'failed' || artifact.status === 'cancelled') return t('The render did not finish');\n return t('Not rendered yet');\n}\n\n/** The label of a download button. */\nexport function artifactDownloadLabel(format: string, t: Translate): string {\n if (format === 'pdf') return 'PDF';\n if (format === 'mp4') return 'MP4';\n if (format === 'pptx') return t('PowerPoint');\n if (format === 'pptx_native') return t('PowerPoint (editable)');\n return format.toUpperCase();\n}\n\n/** The XTM One page of a card, linked only when it is http(s). */\nexport function artifactLink(artifact: ChatArtifact): string | undefined {\n if (!artifact.url) return undefined;\n try {\n const url = new URL(artifact.url);\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The extension a download in *format* is saved with. */\nexport function artifactFileExtension(format: string): string {\n return format === 'pptx_native' ? 'pptx' : format;\n}\n\n/** `m:ss`, the length of a video; `undefined` for nothing to show. */\nexport function formatVideoDuration(ms: number | undefined): string | undefined {\n if (!ms || ms <= 0) return undefined;\n const total = Math.round(ms / 1000);\n return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;\n}\n\n/**\n * The file name a `Content-Disposition` header names: the RFC 5987\n * `filename*=UTF-8''...` form first, else the quoted `filename=\"...\"`.\n */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | undefined {\n if (!header) return undefined;\n const extended = /filename\\*\\s*=\\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header);\n if (extended) {\n try {\n return decodeURIComponent(extended[1].trim().replace(/^\"|\"$/g, '')) || undefined;\n } catch {\n // A malformed escape: fall back to the plain name.\n }\n }\n const plain = /filename\\s*=\\s*(\"([^\"]*)\"|[^;]+)/.exec(header);\n const name = plain ? (plain[2] ?? plain[1]).trim() : '';\n return name || undefined;\n}\n","import type { ApiEndpoints, BackendType, ChatMessagePersistedFeedback, MessageFeedback } from '../types';\n\n/**\n * Persisted feedback on an assistant answer: the requests the thumbs send.\n * A stored rating is read back by `parsePersistedFeedback` with the rest of a\n * session restore (`hooks/protocols/parseRestEvent.ts`).\n *\n * Kept free of local runtime imports so `node --test` runs it as is.\n */\n\n/** Longest comment the feedback endpoint stores. */\nexport const FEEDBACK_COMMENT_MAX_LENGTH = 2000;\n\nexport type FeedbackRating = ChatMessagePersistedFeedback['rating'];\n\nexport const ratingOf = (value: MessageFeedback): FeedbackRating => (value === 'up' ? 'positive' : 'negative');\n\nexport const feedbackValueOf = (rating: FeedbackRating): MessageFeedback => (rating === 'positive' ? 'up' : 'down');\n\n/**\n * How the thumbs of one answer work, or null when it shows none:\n * - `persisted`: the panel stores the rating (`ApiEndpoints.feedback`), which\n * needs the conversation and the answer's persisted id - an answer the\n * backend did not identify cannot be rated;\n * - `callback`: the host stores it (`onMessageFeedback` alone).\n */\nexport type FeedbackMode = 'persisted' | 'callback';\n\nexport function feedbackModeOf(\n serverId: string | undefined,\n feedbackUrl: string | null | undefined,\n conversationId: string | null | undefined,\n hasCallback: boolean,\n): FeedbackMode | null {\n if (feedbackUrl) return conversationId && serverId ? 'persisted' : null;\n return hasCallback ? 'callback' : null;\n}\n\n/** The rating shown on an answer, and whether it can still be changed. */\nexport function shownFeedback(\n session: { value: MessageFeedback | null } | undefined,\n stored: ChatMessagePersistedFeedback | undefined,\n): { value: MessageFeedback | null; locked: boolean } {\n // Rated in this session: the session's answer wins, and can be changed.\n if (session) return { value: session.value, locked: false };\n // Rated before the conversation was reopened: shown, and final.\n if (stored) return { value: feedbackValueOf(stored.rating), locked: true };\n return { value: null, locked: false };\n}\n\n/** A comment as the endpoint stores it: trimmed, capped, and null when empty. */\nexport function normalizeFeedbackComment(comment: string | null | undefined): string | null {\n const trimmed = (comment ?? '').trim();\n return trimmed ? trimmed.slice(0, FEEDBACK_COMMENT_MAX_LENGTH) : null;\n}\n\n/**\n * `{apiBaseUrl}{feedback}`, or null when the panel does not store feedback\n * itself: the path is unset (no default, see `ApiEndpoints.feedback`), the\n * backend is not the REST one, or every request goes to one endpoint.\n */\nexport function feedbackBaseUrl(apiBaseUrl: string, apiEndpoints: ApiEndpoints | undefined, backendType: BackendType): string | null {\n if (backendType !== 'rest' || apiEndpoints?.singleEndpoint || !apiEndpoints?.feedback) return null;\n return `${apiBaseUrl}${apiEndpoints.feedback}`;\n}\n\n/**\n * The request that stores (`rating`) or retracts (`null`) the user's rating\n * of one message.\n */\nexport function feedbackRequest(\n baseUrl: string,\n conversationId: string,\n messageId: string,\n rating: { rating: FeedbackRating; comment: string | null } | null,\n requestHeaders?: Record<string, string>,\n): { url: string; init: RequestInit } {\n const url = `${baseUrl}/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(messageId)}/feedback`;\n if (!rating) {\n return { url, init: { method: 'DELETE', credentials: 'include', headers: { ...requestHeaders } } };\n }\n return {\n url,\n init: {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...requestHeaders },\n body: JSON.stringify({ rating: rating.rating, comment: normalizeFeedbackComment(rating.comment) }),\n },\n };\n}\n\n/** The part of `fetch` the feedback request needs. */\nexport type FeedbackFetch = (url: string, init: RequestInit) => Promise<{ ok: boolean }>;\n\n/**\n * Sends one `feedbackRequest` and says whether the backend stored it. A network\n * failure is a refusal like any other status: the caller rolls the thumbs back\n * either way.\n */\nexport async function submitFeedback(\n fetchImpl: FeedbackFetch,\n baseUrl: string,\n conversationId: string,\n messageId: string,\n rating: { rating: FeedbackRating; comment: string | null } | null,\n requestHeaders?: Record<string, string>,\n): Promise<boolean> {\n const { url, init } = feedbackRequest(baseUrl, conversationId, messageId, rating, requestHeaders);\n try {\n return (await fetchImpl(url, init)).ok;\n } catch {\n return false;\n }\n}\n","import type { ApiEndpoints, BackendType, ChatConversationRef, ChatConversationReferenceCandidate } from '../types';\n\n/**\n * The composer's `@` grammar, as in the XTM One web chat: only a pick from the\n * menu makes `@key` mean a conversation. No regex lookbehind (the bundle ships\n * untranspiled) and no local runtime imports (`node --test` runs it as is).\n */\n\n/** What one message references at most - the backend's own bound. */\nexport const MAX_REFERENCED_CONVERSATIONS = 5;\n\n/** How many conversations the menu lists. */\nexport const REFERENCE_MENU_LIMIT = 8;\n\n/** How long the typed text rests before the conversations are searched. */\nexport const REFERENCE_SEARCH_DEBOUNCE_MS = 150;\n\n/** A character a key is made of: what `[\\w-]` matches. */\nconst isKeyChar = (ch: string | undefined): boolean => ch !== undefined && /[\\w-]/.test(ch);\n\n/** A key the grammar reads back as one token. */\nconst KEY_RE = /^[\\w-]+$/;\n\n/** The `@` being typed: where it sits, and what follows it up to the caret. */\nexport interface ReferenceTrigger {\n /** Index of the `@` in the text. */\n anchor: number;\n query: string;\n}\n\n/**\n * The `@` token being typed before the caret, or null.\n *\n * The `@` must not follow a key character, so an email (`user@host`) never\n * opens the menu - the same rule as `referenceTokens`, so whatever opens the\n * menu also parses as a reference once inserted.\n */\nexport function referenceTrigger(textBeforeCaret: string): ReferenceTrigger | null {\n // Only the last `@` can match: nothing between it and the end may be anything\n // but key characters.\n const match = /@([\\w-]*)$/.exec(textBeforeCaret);\n if (!match || isKeyChar(textBeforeCaret[match.index - 1])) return null;\n return { anchor: match.index, query: match[1] };\n}\n\n/** The `@tokens` of *text*, lowercased, each once, in order of appearance. */\nexport function referenceTokens(text: string): string[] {\n const tokens: string[] = [];\n const re = /@([\\w-]+)/g;\n let match = re.exec(text);\n while (match !== null) {\n const key = match[1].toLowerCase();\n if (!isKeyChar(text[match.index - 1]) && !tokens.includes(key)) tokens.push(key);\n match = re.exec(text);\n }\n return tokens;\n}\n\n/**\n * *refs* without the picks whose `@key` *text* no longer holds - the same\n * array when nothing was dropped, so a state setter can bail out.\n */\nexport function pruneConversationRefs(refs: ChatConversationRef[], text: string): ChatConversationRef[] {\n if (refs.length === 0) return refs;\n const tokens = new Set(referenceTokens(text));\n const kept = refs.filter((r) => tokens.has(r.key.toLowerCase()));\n return kept.length === refs.length ? refs : kept;\n}\n\n/** *refs* plus *pick*, unless that conversation is already there. */\nexport function withConversationRef(refs: ChatConversationRef[], pick: ChatConversationRef): ChatConversationRef[] {\n return refs.some((r) => r.conversationId === pick.conversationId) ? refs : [...refs, pick];\n}\n\n/**\n * The conversations a message references: the picks whose `@key` it holds, in\n * the order the keys appear, each once, at most `MAX_REFERENCED_CONVERSATIONS`.\n */\nexport function referencedConversations(refs: ChatConversationRef[], text: string): ChatConversationRef[] {\n if (refs.length === 0) return [];\n const out: ChatConversationRef[] = [];\n for (const token of referenceTokens(text)) {\n for (const ref of refs) {\n if (ref.key.toLowerCase() !== token || out.some((r) => r.conversationId === ref.conversationId)) continue;\n out.push(ref);\n }\n }\n return out.slice(0, MAX_REFERENCED_CONVERSATIONS);\n}\n\n/**\n * *text* with the `@partial` of *trigger* replaced by `@<key> `, and where the\n * caret goes: after the space. A space already following it is reused rather\n * than doubled.\n */\nexport function insertConversationReference(text: string, trigger: ReferenceTrigger, key: string): { text: string; caret: number } {\n const before = text.slice(0, trigger.anchor);\n const after = text.slice(trigger.anchor + 1 + trigger.query.length);\n const token = `@${key}`;\n const space = /^\\s/.test(after) ? '' : ' ';\n return { text: `${before}${token}${space}${after}`, caret: before.length + token.length + 1 };\n}\n\n/**\n * Defensive parse of the menu's candidates (`{ conversations: [...] }` or a\n * bare array). An entry without an id, or whose key would not read back as\n * one `@token`, is skipped: inserting it would reference nothing.\n */\nexport function parseReferenceCandidates(data: unknown): ChatConversationReferenceCandidate[] {\n const list = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown> | null)?.conversations)\n ? ((data as Record<string, unknown>).conversations as unknown[])\n : [];\n const out: ChatConversationReferenceCandidate[] = [];\n for (const raw of list) {\n if (!raw || typeof raw !== 'object') continue;\n const c = raw as Record<string, unknown>;\n if (typeof c.id !== 'string' || !c.id || typeof c.key !== 'string' || !KEY_RE.test(c.key)) continue;\n if (out.some((o) => o.id === c.id)) continue;\n out.push({\n id: c.id,\n title: typeof c.title === 'string' ? c.title.trim() : '',\n key: c.key,\n updatedAt: typeof c.updated_at === 'string' ? c.updated_at : undefined,\n // Absent reads as the user's own: the hint is for a share, and a\n // backend that does not say has nothing to warn about.\n isOwn: c.is_own !== false,\n });\n }\n return out;\n}\n\n/**\n * The search URL of the menu, or null while the feature is off: the host did\n * not name the route, or the backend has no per-path routing.\n */\nexport function conversationReferencesUrl(apiBaseUrl: string, apiEndpoints: ApiEndpoints | undefined, backendType: BackendType): string | null {\n const path = apiEndpoints?.conversationReferences;\n if (backendType !== 'rest' || apiEndpoints?.singleEndpoint || typeof path !== 'string' || !path) return null;\n return `${apiBaseUrl}${path}`;\n}\n\n/** *url* with the menu's query: the typed text, the page size and the conversation written in. */\nexport function referenceSearchUrl(url: string, query: string, exclude?: string | null): string {\n const params = new URLSearchParams({ limit: String(REFERENCE_MENU_LIMIT) });\n if (query) params.set('q', query);\n if (exclude) params.set('exclude', exclude);\n return `${url}${url.includes('?') ? '&' : '?'}${params.toString()}`;\n}\n\n/** What the search last answered, and for which typed text. */\nexport interface ReferenceSearchState {\n query: string | null;\n items: ChatConversationReferenceCandidate[];\n /** The request failed: nothing is known, so nothing is shown. */\n failed: boolean;\n}\n\nexport const EMPTY_REFERENCE_SEARCH: ReferenceSearchState = { query: null, items: [], failed: false };\n\n/**\n * Whether *candidate* answers the typed *query*, by its key or by its title.\n * A title's spaces become hyphens in its key (`Hi Bob` is `@hi-bob`), so the\n * key typed back must also find it by the words of its title.\n */\nexport function referenceMatches(query: string, candidate: { key: string; title: string }): boolean {\n const q = query.toLowerCase();\n if (!q || candidate.key.toLowerCase().startsWith(q)) return true;\n const title = candidate.title.toLowerCase();\n const words = q.split(/[\\s_-]+/).filter(Boolean);\n return words.length > 0 && words.every((w) => title.includes(w));\n}\n\n/** How many conversations the menu remembers to match locally (`rememberCandidates`). */\nexport const REMEMBERED_CANDIDATES_LIMIT = 200;\n\nconst sameCandidate = (a: ChatConversationReferenceCandidate, b: ChatConversationReferenceCandidate) =>\n a.id === b.id && a.key === b.key && a.title === b.title && a.isOwn === b.isOwn && a.updatedAt === b.updatedAt;\n\n/**\n * *seen* with *items* added: the latest version of each conversation, most\n * recent last, at most `REMEMBERED_CANDIDATES_LIMIT`. *seen* itself when every\n * item is already there as is, so a state holding it does not re-render.\n */\nexport function rememberCandidates(\n seen: ChatConversationReferenceCandidate[],\n items: ChatConversationReferenceCandidate[],\n): ChatConversationReferenceCandidate[] {\n if (items.every((item) => seen.some((c) => sameCandidate(c, item)))) return seen;\n const ids = new Set(items.map((c) => c.id));\n const next = [...seen.filter((c) => !ids.has(c.id)), ...items];\n return next.length > REMEMBERED_CANDIDATES_LIMIT ? next.slice(next.length - REMEMBERED_CANDIDATES_LIMIT) : next;\n}\n\n/**\n * *seen* after a search answer: the rows a settled answer should have listed\n * and did not are forgotten (deleted or unshared since), then its rows are\n * remembered. An absence is proven only under the narrowest contract every\n * backend keeps - the title contains `q` as typed - and by a complete answer\n * (under a page): a backend that does not match by key yet answers `hi-bob`\n * with nothing, and \"Hi Bob\" must stay. The conversation written in is\n * excluded by the request, not gone.\n */\nexport function rememberAnswer(\n seen: ChatConversationReferenceCandidate[],\n search: ReferenceSearchState,\n exclude?: string | null,\n): ChatConversationReferenceCandidate[] {\n if (search.query === null || search.failed) return seen;\n const query = search.query;\n const listed = new Set(search.items.map((c) => c.id));\n const complete = search.items.length < REFERENCE_MENU_LIMIT;\n const q = query.toLowerCase();\n const kept = complete ? seen.filter((c) => c.id === exclude || listed.has(c.id) || !c.title.toLowerCase().includes(q)) : seen;\n return rememberCandidates(kept.length === seen.length ? seen : kept, search.items);\n}\n\n/** A pick of the draft as a menu row; a pick that does not say whose it is reads as the user's own. */\nexport function refAsCandidate(ref: ChatConversationRef): ChatConversationReferenceCandidate {\n return { id: ref.conversationId, title: ref.title, key: ref.key, isOwn: ref.isOwn ?? true };\n}\n\n/** What the menu shows. */\nexport type ReferenceMenuView =\n | { kind: 'closed' }\n | { kind: 'results'; items: ChatConversationReferenceCandidate[] }\n /** A typed query nothing matches. */\n | { kind: 'empty' }\n /** The message already references as many conversations as it may. */\n | { kind: 'full' };\n\n/**\n * The menu for the `@` being typed.\n *\n * The previous answer stays on screen while the next one loads, so typing\n * never empties the menu; \"no match\" is said only once the backend answered\n * the very text typed, and only for a text: an empty `@` with nothing to offer\n * is simply no menu.\n */\nexport function referenceMenuView(options: {\n trigger: ReferenceTrigger | null;\n dismissed: boolean;\n search: ReferenceSearchState;\n /** How many conversations the text already references. */\n referenced: number;\n /** The conversation written in, never offered. */\n exclude?: string | null;\n /**\n * The conversations already met (the menu's past answers, the draft's\n * picks), matched here by key or title after the search's own answer: an\n * edited `@hi-bob`, or one a keystroke broke, still finds \"Hi Bob\" whatever\n * the search answered.\n */\n known?: ChatConversationReferenceCandidate[];\n}): ReferenceMenuView {\n const { trigger, dismissed, search, referenced, exclude, known = [] } = options;\n if (!trigger || dismissed) return { kind: 'closed' };\n if (referenced >= MAX_REFERENCED_CONVERSATIONS) return { kind: 'full' };\n if (search.failed) return { kind: 'closed' };\n const local = trigger.query ? known.filter((c) => referenceMatches(trigger.query, c) && !search.items.some((s) => s.id === c.id)) : [];\n const merged = [...search.items, ...local].slice(0, REFERENCE_MENU_LIMIT);\n const items = exclude ? merged.filter((c) => c.id !== exclude) : merged;\n if (items.length > 0) return { kind: 'results', items };\n if (trigger.query && search.query === trigger.query) return { kind: 'empty' };\n return { kind: 'closed' };\n}\n","import type { ChatConversationSummary, ChatWorkspace } from '../types';\n\n/**\n * The conversation list grouped by workspace, by the XTM One web sidebar's\n * rule so both surfaces show the same groups. No local runtime imports, so\n * `node --test` runs it as is.\n */\n\nexport const ELSEWHERE_GROUP = '__elsewhere__';\n\nexport interface WorkspaceGroup {\n /** `null` for the `elsewhere` group. */\n workspace: ChatWorkspace | null;\n key: string;\n conversations: ChatConversationSummary[];\n}\n\n/** Defensive parse of the workspace list: entries without an id or a name are skipped. */\nexport function parseWorkspaces(data: unknown): ChatWorkspace[] {\n const list = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown> | null)?.workspaces)\n ? ((data as Record<string, unknown>).workspaces as unknown[])\n : [];\n const out: ChatWorkspace[] = [];\n for (const raw of list) {\n if (!raw || typeof raw !== 'object') continue;\n const w = raw as Record<string, unknown>;\n if (typeof w.id !== 'string' || !w.id || typeof w.name !== 'string') continue;\n // An archived workspace takes no conversation; the backend already leaves\n // it out, and a proxy that did not would offer a choice that can only fail.\n if (w.is_archived === true) continue;\n out.push({\n id: w.id,\n name: w.name,\n isOwn: w.is_own === true,\n isDefault: w.is_default === true,\n canManage: w.can_manage === true,\n });\n }\n return out;\n}\n\n/** The caller's own default first, then by name. */\nexport function sortWorkspaces(workspaces: ChatWorkspace[]): ChatWorkspace[] {\n const mine = (w: ChatWorkspace) => w.isDefault && w.isOwn;\n return [...workspaces].sort((a, b) => {\n if (mine(a) !== mine(b)) return mine(a) ? -1 : 1;\n return a.name.localeCompare(b.name);\n });\n}\n\n/**\n * Whether a failed read of the workspace list is a passing one (a timeout, a\n * rate limit, a server error) that keeps the last list, rather than a refusal\n * (not licensed, an older proxy) that turns the grouping off.\n */\nexport function isTransientListFailure(status: number): boolean {\n return status === 408 || status === 429 || (status >= 500 && status !== 501);\n}\n\n/** Whether moving *conversationId* to *destination* would change nothing (it is already there). */\nexport function isNoopMove(\n conversations: Pick<ChatConversationSummary, 'conversationId' | 'workspaceId'>[],\n conversationId: string,\n destination: string | null,\n): boolean {\n const current = conversations.find((c) => c.conversationId === conversationId);\n return !!current && (current.workspaceId ?? null) === destination;\n}\n\n/**\n * Whether the next conversation can still be created in *pendingId*: the list\n * read last offers it to file into. One deleted, archived or unshared since\n * (from another tab, the web chat) is not, and the session request must not\n * name it.\n */\nexport function pendingWorkspaceStillFileable(pendingId: string, workspaces: ChatWorkspace[]): boolean {\n return workspaces.some((w) => w.id === pendingId && w.canManage);\n}\n\n/** The shortest gap between two re-reads on a return to the page (`focus` and `visibilitychange` both fire). */\nexport const RETURN_REFRESH_MIN_GAP_MS = 2000;\n\n/** Whether a return to the page re-reads the lists: once per return, not once per event. */\nexport function returnRefreshDue(now: number, last: number | null): boolean {\n return last === null || now - last >= RETURN_REFRESH_MIN_GAP_MS;\n}\n\n/** The workspaces a conversation can be moved into, in the order the list shows them. */\nexport function fileableWorkspaces(workspaces: ChatWorkspace[]): ChatWorkspace[] {\n return sortWorkspaces(workspaces.filter((w) => w.canManage));\n}\n\nexport function groupConversations(\n conversations: ChatConversationSummary[],\n workspaces: ChatWorkspace[],\n options: { matches?: (c: ChatConversationSummary) => boolean } = {},\n): { groups: WorkspaceGroup[]; unfiled: ChatConversationSummary[] } {\n const { matches } = options;\n const shown = matches ? conversations.filter(matches) : conversations;\n const known = new Set(workspaces.map((w) => w.id));\n const held = new Set(conversations.map((c) => c.workspaceId).filter((id): id is string => !!id));\n\n const byWorkspace = new Map<string, ChatConversationSummary[]>();\n const elsewhere: ChatConversationSummary[] = [];\n const unfiled: ChatConversationSummary[] = [];\n for (const c of shown) {\n const id = c.workspaceId ?? null;\n if (!id) unfiled.push(c);\n else if (known.has(id)) byWorkspace.set(id, [...(byWorkspace.get(id) ?? []), c]);\n else elsewhere.push(c);\n }\n\n const groups: WorkspaceGroup[] = [];\n for (const workspace of sortWorkspaces(workspaces)) {\n const inside = byWorkspace.get(workspace.id) ?? [];\n if (!workspace.canManage && !held.has(workspace.id)) continue;\n if (matches && inside.length === 0) continue;\n groups.push({ workspace, key: workspace.id, conversations: inside });\n }\n if (elsewhere.length > 0) groups.push({ workspace: null, key: ELSEWHERE_GROUP, conversations: elsewhere });\n return { groups, unfiled };\n}\n\n/**\n * Whether a group shows its conversations: not when collapsed, unless it holds\n * the conversation on screen, and always while searching. A group shown open\n * for either reason cannot be toggled (`groupCanToggle`).\n */\nexport function groupIsOpen(\n key: string,\n collapsed: ReadonlySet<string>,\n group: { conversations: ChatConversationSummary[] },\n activeConversationId: string | null,\n searching: boolean,\n): boolean {\n if (searching) return true;\n if (activeConversationId && group.conversations.some((c) => c.conversationId === activeConversationId)) return true;\n return !collapsed.has(key);\n}\n\n/**\n * Whether a group's toggle may fold it: not while it is held open by a search\n * or by the conversation on screen, where a click would flip a remembered\n * state nobody sees, which then folds the group later.\n */\nexport function groupCanToggle(\n group: { conversations: ChatConversationSummary[] },\n activeConversationId: string | null,\n searching: boolean,\n): boolean {\n if (searching) return false;\n return !(activeConversationId && group.conversations.some((c) => c.conversationId === activeConversationId));\n}\n\n/**\n * Undo one refused move in the conversation list: the conversation goes back\n * to where it was, and only while it is still where this move put it - once a\n * later move or a refresh has placed it, that placement stands. Every other\n * row is kept as the list holds it now, not as it was when the move started.\n */\nexport function revertMove<T extends Pick<ChatConversationSummary, 'conversationId' | 'workspaceId'>>(\n list: T[],\n conversationId: string,\n destination: string | null,\n previous: string | null | undefined,\n): T[] {\n const index = list.findIndex((c) => c.conversationId === conversationId);\n if (index < 0 || (list[index].workspaceId ?? null) !== destination) return list;\n const next = [...list];\n next[index] = { ...list[index], workspaceId: previous };\n return next;\n}\n\n/**\n * What an empty \"Not in a workspace\" group says: that there is no\n * conversation at all, that every one is filed, or nothing. Nothing while\n * searching: the group then holds matches only, and a search that matches\n * nothing has its own message.\n */\nexport function unfiledEmptyNote(options: { total: number; unfiled: number; loading: boolean; searching: boolean }): 'none' | 'all-filed' | null {\n const { total, unfiled, loading, searching } = options;\n if (unfiled > 0 || loading || searching) return null;\n return total === 0 ? 'none' : 'all-filed';\n}\n\n/** The message of a refused workspace request, from XTM One's `detail`. */\nexport async function refusalMessage(res: Response): Promise<string | null> {\n try {\n const body: unknown = await res.json();\n const detail = (body as Record<string, unknown> | null)?.detail;\n return typeof detail === 'string' && detail ? detail : null;\n } catch {\n return null;\n }\n}\n","import type {\n ChatArtifact,\n ChatArtifactKind,\n ChatAttachment,\n ChatContextBreakdown,\n ChatContextUsage,\n ChatConversationRef,\n ChatMessage,\n ChatMessagePersistedFeedback,\n ToolApprovalProposal,\n ToolCallTraceEntry,\n TransferChainEntry,\n} from '../../types';\nimport type { PageAction } from '../../utils/pageActions';\nimport type { ParsedAction, ProtocolContext } from './types';\n\n/** Wire key → the breakdown field it populates. */\nconst BREAKDOWN_KEYS: ReadonlyArray<[string, keyof ChatContextBreakdown]> = [\n ['system', 'system'],\n ['tools', 'tools'],\n ['dynamic_tools', 'dynamicTools'],\n ['summary', 'summary'],\n ['conversation', 'conversation'],\n ['tool_results', 'toolResults'],\n];\n\n/**\n * Normalize the optional `context_breakdown` object.\n *\n * Only positive numbers for keys we know how to label survive: an unlabelled\n * bucket cannot be rendered, and a zero one is noise in a list meant to show\n * where the context actually went. Returns `undefined` when nothing usable is\n * left, so the gauge keeps its number and simply has no detail to open.\n */\nfunction parseBreakdown(raw: unknown): ChatContextBreakdown | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const src = raw as Record<string, unknown>;\n const out: ChatContextBreakdown = {};\n let any = false;\n for (const [wireKey, field] of BREAKDOWN_KEYS) {\n const value = src[wireKey];\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) {\n out[field] = value;\n any = true;\n }\n }\n return any ? out : undefined;\n}\n\n/**\n * Read the context-window occupancy carried by a progress or `done` frame.\n *\n * Both halves are required and the window must be positive: a token count with\n * no window to measure it against is not a ratio, and a zero window would make\n * one out of a division by zero. Returns `undefined` for anything else, so a\n * backend that reports nothing simply leaves the gauge as it was.\n */\nexport function parseContextUsage(evt: Record<string, unknown>): ChatContextUsage | undefined {\n const used = evt.context_tokens;\n const limit = evt.context_window;\n if (typeof used !== 'number' || typeof limit !== 'number') return undefined;\n if (!Number.isFinite(used) || !Number.isFinite(limit) || limit <= 0 || used < 0) return undefined;\n const breakdown = parseBreakdown(evt.context_breakdown);\n return breakdown ? { used, limit, breakdown } : { used, limit };\n}\n\n/**\n * Normalize the raw `attachments` array from a backend `done` event into\n * typed {@link ChatAttachment} objects. Defensive: skips non-object entries\n * and entries without a `file_id`. Returns `undefined` when there is nothing\n * renderable so the `done` action stays lean for backends without #810.\n */\nexport function parseAttachments(raw: unknown): ChatAttachment[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ChatAttachment[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const a = item as Record<string, unknown>;\n const fileId = a.file_id;\n if (typeof fileId !== 'string' || !fileId) continue;\n out.push({\n fileId,\n filename: typeof a.filename === 'string' ? a.filename : 'file',\n type: typeof a.type === 'string' ? a.type : undefined,\n size: typeof a.size === 'number' ? a.size : undefined,\n contentType: typeof a.content_type === 'string' ? a.content_type : undefined,\n fileTag: a.file_tag === 'working_file' ? 'working_file' : 'download_file',\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\nconst ARTIFACT_KINDS: readonly ChatArtifactKind[] = ['presentation', 'report', 'video'];\n\nconst countOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined);\n\n/**\n * Normalize one artifact descriptor (`artifacts` entry, or the answer of\n * `GET {artifacts}/{kind}/{id}`). `undefined` without a known kind and an id:\n * a card it could not address would offer actions that go nowhere.\n */\nexport function parseArtifact(raw: unknown): ChatArtifact | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const a = raw as Record<string, unknown>;\n const kind = ARTIFACT_KINDS.find((k) => k === a.kind);\n if (!kind || typeof a.id !== 'string' || !a.id) return undefined;\n return {\n kind,\n id: a.id,\n title: typeof a.title === 'string' ? a.title : '',\n url: typeof a.url === 'string' && a.url ? a.url : undefined,\n slideRef: typeof a.slide_ref === 'string' && a.slide_ref ? a.slide_ref : undefined,\n slideCount: countOf(a.slide_count),\n sectionCount: countOf(a.section_count),\n sceneCount: countOf(a.scene_count),\n durationMs: countOf(a.duration_ms),\n status: typeof a.status === 'string' && a.status ? a.status : undefined,\n progress: countOf(a.progress),\n downloads: Array.isArray(a.downloads) ? a.downloads.filter((f): f is string => typeof f === 'string' && !!f) : [],\n };\n}\n\n/** Normalize the `artifacts` of a `done` event or a restored answer; `undefined` when nothing is usable. */\nexport function parseArtifacts(raw: unknown): ChatArtifact[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out = raw.map(parseArtifact).filter((a): a is ChatArtifact => !!a);\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the raw `tool_call_trace` array (from a `done` event or restored\n * session metadata) into typed {@link ToolCallTraceEntry} objects. Defensive:\n * skips entries without a `name`. Returns `undefined` when empty so the\n * reasoning-details dialog falls back to the flat tool-name list.\n */\nexport function parseToolCallTrace(raw: unknown): ToolCallTraceEntry[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ToolCallTraceEntry[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const e = item as Record<string, unknown>;\n if (typeof e.name !== 'string' || !e.name) continue;\n out.push({\n name: e.name,\n input: typeof e.input === 'string' ? e.input : undefined,\n output: typeof e.output === 'string' ? e.output : undefined,\n // Only a boolean is honored; a missing/malformed value defaults to\n // success so unknown states never render a false failure icon.\n success: typeof e.success === 'boolean' ? e.success : true,\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the `conversation_refs` of a restored user message: the\n * conversations it referenced with `@`, as the backend recorded them. An entry\n * without a conversation id is skipped; `undefined` when nothing is left.\n */\nexport function parseConversationRefs(raw: unknown): ChatConversationRef[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ChatConversationRef[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n if (typeof r.conversation_id !== 'string' || !r.conversation_id) continue;\n if (out.some((o) => o.conversationId === r.conversation_id)) continue;\n out.push({\n conversationId: r.conversation_id,\n title: typeof r.title === 'string' ? r.title.trim() : '',\n key: typeof r.key === 'string' ? r.key : '',\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the raw `transfer_chain` array (from a `done` event or restored\n * session metadata) into typed {@link TransferChainEntry} objects.\n */\nexport function parseTransferChain(raw: unknown): TransferChainEntry[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: TransferChainEntry[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const e = item as Record<string, unknown>;\n if (typeof e.agent_name !== 'string' || !e.agent_name) continue;\n out.push({\n agentId: typeof e.agent_id === 'string' ? e.agent_id : '',\n agentName: e.agent_name,\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Normalize the `proposals` array of an `approval_required` event.\n *\n * Only `tool_call_id` is load-bearing — it is what a decision is keyed on, so\n * an entry without one could never be answered and is dropped. Everything else\n * degrades: a proposal with no name still renders under a placeholder rather\n * than vanishing, because a call silently hidden from the reviewer is a call\n * that stalls the turn with nothing on screen to explain it.\n *\n * Returns `undefined` when nothing decidable is left, so the consumer can treat\n * an unusable pause as one it must not claim to have prompted for.\n */\nexport function parseToolApprovalProposals(raw: unknown): ToolApprovalProposal[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: ToolApprovalProposal[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const p = item as Record<string, unknown>;\n const toolCallId = p.tool_call_id;\n if (typeof toolCallId !== 'string' || !toolCallId) continue;\n const args = p.arguments;\n const schema = p.input_schema;\n out.push({\n toolCallId,\n // Left empty for the UI to label: a parser has no `t`, and a placeholder\n // baked in here would reach the reviewer untranslated.\n toolName: typeof p.tool_name === 'string' && p.tool_name ? p.tool_name : '',\n toolDescription: typeof p.tool_description === 'string' ? p.tool_description : undefined,\n arguments: args && typeof args === 'object' && !Array.isArray(args) ? (args as Record<string, unknown>) : {},\n inputSchema: schema && typeof schema === 'object' && !Array.isArray(schema) ? (schema as Record<string, unknown>) : undefined,\n source: typeof p.source === 'string' ? p.source : undefined,\n });\n }\n return out.length > 0 ? out : undefined;\n}\n\n/** The page action of an `act_on_page` frame; anything unreadable becomes `unsupported`, never nothing. */\nfunction parsePageAction(raw: unknown): PageAction {\n if (!raw || typeof raw !== 'object') return { type: 'unsupported', requested: 'malformed' };\n const a = raw as Record<string, unknown>;\n const str = (v: unknown) => typeof v === 'string' && v.length > 0;\n if (a.type === 'snapshot') return { type: 'snapshot' };\n if (a.type === 'navigate' && str(a.path)) return { type: 'navigate', path: a.path as string };\n if (a.type === 'click' && str(a.ref)) return { type: 'click', ref: a.ref as string };\n if (a.type === 'open' && str(a.ref)) return { type: 'open', ref: a.ref as string };\n if (a.type === 'type' && str(a.ref) && typeof a.text === 'string') {\n return { type: 'type', ref: a.ref as string, text: a.text };\n }\n // Answered, not dropped: the backend holds the turn open until the action\n // comes back, so an unknown shape would stall until its timeout.\n return { type: 'unsupported', requested: typeof a.type === 'string' ? a.type.slice(0, 64) : 'unknown' };\n}\n\n/**\n * Parse an XTM One (REST) SSE event into a normalized action.\n */\nexport function parseRestEvent(evt: Record<string, unknown>, ctx: ProtocolContext): ParsedAction {\n const type = evt.type as string | undefined;\n\n if (type === 'error') {\n return { action: 'error', content: (evt.content as string) || '' };\n }\n\n if (type === 'status') {\n const st = evt.status as string;\n if (st === 'tool_done' || st === 'wind_down') {\n return { action: 'noop' };\n }\n if (st === 'streaming') {\n return { action: 'status', status: 'streaming' };\n }\n if (st === 'thinking_text') {\n return { action: 'status', status: 'thinking_text', thinkingContent: evt.content as string };\n }\n if (st === 'tool_start') {\n ctx.hasUsedTools = true;\n return { action: 'status', status: 'tool_start', tools: evt.tools as string[] | undefined };\n }\n if (st === 'tool_progress' && evt.event === 'page_action_required') {\n // Without an action_id there is nothing to answer against, so that frame\n // alone is dropped; every other shape is answered.\n if (typeof evt.action_id !== 'string' || !evt.action_id) return { action: 'noop' };\n const pageAction = parsePageAction(evt.action);\n return {\n action: 'page_action_required',\n actionId: evt.action_id,\n pageAction,\n conversationId: typeof evt.conversation_id === 'string' ? evt.conversation_id : undefined,\n };\n }\n if (st === 'tool_heartbeat') {\n // Liveness signal during a long tool execution (background tasks,\n // consults, big integration calls): carries the elapsed seconds but\n // no new semantic state — the consumer must keep its current label.\n return {\n action: 'status',\n status: 'tool_heartbeat',\n tools: evt.tools as string[] | undefined,\n elapsedS: typeof evt.elapsed_s === 'number' ? evt.elapsed_s : undefined,\n };\n }\n // Context occupancy rides on the per-iteration `thinking` frame, so the\n // gauge climbs during a long turn. Read before the `analyzing` relabel\n // below, which rewrites the status but not what the frame carries.\n const contextUsage = parseContextUsage(evt);\n if (st === 'thinking' && ctx.hasUsedTools) {\n return { action: 'status', status: 'analyzing', contextUsage };\n }\n return { action: 'status', status: st, tools: evt.tools as string[] | undefined, contextUsage };\n }\n\n // The turn has paused on a gated tool call. Deliberately NOT terminal: the\n // stream stays open (kept warm by SSE `: keepalive` comment lines, which the\n // reader below drops as non-`data:` lines) and the rest of the turn arrives\n // on it once a decision is POSTed back.\n if (type === 'approval_required') {\n const proposals = parseToolApprovalProposals(evt.proposals);\n if (!proposals) return { action: 'noop' };\n return {\n action: 'approval_required',\n proposals,\n conversationId: typeof evt.conversation_id === 'string' ? evt.conversation_id : undefined,\n };\n }\n\n if (type === 'stream') {\n return { action: 'stream', content: evt.content as string };\n }\n\n if (type === 'done') {\n return {\n action: 'done',\n content: evt.content as string,\n conversationId: evt.conversation_id as string | undefined,\n toolNames: evt.tool_names as string[] | undefined,\n toolCallCount: evt.tool_call_count as number | undefined,\n iterations: evt.iterations as number | undefined,\n transferAgentId: evt.transfer_agent_id as string | undefined,\n transferAgentName: evt.transfer_agent_name as string | undefined,\n attachments: parseAttachments(evt.attachments),\n artifacts: parseArtifacts(evt.artifacts),\n reasoning: typeof evt.reasoning === 'string' ? evt.reasoning : undefined,\n toolCallTrace: parseToolCallTrace(evt.tool_call_trace),\n transferChain: parseTransferChain(evt.transfer_chain),\n isTruncated: evt.is_truncated === true || undefined,\n contextUsage: parseContextUsage(evt),\n messageId: typeof evt.message_id === 'string' && evt.message_id ? evt.message_id : undefined,\n };\n }\n\n return { action: 'noop' };\n}\n\n/** The `feedback` of a restored entry, or undefined for anything that is not a stored rating. */\nexport function parsePersistedFeedback(raw: unknown): ChatMessagePersistedFeedback | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const { rating, comment } = raw as { rating?: unknown; comment?: unknown };\n if (rating !== 'positive' && rating !== 'negative') return undefined;\n return { rating, comment: typeof comment === 'string' && comment.trim() ? comment : null };\n}\n\n/**\n * The messages of a session restore (`POST {sessions}` with a known\n * `conversation_id`), in order.\n *\n * Rows are keyed `restored-<index>`: the key only has to be stable for the\n * life of the transcript, and a restore replaces the transcript whole. The\n * entry's own `id` is the message's persisted id, kept as `serverId` for what\n * is stored against it (feedback); its `created_at` is when it was sent, and\n * a backend that sends neither still restores - with no time to show\n * (`timestampUnknown`) rather than the time of the restore.\n * Entries that are not a user or an assistant message are skipped.\n */\nexport function parseRestoredMessages(raw: unknown): ChatMessage[] {\n if (!Array.isArray(raw)) return [];\n const out: ChatMessage[] = [];\n raw.forEach((item: unknown, i: number) => {\n if (!item || typeof item !== 'object') return;\n const m = item as Record<string, unknown>;\n if (m.role !== 'user' && m.role !== 'assistant') return;\n const createdAt = typeof m.created_at === 'string' ? new Date(m.created_at) : null;\n const sentAt = createdAt && !Number.isNaN(createdAt.getTime()) ? createdAt : null;\n out.push({\n id: `restored-${i}`,\n serverId: typeof m.id === 'string' && m.id ? m.id : undefined,\n role: m.role,\n content: typeof m.content === 'string' ? m.content : '',\n timestamp: sentAt ?? new Date(),\n timestampUnknown: sentAt ? undefined : true,\n feedback: m.role === 'assistant' ? parsePersistedFeedback(m.feedback) : undefined,\n // Per-message attribution when the backend keeps it — the only way a\n // thread that changed hands mid-way reads correctly. Nothing records it\n // today, so this is normally undefined and the conversation's agent\n // applies to the whole thread.\n agentName: typeof m.agent_name === 'string' ? m.agent_name : undefined,\n // Downloadable file chips on both roles: agent-generated deliverables on\n // assistant messages (their [[FILE:…]] markers are stripped at render\n // time) and user uploads, so an upload stays downloadable after a reload\n // and not only in the live session where it is carried on `files`.\n attachments: parseAttachments(m.attachments),\n // The decks, reports and videos an answer made, as cards where their markers stand.\n artifacts: m.role === 'assistant' ? parseArtifacts(m.artifacts) : undefined,\n // The conversations a user message referenced with `@`, shown as chips.\n conversationRefs: m.role === 'user' ? parseConversationRefs(m.conversation_refs) : undefined,\n // The reasoning-details affordance, from the same fields the live `done`\n // event carries.\n toolNames: Array.isArray(m.tool_names) ? (m.tool_names as string[]) : undefined,\n toolCallCount: typeof m.tool_call_count === 'number' ? m.tool_call_count : undefined,\n iterations: typeof m.iterations === 'number' ? m.iterations : undefined,\n reasoning: typeof m.reasoning === 'string' ? m.reasoning : undefined,\n toolCallTrace: parseToolCallTrace(m.tool_call_trace),\n transferChain: parseTransferChain(m.transfer_chain),\n isTruncated: m.is_truncated === true || undefined,\n });\n });\n return out;\n}\n","import type { ParsedAction, ProtocolContext } from './types';\n\n/**\n * Parse a Flowise-style SSE event into a normalized action.\n */\nexport function parseLegacyEvent(evt: Record<string, unknown>, ctx: ProtocolContext): ParsedAction {\n const eventType = evt.event as string | undefined;\n\n if (eventType === 'nextAgentFlow') {\n const data = evt.data as Record<string, unknown> | undefined;\n const nodeId = data?.nodeId as string | undefined;\n if (data?.status === 'INPROGRESS' && nodeId) {\n ctx.activeNodeId = nodeId;\n }\n return { action: 'noop' };\n }\n\n if (eventType === 'start') {\n return { action: 'noop' };\n }\n\n if (eventType === 'token') {\n const tokenData = ((evt.data as string) ?? '').replace(/<br\\s*\\/?>/g, '\\n');\n return { action: 'stream', content: tokenData };\n }\n\n if (eventType === 'agentReasoning') {\n const reasoning = evt.data as Record<string, unknown> | undefined;\n const usedTools = reasoning?.usedTools as Array<{ tool: string }> | undefined;\n if (usedTools?.length) {\n ctx.hasUsedTools = true;\n return { action: 'status', status: 'tool_start', tools: usedTools.map((t) => t.tool) };\n }\n if (ctx.hasUsedTools) {\n return { action: 'status', status: 'analyzing' };\n }\n return { action: 'status', status: 'thinking' };\n }\n\n if (eventType === 'usedTools') {\n ctx.hasUsedTools = true;\n const data = evt.data as Array<{ tool: string }> | undefined;\n const toolNames = Array.isArray(data) ? data.map((t) => t.tool) : [];\n return { action: 'status', status: 'tool_start', tools: toolNames };\n }\n\n if (eventType === 'metadata') {\n const data = evt.data as Record<string, unknown> | undefined;\n const chatId = data?.chatId as string | undefined;\n if (chatId) {\n return { action: 'set_chat_id', chatId };\n }\n return { action: 'noop' };\n }\n\n if (eventType === 'error') {\n return { action: 'error', content: (evt.data as string) || '' };\n }\n\n if (eventType === 'end') {\n return { action: 'done', content: '' };\n }\n\n return { action: 'noop' };\n}\n","import type { ParsedAction, ProtocolContext } from './types';\n\n/**\n * AG-UI protocol event types.\n * @see https://github.com/ag-ui-protocol/ag-ui\n */\n\n/**\n * Parse an AG-UI protocol SSE event into a normalized action.\n *\n * AG-UI uses a Start/Content/End lifecycle for messages and tool calls.\n * We map these to the same internal actions used by the other protocols.\n */\nexport function parseAgUiEvent(evt: Record<string, unknown>, ctx: ProtocolContext): ParsedAction {\n const type = evt.type as string | undefined;\n\n // --- Run lifecycle ---\n\n if (type === 'RUN_STARTED') {\n return { action: 'status', status: 'thinking' };\n }\n\n if (type === 'RUN_FINISHED') {\n return { action: 'done', content: '' };\n }\n\n if (type === 'RUN_ERROR') {\n // Empty rather than a literal English fallback: the content is rendered as\n // the assistant's message, and the consumer supplies its own translated\n // text when the backend sends none — as the other protocols already do.\n return { action: 'error', content: typeof evt.message === 'string' ? evt.message : '' };\n }\n\n // --- Step lifecycle ---\n\n if (type === 'STEP_STARTED') {\n const stepName = evt.stepName as string | undefined;\n return { action: 'status', status: stepName || 'thinking' };\n }\n\n if (type === 'STEP_FINISHED') {\n return { action: 'noop' };\n }\n\n // --- Text message streaming ---\n\n if (type === 'TEXT_MESSAGE_START') {\n return { action: 'status', status: 'streaming' };\n }\n\n if (type === 'TEXT_MESSAGE_CONTENT') {\n const delta = evt.delta as string;\n if (delta) {\n return { action: 'stream', content: delta };\n }\n return { action: 'noop' };\n }\n\n if (type === 'TEXT_MESSAGE_END') {\n return { action: 'noop' };\n }\n\n // TEXT_MESSAGE_CHUNK is a convenience event that combines Start+Content+End\n if (type === 'TEXT_MESSAGE_CHUNK') {\n const delta = evt.delta as string | undefined;\n if (delta) {\n return { action: 'stream', content: delta };\n }\n return { action: 'noop' };\n }\n\n // --- Tool call lifecycle ---\n\n if (type === 'TOOL_CALL_START') {\n ctx.hasUsedTools = true;\n const toolName = evt.toolCallName as string | undefined;\n return { action: 'status', status: 'tool_start', tools: toolName ? [toolName] : [] };\n }\n\n if (type === 'TOOL_CALL_ARGS') {\n // Tool arguments streaming — no UI equivalent, skip\n return { action: 'noop' };\n }\n\n if (type === 'TOOL_CALL_END') {\n return { action: 'status', status: 'analyzing' };\n }\n\n if (type === 'TOOL_CALL_RESULT') {\n // Tool result — no direct UI mapping, skip\n return { action: 'noop' };\n }\n\n if (type === 'TOOL_CALL_CHUNK') {\n // Convenience form — treat like TOOL_CALL_START if it has a name\n const toolName = evt.toolCallName as string | undefined;\n if (toolName) {\n ctx.hasUsedTools = true;\n return { action: 'status', status: 'tool_start', tools: [toolName] };\n }\n return { action: 'noop' };\n }\n\n // --- Reasoning / thinking ---\n\n if (type === 'REASONING_START' || type === 'REASONING_MESSAGE_START') {\n return { action: 'status', status: 'thinking' };\n }\n\n if (type === 'REASONING_MESSAGE_CONTENT' || type === 'REASONING_MESSAGE_CHUNK') {\n // Reasoning text — surface it in the dedicated thinking pane\n const delta = evt.delta as string | undefined;\n if (delta) {\n return { action: 'status', status: 'thinking_text', thinkingContent: delta };\n }\n return { action: 'status', status: 'thinking' };\n }\n\n if (type === 'REASONING_MESSAGE_END' || type === 'REASONING_END' || type === 'REASONING_ENCRYPTED_VALUE') {\n return { action: 'noop' };\n }\n\n // --- State management ---\n\n if (type === 'STATE_SNAPSHOT' || type === 'STATE_DELTA' || type === 'MESSAGES_SNAPSHOT') {\n // State sync — not mapped to chat UI currently\n return { action: 'noop' };\n }\n\n // --- Activity events ---\n\n if (type === 'ACTIVITY_SNAPSHOT' || type === 'ACTIVITY_DELTA') {\n return { action: 'noop' };\n }\n\n // --- Pass-through / custom ---\n\n if (type === 'RAW' || type === 'CUSTOM') {\n return { action: 'noop' };\n }\n\n return { action: 'noop' };\n}\n","/**\n * The one session request of the chat on screen. A new chat abandons it: the\n * request is aborted, and `isCurrent()` turns false so a late answer touches\n * nothing. No local runtime imports, so `node --test` runs it as is.\n */\nexport interface SessionGate {\n /** Which chat is on screen; compare two readings to tell whether it changed. */\n readonly generation: number;\n /** The session request in flight for the chat on screen, if any. */\n readonly pending: Promise<string | null> | null;\n /**\n * Join the chat's request, or start it. A request that fails resolves to\n * `null`, like one abandoned.\n */\n run(request: (isCurrent: () => boolean, signal: AbortSignal) => Promise<string | null>): Promise<string | null>;\n /** A new chat: the request in flight, if any, is aborted and no longer its. */\n abandon(): void;\n}\n\nexport function createSessionGate(): SessionGate {\n let generation = 0;\n let pending: Promise<string | null> | null = null;\n let controller: AbortController | null = null;\n return {\n get generation() {\n return generation;\n },\n get pending() {\n return pending;\n },\n run(request) {\n if (pending) return pending;\n const started = generation;\n const own = new AbortController();\n controller = own;\n const promise = request(() => started === generation, own.signal).catch(() => null);\n pending = promise;\n // Released once settled, and only while it is still this request's:\n // after a new chat the next request may hold it already.\n void promise.finally(() => {\n if (pending === promise) pending = null;\n if (controller === own) controller = null;\n });\n return promise;\n },\n abandon() {\n generation += 1;\n pending = null;\n // The backend would otherwise still create the abandoned conversation,\n // filed in the workspace it was started in.\n controller?.abort();\n controller = null;\n },\n };\n}\n","/**\n * Performing one `act_on_page` action on the host page (#5559). Navigation goes\n * through the host's router, never a page load, which would end the chat turn —\n * so a link is followed by routing its href, not by clicking it.\n */\n\nexport type PageAction =\n | { type: 'snapshot' }\n | { type: 'navigate'; path: string }\n | { type: 'click'; ref: string }\n | { type: 'type'; ref: string; text: string }\n | { type: 'open'; ref: string }\n /** A frame naming an action this version does not know (backend ahead of the panel). */\n | { type: 'unsupported'; requested: string };\n\n/**\n * Whether the panel may declare `supports_page_actions` (#5559). Passing\n * `onRelativeLinkClick` is the host's opt-in: a proxy that relays tool\n * approvals but not page answers would stall every step on its timeout.\n */\nexport function hostTakesPageActions(approveUrl: string | null, onNavigate?: (path: string) => void): boolean {\n return approveUrl !== null && typeof onNavigate === 'function';\n}\n\n/** The document's own address, which every href is resolved against. */\nfunction baseHref(doc?: Document): string | undefined {\n return doc?.defaultView?.location?.href ?? (typeof window === 'undefined' ? undefined : window.location.href);\n}\n\n/**\n * The host-internal form of *href*, or null when it leads anywhere else.\n * Resolved and origin-compared even when it looks relative: `/\\evil.com` and\n * ` //evil.com` do not, and resolve to another origin.\n */\nexport const toInternalHref = (href?: string, base?: string): string | null => {\n const from = base ?? baseHref();\n if (!href || !from) return null;\n try {\n const url = new URL(href, from);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;\n if (url.origin !== new URL(from).origin) return null;\n const path = `${url.pathname}${url.search}${url.hash}` || '/';\n // `/.//host/x` normalises to `//host/x`, which passes the origin check here\n // and then reads as protocol-relative to a host that resolves it again.\n return path.startsWith('//') ? null : path;\n } catch {\n return null;\n }\n};\n\n/**\n * Whether *href* is *written* as a relative reference. Not a safety boundary -\n * `toInternalHref` is - but the shape a link was authored in: a same-origin\n * absolute link still opens in a new tab when the host routes nothing.\n */\nexport const isRelativeHref = (href?: string): boolean => {\n if (!href) return false;\n if (href.startsWith('//')) return false;\n return !/^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(href);\n};\n\nexport interface PageActionResult {\n ok: boolean;\n error?: string;\n}\n\n/** The panel's own subtree, whose mutations must never count as the page reacting. */\nconst PANEL_SELECTOR = '.filigran-chatbot';\n\n/** How long a hover is given to open a menu. */\nconst HOVER_WAIT_MS = 300;\n\nfunction insidePanel(node: Node | null): boolean {\n // Duck-typed: `instanceof Element` throws where there is no such global, and\n // the observer swallows the throw, losing the mutation.\n const el = (node && 'closest' in node ? node : node?.parentElement) as Element | null | undefined;\n return !!el?.closest?.(PANEL_SELECTOR);\n}\n\n/**\n * Fields `type` may write to. A `<select>`, link or button would otherwise fall\n * through to `textContent` and lose its options or its children. Password is\n * left out on purpose: the panel neither reads nor fills credentials.\n */\nconst TYPEABLE =\n 'textarea, [contenteditable=\"true\"], input:not([type]), input[type=\"text\"], input[type=\"search\"], input[type=\"email\"], input[type=\"url\"], input[type=\"tel\"], input[type=\"number\"]';\n\nfunction isTypeable(el: Element): boolean {\n return el.matches?.(TYPEABLE) ?? false;\n}\n\n/**\n * Secret fields, by autocomplete. Mirrors `pageSnapshot`'s own test, which\n * cannot be shared: both modules are loaded by `node --test`, where a runtime\n * relative import does not resolve. `secretFieldsAgree` in the tests pins them\n * to the same answer.\n */\nconst SECRET_AUTOCOMPLETE = /^(current-password|new-password|one-time-code|cc-)/;\n\nexport function isSecretField(el: Element): boolean {\n if ((el.getAttribute('type') || '').toLowerCase() === 'password') return true;\n return (el.getAttribute('autocomplete') || '')\n .toLowerCase()\n .split(/\\s+/)\n .some((token) => SECRET_AUTOCOMPLETE.test(token));\n}\n\n/** Set *text* the way a user's typing does, so a React-controlled field sees it. */\nfunction setValue(el: Element, text: string): void {\n const view = el.ownerDocument.defaultView as (Window & typeof globalThis) | null;\n if (view && (el instanceof view.HTMLInputElement || el instanceof view.HTMLTextAreaElement)) {\n // React tracks the value it last rendered on the element itself; only the\n // prototype's setter goes around that tracker, so the input event below\n // reaches the component as a change.\n const proto = el instanceof view.HTMLInputElement ? view.HTMLInputElement.prototype : view.HTMLTextAreaElement.prototype;\n Object.getOwnPropertyDescriptor(proto, 'value')?.set?.call(el, text);\n } else {\n el.textContent = text;\n }\n el.dispatchEvent(new (view?.Event ?? Event)('input', { bubbles: true }));\n el.dispatchEvent(new (view?.Event ?? Event)('change', { bubbles: true }));\n}\n\n/** Hover *el* the way a pointer does: what opens a menu on hover opens. */\nfunction hover(el: Element): void {\n const view = el.ownerDocument.defaultView as (Window & typeof globalThis) | null;\n const init = { bubbles: true, cancelable: true, view: view ?? undefined, pointerType: 'mouse' };\n const Pointer = view?.PointerEvent ?? view?.MouseEvent ?? MouseEvent;\n const Mouse = view?.MouseEvent ?? MouseEvent;\n el.dispatchEvent(new Pointer('pointerover', init));\n el.dispatchEvent(new Pointer('pointerenter', { ...init, bubbles: false }));\n el.dispatchEvent(new Mouse('mouseover', init));\n el.dispatchEvent(new Mouse('mouseenter', { ...init, bubbles: false }));\n}\n\n/**\n * Whether *act* adds anything to the page within *ms*: a menu that opened.\n * The panel's own re-render (the \"Acting on the page…\" status) lands inside the\n * same window, so its subtree is ignored or every hover would look successful.\n */\nfunction addsContent(doc: Document, act: () => void, ms = HOVER_WAIT_MS): Promise<boolean> {\n const view = doc.defaultView as (Window & typeof globalThis) | null;\n const Observer = view?.MutationObserver ?? globalThis.MutationObserver;\n if (!Observer) {\n act();\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n const observer = new Observer((records) => {\n const added = records.some(\n (r) => r.addedNodes.length > 0 && !insidePanel(r.target) && Array.from(r.addedNodes).some((n) => !insidePanel(n)),\n );\n if (!added) return;\n observer.disconnect();\n clearTimeout(timer);\n resolve(true);\n });\n observer.observe(doc.body ?? doc.documentElement, { subtree: true, childList: true });\n act();\n const timer = setTimeout(() => {\n observer.disconnect();\n resolve(false);\n }, ms);\n });\n}\n\n/**\n * Run *act*, cancelling the default action of whatever event it fires. Capture\n * phase, so handlers still run: the panel may activate a control but must never\n * cause the page load that would end the turn.\n */\nfunction withoutDefault(doc: Document, types: string[], act: () => void): void {\n const suppress = (event: Event) => event.preventDefault();\n for (const type of types) doc.addEventListener(type, suppress, true);\n try {\n act();\n } finally {\n for (const type of types) doc.removeEventListener(type, suppress, true);\n }\n}\n\n/**\n * Click *el*, routing an anchor through the host so the page is not left and\n * the turn ended. Only *el* itself: a control inside a link row has its own\n * handler, which routing the row would skip.\n */\nfunction clickOrRoute(el: Element, onNavigate?: (path: string) => void, base?: string): PageActionResult {\n if (el.matches?.('a[href]')) {\n // Before the fragment case below: `<a href=\"#\" target=\"_blank\">` still\n // opens a tab, which leaves the page the turn is acting on.\n const target = el.getAttribute('target');\n if (target && target !== '_self') return { ok: false, error: 'opens_new_tab' };\n // A fragment is an in-page trigger carrying a handler, not a destination,\n // so it is clicked like anything else.\n const href = el.getAttribute('href') ?? '';\n if (href && !href.startsWith('#')) {\n const internal = toInternalHref(href, base);\n if (!internal) return { ok: false, error: 'external_link' };\n if (onNavigate) {\n onNavigate(internal);\n return { ok: true };\n }\n }\n }\n // Focus first: a click moves no focus of its own, so a field edited just\n // before would never blur, and a host that commits on blur (a tag input)\n // would run this activation without the edit.\n (el as HTMLElement).focus?.();\n // A submit control loads its form's action, and a click anywhere inside an\n // anchor activates it - both end the turn. Their handlers still run.\n // A fragment moves within the page, so its default stands; anything else an\n // anchor does loads one.\n const anchor = el.closest?.('a[href]');\n const inAnchor = !!anchor && !(anchor.getAttribute('href') ?? '').startsWith('#');\n const cancels = inAnchor ? ['submit', 'click'] : ['submit'];\n const checkable = el.matches?.('input[type=\"checkbox\"], input[type=\"radio\"]') ?? false;\n const before = (el as HTMLInputElement).checked;\n withoutDefault(el.ownerDocument, cancels, () => (el as HTMLElement).click());\n // Cancelling the click also rolled back a checkable's own activation, which\n // is its behaviour rather than the anchor's: applied here instead.\n if (checkable && inAnchor && (el as HTMLInputElement).checked === before) {\n const input = el as HTMLInputElement;\n input.checked = input.type === 'radio' ? true : !before;\n input.dispatchEvent(new (el.ownerDocument.defaultView?.Event ?? Event)('input', { bubbles: true }));\n input.dispatchEvent(new (el.ownerDocument.defaultView?.Event ?? Event)('change', { bubbles: true }));\n }\n return { ok: true };\n}\n\n/** Resolve once *test* holds, or after *ms*. */\nfunction waitUntil(test: () => boolean, ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n const started = Date.now();\n const tick = () => {\n if (test()) return resolve(true);\n if (Date.now() - started >= ms) return resolve(false);\n setTimeout(tick, 30);\n };\n tick();\n });\n}\n\n/** Whether *el* and every ancestor are rendered: a wrapper hides what it holds. */\nfunction visible(el: Element): boolean {\n const details = el.closest?.('details:not([open])');\n if (details && details !== el) {\n const summary = Array.from(details.children).find((c) => c.tagName.toLowerCase() === 'summary');\n if (!summary?.contains(el)) return false;\n }\n for (let node: Element | null = el; node; node = node.parentElement) {\n if ((node as HTMLElement).hidden || node.hasAttribute('inert')) return false;\n if (node.getAttribute('aria-hidden') === 'true') return false;\n const style = node.ownerDocument.defaultView?.getComputedStyle(node);\n if (style?.display === 'none' || style?.visibility === 'hidden') return false;\n }\n return true;\n}\n\n/** Whether the menu *el* controls is showing, by what the trigger says about it. */\nfunction menuShowing(el: Element): boolean {\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true') return true;\n // A stated collapsed state settles it, whatever the target looks like.\n if (expanded === 'false') return false;\n const id = el.getAttribute('aria-controls');\n if (!id) return false;\n const menu = el.ownerDocument.getElementById(id);\n return !!menu && visible(menu);\n}\n\n/**\n * Open the menu *el* triggers: by hover where that opens it, else by click.\n * A trigger stating its own state is believed; only one that says nothing\n * falls back to \"did the page grow\", which a tooltip would answer for it.\n */\nasync function openMenu(el: Element, base?: string, signal?: AbortSignal): Promise<PageActionResult> {\n const statesItself = el.hasAttribute('aria-expanded') || el.hasAttribute('aria-controls');\n if (menuShowing(el)) return { ok: true };\n if (statesItself) {\n // Waited on for its own state: anything else the hover adds, a tooltip,\n // says nothing about the menu and would cut the wait short.\n hover(el);\n if (await waitUntil(() => menuShowing(el), HOVER_WAIT_MS)) return { ok: true };\n } else if (await addsContent(el.ownerDocument, () => hover(el))) {\n return { ok: true };\n }\n // The turn may have been stopped during the hover wait; the click below would\n // land on the user's page after they asked for it to end.\n if (signal?.aborted) return { ok: false, error: 'aborted' };\n // No router: a trigger that happens to be an anchor must run its own click\n // handler rather than navigate to its href. The link guards still apply.\n return clickOrRoute(el, undefined, base);\n}\n\n/** Everything in a form a user fills in, for telling a search from a dialog. */\nconst SUBMITTABLE =\n 'input:not([type=\"hidden\"]):not([type=\"submit\"]):not([type=\"button\"]):not([type=\"reset\"]):not([type=\"image\"]), select, textarea, [contenteditable=\"true\"]';\n\n/** Words a search field is labelled with, where a create dialog's is not. */\nconst SEARCH_WORDS = /\\b(search|query|filter|find|recherche|rechercher)\\b/i;\n\n/**\n * Whether Enter in *el* asks for what was typed. Only a field that says it is a\n * search: a form of one field is just as likely a create or rename dialog, and\n * submitting it would commit the change the user has not asked for yet.\n */\nfunction entersSearch(el: Element): boolean {\n if (el.getAttribute('role') === 'searchbox') return true;\n if ((el as HTMLInputElement).type === 'search') return true;\n if (el.closest('[role=\"search\"]') !== null) return true;\n if (!['name', 'id', 'placeholder', 'aria-label', 'title'].some((attr) => SEARCH_WORDS.test(el.getAttribute(attr) ?? ''))) return false;\n // Named like a search, but a \"Filter name\" beside other fields is a dialog\n // saving a filter, not a search: only the form's sole field is sent.\n const form = (el as HTMLInputElement).form;\n return !form || form.querySelectorAll(SUBMITTABLE).length === 1;\n}\n\nfunction pressEnter(el: Element): void {\n const view = el.ownerDocument.defaultView as (Window & typeof globalThis) | null;\n const Keyboard = view?.KeyboardEvent ?? KeyboardEvent;\n const init = { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true };\n const down = new Keyboard('keydown', init);\n el.dispatchEvent(down);\n el.dispatchEvent(new Keyboard('keyup', init));\n // A synthetic key event never triggers the browser's implicit submission, so\n // a form the field belongs to is submitted unless a handler took the key.\n // Its native submission is cancelled: `requestSubmit` still validates and\n // still reaches the host's own handler, but cannot unload the page.\n const form = (el as HTMLInputElement).form;\n if (form && !down.defaultPrevented) {\n withoutDefault(el.ownerDocument, ['submit'], () => form.requestSubmit?.());\n }\n}\n\n/**\n * Mirrors `pageSnapshot`'s own test, which cannot be shared: both modules are\n * loaded by `node --test`, where a runtime relative import does not resolve.\n * `disabledTestsAgree` in the tests pins them to the same answer.\n */\nexport function isDisabled(el: Element): boolean {\n // The attribute as authored, so what the snapshot prints `(disabled)` for is\n // what is refused here - a custom `<a disabled>` included.\n if (el.hasAttribute('disabled')) return true;\n if (el.getAttribute('aria-disabled') === 'true') return true;\n if (el.matches?.(':disabled')) return true;\n // Only the native form controls a `<fieldset>` governs: a link or an ARIA\n // widget inside a disabled one still works. Its first `<legend>` is exempt.\n if (!el.matches?.('button, input, select, textarea')) return false;\n const fieldset = el.closest?.('fieldset[disabled]');\n if (!fieldset) return false;\n const legend = Array.from(fieldset.children).find((c) => c.tagName.toLowerCase() === 'legend');\n return !legend?.contains(el);\n}\n\n/** A field the user cannot edit either: the native setter would still write to it. */\nfunction isReadOnly(el: Element): boolean {\n return (el as HTMLInputElement).readOnly === true || el.getAttribute('aria-readonly') === 'true';\n}\n\nexport async function performPageAction(\n action: PageAction,\n refs: Map<string, Element>,\n onNavigate?: (path: string) => void,\n doc?: Document,\n signal?: AbortSignal,\n): Promise<PageActionResult> {\n try {\n if (signal?.aborted) return { ok: false, error: 'aborted' };\n if (action.type === 'snapshot') return { ok: true };\n if (action.type === 'unsupported') return { ok: false, error: `unsupported_action: ${action.requested}`.slice(0, 500) };\n if (action.type === 'navigate') {\n if (!onNavigate) return { ok: false, error: 'navigation_unavailable' };\n const path = toInternalHref(action.path, baseHref(doc));\n if (!path) return { ok: false, error: 'external_path' };\n onNavigate(path);\n return { ok: true };\n }\n const el = refs.get(action.ref);\n if (!el || !el.isConnected) return { ok: false, error: 'unknown_ref' };\n // Still in the document is not still reachable: a dialog may have closed or\n // an ancestor gone inert since the snapshot named it.\n if (!visible(el)) return { ok: false, error: 'not_visible' };\n if (isDisabled(el)) return { ok: false, error: 'disabled' };\n // The file chooser is an operating-system window: it cannot be driven from\n // here, and the turn would wait behind it.\n if (el.matches?.('input[type=\"file\"]')) return { ok: false, error: 'opens_file_dialog' };\n if (action.type === 'open') return await openMenu(el, baseHref(doc ?? el.ownerDocument), signal);\n if (action.type === 'click') return clickOrRoute(el, onNavigate, baseHref(doc ?? el.ownerDocument));\n if (!isTypeable(el)) return { ok: false, error: 'not_a_text_field' };\n if (isReadOnly(el)) return { ok: false, error: 'read_only' };\n // A revealed password or one-time code is masked in the snapshot; writing\n // to it would be filling a credential the panel will not read back.\n if (isSecretField(el)) return { ok: false, error: 'secret_field' };\n (el as HTMLElement).focus?.();\n setValue(el, action.text);\n if (entersSearch(el)) pressEnter(el);\n return { ok: true };\n } catch (err) {\n return { ok: false, error: `failed: ${err instanceof Error ? err.message : String(err)}`.slice(0, 500) };\n }\n}\n\n/**\n * Resolve once the page has not changed for *quietMs*, or after *maxMs* at most.\n * The panel's own subtree is ignored: its status re-renders would otherwise keep\n * resetting the quiet timer until the cap.\n */\nexport function waitForDomSettle(\n doc: Document,\n { quietMs = 300, maxMs = 3000, signal }: { quietMs?: number; maxMs?: number; signal?: AbortSignal } = {},\n): Promise<void> {\n return new Promise((resolve) => {\n // Before anything is set up: a stopped turn has nothing to wait for.\n if (signal?.aborted) return resolve();\n const view = doc.defaultView as (Window & typeof globalThis) | null;\n const Observer = view?.MutationObserver ?? globalThis.MutationObserver;\n let quiet: ReturnType<typeof setTimeout>;\n const done = () => {\n clearTimeout(quiet);\n clearTimeout(cap);\n observer?.disconnect();\n signal?.removeEventListener('abort', done);\n resolve();\n };\n const observer = Observer\n ? new Observer((records) => {\n if (!records.some((r) => !insidePanel(r.target))) return;\n clearTimeout(quiet);\n quiet = setTimeout(done, quietMs);\n })\n : null;\n observer?.observe(doc.body ?? doc.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });\n quiet = setTimeout(done, quietMs);\n const cap = setTimeout(done, maxMs);\n signal?.addEventListener('abort', done);\n });\n}\n","/**\n * The host page as `act_on_page` reads it (#5559): one line per element a user\n * could act on, keyed by a reference the next action names it by. The panel\n * itself is never part of it. The line format is in the README, under \"Acting\n * on the host page\".\n */\n\nexport const MAX_SNAPSHOT_CHARS = 20_000;\nconst MAX_NAME_CHARS = 80;\nconst MAX_URL_CHARS = 500;\nconst TRUNCATION_MARKER = '[truncated]';\n\nexport interface PageSnapshot {\n text: string;\n url: string;\n title: string;\n /** Reference → element, valid until the next snapshot. */\n refs: Map<string, Element>;\n}\n\nconst EXPLICIT_ROLES = new Set([\n 'button',\n 'link',\n 'tab',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'checkbox',\n 'radio',\n 'switch',\n 'textbox',\n 'searchbox',\n 'combobox',\n 'treeitem',\n]);\n\n/** Anything that could carry an actionable role, for the descent test below. */\nconst MAYBE_ACTIONABLE = 'a[href], button, summary, select, textarea, input, [contenteditable=\"true\"], [role]';\n\n/**\n * Whether an actionable element wraps further controls, which need references\n * of their own. A plain link is named by its contents; a `<select>`'s are not\n * controls.\n */\nfunction wrapsControls(el: Element): boolean {\n if (el.tagName.toLowerCase() === 'select') return false;\n for (const child of Array.from(el.querySelectorAll(MAYBE_ACTIONABLE))) {\n if (actionableRole(child)) return true;\n }\n return false;\n}\n\n/** The role an element is acted on as, or `null` when it is not actionable. */\nfunction actionableRole(el: Element): string | null {\n const explicit = el.getAttribute('role');\n if (explicit && EXPLICIT_ROLES.has(explicit)) return explicit;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' && el.hasAttribute('href')) return 'link';\n if (tag === 'button' || tag === 'summary') return 'button';\n if (tag === 'select') return 'combobox';\n if (tag === 'textarea') return 'textbox';\n if (tag === 'input') {\n const type = (el.getAttribute('type') || 'text').toLowerCase();\n if (type === 'hidden') return null;\n if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button';\n if (type === 'checkbox' || type === 'radio') return type;\n if (type === 'search') return 'searchbox';\n // Opens a chooser rather than taking text; calling it a textbox invites a\n // `type` that is refused anyway.\n if (type === 'file') return 'button';\n return 'textbox';\n }\n if (el.getAttribute('contenteditable') === 'true') return 'textbox';\n return null;\n}\n\nfunction headingLevel(el: Element): number | null {\n const m = /^h([1-6])$/i.exec(el.tagName);\n return m ? Number(m[1]) : null;\n}\n\n/**\n * The element's text with a space wherever a non-inline element starts or\n * ends. `textContent` glues a table row's cells together (\"AdministratorZone de\n * danger1\"), and a name whose first cell is not a word cannot be matched.\n */\nfunction spacedText(el: Element): string {\n const view = el.ownerDocument.defaultView;\n let out = '';\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType === 3) {\n out += node.textContent ?? '';\n } else if (node.nodeType === 1) {\n // The walk skips hidden subtrees, and a secret's value is masked; without\n // the same tests here both return as part of an ancestor's name, its\n // value, or a heading above them.\n if (hidden(node as Element) || isSecret(node as Element)) continue;\n const display = view?.getComputedStyle(node as Element).display ?? '';\n // An unknown display (no layout engine) is read as inline: never split a word.\n const inline = display === '' || display === 'inline' || display === 'contents';\n out += inline ? spacedText(node as Element) : ` ${spacedText(node as Element)} `;\n }\n }\n return out;\n}\n\nfunction clean(text: string | null | undefined): string {\n return (text ?? '').replace(/\\s+/g, ' ').trim();\n}\n\n/** Roles named by what they contain, where `title` is only a last resort. */\nconst NAMED_BY_CONTENT = new Set(['button', 'link', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'treeitem', 'switch']);\n\n/** The name a user reads for *el*, in the accessible-name order. */\nfunction accessibleName(el: Element, role: string): string {\n const doc = el.ownerDocument;\n // `aria-labelledby` outranks `aria-label`, and is read even when hidden: a\n // visually-hidden span is how an icon button usually gets its name.\n const labelledBy = el.getAttribute('aria-labelledby');\n if (labelledBy) {\n const text = clean(\n labelledBy\n .split(/\\s+/)\n .map((id) => doc.getElementById(id)?.textContent ?? '')\n .join(' '),\n );\n if (text) return text;\n }\n const fromAttr = clean(el.getAttribute('aria-label'));\n if (fromAttr) return fromAttr;\n const id = el.getAttribute('id');\n const label = (id && Array.from(doc.getElementsByTagName('label')).find((l) => l.htmlFor === id)) || el.closest('label');\n if (label) {\n // The label's own words, not the options of a select it wraps.\n const own = clean(\n Array.from(label.childNodes)\n .filter((n) => n.nodeType === 3)\n .map((n) => n.textContent)\n .join(' '),\n );\n if (own || clean(label.textContent)) return own || clean(label.textContent);\n }\n // An `<input>` button carries its label in `value`, not in any content.\n const tag = el.tagName.toLowerCase();\n const type = (el.getAttribute('type') || '').toLowerCase();\n if (tag === 'input' && ['submit', 'reset', 'button'].includes(type)) {\n const value = clean(el.getAttribute('value'));\n if (value) return value;\n if (type !== 'button') return type === 'submit' ? 'Submit' : 'Reset';\n }\n const alt = clean(el.getAttribute('alt')) || clean(el.querySelector('img[alt]')?.getAttribute('alt'));\n if (alt) return alt;\n // Its contents would hand over what `value()` just masked.\n const contents = isSecret(el) ? '' : clean(spacedText(el));\n // A control named by what it shows: the visible words beat a `title`, which\n // often holds a shortcut rather than a label.\n if (NAMED_BY_CONTENT.has(role) && contents) return contents;\n const placeholder = clean(el.getAttribute('placeholder'));\n if (placeholder) return placeholder;\n const title = clean(el.getAttribute('title'));\n if (title) return title;\n return contents;\n}\n\nfunction quote(text: string): string {\n // JSON quoting, so a newline in a textarea value cannot split one control\n // across lines or make its text read as another `[e2] button \"…\"` row.\n return JSON.stringify(text.slice(0, MAX_NAME_CHARS));\n}\n\n/**\n * Whether an ancestor `<fieldset disabled>` disables *el*. Only the native form\n * controls it governs - a link or an ARIA widget inside one still works - and\n * never what sits in its first `<legend>`.\n */\nfunction disabledByFieldset(el: Element): boolean {\n if (!el.matches?.('button, input, select, textarea')) return false;\n const fieldset = el.closest?.('fieldset[disabled]');\n if (!fieldset) return false;\n const legend = Array.from(fieldset.children).find((c) => c.tagName.toLowerCase() === 'legend');\n return !legend?.contains(el);\n}\n\nfunction states(el: Element): string[] {\n const out: string[] = [];\n if (el.hasAttribute('disabled') || disabledByFieldset(el) || el.getAttribute('aria-disabled') === 'true') out.push('disabled');\n if (el.getAttribute('aria-selected') === 'true') out.push('selected');\n if ((el as HTMLInputElement).checked || el.getAttribute('aria-checked') === 'true') out.push('checked');\n if (el.getAttribute('aria-expanded') === 'true') out.push('expanded');\n // A menu that opens on hover or click and is closed now: its items are not\n // in the page until it opens (`open` action), so the snapshot says it is there.\n else if ((el.getAttribute('aria-haspopup') ?? 'false') !== 'false') out.push('menu');\n // A closed disclosure (a collapsed navigation group): what it holds appears\n // once it is clicked, which its name alone does not say.\n else if (el.getAttribute('aria-expanded') === 'false') out.push('collapsed');\n if (el.getAttribute('aria-pressed') === 'true') out.push('pressed');\n const current = el.getAttribute('aria-current');\n if (current && current !== 'false') out.push('current');\n return out;\n}\n\n/**\n * Secret fields, by autocomplete: `type=password` alone misses a revealed\n * password, card fields and one-time codes.\n */\nconst SECRET_AUTOCOMPLETE = /^(current-password|new-password|one-time-code|cc-)/;\n\nfunction isSecret(el: Element): boolean {\n if ((el.getAttribute('type') || '').toLowerCase() === 'password') return true;\n // The attribute may carry section/billing tokens before the field name.\n return (el.getAttribute('autocomplete') || '')\n .toLowerCase()\n .split(/\\s+/)\n .some((token) => SECRET_AUTOCOMPLETE.test(token));\n}\n\nfunction value(el: Element, role: string): string | null {\n if (!['textbox', 'searchbox', 'combobox'].includes(role)) return null;\n if (isSecret(el)) return null;\n // `spacedText`, not `textContent`: a contenteditable's hidden descendants\n // are excluded from the walk and its name, and must not return as its value.\n const v = 'value' in el ? String((el as HTMLInputElement).value ?? '') : clean(spacedText(el));\n return v ? v : null;\n}\n\n/**\n * Where an element with an address within the host goes (` -> /path?query`), so a link named for a\n * section (\"Analyses\") still says it leads to the page asked for. Nothing for a\n * link to another site: its address would only be text the host never shows.\n */\nfunction destination(el: Element): string {\n const href = el.getAttribute('href');\n const loc = el.ownerDocument.defaultView?.location;\n if (!href || !loc) return '';\n try {\n const url = new URL(href, loc.href);\n return url.origin === loc.origin ? ` -> ${url.pathname}${url.search}` : '';\n } catch {\n return '';\n }\n}\n\nfunction hidden(el: Element): boolean {\n if (el.classList.contains('filigran-chatbot')) return true;\n // A closed `<details>` renders nothing but its first `<summary>`, though its\n // descendants keep ordinary computed styles.\n const details = el.closest?.('details:not([open])');\n if (details && details !== el) {\n const summary = Array.from(details.children).find((c) => c.tagName.toLowerCase() === 'summary');\n if (!summary?.contains(el)) return true;\n }\n if ((el as HTMLElement).hidden || el.hasAttribute('inert')) return true;\n if (el.getAttribute('aria-hidden') === 'true') return true;\n const style = el.ownerDocument.defaultView?.getComputedStyle(el);\n return style?.display === 'none' || style?.visibility === 'hidden';\n}\n\nexport function takePageSnapshot(doc: Document, maxChars = MAX_SNAPSHOT_CHARS): PageSnapshot {\n const loc = doc.defaultView?.location;\n const url = (loc ? `${loc.pathname}${loc.search}` : '').slice(0, MAX_URL_CHARS);\n const title = clean(doc.title).slice(0, MAX_NAME_CHARS);\n // Without a marker the agent reads a list cut off at the cap as the whole\n // page, so its room is taken out of the budget before anything is listed -\n // as is the header's, which a long title and path could otherwise blow on\n // their own.\n const budget = Math.max(0, maxChars - (TRUNCATION_MARKER.length + 1));\n let truncated = false;\n let header = `# ${title} — ${url}`;\n if (header.length > budget) {\n header = header.slice(0, budget);\n truncated = true;\n }\n const lines = [header];\n let size = header.length;\n const refs = new Map<string, Element>();\n\n const walk = (node: Element): boolean => {\n for (const el of Array.from(node.children)) {\n if (hidden(el)) continue;\n const role = actionableRole(el);\n const level = headingLevel(el);\n let line: string | null = null;\n if (role) {\n const ref = `e${refs.size + 1}`;\n const v = value(el, role);\n const st = states(el);\n line = `[${ref}] ${role} ${quote(accessibleName(el, role))}${st.length ? ` (${st.join(', ')})` : ''}${v ? ` = ${quote(v)}` : ''}${destination(el)}`;\n if (size + line.length + 1 > budget) {\n truncated = true;\n return false;\n }\n refs.set(ref, el);\n } else if (level) {\n line = `heading ${quote(clean(spacedText(el)))} (level ${level})`;\n if (size + line.length + 1 > budget) {\n truncated = true;\n return false;\n }\n }\n if (line) {\n lines.push(line);\n size += line.length + 1;\n }\n // An actionable element's own content is its name, not more elements -\n // unless it wraps controls of its own, which need their own references.\n if ((!role || wrapsControls(el)) && !walk(el)) return false;\n }\n return true;\n };\n if (doc.body && !truncated) walk(doc.body);\n if (truncated) lines.push(TRUNCATION_MARKER);\n\n return { text: lines.join('\\n'), url, title, refs };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type {\n AgentStatusState,\n ApiEndpoints,\n BackendType,\n ChatContextUsage,\n ChatConversationRef,\n ChatFile,\n ChatMessage,\n ToolApprovalDecision,\n ToolApprovalProposal,\n} from '../types';\nimport type { ParsedAction, ProtocolContext } from './protocols';\nimport { parseAgUiEvent, parseLegacyEvent, parseRestEvent } from './protocols';\nimport { parseToolApprovalProposals } from './protocols/parseRestEvent';\nimport { createStreamDeltas, type StreamDeltas } from './streamDeltas';\nimport { createSessionGate } from '../utils/sessionGate';\nimport { conversationReferencesUrl, pruneConversationRefs, referencedConversations, withConversationRef } from '../utils/conversationRefs';\nimport { hostTakesPageActions, performPageAction, waitForDomSettle, type PageAction } from '../utils/pageActions';\nimport { takePageSnapshot } from '../utils/pageSnapshot';\n\nconst STORAGE_KEY = 'filigranChatConversationId';\nconst LEGACY_CHAT_ID_KEY = 'filigranChatLegacyChatId';\n\n/**\n * Unsent composer text is kept per conversation so closing the panel (hosts\n * unmount `<ChatPanel/>` when it is closed) or switching conversation doesn't\n * discard a half-written question. `sessionStorage`, not `localStorage`: a\n * draft is scoped to the tab and dies with it.\n */\nconst DRAFT_KEY_PREFIX = 'filigranChatDraft:';\n/** Debounce on draft writes so a fast typist doesn't hit storage per keystroke. */\nconst DRAFT_PERSIST_DELAY_MS = 300;\n\nconst draftKey = (conversationId: string | null): string => `${DRAFT_KEY_PREFIX}${conversationId ?? 'new'}`;\n\nfunction loadDraft(conversationId: string | null): string {\n if (typeof window === 'undefined') return '';\n try {\n return sessionStorage.getItem(draftKey(conversationId)) ?? '';\n } catch {\n // Storage can throw in restricted/private browsing contexts — a chat\n // without draft recovery is far better than a chat that fails to mount.\n return '';\n }\n}\n\nfunction persistDraft(conversationId: string | null, value: string): void {\n if (typeof window === 'undefined') return;\n try {\n if (value) sessionStorage.setItem(draftKey(conversationId), value);\n else sessionStorage.removeItem(draftKey(conversationId));\n } catch {\n /* ignore — see loadDraft */\n }\n}\n\n/**\n * The `@` picks of a draft, kept beside its text: only a pick makes `@key`\n * reference a conversation, so a draft restored without them would go out with\n * its `@key`s as plain text.\n */\nconst DRAFT_REFS_KEY_PREFIX = 'filigranChatDraftRefs:';\nconst draftRefsKey = (conversationId: string | null): string => `${DRAFT_REFS_KEY_PREFIX}${conversationId ?? 'new'}`;\n\nfunction loadDraftRefs(conversationId: string | null): ChatConversationRef[] {\n if (typeof window === 'undefined') return [];\n try {\n const parsed: unknown = JSON.parse(sessionStorage.getItem(draftRefsKey(conversationId)) ?? '[]');\n if (!Array.isArray(parsed)) return [];\n return parsed.filter(\n (r): r is ChatConversationRef =>\n !!r && typeof r === 'object' && typeof r.conversationId === 'string' && typeof r.key === 'string' && typeof r.title === 'string',\n );\n } catch {\n return [];\n }\n}\n\nfunction persistDraftRefs(conversationId: string | null, refs: ChatConversationRef[]): void {\n if (typeof window === 'undefined') return;\n try {\n if (refs.length > 0) sessionStorage.setItem(draftRefsKey(conversationId), JSON.stringify(refs));\n else sessionStorage.removeItem(draftRefsKey(conversationId));\n } catch {\n /* ignore — see loadDraft */\n }\n}\n\n/** A conversation's draft: its text and the `@` picks it still holds. */\nfunction loadDraftState(conversationId: string | null): { text: string; refs: ChatConversationRef[] } {\n const text = loadDraft(conversationId);\n return { text, refs: pruneConversationRefs(loadDraftRefs(conversationId), text) };\n}\n\n/**\n * How often to check on a turn resumed by a decision made on a recovered\n * (streamless) prompt, and the backstop that ends the watch regardless.\n *\n * Such a turn has no stream left to write to — the backend persists the answer\n * and suppresses the live `done` frame — so the panel watches the pause-recovery\n * route instead, which reports whether the turn is still running. That is a\n * definite stop condition rather than a guess at how long an agent might take,\n * and each poll doubles as the sign of life that keeps the turn from being\n * abandoned. The deadline is only a backstop against a turn-state marker that\n * somehow never clears; the ordinary end is the turn reporting itself idle.\n */\nconst RESUME_POLL_MS = 5000;\nconst RESUME_WATCH_MS = 900000;\n\n/**\n * How often to re-assert that somebody is still here while a recovered prompt\n * is on screen.\n *\n * A paused turn gives up after 30 minutes with no sign of a client, and after a\n * reload the stream that would have vouched for the reviewer is gone for good —\n * so presence is inferred from requests about the conversation instead. A tab\n * left open on the prompt IS a client present, but it makes no requests, so\n * without this the turn would abandon a reviewer who is simply taking their\n * time. Well inside the server's window, since missing it costs the whole turn.\n */\nconst APPROVAL_PRESENCE_INTERVAL_MS = 600000;\n\n/** Maximum number of files that can be attached to a single message. */\nconst DEFAULT_MAX_FILE_COUNT = 10;\n/** Maximum total size of all attached files (50 MB). */\nconst DEFAULT_MAX_TOTAL_SIZE = 50 * 1024 * 1024;\n\ninterface UseChatOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n agentSlug: string | null | undefined;\n requestHeaders?: Record<string, string>;\n /** Arbitrary host page/application context, sent as `context` on the REST message body. */\n pageContext?: Record<string, unknown>;\n /** The host's in-app navigation, which `act_on_page` uses to open a path (#5559). */\n onRelativeLinkClick?: (href: string) => void;\n t: (key: string) => string;\n maxFileCount?: number;\n maxTotalSize?: number;\n}\n\nexport interface TransferredAgent {\n id: string;\n name: string;\n}\n\ninterface UseChatReturn {\n messages: ChatMessage[];\n inputValue: string;\n setInputValue: (value: string) => void;\n isLoading: boolean;\n agentStatus: AgentStatusState | null;\n attachedFiles: ChatFile[];\n conversationId: string | null;\n /**\n * Context-window occupancy for the active conversation, or `null` while the\n * backend has reported none (a fresh chat, or a backend that does not carry\n * the figures at all). Tracked live off the per-iteration progress frames and\n * finalised on `done`.\n */\n contextUsage: ChatContextUsage | null;\n transferredAgent: TransferredAgent | null;\n /**\n * True while a response is streaming AND the typed text can be dispatched\n * immediately as a mid-run steering message (REST backend with a steer\n * endpoint and a known conversation id). Gates the steering affordances in\n * the composer (accent Send next to Stop, \"Enter to send now\" copy).\n */\n canSteer: boolean;\n /**\n * Tool calls the running turn has stopped on, or `null` when nothing is\n * waiting. While set, the turn is paused mid-answer: the stream is open and\n * silent, and only a decision (or aborting the turn) moves it on.\n */\n pendingApprovals: ToolApprovalProposal[] | null;\n /** True while a decision set is in flight to the approve endpoint. */\n isSubmittingApproval: boolean;\n /**\n * Why the last decision submission failed, or `null`. Kept alongside the\n * still-visible prompt rather than replacing it: the turn is paused either\n * way, so the reviewer needs the retry as much as the explanation.\n */\n approvalError: string | null;\n /**\n * Answer a paused turn. Every proposed call must appear exactly once — the\n * backend refuses a partial set, because resuming with an undecided call\n * leaves a `tool_use` block without its `tool_result`, which the model\n * providers reject outright.\n */\n submitApprovalDecisions: (decisions: ToolApprovalDecision[]) => Promise<void>;\n /**\n * True while waiting for the answer to a decision made on a recovered prompt.\n * The turn resumed without a stream to report on, so the panel shows the\n * working indicator itself and re-reads the conversation until the answer\n * lands.\n */\n isResumingAfterDecision: boolean;\n /**\n * Bumped whenever the conversation must be re-read from the server. The panel\n * owns the restore, so this is how the hook asks for one.\n */\n historyReloadNonce: number;\n historyLoadedRef: React.MutableRefObject<boolean>;\n /**\n * Ref mirror of {@link conversationId}, always current across async\n * boundaries. Exposed so the history-restore effect can tell, when its\n * `/chat/sessions` response arrives, whether the conversation it was issued\n * for is still the active one — and ignore a genuinely superseded response\n * (new chat / agent switch) without discarding a restore that was merely\n * torn down by a benign host re-render or a StrictMode double-invoke.\n */\n conversationIdRef: React.MutableRefObject<string | null>;\n handleFileAdd: (fileList: FileList | null) => void;\n handlePaste: (e: React.ClipboardEvent) => void;\n handleSendMessage: () => Promise<void>;\n /**\n * Start a fresh conversation; with *workspaceId* (a string), the session is\n * created inside that workspace (`workspace_id` on the session `POST`).\n */\n handleNewChat: (workspaceId?: string) => void;\n /** The workspace the next conversation will be created in, if any. */\n pendingWorkspaceId: string | null;\n /** Forget *workspaceId* as the next conversation's workspace (it was deleted). */\n clearPendingWorkspace: (workspaceId: string) => void;\n handleStopGenerating: () => void;\n /**\n * The conversations picked from the composer's `@` menu whose `@key` the\n * draft still holds; sent as `referenced_conversation_ids` with the next\n * message.\n */\n conversationRefs: ChatConversationRef[];\n /** Record a pick from the `@` menu. */\n addConversationRef: (ref: ChatConversationRef) => void;\n setAttachedFiles: React.Dispatch<React.SetStateAction<ChatFile[]>>;\n setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>;\n /**\n * Seed the context gauge from outside a live turn — the history-restore path,\n * which reads the newest restored assistant message's figures.\n */\n setContextUsage: React.Dispatch<React.SetStateAction<ChatContextUsage | null>>;\n /**\n * Set (or clear) the active conversation id, keeping React state, the\n * cross-async-boundary ref mirror, and localStorage all in sync. Pass\n * `null` to reset. Prefer this over a raw state setter so the id consumed\n * by `handleSendMessage` (which reads the ref) never drifts from what the\n * UI shows.\n */\n updateConversationId: (id: string | null) => void;\n /**\n * Switch to another existing conversation (history menu). Aborts any\n * in-flight request, clears the transcript, and re-arms the history-restore\n * effect so the selected conversation's messages are fetched via the\n * sessions endpoint.\n */\n handleSwitchConversation: (id: string) => void;\n}\n\nfunction getParser(backendType: BackendType): (evt: Record<string, unknown>, ctx: ProtocolContext) => ParsedAction {\n switch (backendType) {\n case 'legacy':\n return parseLegacyEvent;\n case 'ag-ui':\n return parseAgUiEvent;\n default:\n return parseRestEvent;\n }\n}\n\nfunction buildRequestBody(\n backendType: BackendType,\n content: string,\n opts: {\n legacyChatId: string | null;\n conversationId: string | null;\n agentSlug: string | null | undefined;\n pageContext?: Record<string, unknown>;\n /** See {@link ApiEndpoints.approve} — derived, never a prop of its own. */\n supportsToolApproval?: boolean;\n /** See {@link ApiEndpoints.conversationReferences}. */\n referencedConversationIds?: string[];\n /** Same promise, for `act_on_page` frames (#5559): answered on the approve path. */\n supportsPageActions?: boolean;\n },\n): Record<string, unknown> {\n switch (backendType) {\n case 'legacy':\n return { question: content, chatId: opts.legacyChatId ?? undefined, streaming: true };\n case 'ag-ui':\n return {\n threadId: opts.conversationId ?? crypto.randomUUID(),\n runId: crypto.randomUUID(),\n messages: [{ id: crypto.randomUUID(), role: 'user', content }],\n tools: [],\n context: [],\n state: {},\n forwardedProps: opts.agentSlug ? { agentSlug: opts.agentSlug } : {},\n };\n default: {\n const body: Record<string, unknown> = { content, conversation_id: opts.conversationId, agent_slug: opts.agentSlug };\n // Tell the backend this turn may pause on a gated tool call and that we\n // will answer. Sent only when the host named an approve path, because\n // the flag is a promise: a backend that pauses waits indefinitely, so a\n // client that cannot answer must never claim it can. Omitted rather than\n // sent false, so a proxy that rebuilds the body from a fixed field list\n // drops nothing meaningful.\n if (opts.supportsToolApproval) {\n body.supports_tool_approval = true;\n }\n // Only when the message holds a pick: a host that never named the route\n // sends exactly the body it always did.\n if (opts.referencedConversationIds && opts.referencedConversationIds.length > 0) {\n body.referenced_conversation_ids = opts.referencedConversationIds;\n }\n if (opts.supportsPageActions) {\n body.supports_page_actions = true;\n }\n // The panel renders the deck, report and video markers itself whatever\n // the host proxies: the cards need no route to show and link to XTM One.\n body.supports_artifacts = true;\n // Forward arbitrary host page context (e.g. current URL) so the agent\n // knows where the user is. Omitted when empty to keep payloads lean.\n // Guard serialization: the whole body is later JSON.stringify'd, so a\n // non-serializable value (circular reference, BigInt, …) would otherwise\n // throw and break the message send. Drop the context instead — page\n // context is supplementary and must never prevent a message from going out.\n // Decide using the serialized result so values that normalize to an empty\n // object (e.g. `{ url: undefined }`, `{ fn: () => {} }`) are also omitted.\n if (opts.pageContext && Object.keys(opts.pageContext).length > 0) {\n try {\n const serialized = JSON.stringify(opts.pageContext);\n if (serialized && serialized !== '{}') {\n body.context = opts.pageContext;\n }\n } catch {\n // Non-serializable page context — skip it rather than fail the send.\n }\n }\n return body;\n }\n }\n}\n\nexport function useChat({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n agentSlug,\n requestHeaders,\n pageContext,\n onRelativeLinkClick,\n t,\n maxFileCount = DEFAULT_MAX_FILE_COUNT,\n maxTotalSize = DEFAULT_MAX_TOTAL_SIZE,\n}: UseChatOptions): UseChatReturn {\n const isLegacy = backendType === 'legacy';\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [agentStatus, setAgentStatus] = useState<AgentStatusState | null>(null);\n const [conversationId, setConversationId] = useState<string | null>(() => {\n if (typeof window === 'undefined') return null;\n return localStorage.getItem(STORAGE_KEY);\n });\n // Seeded from the persisted draft of whichever conversation we mount into,\n // so re-opening the panel restores what the user had typed - and the\n // conversations it references.\n const [initialDraft] = useState(() => loadDraftState(typeof window === 'undefined' ? null : localStorage.getItem(STORAGE_KEY)));\n const [inputValue, setInputValue] = useState(initialDraft.text);\n const [conversationRefs, setConversationRefs] = useState<ChatConversationRef[]>(initialDraft.refs);\n const [attachedFiles, setAttachedFiles] = useState<ChatFile[]>([]);\n const [transferredAgent, setTransferredAgent] = useState<TransferredAgent | null>(null);\n // How full the model's context window is for this conversation. Conversation\n // state rather than per-message: it describes what the NEXT turn will carry,\n // which is the only thing the user can still act on.\n const [contextUsage, setContextUsage] = useState<ChatContextUsage | null>(null);\n // Tool calls the running turn is paused on. Conversation-level rather than\n // per-message: the pause belongs to the turn, not to any one bubble, and the\n // prompt outlives the segment that was streaming when it arrived.\n const [pendingApprovals, setPendingApprovals] = useState<ToolApprovalProposal[] | null>(null);\n const [isSubmittingApproval, setIsSubmittingApproval] = useState(false);\n const [approvalError, setApprovalError] = useState<string | null>(null);\n // A prompt recovered after a reload is answered the same way, but resumes\n // differently: there is no stream left to carry the rest of the turn.\n const [isResumingAfterDecision, setIsResumingAfterDecision] = useState(false);\n const [historyReloadNonce, setHistoryReloadNonce] = useState(0);\n // Drives the resume watch's next poll: each tick re-arms the effect.\n const [resumeTick, setResumeTick] = useState(0);\n const [legacyChatId, setLegacyChatId] = useState<string | null>(() => {\n if (typeof window === 'undefined') return null;\n return localStorage.getItem(LEGACY_CHAT_ID_KEY);\n });\n\n const historyLoadedRef = useRef(false);\n const abortControllerRef = useRef<AbortController | null>(null);\n // Page actions abort on their own: closing the panel must stop them touching\n // the host page without cancelling the turn, whose answer a host expects to\n // find in history when the panel reopens.\n const pageActionControllerRef = useRef<AbortController | null>(null);\n // The running stream's pending deltas, so stopping it can apply them and a\n // new chat can drop them.\n const streamDeltasRef = useRef<StreamDeltas | null>(null);\n const hasUsedToolsRef = useRef(false);\n // Ref mirror of conversationId — always current across async boundaries\n const conversationIdRef = useRef(conversationId);\n // Ref mirror of isLoading, so the recovery probe can tell at apply time\n // whether a live turn has started owning the prompt since it was issued.\n const isLoadingRef = useRef(isLoading);\n isLoadingRef.current = isLoading;\n // Ref mirror of pageContext so the value sent reflects the page the user is\n // on at send time, regardless of when the send handler closure was created.\n const pageContextRef = useRef(pageContext);\n pageContextRef.current = pageContext;\n // The elements of the last host-page snapshot, by the reference the next\n // `act_on_page` action names them with (#5559).\n const pageRefsRef = useRef<Map<string, Element>>(new Map());\n const onRelativeLinkClickRef = useRef(onRelativeLinkClick);\n onRelativeLinkClickRef.current = onRelativeLinkClick;\n // A page action answers from the closure of the render that began the turn,\n // so a header rotated since would go out stale and 401 the answer.\n const requestHeadersRef = useRef(requestHeaders);\n requestHeadersRef.current = requestHeaders;\n // Conversation id as the paused turn itself reported it. The decision POST\n // needs an id, and the first turn of a fresh conversation has none yet —\n // `conversationId` is normally learned from `done`, which a paused turn has\n // by definition not reached. Kept separate from `conversationIdRef` rather\n // than adopted into it: a pause should not quietly switch on the affordances\n // (steering, history) that having an id unlocks.\n const approvalConversationIdRef = useRef<string | null>(null);\n // True when the pending prompt was recovered from the server rather than read\n // off a live stream — the turn is running, but nothing is listening to it.\n const approvalDetachedRef = useRef(false);\n // Conversations already asked about a pause, so the recovery probe runs once\n // per conversation instead of on every render that settles.\n const probedConversationRef = useRef<string | null>(null);\n // When the resume watch stops regardless of what the turn reports.\n const resumeDeadlineRef = useRef(0);\n // One session creation at a time, for the chat on screen: a new chat\n // abandons the one in flight (see `createSessionGate`).\n const [sessionGate] = useState(createSessionGate);\n // The workspace the next session is created in (\"new conversation\" inside\n // a workspace group). A ref for the request, state for the list to show it.\n const pendingWorkspaceRef = useRef<string | null>(null);\n const [pendingWorkspaceId, setPendingWorkspaceId] = useState<string | null>(null);\n // Abort controller for in-flight file uploads (cancelled on new chat)\n const uploadAbortRef = useRef<AbortController>(new AbortController());\n\n // Guard invalid consumer values and keep deterministic limits.\n const effectiveMaxFileCount = Number.isFinite(maxFileCount) && maxFileCount > 0 ? Math.floor(maxFileCount) : DEFAULT_MAX_FILE_COUNT;\n const effectiveMaxTotalSize = Number.isFinite(maxTotalSize) && maxTotalSize > 0 ? maxTotalSize : DEFAULT_MAX_TOTAL_SIZE;\n\n // Determine message endpoint URL\n const getMessagesUrl = () => {\n if (isLegacy || apiEndpoints?.singleEndpoint) {\n return apiBaseUrl; // POST directly to base URL\n }\n return `${apiBaseUrl}${apiEndpoints?.messages ?? '/chat/messages'}`;\n };\n\n // A pick counts while its `@key` is in the text: editing it out drops it.\n useEffect(() => {\n setConversationRefs((prev) => pruneConversationRefs(prev, inputValue));\n }, [inputValue]);\n\n const addConversationRef = useCallback((ref: ChatConversationRef) => {\n setConversationRefs((prev) => withConversationRef(prev, ref));\n }, []);\n\n // Determine mid-run steering endpoint URL (null disables steering)\n const getSteerUrl = (): string | null => {\n if (isLegacy || backendType === 'ag-ui' || apiEndpoints?.singleEndpoint || apiEndpoints?.steer === null) {\n return null;\n }\n return `${apiBaseUrl}${apiEndpoints?.steer ?? '/chat/messages/steer'}`;\n };\n\n /**\n * Determine the tool-approval endpoint URL, or null when this host has not\n * opted in.\n *\n * Unlike its siblings there is no default path — see {@link ApiEndpoints.approve}.\n * Whether this returns a URL is exactly what decides if the widget advertises\n * `supports_tool_approval`, so \"configured\" and \"able to answer\" are the same\n * fact rather than two that can drift apart.\n */\n const getApproveUrl = (): string | null => {\n if (isLegacy || backendType === 'ag-ui' || apiEndpoints?.singleEndpoint) return null;\n const path = apiEndpoints?.approve;\n if (!path) return null;\n return `${apiBaseUrl}${path}`;\n };\n // Same reason as `requestHeadersRef`: the answer must resolve the route\n // against the endpoints as they are now, not as they were at turn start.\n const getApproveUrlRef = useRef(getApproveUrl);\n getApproveUrlRef.current = getApproveUrl;\n\n /**\n * Determine the pause-recovery URL for one conversation, or null when the\n * host has not exposed the route. See {@link ApiEndpoints.pendingApprovals}.\n */\n const getPendingApprovalsUrl = (convId: string): string | null => {\n if (isLegacy || backendType === 'ag-ui' || apiEndpoints?.singleEndpoint) return null;\n const base = apiEndpoints?.pendingApprovals;\n if (!base) return null;\n return `${apiBaseUrl}${base}/${convId}/pending-approvals`;\n };\n\n /**\n * Read what a conversation is paused on, and whether its turn is still going.\n *\n * One request serves three purposes: recovering a prompt the page never saw,\n * telling a resumed turn's watcher when to stop, and counting as the sign of\n * life that keeps a paused turn from being abandoned. Returns null on any\n * failure — every caller treats that as \"learned nothing\" and tries again or\n * leaves the panel as it was.\n */\n const readPendingApprovals = async (convId: string): Promise<{ proposals?: ToolApprovalProposal[]; turnRunning: boolean } | null> => {\n const url = getPendingApprovalsUrl(convId);\n if (!url) return null;\n try {\n const res = await fetch(url, { headers: { ...(requestHeaders ?? {}) } });\n if (!res.ok) return null;\n const data = await res.json();\n return {\n proposals: parseToolApprovalProposals(data?.proposals),\n // Anything but an explicit `running` ends the watch. A backend that\n // omits the field is one that cannot say, and waiting forever on a\n // turn nobody can report on is the worse failure.\n turnRunning: data?.turn === 'running',\n };\n } catch {\n return null;\n }\n };\n\n /**\n * Ask the panel to re-read the conversation from the server.\n *\n * Clearing the guard alone would not do it — the restore effect lives in the\n * panel and only re-runs when something in its dependencies changes, which is\n * what the nonce is for.\n */\n const reloadHistory = useCallback(() => {\n historyLoadedRef.current = false;\n setHistoryReloadNonce((n) => n + 1);\n }, []);\n\n // Determine upload endpoint URL (null disables file upload proxying)\n const getUploadUrl = (): string | null => {\n if (isLegacy || apiEndpoints?.singleEndpoint || apiEndpoints?.upload === null) {\n return null;\n }\n return `${apiBaseUrl}${apiEndpoints?.upload ?? '/chat/upload'}`;\n };\n\n // Determine sessions endpoint URL\n const getSessionsUrl = (): string | null => {\n if (isLegacy || apiEndpoints?.singleEndpoint || apiEndpoints?.sessions === null) {\n return null;\n }\n return `${apiBaseUrl}${apiEndpoints?.sessions ?? '/chat/sessions'}`;\n };\n\n /**\n * Update conversationId in React state, the ref mirror, and localStorage.\n * Stable identity (useCallback) so it can be used as an effect dependency.\n */\n const updateConversationId = useCallback((id: string | null) => {\n conversationIdRef.current = id;\n setConversationId(id);\n if (id) {\n localStorage.setItem(STORAGE_KEY, id);\n } else {\n localStorage.removeItem(STORAGE_KEY);\n }\n }, []);\n\n /**\n * Ensure a conversation exists. Concurrent callers of the same chat (e.g.\n * multiple files selected at once) share a single session creation, and a\n * creation answered after a new chat was started resolves to `null` without\n * touching the chat that replaced it.\n */\n const ensureConversation = async (slug: string | null | undefined): Promise<string | null> => {\n // Fast path: already have one\n if (conversationIdRef.current) return conversationIdRef.current;\n\n // If another call is already creating, wait for it\n if (sessionGate.pending) return sessionGate.pending;\n\n const sessionsUrl = getSessionsUrl();\n if (!sessionsUrl) return null;\n\n return sessionGate.run(async (isCurrent, signal) => {\n const workspaceId = pendingWorkspaceRef.current;\n const res = await fetch(sessionsUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify(workspaceId ? { agent_slug: slug, workspace_id: workspaceId } : { agent_slug: slug }),\n signal,\n });\n if (!res.ok || !isCurrent()) return null;\n const data = await res.json();\n // The user started another chat meanwhile: this conversation is not\n // its, and neither is the workspace or the history guard to reset.\n if (!isCurrent()) return null;\n const convId = (data?.conversation_id as string) ?? null;\n if (convId) {\n // Just created: there is no history to restore. Left armed, the\n // panel's restore would fetch it while the first turn streams and\n // replace the answer being written with the one message persisted.\n historyLoadedRef.current = true;\n updateConversationId(convId);\n pendingWorkspaceRef.current = null;\n setPendingWorkspaceId(null);\n }\n return convId;\n });\n };\n\n /**\n * Upload a single file to the backend and return its file_id.\n */\n const uploadSingleFile = async (file: File, convId: string, signal: AbortSignal): Promise<string> => {\n const uploadUrl = getUploadUrl()!;\n const formData = new FormData();\n formData.append('conversation_id', convId);\n formData.append('file', file, file.name);\n\n const uploadHeaders = requestHeaders\n ? Object.fromEntries(\n Object.entries(requestHeaders).filter(([k]) => {\n const key = k.toLowerCase();\n return key !== 'content-type';\n }),\n )\n : undefined;\n\n const res = await fetch(uploadUrl, {\n method: 'POST',\n headers: uploadHeaders,\n body: formData,\n signal,\n });\n if (!res.ok) {\n throw new Error(`File upload failed: ${res.status}`);\n }\n const data = await res.json();\n const ids: string[] = data.file_ids ?? [];\n if (ids.length === 0) throw new Error('No file_id returned');\n return ids[0];\n };\n\n /**\n * Handle file selection: validate limits, add files to state immediately,\n * then upload them in the background. Each file chip shows its upload status.\n */\n const handleFileAdd = (fileList: FileList | null) => {\n if (!fileList || fileList.length === 0 || !getUploadUrl()) return;\n\n // Build the list of accepted files outside the state updater (pure logic)\n const incoming = Array.from(fileList);\n\n // We need current state to check limits — use a ref-like approach:\n // read attachedFiles via a one-shot updater that returns prev unchanged,\n // then compute outside. Simpler: just compute optimistically and let the\n // updater do the final gating.\n\n // Pre-generate stable IDs and entries so side effects use the same IDs\n const candidates: { file: File; tempId: string }[] = incoming.map((file) => ({\n file,\n tempId: crypto.randomUUID(),\n }));\n\n // Update state (pure — no side effects)\n let accepted: { file: File; tempId: string }[] = [];\n setAttachedFiles((prev) => {\n const currentCount = prev.length;\n const currentSize = prev.reduce((sum, f) => sum + f.size, 0);\n\n const slotsAvailable = effectiveMaxFileCount - currentCount;\n if (slotsAvailable <= 0) return prev;\n\n let sizeLeft = effectiveMaxTotalSize - currentSize;\n const filtered: { file: File; tempId: string }[] = [];\n for (const c of candidates.slice(0, slotsAvailable)) {\n if (c.file.size <= sizeLeft) {\n filtered.push(c);\n sizeLeft -= c.file.size;\n }\n }\n if (filtered.length === 0) return prev;\n\n accepted = filtered;\n\n const newEntries: ChatFile[] = filtered.map(({ file, tempId }) => ({\n name: file.name,\n type: file.type,\n size: file.size,\n rawFile: file,\n uploadStatus: 'pending' as const,\n fileId: tempId,\n }));\n\n return [...prev, ...newEntries];\n });\n\n // Launch uploads OUTSIDE the state updater (side effects)\n // Use setTimeout(0) to ensure state has settled after the updater\n setTimeout(() => {\n const signal = uploadAbortRef.current.signal;\n for (const { file, tempId } of accepted) {\n (async () => {\n try {\n const convId = await ensureConversation(agentSlug);\n if (!convId) {\n setAttachedFiles((p) => p.map((f) => (f.fileId === tempId ? { ...f, uploadStatus: 'error' } : f)));\n return;\n }\n const fileId = await uploadSingleFile(file, convId, signal);\n setAttachedFiles((p) => p.map((f) => (f.fileId === tempId ? { ...f, fileId, uploadStatus: 'done' } : f)));\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') return;\n setAttachedFiles((p) => p.map((f) => (f.fileId === tempId ? { ...f, uploadStatus: 'error' } : f)));\n }\n })();\n }\n }, 0);\n };\n\n const handlePaste = (e: React.ClipboardEvent) => {\n const { files } = e.clipboardData;\n if (files.length > 0) {\n e.preventDefault();\n handleFileAdd(files);\n }\n };\n\n /**\n * Mid-run steering: dispatch a message while the agent is still generating.\n * The user bubble is added optimistically and the steer endpoint is POSTed;\n * the backend persists the message and injects it into the running agentic\n * loop at the next iteration boundary. On failure (network error, or a\n * backend without steering support answering non-2xx) the optimistic bubble\n * is rolled back and the text is restored into the composer — prepended on\n * its own line if the user already typed something new — so the message is\n * never silently lost and never resets the in-flight run state.\n */\n const steerMessage = async (content: string) => {\n const steerUrl = getSteerUrl();\n const convId = conversationIdRef.current;\n if (!steerUrl || !convId) return;\n\n const optimistic: ChatMessage = {\n id: crypto.randomUUID(),\n role: 'user',\n content,\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, optimistic]);\n\n try {\n const res = await fetch(steerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ conversation_id: convId, content, agent_slug: agentSlug }),\n });\n if (!res.ok) throw new Error(`Steer failed: ${res.status}`);\n } catch {\n setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));\n setInputValue((prev) => (prev ? `${content}\\n${prev}` : content));\n }\n };\n\n /**\n * Answer a turn that paused on a gated tool call.\n *\n * The decision travels the same way a steering message does — a POST beside\n * the open stream — and for the same reason: the turn is still running, so\n * the answer cannot ride on a new one. The paused turn is polling for it and\n * resumes on the stream that is already open, with no lost context.\n *\n * Deliberately not carried on the turn's own AbortController: the two are\n * independent requests, and aborting the turn must not look like a decision.\n *\n * A failure leaves the prompt on screen. The alternative — clearing it —\n * would strand the turn paused with nothing to answer it, which is the exact\n * state this whole opt-in exists to avoid.\n */\n const submitApprovalDecisions = async (decisions: ToolApprovalDecision[]) => {\n const approveUrl = getApproveUrl();\n const convId = approvalConversationIdRef.current ?? conversationIdRef.current;\n // Nothing decided is a no-op, not a failure — the prompt only submits a\n // full set, so this is unreachable from the UI.\n if (decisions.length === 0) return;\n // Missing prerequisites must be VISIBLE. The prompt is on screen, the turn\n // is paused behind it, and a silent return would leave the reviewer\n // clicking a control that does nothing — the exact failure this feature\n // exists to prevent, reintroduced at the last step. Reachable if the host\n // never named an approve path, or if a paused turn arrived without a\n // conversation id on the first turn of a fresh conversation, where the id\n // is otherwise only learned from `done`.\n if (!approveUrl || !convId) {\n setApprovalError(t('This decision could not be sent. Reload the chat and try again.'));\n return;\n }\n\n setApprovalError(null);\n setIsSubmittingApproval(true);\n try {\n const res = await fetch(approveUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({\n conversation_id: convId,\n decisions: decisions.map((d) => ({\n tool_call_id: d.toolCallId,\n decision: d.verdict,\n // Only ever sent with a rejection, and only when the reviewer\n // actually wrote something — an empty string reaches the agent as\n // a reason that says nothing.\n ...(d.verdict === 'reject' && d.rejectionReason ? { rejection_reason: d.rejectionReason } : {}),\n })),\n }),\n });\n if (res.ok) {\n setPendingApprovals(null);\n if (approvalDetachedRef.current) {\n // Answered after a reload: the turn resumes, but the stream it would\n // have reported on died with the old page. The backend persists the\n // answer and suppresses the live `done`, so re-reading the\n // conversation is the only way it can ever appear — and without this\n // the click would look like it did nothing at all.\n approvalDetachedRef.current = false;\n resumeDeadlineRef.current = Date.now() + RESUME_WATCH_MS;\n setIsResumingAfterDecision(true);\n return;\n }\n // The turn is moving again; show that immediately rather than leaving\n // the composer looking idle until the next server event lands.\n setAgentStatus((prev) => (prev ? { ...prev, status: 'thinking' } : { status: 'thinking' }));\n return;\n }\n // 409: nothing is waiting any more — the turn finished, was cancelled, or\n // somebody else answered it. Distinguished from a transient failure\n // because retrying cannot help; the stream ending clears the prompt.\n setApprovalError(\n res.status === 409 ? t('This turn is no longer waiting for a decision.') : t('Could not send your decision. Please try again.'),\n );\n } catch {\n setApprovalError(t('Could not send your decision. Please try again.'));\n } finally {\n setIsSubmittingApproval(false);\n }\n };\n\n /**\n * Perform one `act_on_page` action on the host page and answer it with a\n * fresh snapshot (#5559). The answer goes to the approve path, which the host\n * proxies already forward; the turn waits for it on the open stream.\n *\n * A 409 means the turn no longer waits for this action (it timed out or\n * ended): nothing to retry, so it is dropped.\n */\n const answerPageAction = async (actionId: string, action: PageAction, conversationIdHint?: string) => {\n const approveUrl = getApproveUrlRef.current();\n const convId = conversationIdHint ?? conversationIdRef.current;\n if (!approveUrl || !convId || typeof document === 'undefined') return;\n // The turn's own signal: Stop, New chat and switching conversation abort it,\n // and this runs detached from the stream, so without it a stopped turn would\n // still click the page and then answer for a conversation that is gone.\n const signal = pageActionControllerRef.current?.signal;\n // The stream outlives a closed panel, so the turn is still waiting: it is\n // answered without the page and without the aborted signal, which would\n // cancel the request too and leave it waiting out its timeout per step.\n const refuse = async (error: string) => {\n try {\n await fetch(approveUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeadersRef.current ?? {}) },\n body: JSON.stringify({\n conversation_id: convId,\n page_action: { action_id: actionId, ok: false, error, url: '', title: '', snapshot: '' },\n }),\n });\n } catch {\n // The turn's own page wait ends it; there is nothing to show here.\n }\n };\n if (signal?.aborted) return refuse('panel_closed');\n // The same opt-in that decides whether the capability is advertised, tested\n // again on the way in: an unsolicited frame must not read or act on the page\n // of a host that never offered it. Answered, so the turn does not hang.\n if (!hostTakesPageActions(approveUrl, onRelativeLinkClickRef.current)) {\n return refuse('page_actions_not_supported');\n }\n setAgentStatus((prev) => (prev ? { ...prev, status: 'acting_on_page' } : { status: 'acting_on_page' }));\n try {\n const result = await performPageAction(action, pageRefsRef.current, onRelativeLinkClickRef.current, document, signal);\n if (signal?.aborted) return refuse('panel_closed');\n if (action.type !== 'snapshot') await waitForDomSettle(document, { signal });\n if (signal?.aborted) return refuse('panel_closed');\n // The snapshot can throw on its own (a very deep DOM, a host\n // `getComputedStyle` that raises). It rides in `error` while `ok` stays\n // the action's own result: `ok: false` would have the agent retry a click\n // that already ran, and a field of its own would be dropped unseen by a\n // backend that does not know it, leaving an empty page and no sign why.\n let page = { text: '', url: '', title: '' };\n let snapshotError: string | null = null;\n try {\n const snapshot = takePageSnapshot(document);\n pageRefsRef.current = snapshot.refs;\n page = { text: snapshot.text, url: snapshot.url, title: snapshot.title };\n } catch (err) {\n pageRefsRef.current = new Map();\n snapshotError = `${err instanceof Error ? err.message : String(err)}`.slice(0, 500);\n }\n await fetch(approveUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeadersRef.current ?? {}) },\n signal,\n body: JSON.stringify({\n conversation_id: convId,\n page_action: {\n action_id: actionId,\n ok: result.ok,\n error: result.error ?? (snapshotError === null ? null : `snapshot_failed: ${snapshotError}`),\n url: page.url,\n title: page.title,\n snapshot: page.text,\n },\n }),\n });\n } catch {\n // The turn's own page wait ends it; there is nothing to show here.\n } finally {\n // Not for a turn that was stopped: its replacement owns the status line.\n if (!signal?.aborted) {\n setAgentStatus((prev) => (prev?.status === 'acting_on_page' ? { ...prev, status: 'thinking' } : prev));\n }\n }\n };\n\n const handleSendMessage = async () => {\n const steerText = inputValue.trim();\n // The picks the text still holds, when the host still offers the feature.\n const sentRefs = conversationReferencesUrl(apiBaseUrl, apiEndpoints, backendType) ? referencedConversations(conversationRefs, inputValue) : [];\n if (isLoading) {\n // Mid-run steering — text-only sends while a response is streaming.\n // Attachments keep the legacy wait behavior (the upload + message pair\n // cannot be injected into a running loop), and so do references: a steer\n // reaches the loop as text alone, and the agent would never read them.\n if (steerText && attachedFiles.length === 0 && sentRefs.length === 0 && getSteerUrl() && conversationIdRef.current) {\n setInputValue('');\n await steerMessage(steerText);\n }\n return;\n }\n if (!inputValue.trim() && attachedFiles.length === 0) return;\n const content = inputValue.trim();\n\n const userMsg: ChatMessage = {\n id: crypto.randomUUID(),\n role: 'user',\n content,\n timestamp: new Date(),\n files: attachedFiles.length > 0 ? [...attachedFiles] : undefined,\n conversationRefs: sentRefs.length > 0 ? sentRefs : undefined,\n };\n setMessages((prev) => [...prev, userMsg]);\n setInputValue('');\n setConversationRefs([]);\n // Clear attachment chips after sending so the input returns to a clean state.\n setAttachedFiles([]);\n setIsLoading(true);\n setAgentStatus({ status: 'thinking' });\n hasUsedToolsRef.current = false;\n // The chat this turn belongs to: a new chat (or a switch) moves the gate\n // on, and the turn's end must then leave the replacing chat's state alone.\n const turnGeneration = sessionGate.generation;\n\n const assistantId = crypto.randomUUID();\n setMessages((prev) => [...prev, { id: assistantId, role: 'assistant', content: '', timestamp: new Date() }]);\n\n // The assistant message currently being streamed into. A steered turn can\n // produce multiple response segments on one SSE stream: the backend\n // completes the current segment (intermediate `done`), then runs a\n // follow-up pass for the steering message (fresh `thinking` + `stream`\n // events). Each segment gets its own assistant bubble. Declared outside\n // the try so the catch below writes the error into the LIVE segment, not\n // an already-completed one.\n let currentAssistantId = assistantId;\n let accumulated = '';\n let doneReceived = false;\n\n const deltas = createStreamDeltas((textChanged, thinking) => {\n if (textChanged) {\n // Snapshot the segment id and text: the state updater runs\n // asynchronously and `currentAssistantId` / `accumulated` may\n // already belong to the NEXT segment by then.\n const segId = currentAssistantId;\n const text = accumulated;\n setAgentStatus((prev) => ({ status: 'streaming', thinkingContent: prev?.thinkingContent }));\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: text } : m)));\n }\n if (thinking) {\n setAgentStatus((prev) => ({\n ...prev,\n status: prev?.status ?? 'thinking',\n thinkingContent: (prev?.thinkingContent ?? '') + thinking,\n }));\n }\n });\n streamDeltasRef.current = deltas;\n\n const controller = new AbortController();\n pageActionControllerRef.current?.abort();\n const pageActions = new AbortController();\n try {\n abortControllerRef.current = controller;\n pageActionControllerRef.current = pageActions;\n\n // Collect file_ids from already-uploaded files (uploaded eagerly on selection)\n const fileIds = (userMsg.files ?? []).filter((f) => f.uploadStatus === 'done' && f.fileId).map((f) => f.fileId!);\n\n // A conversation started inside a workspace is created first, filed\n // there: the message endpoint would create it in no workspace. Should\n // that fail (the workspace was archived or is no longer shared), the\n // message still goes, in a conversation of no workspace, rather than\n // being lost.\n if (!conversationIdRef.current && pendingWorkspaceRef.current) {\n const generation = sessionGate.generation;\n const created = await ensureConversation(agentSlug);\n // A new chat replaced this one meanwhile: the send went with it, and\n // the workspace now pending is the new chat's, not this send's.\n if (sessionGate.generation !== generation) return;\n if (!created) {\n pendingWorkspaceRef.current = null;\n setPendingWorkspaceId(null);\n }\n }\n\n // Step 1: Send the message (with file_ids if files were uploaded)\n // Use conversationIdRef to get the latest value (may have been set by eager upload)\n const requestBody = buildRequestBody(backendType, content, {\n legacyChatId,\n conversationId: conversationIdRef.current,\n agentSlug,\n pageContext: pageContextRef.current,\n supportsToolApproval: getApproveUrl() !== null,\n referencedConversationIds: sentRefs.map((r) => r.conversationId),\n supportsPageActions: hostTakesPageActions(getApproveUrl(), onRelativeLinkClickRef.current),\n });\n if (fileIds.length > 0) {\n (requestBody as Record<string, unknown>).file_ids = fileIds;\n }\n\n setAgentStatus({ status: 'thinking' });\n\n const res = await fetch(getMessagesUrl(), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify(requestBody),\n signal: controller.signal,\n });\n\n if (!res.ok || !res.body) {\n setMessages((prev) =>\n prev.map((m) => (m.id === assistantId ? { ...m, content: t('Unable to connect. Please check the configuration.') } : m)),\n );\n return;\n }\n\n const parseEvent = getParser(backendType);\n const ctx: ProtocolContext = { hasUsedTools: false, activeNodeId: '' };\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n /**\n * Open a new response segment when events keep flowing after a `done`.\n * Appends a fresh empty assistant message (after any steered user\n * bubble) and resets the per-segment accumulators. The fresh `thinking`\n * status also clears the reasoning window — each segment carries its\n * own reasoning, mirroring the web chat behavior.\n */\n const ensureSegment = () => {\n if (!doneReceived) return;\n // Nothing of the closed segment may land in the new one.\n deltas.flush();\n doneReceived = false;\n accumulated = '';\n currentAssistantId = crypto.randomUUID();\n const segmentId = currentAssistantId;\n setMessages((prev) => [...prev, { id: segmentId, role: 'assistant', content: '', timestamp: new Date() }]);\n setAgentStatus({ status: 'thinking' });\n };\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n for (const rawLine of lines) {\n const line = rawLine.replace(/\\r$/, '');\n if (!line.startsWith('data:')) continue;\n const jsonStr = line.startsWith('data: ') ? line.slice(6) : line.slice(5);\n try {\n const evt = JSON.parse(jsonStr) as Record<string, unknown>;\n const parsed: ParsedAction = parseEvent(evt, ctx);\n\n // Sync ref → context for cross-event tracking\n ctx.hasUsedTools = ctx.hasUsedTools || hasUsedToolsRef.current;\n\n switch (parsed.action) {\n case 'status': {\n ensureSegment();\n const segId = currentAssistantId;\n // Orthogonal to the status label below: a progress frame can\n // carry a fresh context reading whatever phase it announces.\n if (parsed.contextUsage) setContextUsage(parsed.contextUsage);\n if (parsed.status === 'tool_start') hasUsedToolsRef.current = true;\n if (parsed.status === 'thinking_text') {\n deltas.thinking(parsed.thinkingContent ?? '');\n break;\n }\n // Every other status lands after the text and reasoning that\n // arrived before it.\n deltas.flush();\n if (parsed.status === 'stream_retract') {\n // Rare: text that streamed as a provisional answer turned\n // out to precede tool calls — discard the answer bubble\n // (the text re-arrives as thinking_text right after, so it\n // lands in the reasoning window instead).\n accumulated = '';\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: '' } : m)));\n setAgentStatus((prev) => ({\n status: 'analyzing',\n thinkingContent: prev?.thinkingContent,\n }));\n } else if (parsed.status === 'tool_heartbeat') {\n // Liveness signal during a long tool execution: update the\n // elapsed counter but KEEP the current status label/tools —\n // replacing the status would flip e.g. \"Waiting for\n // background task…\" back to \"Thinking…\" mid-execution.\n // Re-anchor the elapsed origin on every beat so the local\n // 1s ticker in ChatThinking stays true to the server clock.\n const elapsedStartMs = typeof parsed.elapsedS === 'number' ? Date.now() - parsed.elapsedS * 1000 : undefined;\n setAgentStatus((prev) =>\n prev\n ? { ...prev, elapsedS: parsed.elapsedS, elapsedStartMs }\n : { status: 'tool_start', tools: parsed.tools, elapsedS: parsed.elapsedS, elapsedStartMs },\n );\n } else {\n setAgentStatus((prev) => ({\n status: parsed.status,\n tools: parsed.tools,\n thinkingContent: prev?.thinkingContent,\n }));\n }\n break;\n }\n\n case 'stream': {\n ensureSegment();\n accumulated += parsed.content;\n deltas.text();\n break;\n }\n\n case 'done': {\n deltas.flush();\n doneReceived = true;\n // A completed segment cannot still be waiting on a decision, so\n // any prompt left standing (a submission that failed against a\n // turn somebody else already answered) is stale.\n setPendingApprovals(null);\n setApprovalError(null);\n if (parsed.conversationId) {\n updateConversationId(parsed.conversationId);\n }\n // Closing reading wins: a turn whose last iteration compacted\n // ends lower than it peaked mid-run.\n if (parsed.contextUsage) setContextUsage(parsed.contextUsage);\n if (parsed.transferAgentId && parsed.transferAgentName) {\n setTransferredAgent({ id: parsed.transferAgentId, name: parsed.transferAgentName });\n }\n const segId = currentAssistantId;\n const finalContent = parsed.content || accumulated;\n // The backend stores a segment when its `done` is sent, and a\n // restore shows that time: stamping the send time instead would\n // change the footer on the next reload.\n const completedAt = new Date();\n setMessages((prev) =>\n prev.map((m) =>\n m.id === segId\n ? {\n ...m,\n content: finalContent,\n timestamp: completedAt,\n toolNames: parsed.toolNames,\n toolCallCount: parsed.toolCallCount,\n iterations: parsed.iterations,\n attachments: parsed.attachments,\n artifacts: parsed.artifacts,\n reasoning: parsed.reasoning,\n toolCallTrace: parsed.toolCallTrace,\n transferChain: parsed.transferChain,\n isTruncated: parsed.isTruncated,\n serverId: parsed.messageId ?? m.serverId,\n }\n : m,\n ),\n );\n break;\n }\n\n case 'page_action_required': {\n deltas.flush();\n // Not awaited: the stream stays silent until the answer lands,\n // and the reader must keep draining its keep-alives meanwhile.\n void answerPageAction(parsed.actionId, parsed.pageAction, parsed.conversationId);\n break;\n }\n\n case 'approval_required': {\n // The turn stops here and the stream goes silent until a\n // decision is POSTed back. Not an end state: no segment is\n // opened or closed, `isLoading` stays true, and the rest of\n // the turn arrives on this same reader afterwards.\n deltas.flush();\n approvalConversationIdRef.current = parsed.conversationId ?? conversationIdRef.current;\n setApprovalError(null);\n setPendingApprovals(parsed.proposals);\n // Keep whatever reasoning the turn had already streamed: the\n // pause interrupts the turn, it does not start a new one, and\n // the prose leading up to the proposed call is exactly the\n // context the reviewer is about to judge it on.\n setAgentStatus((prev) => (prev ? { ...prev, status: 'awaiting_approval' } : { status: 'awaiting_approval' }));\n break;\n }\n\n case 'error': {\n ensureSegment();\n deltas.flush();\n const segId = currentAssistantId;\n setMessages((prev) =>\n prev.map((m) =>\n // The backend reported a failure of its own, so the generic\n // apology rather than \"check the configuration\": the\n // connection plainly worked.\n m.id === segId ? { ...m, content: parsed.content || t('Sorry, an error occurred. Please try again.') } : m,\n ),\n );\n return;\n }\n\n case 'set_chat_id':\n setLegacyChatId(parsed.chatId);\n localStorage.setItem(LEGACY_CHAT_ID_KEY, parsed.chatId);\n break;\n\n case 'noop':\n break;\n }\n\n // Keep ref in sync with context\n hasUsedToolsRef.current = ctx.hasUsedTools;\n } catch {\n /* skip malformed SSE */\n }\n }\n }\n deltas.flush();\n if (accumulated && !doneReceived) {\n const segId = currentAssistantId;\n const text = accumulated;\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: text || t('No response.') } : m)));\n }\n } catch (err) {\n // A frame still pending would land after the error below, or in the\n // chat that replaced an aborted stream.\n deltas.close();\n if (err instanceof DOMException && err.name === 'AbortError') return;\n const segId = currentAssistantId;\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: t('Sorry, an error occurred. Please try again.') } : m)));\n } finally {\n deltas.close();\n if (streamDeltasRef.current === deltas) streamDeltasRef.current = null;\n // The turn is over, so its page actions are too - but only this turn's:\n // a replacement already owns the refs by then.\n if (pageActionControllerRef.current === pageActions) pageActions.abort();\n if (abortControllerRef.current === controller) abortControllerRef.current = null;\n // An abandoned turn's chat is gone: `handleNewChat` reset the shared\n // state already, and resetting it again here would cut the Stop button,\n // the status and the approvals of a turn the new chat started since.\n if (sessionGate.generation === turnGeneration) {\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n // The stream is gone, so nothing can carry a decision any more —\n // whether the turn finished, errored, or was stopped. Leaving the prompt\n // up would offer an answer to a question nobody is listening for.\n setPendingApprovals(null);\n setApprovalError(null);\n approvalConversationIdRef.current = null;\n approvalDetachedRef.current = false;\n // We watched this turn end, so there is nothing for the recovery probe to\n // find — including on a fresh conversation, whose id only just arrived.\n probedConversationRef.current = conversationIdRef.current;\n }\n }\n };\n\n const handleNewChat = (workspaceId?: string) => {\n // A string only: the header and the sidebar pass this as a click handler,\n // and the click event must never reach the session request.\n const workspace = typeof workspaceId === 'string' && workspaceId ? workspaceId : null;\n pendingWorkspaceRef.current = workspace;\n setPendingWorkspaceId(workspace);\n // Nothing of the abandoned stream may land in the fresh chat.\n streamDeltasRef.current?.close();\n streamDeltasRef.current = null;\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n pageActionControllerRef.current?.abort();\n pageActionControllerRef.current = null;\n // Cancel any in-flight file uploads\n uploadAbortRef.current.abort();\n uploadAbortRef.current = new AbortController();\n // A session still being created was the abandoned chat's.\n sessionGate.abandon();\n setMessages([]);\n setInputValue('');\n setConversationRefs([]);\n setAttachedFiles([]);\n setIsLoading(false);\n setAgentStatus(null);\n setTransferredAgent(null);\n // A fresh (or newly selected) conversation starts with no known occupancy;\n // the restore or the first turn fills it back in. Carrying the previous\n // conversation's reading over would be a plain lie.\n setContextUsage(null);\n setPendingApprovals(null);\n setApprovalError(null);\n setIsResumingAfterDecision(false);\n approvalConversationIdRef.current = null;\n approvalDetachedRef.current = false;\n // Re-arm the probe: the conversation being switched to may well be paused.\n probedConversationRef.current = null;\n hasUsedToolsRef.current = false;\n historyLoadedRef.current = false;\n if (isLegacy) {\n setLegacyChatId(null);\n localStorage.removeItem(LEGACY_CHAT_ID_KEY);\n } else {\n updateConversationId(null);\n }\n };\n\n const clearPendingWorkspace = (workspaceId: string) => {\n if (pendingWorkspaceRef.current !== workspaceId) return;\n pendingWorkspaceRef.current = null;\n setPendingWorkspaceId(null);\n };\n\n const handleSwitchConversation = (id: string) => {\n if (!isLegacy && id === conversationIdRef.current) return;\n // Reuse the full new-chat reset (abort in-flight request + uploads,\n // clear transcript/composer/status), then adopt the selected id and\n // re-arm the history-restore effect so the host panel fetches the\n // conversation's messages via the sessions endpoint.\n handleNewChat();\n if (!isLegacy) {\n updateConversationId(id);\n // `handleNewChat` blanked the composer; bring back this conversation's\n // own unsent draft, if any, with its references.\n const draft = loadDraftState(id);\n setInputValue(draft.text);\n setConversationRefs(draft.refs);\n }\n };\n\n const handleStopGenerating = () => {\n // The text that arrived before the stop stays on screen, including what the\n // next frame would have applied; nothing after it does.\n streamDeltasRef.current?.flush();\n streamDeltasRef.current?.close();\n streamDeltasRef.current = null;\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n pageActionControllerRef.current?.abort();\n pageActionControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n // Stopping IS the way out of a pause the reviewer does not want to answer:\n // the backend waits indefinitely by design, so abandoning the stream is\n // the client's only other move.\n setPendingApprovals(null);\n setApprovalError(null);\n setIsResumingAfterDecision(false);\n approvalConversationIdRef.current = null;\n approvalDetachedRef.current = false;\n pageRefsRef.current = new Map();\n setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.content)));\n };\n\n // Persist the composer draft against the conversation it belongs to. Writing\n // an empty value removes the entry, so sending (which blanks the composer)\n // also clears the draft — no explicit cleanup needed at the send sites.\n useEffect(() => {\n const id = window.setTimeout(() => {\n persistDraft(conversationId, inputValue);\n persistDraftRefs(conversationId, conversationRefs);\n }, DRAFT_PERSIST_DELAY_MS);\n return () => window.clearTimeout(id);\n }, [inputValue, conversationId, conversationRefs]);\n\n // A panel closed mid-stream has no state left for the stream's frames to\n // update. Its page actions stop, so a hover fallback cannot click the host\n // page after the panel closed; the stream itself runs on, which is how its\n // answer is in history when the panel reopens.\n useEffect(\n () => () => {\n streamDeltasRef.current?.close();\n pageActionControllerRef.current?.abort();\n },\n [],\n );\n\n // Flush the pending draft on unmount. Hosts unmount the panel the instant it\n // is closed, which would otherwise drop anything typed inside the debounce\n // window — exactly the keystrokes the draft exists to protect.\n const draftFlushRef = useRef({ conversationId, inputValue, conversationRefs });\n draftFlushRef.current = { conversationId, inputValue, conversationRefs };\n useEffect(\n () => () => {\n const { conversationId: id, inputValue: value, conversationRefs: refs } = draftFlushRef.current;\n persistDraft(id, value);\n persistDraftRefs(id, refs);\n },\n [],\n );\n\n /**\n * Recover a prompt the page never saw, or lost to a reload.\n *\n * `approval_required` is one event on one stream: reload while it is showing\n * and the panel holds nothing — not even the `tool_call_id`s a decision has\n * to name — while the turn goes on waiting for an answer that can no longer\n * be given. Asked once per conversation; an empty list is the ordinary\n * answer, and the whole probe is best-effort, since a host that has not\n * exposed the route simply keeps the pre-recovery behaviour.\n *\n * Skipped while a turn is live: that prompt arrives on the stream, and the\n * stream is the more current of the two.\n */\n useEffect(() => {\n const convId = conversationId;\n if (!convId || isLoading) return;\n if (probedConversationRef.current === convId) return;\n // Recovering a prompt there is no way to answer would only strand the\n // reviewer differently, so both routes have to be configured.\n const url = getPendingApprovalsUrl(convId);\n if (!url || !getApproveUrl()) return;\n probedConversationRef.current = convId;\n\n (async () => {\n // Best-effort: a failure leaves the panel exactly as it was, which is the\n // pre-recovery behaviour.\n const state = await readPendingApprovals(convId);\n if (!state?.proposals) return;\n // Validate at apply time against the live refs rather than dropping the\n // response on effect teardown — the same reasoning as the panel's\n // history restore. A StrictMode double-invoke or a host re-render tears\n // this effect down while the request is in flight without the\n // conversation having changed, and a teardown flag would discard the\n // recovery in exactly the case it is needed. Only a genuinely superseded\n // response is dropped: another conversation, or a live turn that has\n // since started and will carry its own prompt.\n if (conversationIdRef.current !== convId || isLoadingRef.current) return;\n approvalConversationIdRef.current = convId;\n approvalDetachedRef.current = true;\n setApprovalError(null);\n setPendingApprovals(state.proposals);\n })();\n // Keyed on the conversation and whether a turn is live; the endpoint\n // getters read current props on each run and must not re-trigger a probe.\n }, [conversationId, isLoading]);\n\n /**\n * Keep a recovered prompt answerable for as long as it is displayed.\n *\n * Only for prompts recovered after a reload: a live one is held open by its\n * own stream, which vouches for the reviewer on its own. Re-reading the\n * pending approvals is the lightest request that counts as a sign of life,\n * and its result is deliberately ignored — this is a heartbeat, not a poll,\n * and a prompt that has since gone stale is better answered with the 409 the\n * reviewer can see than made to vanish under them.\n */\n useEffect(() => {\n if (!pendingApprovals?.length || !approvalDetachedRef.current) return;\n const convId = approvalConversationIdRef.current;\n const url = convId ? getPendingApprovalsUrl(convId) : null;\n if (!url) return;\n const id = window.setInterval(() => {\n fetch(url, { headers: { ...(requestHeaders ?? {}) } }).catch(() => {\n /* A missed heartbeat is survivable: the next one is well inside the\n server's window. */\n });\n }, APPROVAL_PRESENCE_INTERVAL_MS);\n return () => window.clearInterval(id);\n // Re-armed whenever the prompt itself changes; the endpoint getter reads\n // current props on each run.\n }, [pendingApprovals]);\n\n /**\n * Watch a turn resumed by a decision made on a recovered prompt.\n *\n * The turn has no stream left to announce itself on, so its state is read\n * from the pause-recovery route: keep watching while it reports `running`,\n * and re-read the conversation once — the answer is there — when it reports\n * idle. Polling that route rather than the transcript is what makes the stop\n * condition definite instead of a guess, and it keeps the turn alive as a\n * side effect.\n *\n * A resumed turn can also pause *again* on a second gated call. With no\n * stream, this poll is the only way that prompt could ever reach the user, so\n * finding proposals puts the panel straight back into deciding.\n */\n useEffect(() => {\n if (!isResumingAfterDecision) return;\n const convId = approvalConversationIdRef.current;\n if (!convId) {\n setIsResumingAfterDecision(false);\n return;\n }\n if (Date.now() >= resumeDeadlineRef.current) {\n // Backstop only, for a turn-state marker that never clears. Re-read once\n // on the way out so a finished answer still lands.\n setIsResumingAfterDecision(false);\n reloadHistory();\n return;\n }\n\n let cancelled = false;\n const id = window.setTimeout(async () => {\n const state = await readPendingApprovals(convId);\n if (cancelled) return;\n if (!state) {\n // Learned nothing — a transient failure. Try again rather than\n // declaring a running turn finished.\n setResumeTick((n) => n + 1);\n return;\n }\n if (state.proposals) {\n approvalDetachedRef.current = true;\n setApprovalError(null);\n setPendingApprovals(state.proposals);\n setIsResumingAfterDecision(false);\n return;\n }\n if (!state.turnRunning) {\n setIsResumingAfterDecision(false);\n reloadHistory();\n return;\n }\n setResumeTick((n) => n + 1);\n }, RESUME_POLL_MS);\n\n return () => {\n cancelled = true;\n window.clearTimeout(id);\n };\n }, [isResumingAfterDecision, resumeTick, reloadHistory]);\n\n // Steering affordances are only advertised when the typed text can actually\n // be dispatched mid-run: a response is streaming (isLoading), the REST steer\n // endpoint is configured, and the conversation already has a server id (the\n // very first turn of a fresh conversation only receives its id on `done`).\n const canSteer = isLoading && getSteerUrl() !== null && conversationId !== null;\n\n return {\n messages,\n inputValue,\n setInputValue,\n isLoading,\n agentStatus,\n attachedFiles,\n conversationId,\n contextUsage,\n transferredAgent,\n canSteer,\n pendingApprovals,\n isSubmittingApproval,\n approvalError,\n submitApprovalDecisions,\n isResumingAfterDecision,\n historyReloadNonce,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n pendingWorkspaceId,\n clearPendingWorkspace,\n handleStopGenerating,\n conversationRefs,\n addConversationRef,\n setAttachedFiles,\n setMessages,\n setContextUsage,\n updateConversationId,\n handleSwitchConversation,\n };\n}\n","/**\n * Streamed answer text and reasoning, applied to React state at most once per\n * animation frame.\n *\n * A backend can emit one event per model delta, dozens a second: applied one by\n * one, each re-renders the panel and re-parses the live answer, far more often\n * than the screen can show. The deltas are gathered here and applied together\n * on the next frame. Every other event is handled after a `flush()`, so state\n * still changes in the order the events arrived.\n *\n * A hidden tab runs no frames, and needs none: what waits is the text itself,\n * not a queue of events, and the first frame once the tab is visible applies\n * it - or, before that, the next event of another kind or the end of the\n * stream.\n */\nexport interface StreamDeltas {\n /** The answer text grew; the applier reads the text itself. */\n text: () => void;\n /** A chunk of reasoning prose arrived. */\n thinking: (chunk: string) => void;\n /** Apply what is pending now. */\n flush: () => void;\n /** Drop what is pending and ignore any later delta: the stream is over or abandoned. */\n close: () => void;\n}\n\nexport function createStreamDeltas(apply: (textChanged: boolean, thinking: string) => void): StreamDeltas {\n let textChanged = false;\n let thinking = '';\n let frame: number | null = null;\n let closed = false;\n\n const cancelFrame = () => {\n if (frame !== null) cancelAnimationFrame(frame);\n frame = null;\n };\n const flush = () => {\n cancelFrame();\n if (!textChanged && !thinking) return;\n const changed = textChanged;\n const chunk = thinking;\n textChanged = false;\n thinking = '';\n apply(changed, chunk);\n };\n const schedule = () => {\n if (frame !== null) return;\n if (typeof requestAnimationFrame !== 'function') {\n flush();\n return;\n }\n frame = requestAnimationFrame(() => {\n frame = null;\n flush();\n });\n };\n\n return {\n text: () => {\n if (closed) return;\n textChanged = true;\n schedule();\n },\n thinking: (chunk) => {\n if (closed) return;\n thinking += chunk;\n schedule();\n },\n flush,\n close: () => {\n closed = true;\n cancelFrame();\n textChanged = false;\n thinking = '';\n },\n };\n}\n","import { useEffect, useState } from 'react';\nimport type { ApiEndpoints, BackendType, XtmAgent } from '../types';\n\nconst STORAGE_AGENT_KEY = 'filigranChatAgentSlug';\n\ninterface UseAgentsOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\ninterface UseAgentsReturn {\n agents: XtmAgent[];\n /** True while the first fetch is in flight. */\n agentsLoading: boolean;\n /**\n * Set when the agent list could not be retrieved — the backend is\n * unreachable, or answered an error. Distinguishes \"still loading\" from\n * \"there is nothing to load\", which an empty array alone cannot.\n */\n agentsError: boolean;\n selectedAgent: XtmAgent | null;\n setSelectedAgent: React.Dispatch<React.SetStateAction<XtmAgent | null>>;\n agentMenuOpen: boolean;\n setAgentMenuOpen: React.Dispatch<React.SetStateAction<boolean>>;\n handleSwitchAgent: (agent: XtmAgent, onSwitch?: () => void) => void;\n}\n\n/**\n * Normalize the raw agents list response.\n * Defensive: the endpoint may answer with something other than a JSON array\n * (an error envelope, an HTML error page that happens to parse), and an\n * `agents.map is not a function` thrown in ChatHeader blanks the whole panel.\n * Accepts both the bare array and the `{ agents: [...] }` envelope, mirroring\n * what useConversations tolerates, and drops entries without an agent id.\n */\nfunction parseAgents(data: unknown): XtmAgent[] {\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.agents)\n ? ((data as Record<string, unknown>).agents as unknown[])\n : [];\n return rawList.filter((raw): raw is XtmAgent => !!raw && typeof raw === 'object' && typeof (raw as XtmAgent).id === 'string');\n}\n\nexport function useAgents({ apiBaseUrl, apiEndpoints, backendType = 'rest', requestHeaders }: UseAgentsOptions): UseAgentsReturn {\n const [agents, setAgents] = useState<XtmAgent[]>([]);\n const [agentsLoading, setAgentsLoading] = useState(false);\n const [agentsError, setAgentsError] = useState(false);\n const [selectedAgent, setSelectedAgent] = useState<XtmAgent | null>(null);\n const [agentMenuOpen, setAgentMenuOpen] = useState(false);\n\n useEffect(() => {\n // Skip agents fetch if disabled, using single endpoint mode, or legacy backend\n if (apiEndpoints?.agents === null || apiEndpoints?.singleEndpoint || backendType === 'legacy') {\n return;\n }\n const agentsUrl = `${apiBaseUrl}${apiEndpoints?.agents ?? '/chat/agents'}`;\n setAgentsLoading(true);\n setAgentsError(false);\n fetch(agentsUrl, { headers: requestHeaders })\n .then((res) => {\n // A non-2xx is a failure, not an empty catalogue. Mapping it to `[]`\n // was why an unreachable backend left the menu spinning forever with\n // nothing to explain it.\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.json();\n })\n .then((data: unknown) => {\n const list = parseAgents(data);\n setAgents(list);\n if (list.length > 0 && !selectedAgent) {\n const savedSlug = localStorage.getItem(STORAGE_AGENT_KEY);\n const match = savedSlug ? list.find((a) => a.slug === savedSlug) : null;\n setSelectedAgent(match || list[0]);\n }\n })\n .catch(() => {\n setAgents([]);\n setAgentsError(true);\n })\n .finally(() => setAgentsLoading(false));\n }, [apiBaseUrl, apiEndpoints, backendType, requestHeaders]);\n\n const handleSwitchAgent = (agent: XtmAgent, onSwitch?: () => void) => {\n if (agent.id === selectedAgent?.id) {\n setAgentMenuOpen(false);\n return;\n }\n setSelectedAgent(agent);\n if (agent.slug) localStorage.setItem(STORAGE_AGENT_KEY, agent.slug);\n setAgentMenuOpen(false);\n onSwitch?.();\n };\n\n return {\n agents,\n agentsLoading,\n agentsError,\n selectedAgent,\n setSelectedAgent,\n agentMenuOpen,\n setAgentMenuOpen,\n handleSwitchAgent,\n };\n}\n","import { useCallback, useState } from 'react';\nimport type { ApiEndpoints, BackendType, ChatConversationSummary } from '../types';\nimport { refusalMessage, revertMove } from '../utils/workspaces';\n\ninterface UseConversationsOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\ninterface UseConversationsReturn {\n /** Whether the history feature is available at all (REST backend with a sessions endpoint). */\n historyEnabled: boolean;\n conversations: ChatConversationSummary[];\n conversationsLoading: boolean;\n /** Fetch (or re-fetch) the conversation list. No-ops when history is disabled. */\n refreshConversations: () => Promise<void>;\n /** Delete a conversation server-side. Returns true on success. */\n deleteConversation: (id: string) => Promise<boolean>;\n /** Rename a conversation server-side. Returns true on success. */\n renameConversation: (id: string, title: string) => Promise<boolean>;\n /**\n * File a conversation into a workspace (`null` takes it out of one) with\n * `PATCH {history}/{id}`. Resolves to `null` on success, or the backend's\n * reason (an empty string when it gave none).\n */\n moveConversation: (id: string, workspaceId: string | null) => Promise<string | null>;\n}\n\n/**\n * Normalize one raw conversation entry from the backend list response.\n * Defensive: skips entries without a conversation id, accepts both the\n * snake_case REST shape and a few aliases so older proxies keep working.\n */\nfunction parseConversation(raw: unknown): ChatConversationSummary | null {\n if (!raw || typeof raw !== 'object') return null;\n const c = raw as Record<string, unknown>;\n const id = c.conversation_id ?? c.id;\n if (typeof id !== 'string' || !id) return null;\n // Keep the raw (trimmed) title; the localized \"Untitled conversation\"\n // fallback is applied at render time (ChatHeader) so it goes through the\n // component's translation function instead of being hardcoded in English.\n const title = typeof c.title === 'string' ? c.title.trim() : '';\n const updatedAt = typeof c.updated_at === 'string' ? c.updated_at : typeof c.created_at === 'string' ? c.created_at : undefined;\n const messageCount = typeof c.message_count === 'number' ? c.message_count : undefined;\n const agentName = typeof c.agent_name === 'string' && c.agent_name ? c.agent_name : undefined;\n // Present (string or null) only when the backend reports filing at all.\n const workspaceId = typeof c.workspace_id === 'string' && c.workspace_id ? c.workspace_id : c.workspace_id === null ? null : undefined;\n return { conversationId: id, title, updatedAt, messageCount, agentName, workspaceId };\n}\n\n/**\n * Multi-conversation history for the REST backend (mirrors the XTM One web\n * chat sidebar). The conversation list is fetched lazily — when the history\n * menu opens — via `GET {apiBaseUrl}{sessions}`, and conversations are\n * deleted via `DELETE {apiBaseUrl}{sessions}/{conversation_id}`.\n *\n * Degrades gracefully: a backend that doesn't implement the list endpoint\n * yet (404/405/network error) simply yields an empty list, so the menu shows\n * its empty state instead of breaking the chat.\n */\nexport function useConversations({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n requestHeaders,\n}: UseConversationsOptions): UseConversationsReturn {\n const [conversations, setConversations] = useState<ChatConversationSummary[]>([]);\n const [conversationsLoading, setConversationsLoading] = useState(false);\n\n const historyEnabled = backendType === 'rest' && !apiEndpoints?.singleEndpoint && apiEndpoints?.sessions !== null && apiEndpoints?.history !== null;\n\n const sessionsUrl = `${apiBaseUrl}${apiEndpoints?.history ?? apiEndpoints?.sessions ?? '/chat/sessions'}`;\n\n const refreshConversations = useCallback(async () => {\n if (!historyEnabled) return;\n setConversationsLoading(true);\n try {\n const res = await fetch(sessionsUrl, {\n method: 'GET',\n headers: { ...(requestHeaders ?? {}) },\n });\n if (!res.ok) {\n setConversations([]);\n return;\n }\n const data: unknown = await res.json();\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.conversations)\n ? ((data as Record<string, unknown>).conversations as unknown[])\n : [];\n setConversations(rawList.map(parseConversation).filter((c): c is ChatConversationSummary => c !== null));\n } catch {\n setConversations([]);\n } finally {\n setConversationsLoading(false);\n }\n }, [historyEnabled, sessionsUrl, requestHeaders]);\n\n const deleteConversation = useCallback(\n async (id: string): Promise<boolean> => {\n if (!historyEnabled) return false;\n try {\n const res = await fetch(`${sessionsUrl}/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n headers: { ...(requestHeaders ?? {}) },\n });\n if (!res.ok) return false;\n setConversations((prev) => prev.filter((c) => c.conversationId !== id));\n return true;\n } catch {\n return false;\n }\n },\n [historyEnabled, sessionsUrl, requestHeaders],\n );\n\n const renameConversation = useCallback(\n async (id: string, title: string): Promise<boolean> => {\n const trimmed = title.trim();\n // An empty title is a no-op rather than an error: the backend would name\n // the conversation from its first message anyway, and silently wiping a\n // title because the user cleared the field and hit Enter is worse.\n if (!historyEnabled || !trimmed) return false;\n // Optimistic: the row is being edited in place, so waiting for the\n // round-trip would make it flicker back to the old title first.\n const previous = conversations;\n setConversations((prev) => prev.map((c) => (c.conversationId === id ? { ...c, title: trimmed } : c)));\n try {\n const res = await fetch(`${sessionsUrl}/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ title: trimmed }),\n });\n if (!res.ok) {\n setConversations(previous);\n return false;\n }\n return true;\n } catch {\n setConversations(previous);\n return false;\n }\n },\n [historyEnabled, sessionsUrl, requestHeaders, conversations],\n );\n\n const moveConversation = useCallback(\n async (id: string, workspaceId: string | null): Promise<string | null> => {\n if (!historyEnabled) return '';\n // Optimistic, like a rename: the row moves under the pointer that\n // dropped it, and goes back if the backend refuses. Only this row, and\n // only while it is still where this move put it: other moves may have\n // landed, or the list been refreshed, while this one was in flight.\n const previous = conversations.find((c) => c.conversationId === id)?.workspaceId;\n const revert = () => setConversations((prev) => revertMove(prev, id, workspaceId, previous));\n setConversations((prev) => prev.map((c) => (c.conversationId === id ? { ...c, workspaceId } : c)));\n try {\n const res = await fetch(`${sessionsUrl}/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ workspace_id: workspaceId }),\n });\n if (!res.ok) {\n revert();\n return (await refusalMessage(res)) ?? '';\n }\n return null;\n } catch {\n revert();\n return '';\n }\n },\n [historyEnabled, sessionsUrl, requestHeaders, conversations],\n );\n\n return { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation, renameConversation, moveConversation };\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { ChatMode } from '../types';\n\nconst SIDEBAR_WIDTH = 400;\nconst SIDEBAR_WIDTH_STORAGE_KEY = 'filigranChatSidebarWidth';\nconst MAX_SIDEBAR_RATIO = 0.4;\n\ninterface UseSidebarResizeOptions {\n mode: ChatMode;\n resizable: boolean;\n onWidthChange?: (width: number) => void;\n onResizeStart?: () => void;\n onResizeEnd?: () => void;\n}\n\ninterface UseSidebarResizeReturn {\n sidebarWidth: number;\n handleResizeStart: (e: React.MouseEvent) => void;\n defaultWidth: number;\n isResizing: boolean;\n}\n\nexport function useSidebarResize({ mode, resizable, onWidthChange, onResizeStart, onResizeEnd }: UseSidebarResizeOptions): UseSidebarResizeReturn {\n const [sidebarWidth, setSidebarWidth] = useState<number>(() => {\n if (typeof window === 'undefined') return SIDEBAR_WIDTH;\n const stored = localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY);\n if (stored) {\n const parsed = parseInt(stored, 10);\n if (!Number.isNaN(parsed) && parsed >= SIDEBAR_WIDTH) return parsed;\n }\n return SIDEBAR_WIDTH;\n });\n const [isResizing, setIsResizing] = useState(false);\n\n const isResizingRef = useRef(false);\n const sidebarWidthRef = useRef(sidebarWidth);\n sidebarWidthRef.current = sidebarWidth;\n const onWidthChangeRef = useRef(onWidthChange);\n onWidthChangeRef.current = onWidthChange;\n const onResizeEndRef = useRef(onResizeEnd);\n onResizeEndRef.current = onResizeEnd;\n\n // Notify parent of sidebar width when entering sidebar mode\n useEffect(() => {\n if (mode === 'sidebar' && resizable) {\n onWidthChangeRef.current?.(sidebarWidthRef.current);\n }\n }, [mode, resizable]);\n\n // Resize event handlers\n useEffect(() => {\n if (mode !== 'sidebar' || !resizable) return undefined;\n\n const handleMouseMove = (e: MouseEvent) => {\n if (!isResizingRef.current) return;\n e.preventDefault();\n const newWidth = window.innerWidth - e.clientX;\n const maxWidth = window.innerWidth * MAX_SIDEBAR_RATIO;\n const clamped = Math.min(Math.max(newWidth, SIDEBAR_WIDTH), maxWidth);\n setSidebarWidth(clamped);\n sidebarWidthRef.current = clamped;\n onWidthChangeRef.current?.(clamped);\n };\n\n const handleMouseUp = () => {\n if (!isResizingRef.current) return;\n isResizingRef.current = false;\n setIsResizing(false);\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(sidebarWidthRef.current));\n onResizeEndRef.current?.();\n };\n\n const handleWindowResize = () => {\n const maxWidth = window.innerWidth * MAX_SIDEBAR_RATIO;\n if (sidebarWidthRef.current > maxWidth) {\n const clamped = Math.max(maxWidth, SIDEBAR_WIDTH);\n setSidebarWidth(clamped);\n sidebarWidthRef.current = clamped;\n onWidthChangeRef.current?.(clamped);\n }\n };\n\n document.addEventListener('mousemove', handleMouseMove);\n document.addEventListener('mouseup', handleMouseUp);\n window.addEventListener('resize', handleWindowResize);\n\n return () => {\n document.removeEventListener('mousemove', handleMouseMove);\n document.removeEventListener('mouseup', handleMouseUp);\n window.removeEventListener('resize', handleWindowResize);\n };\n }, [mode, resizable]);\n\n const handleResizeStart = (e: React.MouseEvent) => {\n e.preventDefault();\n isResizingRef.current = true;\n setIsResizing(true);\n document.body.style.cursor = 'col-resize';\n document.body.style.userSelect = 'none';\n onResizeStart?.();\n };\n\n return {\n sidebarWidth,\n handleResizeStart,\n defaultWidth: SIDEBAR_WIDTH,\n isResizing,\n };\n}\n","import { useEffect, useRef } from 'react';\nimport { translate } from '../utils';\n\n/**\n * A turn must run at least this long before its completion is worth a\n * notification — instant replies never raise one.\n */\nconst MIN_NOTICE_MS = 4000;\n/** Document-title flash cadence while the user is away. */\nconst TITLE_FLASH_MS = 1200;\n\n// The document title is a single page-global resource, so the flash is shared\n// across hook instances on purpose (per-hook timers would fight over the one\n// `document.title` and clobber each other's saved title). `activeHooks` ref-\n// counts mounted, enabled instances so one panel unmounting never cancels a\n// flash another panel still owns — only the last one to leave restores it.\nlet flashTimer: number | null = null;\nlet originalTitle: string | null = null;\nlet activeHooks = 0;\n\n/** Stop flashing and restore the page title captured when the flash began. */\nfunction stopTitleFlash(): void {\n if (flashTimer !== null) {\n window.clearInterval(flashTimer);\n flashTimer = null;\n }\n if (originalTitle !== null) {\n document.title = originalTitle;\n originalTitle = null;\n }\n}\n\n/**\n * Flash the document title so a multitasking user notices the answer landed\n * even from another tab or window. The flash is stopped (and the title\n * restored) the moment the tab is visible AND focused again, by the\n * hook-scoped listeners below. Title flashing needs no permission and is the\n * reliable baseline of the completion notification.\n */\nfunction startTitleFlash(message: string): void {\n if (typeof document === 'undefined') return;\n if (originalTitle === null) originalTitle = document.title;\n if (flashTimer !== null) window.clearInterval(flashTimer);\n let showMessage = true;\n document.title = message;\n flashTimer = window.setInterval(() => {\n showMessage = !showMessage;\n document.title = showMessage ? message : (originalTitle ?? message);\n }, TITLE_FLASH_MS);\n}\n\n/**\n * Best-effort OS notification — only fired when the user has already granted\n * permission. We deliberately never call `Notification.requestPermission()`\n * unprompted: the title flash (and the host toast) cover the case where OS\n * notifications are unavailable.\n */\nfunction notifyOS(title: string, body: string): void {\n try {\n if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return;\n new Notification(title, { body, tag: 'filigran-chat-complete' });\n } catch {\n /* Notification constructor can throw on some platforms — ignore. */\n }\n}\n\ninterface UseAwayCompletionNoticeOptions {\n /** True while a response is being generated. */\n isLoading: boolean;\n /** Name of the answering agent, used in the notification body. */\n agentName: string;\n t: (key: string) => string;\n /** Master switch (default true). */\n enabled?: boolean;\n /**\n * Host hook fired when a long turn finishes and the user is not actively\n * watching the chat — either away (tab hidden / another window) or in-app\n * with the chat surface closed/hidden (`isViewingChat` reports not-viewing).\n * Lets the host raise its own in-app toast (the chatbot has no toast surface\n * of its own). Receives the translated strings.\n */\n onComplete?: (title: string, body: string) => void;\n /**\n * Returns true when the chat surface is on screen for the user (the panel is\n * open and visible) — NOT merely whether focus sits inside it. When provided,\n * the notice also fires if the chat surface is hidden/closed while the tab is\n * still focused (e.g. a docked sidebar the host has collapsed). It must NOT\n * key on focus-within: in sidebar/floating mode the user reads a streamed\n * answer while their focus stays in the host app, and pinging them for an\n * answer they can already see is exactly the noise this guards against. When\n * omitted, only the away case (tab hidden / window unfocused) triggers it.\n */\n isViewingChat?: () => boolean;\n}\n\n/**\n * Notify the user when a long-running turn finishes and they are not watching\n * the chat. State is read at completion (never latched mid-turn) so someone who\n * stepped away but returned before the turn finished is not pinged:\n * - **Away** (tab hidden or another window/app focused): document-title flash +\n * OS notification (when granted) + host toast.\n * - **Surface not visible** (window focused & tab visible, but the chat panel\n * is closed/hidden — only when `isViewingChat` reports not-viewing): host\n * toast only.\n * - **Actively watching** (tab visible, window focused, panel on screen):\n * nothing — the streamed answer is itself the feedback.\n */\nexport function useAwayCompletionNotice({\n isLoading,\n agentName,\n t,\n enabled = true,\n onComplete,\n isViewingChat,\n}: UseAwayCompletionNoticeOptions): void {\n const wasLoadingRef = useRef(false);\n const startRef = useRef(0);\n\n // Stop the flash and restore the title as soon as the user returns to a\n // visible, focused tab. Bound only while enabled and torn down on unmount (or\n // when the host disables it), so we never leak listeners or leave the title\n // flashing after the panel is gone.\n useEffect(() => {\n if (!enabled || typeof document === 'undefined') return;\n activeHooks += 1;\n const clearOnReturn = () => {\n if (!document.hidden && document.hasFocus()) stopTitleFlash();\n };\n document.addEventListener('visibilitychange', clearOnReturn);\n window.addEventListener('focus', clearOnReturn);\n return () => {\n document.removeEventListener('visibilitychange', clearOnReturn);\n window.removeEventListener('focus', clearOnReturn);\n activeHooks = Math.max(0, activeHooks - 1);\n // Only restore the title once the last consumer leaves, so unmounting one\n // panel never cancels another panel's in-flight flash.\n if (activeHooks === 0) stopTitleFlash();\n };\n }, [enabled]);\n\n useEffect(() => {\n const wasLoading = wasLoadingRef.current;\n wasLoadingRef.current = isLoading;\n\n if (isLoading && !wasLoading) {\n startRef.current = Date.now();\n return;\n }\n\n if (!isLoading && wasLoading && enabled) {\n const elapsed = Date.now() - startRef.current;\n if (elapsed < MIN_NOTICE_MS) return;\n const hidden = typeof document !== 'undefined' && document.hidden;\n const unfocused = typeof document !== 'undefined' && !document.hasFocus();\n const away = hidden || unfocused;\n const viewingChat = isViewingChat ? isViewingChat() : true;\n // Focused tab + looking at the chat → the streamed answer is the feedback.\n if (!away && viewingChat) return;\n const title = t('Response ready');\n const body = agentName ? translate(t, '{agent} has finished', { agent: agentName }) : t('Your answer is ready');\n if (away) {\n startTitleFlash(title);\n notifyOS(title, body);\n }\n onComplete?.(title, body);\n }\n }, [isLoading, enabled, agentName, t, onComplete, isViewingChat]);\n}\n","import { useCallback, useEffect, useState } from 'react';\nimport type { ApiEndpoints, BackendType, ChatPromptTemplate, ChatQuotaStatus } from '../types';\nimport { parseQuota } from '../utils/quota';\n\ninterface UseComposerExtrasOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\ninterface UseComposerExtrasReturn {\n /** Null while unavailable — the toolbar then omits the affordance entirely. */\n prompts: ChatPromptTemplate[] | null;\n quota: ChatQuotaStatus | null;\n /** Re-read the quota after a turn completes, so the indicator stays honest. */\n refreshQuota: () => void;\n}\n\n/** Defensive parse: an unexpected payload yields no prompts rather than a crash. */\nfunction parsePrompts(data: unknown): ChatPromptTemplate[] {\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.prompts)\n ? ((data as Record<string, unknown>).prompts as unknown[])\n : [];\n const out: ChatPromptTemplate[] = [];\n for (const item of rawList) {\n if (!item || typeof item !== 'object') continue;\n const p = item as Record<string, unknown>;\n const id = typeof p.id === 'string' ? p.id : '';\n const content = typeof p.content === 'string' ? p.content : '';\n // A prompt with nothing to insert is not worth listing.\n if (!id || !content) continue;\n out.push({\n id,\n title: typeof p.title === 'string' && p.title ? p.title : id,\n content,\n description: typeof p.description === 'string' ? p.description : undefined,\n });\n }\n return out;\n}\n\n/**\n * Fetches the two data-driven composer toolbar items: the prompt library and\n * the quota indicator.\n *\n * Both are opt-in by configuration rather than by a mode flag — a host that\n * does not serve the route (or sets it to null) simply gets no affordance, so\n * the UI can never advertise something the backend cannot answer. Neither is\n * available on the legacy / ag-ui backends or in single-endpoint mode, which\n * have no route to carry them.\n */\nexport function useComposerExtras({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n requestHeaders,\n}: UseComposerExtrasOptions): UseComposerExtrasReturn {\n const [prompts, setPrompts] = useState<ChatPromptTemplate[] | null>(null);\n const [quota, setQuota] = useState<ChatQuotaStatus | null>(null);\n\n const restLike = backendType === 'rest' && !apiEndpoints?.singleEndpoint;\n const promptsPath = apiEndpoints?.prompts === undefined ? '/chat/prompts' : apiEndpoints.prompts;\n const quotaPath = apiEndpoints?.quota === undefined ? '/chat/quota' : apiEndpoints.quota;\n const promptsUrl = restLike && promptsPath ? `${apiBaseUrl}${promptsPath}` : null;\n const quotaUrl = restLike && quotaPath ? `${apiBaseUrl}${quotaPath}` : null;\n\n useEffect(() => {\n if (!promptsUrl) {\n setPrompts(null);\n return;\n }\n let cancelled = false;\n fetch(promptsUrl, { credentials: 'include', headers: { ...(requestHeaders ?? {}) } })\n .then((res) => (res.ok ? res.json() : null))\n .then((data) => {\n if (cancelled) return;\n // A failed or empty fetch leaves the affordance hidden rather than\n // showing an empty menu the user cannot act on.\n const parsed = data === null ? [] : parsePrompts(data);\n setPrompts(parsed.length > 0 ? parsed : null);\n })\n .catch(() => {\n if (!cancelled) setPrompts(null);\n });\n return () => {\n cancelled = true;\n };\n }, [promptsUrl, requestHeaders]);\n\n const [quotaNonce, setQuotaNonce] = useState(0);\n const refreshQuota = useCallback(() => setQuotaNonce((n) => n + 1), []);\n\n useEffect(() => {\n if (!quotaUrl) {\n setQuota(null);\n return;\n }\n let cancelled = false;\n fetch(quotaUrl, { credentials: 'include', headers: { ...(requestHeaders ?? {}) } })\n .then((res) => (res.ok ? res.json() : null))\n .then((data) => {\n if (!cancelled) setQuota(parseQuota(data));\n })\n .catch(() => {\n if (!cancelled) setQuota(null);\n });\n return () => {\n cancelled = true;\n };\n }, [quotaUrl, requestHeaders, quotaNonce]);\n\n return { prompts, quota, refreshQuota };\n}\n","import type { ChatQuotaStatus, Translate } from '../types';\n\n/**\n * The quota the composer indicator shows, as the quota route sends it.\n *\n * Kept free of local runtime imports so `node --test` runs it as is.\n */\n\n/** Defensive parse: an unexpected payload shows no indicator rather than a wrong one. */\nexport function parseQuota(data: unknown): ChatQuotaStatus | null {\n if (!data || typeof data !== 'object') return null;\n const q = data as Record<string, unknown>;\n if (typeof q.used !== 'number') return null;\n return {\n used: q.used,\n // Explicitly nullable: absent and null both mean \"no ceiling\".\n limit: typeof q.limit === 'number' ? q.limit : null,\n period: typeof q.period === 'string' ? q.period : '',\n ...(q.scope === 'global' || q.scope === 'user' ? { scope: q.scope } : {}),\n };\n}\n\n/**\n * The period a limit applies to, as the tooltip words it: the periods XTM One\n * sets a quota for are translated, anything else is shown as sent.\n */\nexport function quotaPeriodLabel(period: string, t: Translate): string {\n switch (period) {\n case 'daily':\n return t('today');\n case 'monthly':\n return t('this month');\n case 'yearly':\n return t('this year');\n default:\n return period;\n }\n}\n","import { useEffect, useState } from 'react';\nimport type { ApiEndpoints, BackendType } from '../types';\n\ninterface UseAgentSuggestionsOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n /** Selected agent; suggestions are re-fetched whenever it changes. */\n agentSlug: string | null | undefined;\n}\n\ninterface UseAgentSuggestionsReturn {\n /** Null when unavailable — the caller then falls back to its own list. */\n suggestions: string[] | null;\n loading: boolean;\n}\n\n/** Accepts a bare array or `{ suggestions: [...] }`, and drops non-strings. */\nfunction parseSuggestions(data: unknown): string[] {\n const rawList = Array.isArray(data)\n ? data\n : Array.isArray((data as Record<string, unknown>)?.suggestions)\n ? ((data as Record<string, unknown>).suggestions as unknown[])\n : [];\n return rawList\n .map((s) => {\n if (typeof s === 'string') return s.trim();\n // Tolerate `{ label }` / `{ prompt }` objects: an \"action suggestion\"\n // is likely to grow fields, and a richer payload should not blank the\n // welcome screen for older clients.\n if (s && typeof s === 'object') {\n const o = s as Record<string, unknown>;\n const v = o.prompt ?? o.label ?? o.text;\n if (typeof v === 'string') return v.trim();\n }\n return '';\n })\n .filter((s) => s.length > 0);\n}\n\n/**\n * Suggested opening actions for the selected agent.\n *\n * Fetched per agent so the welcome screen changes when you switch — which is\n * also the confirmation that the switch took effect. Generic today; the\n * endpoint is the seam through which they can become per-user later without\n * touching this package.\n *\n * Returns null (rather than an empty list) whenever the route is unavailable\n * or answers nothing usable, so the caller can fall back to its own\n * `promptSuggestions` instead of rendering an empty section.\n */\nexport function useAgentSuggestions({\n apiBaseUrl,\n apiEndpoints,\n backendType = 'rest',\n requestHeaders,\n agentSlug,\n}: UseAgentSuggestionsOptions): UseAgentSuggestionsReturn {\n const [suggestions, setSuggestions] = useState<string[] | null>(null);\n const [loading, setLoading] = useState(false);\n\n const restLike = backendType === 'rest' && !apiEndpoints?.singleEndpoint;\n const path = apiEndpoints?.suggestions === undefined ? '/chat/suggestions' : apiEndpoints.suggestions;\n const baseUrl = restLike && path ? `${apiBaseUrl}${path}` : null;\n\n useEffect(() => {\n if (!baseUrl) {\n setSuggestions(null);\n return;\n }\n let cancelled = false;\n setLoading(true);\n // The agent is a query parameter rather than a path segment: a backend\n // that ignores it still answers with its generic set, which is exactly the\n // \"generic today, personalised later\" progression.\n const url = agentSlug ? `${baseUrl}?agent_slug=${encodeURIComponent(agentSlug)}` : baseUrl;\n fetch(url, { credentials: 'include', headers: { ...(requestHeaders ?? {}) } })\n .then((res) => (res.ok ? res.json() : null))\n .then((data) => {\n if (cancelled) return;\n const parsed = data === null ? [] : parseSuggestions(data);\n setSuggestions(parsed.length > 0 ? parsed : null);\n })\n .catch(() => {\n if (!cancelled) setSuggestions(null);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [baseUrl, agentSlug, requestHeaders]);\n\n return { suggestions, loading };\n}\n","import { useCallback, useInsertionEffect, useRef } from 'react';\n\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every(\n (key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\n/**\n * `value`, keeping the previous object while its keys and values are the same.\n *\n * For plain-data props a host builds inline (headers, endpoint paths, page\n * context): a new but equal object on every host render would otherwise break\n * the memoized message rows and re-run every effect keyed on it — refetching\n * agents, prompts, quota and suggestions, and every image fetched with the\n * headers.\n */\nexport function useShallowStable<T>(value: T): T {\n const ref = useRef(value);\n if (!shallowEqual(ref.current, value)) ref.current = value;\n return ref.current;\n}\n\n/**\n * A function with a stable identity that always calls the latest `callback`,\n * or `undefined` while there is none (callers test for presence to decide what\n * to render).\n */\nexport function useLatestCallback<Args extends unknown[], Result>(\n callback: ((...args: Args) => Result) | undefined,\n): ((...args: Args) => Result) | undefined {\n const ref = useRef(callback);\n // Updated before any layout or passive effect runs, so an effect of this\n // render never calls the previous callback.\n useInsertionEffect(() => {\n ref.current = callback;\n });\n const stable = useCallback((...args: Args) => ref.current?.(...args) as Result, []);\n return callback ? stable : undefined;\n}\n","import type { IconProps } from '../../types';\n\nexport const AlertTriangleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ArrowRightLeftIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m16 3 4 4-4 4\" />\n <path d=\"M20 7H4\" />\n <path d=\"m8 21-4-4 4-4\" />\n <path d=\"M4 17h16\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const AttachFileIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const BotIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 8V4H8\" />\n <rect width=\"16\" height=\"12\" x=\"4\" y=\"8\" rx=\"2\" />\n <path d=\"M2 14h2\" />\n <path d=\"M20 14h2\" />\n <path d=\"M15 13v2\" />\n <path d=\"M9 13v2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const BrainIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z\" />\n <path d=\"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z\" />\n <path d=\"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4\" />\n <path d=\"M17.599 6.5a3 3 0 0 0 .399-1.375\" />\n <path d=\"M6.003 5.125A3 3 0 0 0 6.401 6.5\" />\n <path d=\"M3.477 10.896a4 4 0 0 1 .585-.396\" />\n <path d=\"M19.938 10.5a4 4 0 0 1 .585.396\" />\n <path d=\"M6 18a4 4 0 0 1-1.967-.516\" />\n <path d=\"M19.967 17.484A4 4 0 0 1 18 18\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CheckCircleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m9 12 2 2 4-4\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CheckIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ChevronDownIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ChevronRightIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m9 18 6-6-6-6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CloseIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M18 6 6 18\" />\n <path d=\"m6 6 12 12\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const CopyIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\" />\n <path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const DatabaseIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\" />\n <path d=\"M3 5V19A9 3 0 0 0 21 19V5\" />\n <path d=\"M3 12A9 3 0 0 0 21 12\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const DefaultLogoIcon = ({ className, size = 24 }: IconProps) => (\n <svg xmlns=\"http://www.w3.org/2000/svg\" width={size} height={size} viewBox=\"0 0 24 24\" fill=\"currentColor\" stroke=\"none\" className={className}>\n <path d=\"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const DownloadIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n <polyline points=\"7 10 12 15 17 10\" />\n <line x1=\"12\" x2=\"12\" y1=\"15\" y2=\"3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const EditIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 20h9\" />\n <path d=\"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ExternalLinkIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 3h6v6\" />\n <path d=\"M10 14 21 3\" />\n <path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FileIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FloatingIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7\" />\n <rect width=\"12\" height=\"12\" x=\"10\" y=\"10\" rx=\"2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FolderIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FolderInputIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1\" />\n <path d=\"M2 13h10\" />\n <path d=\"m9 16 3-3-3-3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FolderPlusIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 10v6\" />\n <path d=\"M9 13h6\" />\n <path d=\"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FullscreenExitIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M8 3v3a2 2 0 0 1-2 2H3\" />\n <path d=\"M21 8h-3a2 2 0 0 1-2-2V3\" />\n <path d=\"M3 16h3a2 2 0 0 0 2 2v3\" />\n <path d=\"M16 21v-3a2 2 0 0 1 2-2h3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FullscreenIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M8 3H5a2 2 0 0 0-2 2v3\" />\n <path d=\"M21 8V5a2 2 0 0 0-2-2h-3\" />\n <path d=\"M3 16v3a2 2 0 0 0 2 2h3\" />\n <path d=\"M16 21h3a2 2 0 0 0 2-2v-3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const GamepadIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <line x1=\"6\" x2=\"10\" y1=\"11\" y2=\"11\" />\n <line x1=\"8\" x2=\"8\" y1=\"9\" y2=\"13\" />\n <line x1=\"15\" x2=\"15.01\" y1=\"12\" y2=\"12\" />\n <line x1=\"18\" x2=\"18.01\" y1=\"10\" y2=\"10\" />\n <path d=\"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const GlobeIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" />\n <path d=\"M2 12h20\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const HistoryIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n <path d=\"M12 7v5l4 2\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ImageIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\" />\n <circle cx=\"9\" cy=\"9\" r=\"2\" />\n <path d=\"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const InfoIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 16v-4\" />\n <path d=\"M12 8h.01\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MailIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"20\" height=\"16\" x=\"2\" y=\"4\" rx=\"2\" />\n <path d=\"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MaximizeIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 3h6v6\" />\n <path d=\"M9 21H3v-6\" />\n <path d=\"M21 3l-7 7\" />\n <path d=\"M3 21l7-7\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MessageSquareIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const MicIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 19v3\" />\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n <rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\" />\n </svg>\n);\n\nexport const MicOffIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M12 19v3\" />\n <path d=\"M19 10v2a7 7 0 0 1-.11 1.23\" />\n <path d=\"M5 10v2a7 7 0 0 0 12 5\" />\n <path d=\"M15 9.34V5a3 3 0 0 0-5.68-1.33\" />\n <path d=\"M9 9v3a3 3 0 0 0 5.12 2.12\" />\n <path d=\"m2 2 20 20\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const PencilIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z\" />\n <path d=\"m15 5 4 4\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SearchIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.3-4.3\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SendIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"m22 2-7 20-4-9-9-4Z\" />\n <path d=\"m22 2-11 11\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SidebarIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" />\n <path d=\"M15 3v18\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const SparklesIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const StopCircleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <rect width=\"6\" height=\"6\" x=\"9\" y=\"9\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const TerminalIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <polyline points=\"4 17 10 11 4 5\" />\n <line x1=\"12\" x2=\"20\" y1=\"19\" y2=\"19\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ThumbsDownIcon = ({ className, size = 24, filled = false }: IconProps & { filled?: boolean }) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill={filled ? 'currentColor' : 'none'}\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M17 14V2\" />\n <path d=\"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ThumbsUpIcon = ({ className, size = 24, filled = false }: IconProps & { filled?: boolean }) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill={filled ? 'currentColor' : 'none'}\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M7 10v12\" />\n <path d=\"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const TrashIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M3 6h18\" />\n <path d=\"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6\" />\n <path d=\"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2\" />\n <line x1=\"10\" x2=\"10\" y1=\"11\" y2=\"17\" />\n <line x1=\"14\" x2=\"14\" y1=\"11\" y2=\"17\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const UserPlusIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2\" />\n <circle cx=\"9\" cy=\"7\" r=\"4\" />\n <line x1=\"19\" x2=\"19\" y1=\"8\" y2=\"14\" />\n <line x1=\"22\" x2=\"16\" y1=\"11\" y2=\"11\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nconst SPEAKER =\n 'M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z';\n\nexport const VolumeIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d={SPEAKER} />\n <path d=\"M16 9a5 5 0 0 1 0 6\" />\n <path d=\"M19.364 18.364a9 9 0 0 0 0-12.728\" />\n </svg>\n);\n\nexport const VolumeOffIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d={SPEAKER} />\n <path d=\"m22 9-6 6\" />\n <path d=\"m16 9 6 6\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const WrenchIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const XCircleIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m15 9-6 6\" />\n <path d=\"m9 9 6 6\" />\n </svg>\n);\n","import { useCallback, useLayoutEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useClickOutside } from '../hooks/useClickOutside';\nimport { findChatbotRoot } from '../utils';\n\ninterface DropdownProps {\n open: boolean;\n onClose: () => void;\n anchorRef: React.RefObject<HTMLElement | null>;\n placement?: 'bottom-start' | 'bottom-end';\n width?: number;\n children: React.ReactNode;\n}\n\n/** Breathing room between the anchor and the panel, and from the viewport edge. */\nconst GAP = 4;\nconst EDGE_MARGIN = 8;\n\nexport const Dropdown = ({ open, onClose, anchorRef, placement = 'bottom-start', width = 280, children }: DropdownProps) => {\n const panelRef = useRef<HTMLDivElement>(null);\n const [pos, setPos] = useState({ top: 0, left: 0 });\n\n const stableOnClose = useCallback(() => onClose(), [onClose]);\n useClickOutside(panelRef, stableOnClose, open);\n\n // `useLayoutEffect`, not `useEffect`: the panel is measured after it mounts\n // and then moved, so doing it after paint would show it in the wrong place\n // for a frame.\n useLayoutEffect(() => {\n if (!open || !anchorRef.current) return;\n const rect = anchorRef.current.getBoundingClientRect();\n const panelHeight = panelRef.current?.offsetHeight ?? 0;\n\n // Flip above the anchor when there isn't room below and there is more room\n // above. The composer toolbar sits at the bottom of the panel, so its\n // menus would otherwise open straight off the bottom edge and be\n // unreachable — the anchor's own position decides, so callers don't have\n // to know where they are.\n const spaceBelow = window.innerHeight - rect.bottom - EDGE_MARGIN;\n const spaceAbove = rect.top - EDGE_MARGIN;\n const flipUp = panelHeight > 0 && spaceBelow < panelHeight && spaceAbove > spaceBelow;\n const top = flipUp ? Math.max(EDGE_MARGIN, rect.top - panelHeight - GAP) : rect.bottom + GAP;\n\n // Keep it inside the viewport horizontally too: the floating panel is\n // narrow, so a menu anchored near its right edge would otherwise hang off.\n const preferredLeft = placement === 'bottom-end' ? rect.right - width : rect.left;\n const left = Math.max(EDGE_MARGIN, Math.min(preferredLeft, window.innerWidth - width - EDGE_MARGIN));\n\n setPos({ top, left });\n }, [open, anchorRef, placement, width, children]);\n\n if (!open) return null;\n\n const portalTarget = findChatbotRoot(anchorRef.current);\n\n return createPortal(\n <div\n ref={panelRef}\n className=\"fixed z-[10000] rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl\"\n style={{ top: pos.top, left: pos.left, width }}\n >\n {children}\n </div>,\n portalTarget,\n );\n};\n","import { useEffect, type RefObject } from 'react';\n\nexport function useClickOutside(ref: RefObject<HTMLElement | null>, handler: () => void, active = true) {\n useEffect(() => {\n if (!active) return undefined;\n const listener = (e: MouseEvent | TouchEvent) => {\n if (!ref.current || ref.current.contains(e.target as Node)) return;\n handler();\n };\n document.addEventListener('mousedown', listener);\n document.addEventListener('touchstart', listener);\n return () => {\n document.removeEventListener('mousedown', listener);\n document.removeEventListener('touchstart', listener);\n };\n }, [ref, handler, active]);\n}\n","interface SpinnerProps {\n size?: number;\n className?: string;\n}\n\nexport const Spinner = ({ size = 16, className = '' }: SpinnerProps) => (\n <div\n className={`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${className}`}\n style={{ width: size, height: size }}\n />\n);\n","/**\n * Where a tooltip is drawn.\n *\n * It is centred above its anchor. Near the side of the panel (the time under a\n * message) it would run past it - into the host page, or off the screen - and\n * near the top it would run above it, into the host app's top bar. So its width\n * is capped to the room there is (a long label wraps instead), it is shifted back\n * inside, and it opens below its anchor when there is no room above.\n */\n\n/** Space between a tooltip and its anchor. */\nexport const ANCHOR_GAP = 4;\n\n/** Space kept between a tooltip and the side of the panel it would cross. */\nexport const EDGE_MARGIN = 4;\n\n/** A box in viewport coordinates, as `getBoundingClientRect` returns it. */\nexport interface Box {\n readonly top: number;\n readonly bottom: number;\n readonly left: number;\n readonly right: number;\n}\n\n/** A tooltip's anchor and the room it may take: the part of the panel inside the viewport, less the margins. */\nexport interface TooltipOpening {\n readonly top: number;\n readonly bottom: number;\n readonly center: number;\n readonly minTop: number;\n readonly minLeft: number;\n readonly maxRight: number;\n}\n\nexport interface TooltipPlacement {\n /** Drawn below its anchor instead of above. */\n readonly below: boolean;\n /** Horizontal offset from the anchor's centre that keeps it inside. */\n readonly shift: number;\n}\n\nexport function tooltipOpening(anchor: Box, panel: Box, viewportWidth: number): TooltipOpening {\n return {\n top: anchor.top,\n bottom: anchor.bottom,\n center: (anchor.left + anchor.right) / 2,\n minTop: Math.max(panel.top, 0),\n minLeft: Math.max(panel.left, 0) + EDGE_MARGIN,\n maxRight: Math.min(panel.right, viewportWidth) - EDGE_MARGIN,\n };\n}\n\n/** The widest a tooltip may be drawn: wider than that, it would cross the panel's side whatever its shift. */\nexport function tooltipMaxWidth(opening: TooltipOpening): number {\n return Math.max(opening.maxRight - opening.minLeft, 0);\n}\n\n/** Places a tooltip of the measured size, drawn no wider than `tooltipMaxWidth`. */\nexport function placeTooltip(opening: TooltipOpening, size: { readonly width: number; readonly height: number }): TooltipPlacement {\n const left = opening.center - size.width / 2;\n let shift = 0;\n if (left < opening.minLeft) shift = opening.minLeft - left;\n else if (left + size.width > opening.maxRight) shift = opening.maxRight - (left + size.width);\n return { below: opening.top - ANCHOR_GAP - size.height < opening.minTop, shift };\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { findChatbotRoot } from '../utils';\nimport { ANCHOR_GAP, placeTooltip, tooltipMaxWidth, tooltipOpening, type TooltipOpening } from '../utils/tooltipPlacement';\n\ninterface TooltipProps {\n title: string;\n children: React.ReactElement;\n}\n\nexport const Tooltip = ({ title, children }: TooltipProps) => {\n const ref = useRef<HTMLSpanElement>(null);\n const tipRef = useRef<HTMLSpanElement>(null);\n const [opening, setOpening] = useState<TooltipOpening | null>(null);\n const [placement, setPlacement] = useState({ below: false, shift: 0 });\n\n // Its size is its text's, wrapped to the room there is: measured once shown,\n // before the browser paints it. The tooltip lives inside the panel's stacking\n // context (z-[1200] in sidebar mode), so anything drawn above the panel lands\n // in the host app's top-bar zone and is hidden whenever the host bar stacks\n // higher (e.g. OpenAEV's AppBar at theme.zIndex.drawer + 1).\n useLayoutEffect(() => {\n if (!opening || !tipRef.current) return;\n const { width, height } = tipRef.current.getBoundingClientRect();\n setPlacement(placeTooltip(opening, { width, height }));\n }, [opening, title]);\n\n if (!title) return children;\n\n const open = () => {\n if (!ref.current) return;\n const panel = findChatbotRoot(ref.current).getBoundingClientRect();\n setOpening(tooltipOpening(ref.current.getBoundingClientRect(), panel, window.innerWidth));\n };\n\n // A keyboard user reaches the control without hovering it, so its tooltip\n // opens on focus too - on keyboard focus only: a click also focuses, and the\n // hover has already shown the tooltip then.\n const handleFocus = (event: React.FocusEvent) => {\n const target = event.target as HTMLElement;\n if (typeof target.matches === 'function' && target.matches(':focus-visible')) open();\n };\n\n return (\n <span\n ref={ref}\n className=\"inline-flex\"\n onMouseEnter={open}\n onMouseLeave={() => setOpening(null)}\n onFocus={handleFocus}\n onBlur={() => setOpening(null)}\n >\n {children}\n {opening &&\n createPortal(\n <span\n ref={tipRef}\n className={`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${placement.below ? '' : '-translate-y-full'} whitespace-normal break-words rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`}\n style={{\n top: placement.below ? opening.bottom + ANCHOR_GAP : opening.top - ANCHOR_GAP,\n left: opening.center + placement.shift,\n maxWidth: tooltipMaxWidth(opening),\n }}\n role=\"tooltip\"\n >\n {title}\n </span>,\n findChatbotRoot(ref.current),\n )}\n </span>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport type { ChatConversationSummary, ChatMode, Translate, XtmAgent } from '../types';\nimport { timeAgo, translate } from '../utils';\nimport {\n AlertTriangleIcon,\n ChevronDownIcon,\n CloseIcon,\n EditIcon,\n ExternalLinkIcon,\n FloatingIcon,\n FullscreenExitIcon,\n FullscreenIcon,\n HistoryIcon,\n SearchIcon,\n SidebarIcon,\n TrashIcon,\n UserPlusIcon,\n} from './icons';\nimport { Dropdown } from './Dropdown';\nimport { Spinner } from './Spinner';\nimport { Tooltip } from './Tooltip';\n\ninterface ChatHeaderProps {\n mode: ChatMode;\n agentName: string;\n agents: XtmAgent[];\n agentsLoading?: boolean;\n agentsError?: boolean;\n selectedAgent: XtmAgent | null;\n transferredFrom?: string;\n agentMenuOpen: boolean;\n onAgentMenuToggle: () => void;\n onAgentMenuClose: () => void;\n onSwitchAgent: (agent: XtmAgent) => void;\n modeMenuOpen: boolean;\n onModeMenuToggle: () => void;\n onModeMenuClose: () => void;\n onModeChange: (mode: ChatMode) => void;\n onNewChat: () => void;\n onClose: () => void;\n logoIcon: React.ReactNode;\n agentDashboardUrl?: string;\n /** Multi-conversation history menu (REST backend). Hidden when false. */\n historyEnabled?: boolean;\n historyMenuOpen?: boolean;\n onHistoryMenuToggle?: () => void;\n onHistoryMenuClose?: () => void;\n conversations?: ChatConversationSummary[];\n conversationsLoading?: boolean;\n activeConversationId?: string | null;\n onSelectConversation?: (id: string) => void;\n onDeleteConversation?: (id: string) => void;\n t: Translate;\n}\n\n// Labels are thunks rather than bare strings so each key stays a literal call\n// on the host's translator in the source: a table of plain keys resolved later\n// through a variable works at runtime but is invisible to key extraction, which\n// is how a locale ends up missing exactly the strings nobody typed by hand.\nconst modeOptions: { mode: ChatMode; label: (t: Translate) => string; getIcon: (p: { size: number; className: string }) => React.ReactNode }[] = [\n { mode: 'floating', label: (t) => t('Floating'), getIcon: (p) => <FloatingIcon {...p} /> },\n { mode: 'sidebar', label: (t) => t('Sidebar'), getIcon: (p) => <SidebarIcon {...p} /> },\n { mode: 'fullscreen', label: (t) => t('Full screen'), getIcon: (p) => <FullscreenIcon {...p} /> },\n];\n\nexport const ChatHeader = ({\n mode,\n agentName,\n agents,\n agentsLoading = false,\n agentsError = false,\n selectedAgent,\n transferredFrom,\n agentMenuOpen,\n onAgentMenuToggle,\n onAgentMenuClose,\n onSwitchAgent,\n modeMenuOpen,\n onModeMenuToggle,\n onModeMenuClose,\n onModeChange,\n onNewChat,\n onClose,\n logoIcon,\n agentDashboardUrl,\n historyEnabled = false,\n historyMenuOpen = false,\n onHistoryMenuToggle,\n onHistoryMenuClose,\n conversations = [],\n conversationsLoading = false,\n activeConversationId = null,\n onSelectConversation,\n onDeleteConversation,\n t,\n}: ChatHeaderProps) => {\n const agentAnchorRef = useRef<HTMLButtonElement>(null);\n const modeAnchorRef = useRef<HTMLButtonElement>(null);\n const historyAnchorRef = useRef<HTMLButtonElement>(null);\n\n // Agent filter, mirroring the XTM One web chat's picker. Reset whenever the\n // menu closes so re-opening never starts on a stale query with most agents\n // hidden — which reads as \"my agents disappeared\".\n const [agentQuery, setAgentQuery] = useState('');\n useEffect(() => {\n if (!agentMenuOpen) setAgentQuery('');\n }, [agentMenuOpen]);\n\n // Match on name AND description: descriptions are what distinguish agents\n // whose names are near-identical, and they are already shown on every row.\n const filteredAgents = useMemo(() => {\n const q = agentQuery.trim().toLowerCase();\n if (!q) return agents;\n return agents.filter((a) => a.name.toLowerCase().includes(q) || (a.description ?? '').toLowerCase().includes(q));\n }, [agents, agentQuery]);\n\n // Only worth the vertical space once the list is long enough to scan for.\n const showAgentSearch = agents.length > 5;\n\n const CurrentModeIcon = mode === 'sidebar' ? SidebarIcon : mode === 'fullscreen' ? FullscreenExitIcon : FloatingIcon;\n\n return (\n <div\n className={`flex items-center px-3 py-2 min-h-[48px] border-b border-gray-200 dark:border-white/10 bg-gradient-to-br from-[var(--chat-accent-dark)]/[0.13] to-[var(--chat-accent)]/[0.07] ${mode === 'floating' ? 'rounded-t-xl' : ''}`}\n >\n <div className=\"min-w-0\">\n <button\n ref={agentAnchorRef}\n type=\"button\"\n onClick={onAgentMenuToggle}\n className=\"flex items-center gap-1.5 text-sm font-semibold text-gray-900 dark:text-white px-2 py-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <span className=\"flex items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]\">{logoIcon}</span>\n <span>{agentName}</span>\n <ChevronDownIcon size={16} className=\"text-gray-400 dark:text-white/30\" />\n </button>\n {transferredFrom && (\n <div className=\"pl-10 pr-2 text-[0.6rem] font-normal text-gray-400 dark:text-white/30\">\n {translate(t, 'Transferred from {agent}', { agent: transferredFrom })}\n </div>\n )}\n </div>\n\n <Dropdown open={agentMenuOpen} onClose={onAgentMenuClose} anchorRef={agentAnchorRef} width={280}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">\n {t('Switch to another agent')}\n </span>\n {/* Three distinct states, because an empty array alone cannot tell them\n apart — and treating \"failed\" as \"still loading\" is what left this\n menu spinning forever against an unreachable backend.\n\n The last one is NOT \"the catalogue is empty\": XTM One always seeds\n agents, so a working backend never answers with none. It is reached\n when the fetch is skipped altogether — `apiEndpoints.agents: null`,\n single-endpoint mode (OpenCTI) or the legacy backend — where there\n is simply nothing to switch between. The menu still earns its place\n there: it carries the agent-dashboard links below. */}\n {agents.length === 0 && agentsLoading && (\n <div className=\"px-4 py-2\">\n <Spinner size={16} />\n </div>\n )}\n {agents.length === 0 && !agentsLoading && agentsError && (\n <div className=\"px-4 py-3 flex items-start gap-2\">\n <AlertTriangleIcon size={14} className=\"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400\" />\n <span className=\"text-[0.75rem] leading-5 text-gray-600 dark:text-white/60\">{t('Could not reach the assistant service. Check the connection and try again.')}</span>\n </div>\n )}\n {agents.length === 0 && !agentsLoading && !agentsError && (\n <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('Agent switching is not available here')}</div>\n )}\n {showAgentSearch && (\n <div className=\"px-3 pb-2 pt-1\">\n <div className=\"relative\">\n <SearchIcon size={12} className=\"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40\" />\n <input\n autoFocus\n type=\"text\"\n value={agentQuery}\n onChange={(e) => setAgentQuery(e.target.value)}\n // Escape closes the whole menu rather than only clearing the\n // query — the same key the rest of the panel uses to dismiss.\n onKeyDown={(e) => {\n if (e.key === 'Escape') onAgentMenuClose();\n }}\n placeholder={t('Search agents...')}\n aria-label={t('Search agents...')}\n className=\"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]\"\n />\n </div>\n </div>\n )}\n <div className=\"max-h-[240px] overflow-y-auto filigran-chat-scrollable\">\n {agents.length > 0 && filteredAgents.length === 0 && (\n <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No agent matches')}</div>\n )}\n {filteredAgents.map((agent) => (\n <button\n key={agent.id}\n type=\"button\"\n onClick={() => onSwitchAgent(agent)}\n className={`w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors ${\n agent.id === selectedAgent?.id ? 'bg-[var(--chat-accent)]/10' : ''\n }`}\n >\n <div className=\"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5\">\n <span className=\"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4\">{logoIcon}</span>\n </div>\n <div className=\"min-w-0\">\n <div className=\"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate\">{agent.name}</div>\n {agent.description && <div className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">{agent.description}</div>}\n </div>\n </button>\n ))}\n </div>\n <div className=\"h-px bg-gray-200 dark:bg-white/10 mx-2\" />\n <div>\n {agentDashboardUrl && (\n <button\n type=\"button\"\n onClick={() => {\n onAgentMenuClose();\n window.open(`${agentDashboardUrl}/agents`, '_blank');\n }}\n className=\"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <ExternalLinkIcon size={18} className=\"text-gray-400 dark:text-white/40 shrink-0\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{t('Browse agents')}</span>\n </button>\n )}\n {agentDashboardUrl && (\n <button\n type=\"button\"\n onClick={() => {\n onAgentMenuClose();\n window.open(`${agentDashboardUrl}/agents/new`, '_blank');\n }}\n className=\"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <UserPlusIcon size={18} className=\"text-gray-400 dark:text-white/40 shrink-0\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{t('Create agent')}</span>\n </button>\n )}\n </div>\n </Dropdown>\n\n <div className=\"flex-1\" />\n\n {historyEnabled && (\n <>\n <Tooltip title={t('Conversation history')}>\n <button\n ref={historyAnchorRef}\n type=\"button\"\n onClick={onHistoryMenuToggle}\n aria-label={t('Conversation history')}\n aria-haspopup=\"menu\"\n aria-expanded={historyMenuOpen}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <HistoryIcon size={18} />\n </button>\n </Tooltip>\n\n <Dropdown open={historyMenuOpen} onClose={() => onHistoryMenuClose?.()} anchorRef={historyAnchorRef} placement=\"bottom-end\" width={300}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">\n {t('Conversation history')}\n </span>\n <div className=\"max-h-72 overflow-y-auto filigran-chat-scrollable\">\n {conversationsLoading && conversations.length === 0 && (\n <div className=\"px-4 py-2\">\n <Spinner size={16} />\n </div>\n )}\n {!conversationsLoading && conversations.length === 0 && (\n <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversations yet')}</div>\n )}\n {conversations.map((conv) => {\n const isActive = conv.conversationId === activeConversationId;\n const when = timeAgo(conv.updatedAt, t);\n return (\n <div\n key={conv.conversationId}\n className={`group flex items-center gap-2 px-4 py-1.5 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors ${\n isActive ? 'bg-[var(--chat-accent)]/10' : ''\n }`}\n >\n <button type=\"button\" onClick={() => onSelectConversation?.(conv.conversationId)} className=\"flex-1 min-w-0 text-left\">\n <div className=\"text-[0.8125rem] font-medium text-gray-900 dark:text-white truncate\">\n {conv.title || t('Untitled conversation')}\n </div>\n {when && <div className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">{when}</div>}\n </button>\n {onDeleteConversation && (\n <button\n type=\"button\"\n onClick={() => onDeleteConversation(conv.conversationId)}\n title={t('Delete conversation')}\n aria-label={t('Delete conversation')}\n className=\"shrink-0 p-1 rounded-md text-gray-400 dark:text-white/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all\"\n >\n <TrashIcon size={14} />\n </button>\n )}\n </div>\n );\n })}\n </div>\n <div className=\"h-px bg-gray-200 dark:bg-white/10 mx-2\" />\n <button\n type=\"button\"\n onClick={() => {\n onHistoryMenuClose?.();\n onNewChat();\n }}\n className=\"w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <EditIcon size={16} className=\"text-gray-400 dark:text-white/40 shrink-0\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{t('New conversation')}</span>\n </button>\n </Dropdown>\n </>\n )}\n\n <Tooltip title={t('New chat')}>\n <button\n type=\"button\"\n onClick={onNewChat}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <EditIcon size={18} />\n </button>\n </Tooltip>\n\n <Tooltip title={t('Switch view')}>\n <button\n ref={modeAnchorRef}\n type=\"button\"\n onClick={onModeMenuToggle}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <CurrentModeIcon size={18} />\n </button>\n </Tooltip>\n\n <Dropdown open={modeMenuOpen} onClose={onModeMenuClose} anchorRef={modeAnchorRef} placement=\"bottom-end\" width={180}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">{t('Switch to')}</span>\n <div className=\"pb-1\">\n {modeOptions.map((opt) => (\n <button\n key={opt.mode}\n type=\"button\"\n onClick={() => {\n onModeChange(opt.mode);\n onModeMenuClose();\n }}\n className={`w-full flex items-center gap-3 px-4 py-1 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors ${\n mode === opt.mode ? 'bg-[var(--chat-accent)]/10' : ''\n }`}\n >\n {opt.getIcon({ size: 18, className: 'text-gray-400 dark:text-white/40' })}\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/70\">{opt.label(t)}</span>\n </button>\n ))}\n </div>\n </Dropdown>\n\n <Tooltip title={t('Close')}>\n <button\n type=\"button\"\n onClick={onClose}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <CloseIcon size={18} />\n </button>\n </Tooltip>\n </div>\n );\n};\n","import { useEffect, useState } from 'react';\nimport {\n EMPTY_REFERENCE_SEARCH,\n REFERENCE_SEARCH_DEBOUNCE_MS,\n parseReferenceCandidates,\n referenceSearchUrl,\n type ReferenceSearchState,\n} from '../utils/conversationRefs';\n\ninterface UseConversationReferenceSearchOptions {\n /** `conversationReferencesUrl(...)`: null while the feature is off. */\n url: string | null;\n /** The text typed after `@`, or null while no `@` is being typed. */\n query: string | null;\n /** The conversation written in, left out of the answer. */\n exclude?: string | null;\n requestHeaders?: Record<string, string>;\n}\n\n/**\n * The conversations the `@` menu offers for the text typed after `@`.\n *\n * Searched once the text has rested `REFERENCE_SEARCH_DEBOUNCE_MS`. A request\n * overtaken by the next keystroke is aborted, and its answer, should it land\n * anyway, is dropped: only the latest text is ever answered. The previous\n * answer stays until then, so typing never empties the menu.\n */\nexport function useConversationReferenceSearch({ url, query, exclude, requestHeaders }: UseConversationReferenceSearchOptions): ReferenceSearchState {\n const [state, setState] = useState<ReferenceSearchState>(EMPTY_REFERENCE_SEARCH);\n\n useEffect(() => {\n if (!url || query === null) {\n // A menu opened later starts from nothing, not from an old answer.\n setState(EMPTY_REFERENCE_SEARCH);\n return;\n }\n let current = true;\n const controller = new AbortController();\n const timer = window.setTimeout(async () => {\n try {\n const res = await fetch(referenceSearchUrl(url, query, exclude), {\n credentials: 'include',\n headers: { ...(requestHeaders ?? {}) },\n signal: controller.signal,\n });\n const data = res.ok ? await res.json() : null;\n if (!current) return;\n setState(res.ok ? { query, items: parseReferenceCandidates(data), failed: false } : { query, items: [], failed: true });\n } catch {\n if (current) setState({ query, items: [], failed: true });\n }\n }, REFERENCE_SEARCH_DEBOUNCE_MS);\n return () => {\n current = false;\n window.clearTimeout(timer);\n controller.abort();\n };\n }, [url, query, exclude, requestHeaders]);\n\n return state;\n}\n","import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type RefObject } from 'react';\nimport type { ChatConversationRef, ChatConversationReferenceCandidate } from '../types';\nimport {\n insertConversationReference,\n refAsCandidate,\n referenceMenuView,\n rememberAnswer,\n rememberCandidates,\n referenceTrigger,\n referencedConversations,\n type ReferenceMenuView,\n type ReferenceTrigger,\n} from '../utils/conversationRefs';\nimport { useConversationReferenceSearch } from './useConversationReferenceSearch';\n\ninterface UseConversationReferenceMenuOptions {\n /** `conversationReferencesUrl(...)`: null while the feature is off. */\n url: string | null;\n requestHeaders?: Record<string, string>;\n /** The conversation written in: never offered. */\n conversationId?: string | null;\n text: string;\n onTextChange: (text: string) => void;\n textareaRef: RefObject<HTMLTextAreaElement | null>;\n /** The picks the composer holds, to tell when the message is full. */\n refs: ChatConversationRef[];\n /** Called with a pick before the text changes, so pruning sees it inserted. */\n onPick: (ref: ChatConversationRef) => void;\n}\n\nconst sameTrigger = (a: ReferenceTrigger | null, b: ReferenceTrigger | null) =>\n a === b || (!!a && !!b && a.anchor === b.anchor && a.query === b.query);\n\n/**\n * The composer's `@` menu: what typing `@` offers, and how a pick lands in the\n * text.\n *\n * The menu follows the caret, read from the field after every change of the\n * text - typed, dictated, a template, the clear after a send - and after every\n * move of the caret the caller reports through `sync`. The field keeps the\n * focus throughout: the menu is driven from its keys, and a row is picked on\n * `mousedown`.\n */\nexport function useConversationReferenceMenu({\n url,\n requestHeaders,\n conversationId,\n text,\n onTextChange,\n textareaRef,\n refs,\n onPick,\n}: UseConversationReferenceMenuOptions) {\n const enabled = url !== null;\n const [trigger, setTrigger] = useState<ReferenceTrigger | null>(null);\n // Escape closes the menu for the `@` it was open on; a new `@` opens it again.\n const [dismissedAnchor, setDismissedAnchor] = useState<number | null>(null);\n const [activeIndex, setActiveIndex] = useState(0);\n const pendingCaretRef = useRef<number | null>(null);\n const listboxId = useId();\n const optionId = useCallback((index: number) => `${listboxId}-option-${index}`, [listboxId]);\n\n /** Read the caret: open, narrow or close the menu. */\n const sync = useCallback(() => {\n const el = textareaRef.current;\n const next =\n enabled && el && document.activeElement === el && el.selectionStart === el.selectionEnd\n ? referenceTrigger(el.value.slice(0, el.selectionStart))\n : null;\n setTrigger((prev) => (sameTrigger(prev, next) ? prev : next));\n }, [enabled, textareaRef]);\n\n const close = useCallback(() => setTrigger(null), []);\n\n // After a pick the caret goes after the inserted key, before `sync` reads it.\n useLayoutEffect(() => {\n const caret = pendingCaretRef.current;\n if (caret === null) return;\n pendingCaretRef.current = null;\n const el = textareaRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(caret, caret);\n }, [text, textareaRef]);\n\n useEffect(() => {\n sync();\n }, [text, sync]);\n\n useEffect(() => {\n if (!trigger) setDismissedAnchor(null);\n }, [trigger]);\n\n const search = useConversationReferenceSearch({ url, query: trigger?.query ?? null, exclude: conversationId, requestHeaders });\n\n // Every conversation the menu has offered, matched locally by key and title\n // (`referenceMenuView`'s `known`), with the draft's picks.\n // A settled answer also drops the remembered rows it should have listed\n // (deleted, unshared since); another conversation starts from nothing.\n const [seen, setSeen] = useState<ChatConversationReferenceCandidate[]>([]);\n useEffect(() => {\n setSeen([]);\n }, [conversationId]);\n useEffect(() => {\n setSeen((prev) => rememberAnswer(prev, search, conversationId));\n }, [search, conversationId]);\n const known = useMemo(() => rememberCandidates(refs.map(refAsCandidate), seen), [refs, seen]);\n\n // Every new answer starts on its first row.\n useEffect(() => {\n setActiveIndex(0);\n }, [search]);\n\n const view: ReferenceMenuView = referenceMenuView({\n trigger,\n dismissed: trigger !== null && trigger.anchor === dismissedAnchor,\n search,\n referenced: referencedConversations(refs, text).length,\n exclude: conversationId,\n known,\n });\n const items = view.kind === 'results' ? view.items : [];\n const active = Math.min(activeIndex, Math.max(items.length - 1, 0));\n\n const pick = (candidate: ChatConversationReferenceCandidate) => {\n if (!trigger) return;\n const inserted = insertConversationReference(text, trigger, candidate.key);\n onPick({ conversationId: candidate.id, title: candidate.title, key: candidate.key, isOwn: candidate.isOwn });\n pendingCaretRef.current = inserted.caret;\n onTextChange(inserted.text);\n setTrigger(null);\n };\n\n /** The menu's keys; true when the key was the menu's to handle. */\n const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>): boolean => {\n if (view.kind === 'closed' || !trigger || e.nativeEvent.isComposing) return false;\n if (e.key === 'Escape') {\n e.preventDefault();\n setDismissedAnchor(trigger.anchor);\n return true;\n }\n if (items.length === 0) return false;\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n e.preventDefault();\n const step = e.key === 'ArrowDown' ? 1 : -1;\n setActiveIndex((active + step + items.length) % items.length);\n return true;\n }\n if ((e.key === 'Enter' || e.key === 'Tab') && !e.shiftKey) {\n e.preventDefault();\n pick(items[active]);\n return true;\n }\n return false;\n };\n\n // The field stays the focus, so the list is announced through it.\n const textareaAria = enabled\n ? {\n 'aria-autocomplete': 'list' as const,\n 'aria-controls': view.kind === 'results' ? listboxId : undefined,\n 'aria-activedescendant': view.kind === 'results' ? optionId(active) : undefined,\n }\n : {};\n\n return { view, activeIndex: active, setActiveIndex, listboxId, optionId, sync, close, pick, onKeyDown, textareaAria };\n}\n","/**\n * Minimal shape of the Web Speech API surface we use. Typed locally rather\n * than pulled from `lib.dom` - `SpeechRecognition` is still vendor-prefixed and\n * missing from TypeScript's DOM lib, and this package ships no ambient types.\n */\ninterface SpeechRecognitionAlternativeLike {\n transcript: string;\n}\ninterface SpeechRecognitionResultLike {\n isFinal: boolean;\n 0: SpeechRecognitionAlternativeLike;\n}\nexport interface SpeechRecognitionEventLike {\n resultIndex: number;\n results: { length: number; [index: number]: SpeechRecognitionResultLike };\n}\nexport interface SpeechRecognitionLike {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start: () => void;\n stop: () => void;\n abort: () => void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: (() => void) | null;\n onend: (() => void) | null;\n}\n\nexport interface DictationEvents {\n /** A finalised phrase, trimmed, to append to the draft. */\n onFinal: (text: string) => void;\n /** Words heard but not final yet; an empty string clears the preview. */\n onInterim: (text: string) => void;\n onListeningChange: (listening: boolean) => void;\n}\n\nexport interface DictationController {\n /** Start listening, or stop and commit the phrase already heard. */\n toggle: () => void;\n /** Stop listening and drop whatever the session still delivers. */\n cancel: () => void;\n /** Release the recogniser; no event is reported afterwards. */\n dispose: () => void;\n}\n\n/**\n * - `listening`: a session the user wants; the engine ending it after a pause\n * starts it again.\n * - `stopping`: the user stopped it; the phrase in flight is still committed.\n * - `discarding`: cancelled; everything it delivers until its `end` is dropped.\n */\ntype Phase = 'idle' | 'listening' | 'stopping' | 'discarding';\n\n/**\n * Drives one recogniser through successive dictation sessions.\n *\n * A session keeps emitting after `stop()` / `abort()` until its `end` event,\n * and no event says which session it belongs to. The recogniser also refuses\n * `start()` until that `end`, so every event is read against the phase of the\n * one session it can belong to, and a start asked for while the previous\n * session is still ending waits for that `end` instead of failing.\n */\nexport function createDictationController(recognition: SpeechRecognitionLike, events: DictationEvents): DictationController {\n let phase: Phase = 'idle';\n let startQueued = false;\n let disposed = false;\n let reported = false;\n\n const isOn = () => phase === 'listening' || startQueued;\n\n const report = () => {\n if (disposed || isOn() === reported) return;\n reported = isOn();\n events.onListeningChange(reported);\n };\n\n const tryStart = () => {\n try {\n recognition.start();\n return true;\n } catch {\n return false;\n }\n };\n\n const start = () => {\n if (tryStart()) phase = 'listening';\n else if (phase !== 'idle') startQueued = true;\n report();\n };\n\n const stop = () => {\n startQueued = false;\n if (phase === 'listening') {\n phase = 'stopping';\n events.onInterim('');\n try {\n recognition.stop();\n } catch {\n phase = 'idle';\n }\n }\n report();\n };\n\n const cancel = () => {\n if (disposed) return;\n startQueued = false;\n if (phase === 'listening' || phase === 'stopping') {\n phase = 'discarding';\n events.onInterim('');\n try {\n recognition.abort();\n } catch {\n phase = 'idle';\n }\n }\n report();\n };\n\n recognition.onresult = (event) => {\n if (phase !== 'listening' && phase !== 'stopping') return;\n let finalText = '';\n let interimText = '';\n for (let i = event.resultIndex; i < event.results.length; i++) {\n const result = event.results[i];\n if (result.isFinal) finalText += result[0].transcript;\n else interimText += result[0].transcript;\n }\n const phrase = finalText.trim();\n if (phrase) events.onFinal(phrase);\n if (phase === 'listening') events.onInterim(interimText.trim());\n };\n\n recognition.onerror = () => {\n // Permission denied, no microphone, network failure: let the session end\n // rather than restart it into the same failure.\n if (phase === 'listening') {\n phase = 'stopping';\n events.onInterim('');\n }\n report();\n };\n\n recognition.onend = () => {\n events.onInterim('');\n if (phase === 'listening') {\n if (tryStart()) return;\n phase = 'idle';\n } else if (startQueued) {\n startQueued = false;\n phase = tryStart() ? 'listening' : 'idle';\n } else {\n phase = 'idle';\n }\n report();\n };\n\n return {\n toggle: () => {\n if (disposed) return;\n if (isOn()) stop();\n else start();\n },\n cancel,\n dispose: () => {\n if (disposed) return;\n disposed = true;\n recognition.onresult = null;\n recognition.onerror = null;\n recognition.onend = null;\n if (phase !== 'idle') {\n try {\n recognition.abort();\n } catch {\n /* already ended */\n }\n }\n phase = 'idle';\n startQueued = false;\n },\n };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { createDictationController, type DictationController, type SpeechRecognitionLike } from './dictationController';\n\ntype SpeechRecognitionCtor = new () => SpeechRecognitionLike;\n\nfunction getSpeechRecognition(): SpeechRecognitionCtor | null {\n if (typeof window === 'undefined') return null;\n const w = window as unknown as {\n SpeechRecognition?: SpeechRecognitionCtor;\n webkitSpeechRecognition?: SpeechRecognitionCtor;\n };\n return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n}\n\ninterface UseDictationReturn {\n /** False on browsers without the API — the host should render no button. */\n supported: boolean;\n listening: boolean;\n /** Words heard but not yet finalised, for a live preview. */\n interim: string;\n /** Start listening, or stop and still commit the phrase already heard. */\n toggle: () => void;\n /** Stop listening and drop anything still on its way, e.g. once the draft is sent. */\n cancel: () => void;\n}\n\n/**\n * Speech-to-text for the composer, using the browser's own Web Speech API.\n *\n * Entirely client-side: no endpoint, no key, nothing for a host to deploy —\n * which is why it ships regardless of how the backend is configured, unlike the\n * prompt library and quota indicator.\n *\n * Final phrases are appended through `onFinalText`; interim words are returned\n * separately so the composer can preview them without committing.\n */\nexport function useDictation(onFinalText: (text: string) => void): UseDictationReturn {\n const [listening, setListening] = useState(false);\n const [interim, setInterim] = useState('');\n const controllerRef = useRef<DictationController | null>(null);\n // Read through a ref so re-creating the callback each render does not tear\n // down and rebuild the recogniser mid-dictation.\n const onFinalTextRef = useRef(onFinalText);\n onFinalTextRef.current = onFinalText;\n\n const supported = getSpeechRecognition() !== null;\n\n useEffect(() => {\n const Ctor = getSpeechRecognition();\n if (!Ctor) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = typeof navigator !== 'undefined' ? navigator.language || 'en-US' : 'en-US';\n\n const controller = createDictationController(recognition, {\n onFinal: (text) => onFinalTextRef.current(text),\n onInterim: setInterim,\n onListeningChange: setListening,\n });\n controllerRef.current = controller;\n return () => {\n controllerRef.current = null;\n controller.dispose();\n setListening(false);\n setInterim('');\n };\n }, []);\n\n const toggle = useCallback(() => controllerRef.current?.toggle(), []);\n const cancel = useCallback(() => controllerRef.current?.cancel(), []);\n\n return { supported, listening, interim, toggle, cancel };\n}\n","import { useRef, useState } from 'react';\nimport type { ChatContextBreakdown, ChatContextUsage, Translate } from '../types';\nimport { compactCount, translate } from '../utils';\nimport { Dropdown } from './Dropdown';\nimport { Tooltip } from './Tooltip';\n\ninterface ContextUsageIndicatorProps {\n usage: ChatContextUsage;\n t: Translate;\n}\n\n// Thresholds are the agent loop's own gates, not design choices: at 80 %\n// utilization the backend compacts the session (older turns are distilled into\n// a summary), and past 95 % it emergency-prunes. Colouring anywhere else would\n// warn about a moment that never comes, or arrive after it has passed.\nconst COMPACTION_RATIO = 0.8;\nconst PRUNE_RATIO = 0.95;\n\n// Geometry of the ring. Kept at the text's own scale so the gauge reads as part\n// of the label rather than as an icon beside it.\nconst SIZE = 14;\nconst STROKE = 2;\nconst RADIUS = (SIZE - STROKE) / 2;\nconst CIRCUMFERENCE = 2 * Math.PI * RADIUS;\n\n/**\n * Rows of the detail popover, in a FIXED order that mirrors how the prompt is\n * assembled — instructions, then tools, then the conversation and what the\n * backend has done to it. Fixed rather than sorted by size so the same bucket\n * stays in the same place as a chat grows: a legend whose rows reshuffle between\n * two glances cannot be compared against itself.\n *\n * `color` is both the swatch and the stacked-bar segment, so the bar is readable\n * without a legend lookup. Labels name what the user can act on, not the\n * backend's internals: \"Tool results\" rather than \"role=tool messages\".\n */\nconst ROWS: ReadonlyArray<{ field: keyof ChatContextBreakdown; label: (t: Translate) => string; color: string }> = [\n { field: 'system', label: (t) => t('System prompt'), color: '#9ca3af' },\n { field: 'tools', label: (t) => t('Tool definitions'), color: '#a78bfa' },\n { field: 'dynamicTools', label: (t) => t('MCP & dynamic tools'), color: '#f0abfc' },\n { field: 'summary', label: (t) => t('Summarized conversation'), color: '#fb7185' },\n { field: 'toolResults', label: (t) => t('Tool results'), color: '#34d399' },\n { field: 'conversation', label: (t) => t('Conversation'), color: '#a1a1aa' },\n];\n\n/**\n * Context-window occupancy for the current conversation, as a small ring plus\n * percentage — the affordance Cursor popularised — opening a breakdown of where\n * the context went.\n *\n * It answers one question: is this conversation about to get shorter than the\n * user thinks? Long chats do not fail at the window, they get silently\n * summarised, and a user who cannot see that coming reads the summary's gaps as\n * the assistant forgetting. So the gauge is deliberately a *forecast* of the\n * next turn, and its colours are the backend's real thresholds.\n */\nexport const ContextUsageIndicator = ({ usage, t }: ContextUsageIndicatorProps) => {\n const { used, limit, breakdown } = usage;\n const anchorRef = useRef<HTMLButtonElement>(null);\n const [open, setOpen] = useState(false);\n\n // The parser guarantees a positive limit; clamp anyway so a future producer\n // cannot draw a ring past full or a negative arc.\n const ratio = Math.min(Math.max(used / limit, 0), 1);\n const pruning = ratio >= PRUNE_RATIO;\n const compacting = ratio >= COMPACTION_RATIO;\n\n const ringColor = pruning ? 'text-red-500' : compacting ? 'text-amber-500' : 'text-[var(--chat-accent)]';\n const textColor = pruning\n ? 'text-red-500 dark:text-red-400'\n : compacting\n ? 'text-amber-600 dark:text-amber-400'\n : 'text-gray-400 dark:text-white/30';\n\n const percent = Math.round(ratio * 100);\n const counts = `${compactCount(used)}/${compactCount(limit)}`;\n // Naming the consequence beats naming the state: \"80 % full\" leaves the user\n // to guess what happens next, which is the whole reason the gauge exists.\n const headline = pruning\n ? t('Context full — older turns are being dropped')\n : compacting\n ? t('Context nearly full — older turns are being summarized')\n : t('Context used');\n const tokens = translate(t, '{counts} tokens', { counts });\n // Separator only — nothing to translate, so no key of its own: both halves\n // are already whole translated readouts.\n const summary = `${headline} · ${tokens}`;\n\n const rows = breakdown ? ROWS.filter((r) => (breakdown[r.field] ?? 0) > 0) : [];\n // Without a breakdown there is nothing to open, so the readout stays inert\n // rather than offering a click that does nothing.\n const expandable = rows.length > 0;\n\n const gauge = (\n <span className=\"flex items-center gap-1.5\">\n <svg width={SIZE} height={SIZE} viewBox={`0 0 ${SIZE} ${SIZE}`} className={ringColor} aria-hidden=\"true\">\n <circle cx={SIZE / 2} cy={SIZE / 2} r={RADIUS} fill=\"none\" strokeWidth={STROKE} className=\"stroke-gray-200 dark:stroke-white/15\" />\n <circle\n cx={SIZE / 2}\n cy={SIZE / 2}\n r={RADIUS}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={STROKE}\n strokeLinecap=\"round\"\n strokeDasharray={CIRCUMFERENCE}\n strokeDashoffset={CIRCUMFERENCE * (1 - ratio)}\n /* Start at twelve o'clock: a gauge that fills from the side reads\n as a spinner. */\n transform={`rotate(-90 ${SIZE / 2} ${SIZE / 2})`}\n className=\"transition-[stroke-dashoffset] duration-500\"\n />\n </svg>\n <span className={`text-[0.68rem] tabular-nums ${textColor}`}>{percent}%</span>\n </span>\n );\n\n if (!expandable) {\n return (\n <Tooltip title={summary}>\n <span className=\"flex items-center\" role=\"img\" aria-label={`${summary} (${percent}%)`}>\n {gauge}\n </span>\n </Tooltip>\n );\n }\n\n return (\n <>\n <Tooltip title={open ? '' : translate(t, '{summary} — click for details', { summary })}>\n <button\n ref={anchorRef}\n type=\"button\"\n onClick={() => setOpen((prev) => !prev)}\n aria-label={`${summary} (${percent}%)`}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n className=\"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:bg-gray-100 dark:hover:bg-white/10\"\n >\n {gauge}\n </button>\n </Tooltip>\n\n <Dropdown open={open} onClose={() => setOpen(false)} anchorRef={anchorRef} placement=\"bottom-end\" width={296}>\n <div className=\"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3\">\n <span className={`text-[0.8125rem] tabular-nums ${textColor}`}>{translate(t, '{percent}% full', { percent })}</span>\n {/* The tilde is load-bearing: these are char-derived estimates, and a\n bare \"168k/200k\" would read as a measured count. */}\n <span className=\"text-[0.7rem] tabular-nums text-gray-400 dark:text-white/40 shrink-0\">~{tokens}</span>\n </div>\n\n {/* One stacked bar over the whole window: the segments are the legend's\n own colours, so proportions are readable without matching numbers to\n rows. The trailing gap is the headroom left. */}\n <div className=\"px-3.5 pb-2.5 pt-1.5\">\n <span className=\"flex h-1.5 w-full gap-px rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden\">\n {rows.map((row) => (\n <span\n key={row.field}\n className=\"h-full first:rounded-l-full\"\n /* Scaled through the clamped total rather than straight over the\n window, so a producer that reports buckets summing past the\n limit fills the track instead of overflowing it. Identical to\n value/limit whenever the two agree, which is the normal case. */\n style={{\n width: `${((breakdown?.[row.field] ?? 0) / Math.max(used, 1)) * Math.min(used / limit, 1) * 100}%`,\n backgroundColor: row.color,\n }}\n />\n ))}\n </span>\n </div>\n\n <div className=\"px-3.5 pb-1\">\n {rows.map((row) => (\n <div key={row.field} className=\"flex items-center gap-2 py-[3px]\">\n {/* Radius set inline: the panel's reset rounds small spans to a\n pill, which turns the swatches into dots that read as bullets\n rather than as keys to the bar's segments. */}\n <span className=\"h-2 w-2 shrink-0\" style={{ backgroundColor: row.color, borderRadius: 2 }} aria-hidden=\"true\" />\n <span className=\"text-[0.75rem] text-gray-700 dark:text-white/70 truncate\">{row.label(t)}</span>\n <span className=\"ml-auto text-[0.7rem] tabular-nums text-gray-500 dark:text-white/40 shrink-0\">\n {compactCount(breakdown?.[row.field] ?? 0)}\n </span>\n </div>\n ))}\n </div>\n\n {compacting && (\n // The one line that turns a readout into something actionable: at this\n // point the backend is already dropping detail from older turns.\n <p className={`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${textColor}`}>{headline}</p>\n )}\n </Dropdown>\n </>\n );\n};\n","import { useLayoutEffect, useRef } from 'react';\nimport type { ChatConversationReferenceCandidate } from '../types';\nimport { translate } from '../utils';\nimport { MAX_REFERENCED_CONVERSATIONS, type ReferenceMenuView } from '../utils/conversationRefs';\nimport { MessageSquareIcon } from './icons';\n\ninterface ConversationReferenceMenuProps {\n view: ReferenceMenuView;\n activeIndex: number;\n listboxId: string;\n optionId: (index: number) => string;\n onHover: (index: number) => void;\n onPick: (candidate: ChatConversationReferenceCandidate) => void;\n t: (key: string) => string;\n}\n\n/**\n * The composer's `@` menu, driven by `useConversationReferenceMenu`: the\n * conversations a message can reference, opened above the field. The field\n * keeps the focus - the rows are options it points at, picked on `mousedown`\n * so a click never takes the focus away from the text being written.\n */\nexport const ConversationReferenceMenu = ({ view, activeIndex, listboxId, optionId, onHover, onPick, t }: ConversationReferenceMenuProps) => {\n const listRef = useRef<HTMLDivElement>(null);\n\n // The row the arrows reached stays in view in a list longer than the menu.\n useLayoutEffect(() => {\n listRef.current?.querySelector<HTMLElement>('[aria-selected=\"true\"]')?.scrollIntoView?.({ block: 'nearest' });\n }, [activeIndex, view.kind]);\n\n if (view.kind === 'closed') return null;\n const heading = t('Reference a conversation');\n\n return (\n <div className=\"absolute left-0 right-0 bottom-full mb-1.5 z-20 rounded-[10px] overflow-hidden border border-gray-200 dark:border-white/10 bg-white dark:bg-[#2a2a3e] shadow-xl\">\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">{heading}</span>\n\n {view.kind === 'results' && (\n <div ref={listRef} id={listboxId} role=\"listbox\" aria-label={heading} className=\"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable\">\n {view.items.map((c, i) => {\n const active = i === activeIndex;\n return (\n <div\n key={c.id}\n id={optionId(i)}\n role=\"option\"\n aria-selected={active}\n onMouseDown={(e) => {\n e.preventDefault();\n onPick(c);\n }}\n // On a move, not on enter: a menu opening under a still pointer\n // must not take the selection off its first row.\n onMouseMove={() => {\n if (!active) onHover(i);\n }}\n className={`flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors ${active ? 'bg-gray-100 dark:bg-white/10' : ''}`}\n >\n <span className=\"shrink-0 text-[var(--chat-accent)]\">\n <MessageSquareIcon size={14} />\n </span>\n <span className=\"flex flex-col min-w-0 flex-1\">\n <span className=\"text-[0.8125rem] text-gray-900 dark:text-white truncate\">{c.title || t('Untitled conversation')}</span>\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">\n @{c.key}\n {!c.isOwn && ` · ${t('Shared with you')}`}\n </span>\n </span>\n </div>\n );\n })}\n </div>\n )}\n\n {view.kind === 'empty' && (\n <div role=\"status\" className=\"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40\">\n {t('No conversation matches')}\n </div>\n )}\n\n {view.kind === 'full' && (\n <div role=\"status\" className=\"px-4 pt-1 pb-3 text-[0.75rem] text-gray-400 dark:text-white/40\">\n {translate(t, 'A message references at most {count} conversations', { count: MAX_REFERENCED_CONVERSATIONS })}\n </div>\n )}\n </div>\n );\n};\n","import { useRef, useState } from 'react';\nimport type { ChatPromptTemplate } from '../types';\nimport { SparklesIcon } from './icons';\nimport { Dropdown } from './Dropdown';\nimport { Tooltip } from './Tooltip';\n\ninterface PromptPickerProps {\n prompts: ChatPromptTemplate[];\n /** Receives the template body; the composer decides how to place it. */\n onPick: (content: string) => void;\n t: (key: string) => string;\n}\n\n/** Above this many entries the list is worth filtering rather than scrolling. */\nconst SEARCH_THRESHOLD = 5;\n\n/**\n * Inserts a saved prompt template into the composer. Mirrors the XTM One web\n * chat's \"Insert prompt template\" affordance.\n */\nexport const PromptPicker = ({ prompts, onPick, t }: PromptPickerProps) => {\n const anchorRef = useRef<HTMLButtonElement>(null);\n const [open, setOpen] = useState(false);\n const [query, setQuery] = useState('');\n\n const close = () => {\n setOpen(false);\n // Reset on close: re-opening on a stale filter looks like the library\n // lost most of its entries.\n setQuery('');\n };\n\n const q = query.trim().toLowerCase();\n const filtered = q\n ? prompts.filter((p) => p.title.toLowerCase().includes(q) || (p.description ?? '').toLowerCase().includes(q))\n : prompts;\n\n return (\n <>\n <Tooltip title={t('Insert prompt template')}>\n <button\n ref={anchorRef}\n type=\"button\"\n onClick={() => (open ? close() : setOpen(true))}\n aria-label={t('Insert prompt template')}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n className={`w-7 h-7 flex items-center justify-center rounded-lg transition-colors ${\n open\n ? 'text-[var(--chat-accent)] bg-[var(--chat-accent)]/10'\n : 'text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10'\n }`}\n >\n <SparklesIcon size={15} />\n </button>\n </Tooltip>\n\n <Dropdown open={open} onClose={close} anchorRef={anchorRef} width={280}>\n <span className=\"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase text-gray-400 dark:text-white/40\">\n {t('Insert prompt template')}\n </span>\n\n {prompts.length > SEARCH_THRESHOLD && (\n <div className=\"px-3 pb-2 pt-1\">\n <input\n autoFocus\n type=\"text\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') close();\n }}\n placeholder={t('Search prompts...')}\n aria-label={t('Search prompts...')}\n className=\"w-full h-7 px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]\"\n />\n </div>\n )}\n\n <div className=\"max-h-[240px] overflow-y-auto filigran-chat-scrollable\">\n {filtered.length === 0 && <div className=\"px-4 py-3 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No prompt matches')}</div>}\n {filtered.map((p) => (\n <button\n key={p.id}\n type=\"button\"\n onClick={() => {\n onPick(p.content);\n close();\n }}\n className=\"w-full px-4 py-1.5 text-left hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <div className=\"text-[0.8125rem] text-gray-900 dark:text-white truncate\">{p.title}</div>\n {p.description && <div className=\"text-[0.7rem] text-gray-500 dark:text-white/40 truncate\">{p.description}</div>}\n </button>\n ))}\n </div>\n </Dropdown>\n </>\n );\n};\n","import type { ChatQuotaStatus } from '../types';\nimport { compactCount as compact, translate } from '../utils';\nimport { quotaPeriodLabel } from '../utils/quota';\nimport { Tooltip } from './Tooltip';\n\ninterface QuotaIndicatorProps {\n quota: ChatQuotaStatus;\n t: (key: string) => string;\n}\n\n/**\n * Agentic quota headroom, as a small bar plus counts.\n *\n * Colour is earned, not decorative: neutral until 75%, amber past it, red once\n * the allowance is spent — the point is to warn before a turn is refused, not\n * to decorate the composer.\n */\nexport const QuotaIndicator = ({ quota, t }: QuotaIndicatorProps) => {\n const { used, limit } = quota;\n const period = quotaPeriodLabel(quota.period, t);\n // One allowance for the whole platform: say so, or a user reads colleagues'\n // consumption as their own.\n const withScope = (title: string) => (quota.scope === 'global' ? translate(t, '{quota} (shared across all users)', { quota: title }) : title);\n\n // No ceiling: report consumption without implying a limit that isn't there.\n if (limit === null) {\n const title = withScope(period ? translate(t, 'Usage · {period}', { period }) : t('Usage'));\n return (\n <Tooltip title={title}>\n <span className=\"text-[0.68rem] tabular-nums text-gray-400 dark:text-white/30\" role=\"img\" aria-label={`${title} ${compact(used)}`}>\n {compact(used)}\n </span>\n </Tooltip>\n );\n }\n\n // Guard a zero/negative limit rather than dividing by it.\n const ratio = limit > 0 ? Math.min(used / limit, 1) : 1;\n const exhausted = limit > 0 ? used >= limit : true;\n const nearLimit = ratio >= 0.75;\n\n const barColor = exhausted ? 'bg-red-500' : nearLimit ? 'bg-amber-500' : 'bg-[var(--chat-accent)]/60';\n const textColor = exhausted\n ? 'text-red-500 dark:text-red-400'\n : nearLimit\n ? 'text-amber-600 dark:text-amber-400'\n : 'text-gray-400 dark:text-white/30';\n\n const label = `${compact(used)}/${compact(limit)}`;\n const headline = exhausted ? t('Quota reached') : t('Quota');\n const title = withScope(period ? `${headline} · ${period}` : headline);\n\n return (\n <Tooltip title={title}>\n <span className=\"flex items-center gap-1.5\" role=\"img\" aria-label={`${title} ${label}`}>\n <span className=\"h-1 w-10 rounded-full bg-gray-200 dark:bg-white/10 overflow-hidden\">\n <span className={`block h-full rounded-full transition-[width] duration-300 ${barColor}`} style={{ width: `${ratio * 100}%` }} />\n </span>\n <span className={`text-[0.68rem] tabular-nums ${textColor}`}>{label}</span>\n </span>\n </Tooltip>\n );\n};\n","import { useLayoutEffect, useRef, type KeyboardEvent } from 'react';\nimport type { ChatContextUsage, ChatConversationRef, ChatFile, ChatMode, ChatPromptTemplate, ChatQuotaStatus } from '../types';\nimport { AttachFileIcon, FileIcon, MicIcon, MicOffIcon, SendIcon, StopCircleIcon } from './icons';\nimport { useConversationReferenceMenu } from '../hooks/useConversationReferenceMenu';\nimport { useDictation } from '../hooks/useDictation';\nimport { referencedConversations } from '../utils/conversationRefs';\nimport { ContextUsageIndicator } from './ContextUsageIndicator';\nimport { ConversationReferenceMenu } from './ConversationReferenceMenu';\nimport { PromptPicker } from './PromptPicker';\nimport { QuotaIndicator } from './QuotaIndicator';\nimport { Tooltip } from './Tooltip';\n\ninterface ChatInputProps {\n inputValue: string;\n onInputChange: (value: string) => void;\n onSend: () => void;\n onStop: () => void;\n isLoading: boolean;\n /**\n * Mid-run steering availability: while the agent is generating, the typed\n * text can be dispatched immediately (Enter / accent Send button) and is\n * injected into the running run instead of waiting for it to finish.\n * Attachments keep the legacy wait behavior.\n */\n canSteer?: boolean;\n attachedFiles?: ChatFile[];\n onFileAdd?: (files: FileList | null) => void;\n onFileRemove?: (index: number) => void;\n onPaste?: (e: React.ClipboardEvent) => void;\n t: (key: string) => string;\n mode?: ChatMode;\n separatorColor?: string;\n /** Saved prompt templates; omitted entirely when the host serves none. */\n prompts?: ChatPromptTemplate[] | null;\n /** Agentic quota headroom; omitted entirely when the host serves none. */\n quota?: ChatQuotaStatus | null;\n /** Context-window occupancy; omitted until the backend reports it. */\n contextUsage?: ChatContextUsage | null;\n /** Host-supplied controls appended to the toolbar (see `composerToolbar`). */\n composerToolbar?: React.ReactNode;\n /**\n * The `@` conversation menu (`apiEndpoints.conversationReferences`), absent\n * while the feature is off: `@` is then plain text.\n */\n conversationReferences?: {\n /** `conversationReferencesUrl(...)`. */\n url: string;\n requestHeaders?: Record<string, string>;\n /** The conversation written in: never offered. */\n conversationId?: string | null;\n /** The picks the composer holds (see `useChat`). */\n refs: ChatConversationRef[];\n onPick: (ref: ChatConversationRef) => void;\n };\n}\n\nconst MAX_TEXTAREA_HEIGHT = 120;\nconst NO_REFS: ChatConversationRef[] = [];\n\nexport const ChatInput = ({\n inputValue,\n onInputChange,\n onSend,\n onStop,\n isLoading,\n canSteer = false,\n attachedFiles = [],\n onFileAdd,\n onFileRemove,\n onPaste,\n t,\n mode,\n separatorColor,\n prompts,\n quota,\n contextUsage,\n composerToolbar,\n conversationReferences,\n}: ChatInputProps) => {\n const fileInputRef = useRef<HTMLInputElement>(null);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n const referenceMenu = useConversationReferenceMenu({\n url: conversationReferences?.url ?? null,\n requestHeaders: conversationReferences?.requestHeaders,\n conversationId: conversationReferences?.conversationId,\n text: inputValue,\n onTextChange: onInputChange,\n textareaRef,\n refs: conversationReferences?.refs ?? NO_REFS,\n onPick: (ref) => conversationReferences?.onPick(ref),\n });\n\n // A dictated phrase lands at the end of the draft while the focus is on the\n // mic, so nothing scrolls the field to it once the text outgrows the cap.\n const revealEndRef = useRef(false);\n\n // Dictation appends each finalised phrase, so speaking continues a draft\n // rather than replacing it — same contract as picking a template.\n const dictation = useDictation((finalText) => {\n revealEndRef.current = true;\n onInputChange(inputValue.trim() ? `${inputValue.trimEnd()} ${finalText}` : finalText);\n });\n\n // Sized from the value rather than from the textarea's own change event:\n // dictation, template picks, draft restores and the clear after a send all\n // change the text without one.\n useLayoutEffect(() => {\n const el = textareaRef.current;\n if (!el) return;\n el.style.height = 'auto';\n el.style.height = `${Math.min(el.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n if (revealEndRef.current) {\n revealEndRef.current = false;\n el.scrollTop = el.scrollHeight;\n }\n }, [inputValue]);\n\n // Append rather than replace: a user who has already started typing must not\n // lose it to a template pick. The blank line keeps the two blocks distinct.\n const handlePromptPick = (content: string) => {\n onInputChange(inputValue.trim() ? `${inputValue.trimEnd()}\\n\\n${content}` : content);\n textareaRef.current?.focus();\n };\n\n // The toolbar row costs vertical space, so it only exists when something\n // actually occupies it. Dictation is not among them: it acts on the text\n // field, so it lives inside it, next to Send.\n const hasToolbar = Boolean((prompts && prompts.length > 0) || quota || contextUsage || composerToolbar);\n\n const isFileManagementEnabled = Boolean(onFileAdd && onFileRemove && onPaste);\n const hasContent = inputValue.trim() || (isFileManagementEnabled && attachedFiles.length > 0);\n const hasFilesUploading = isFileManagementEnabled && attachedFiles.some((f) => f.uploadStatus === 'pending');\n const canSend = hasContent && !hasFilesUploading;\n const hasAttachments = isFileManagementEnabled && attachedFiles.length > 0;\n // A steer reaches the running loop as text alone, so the agent would never\n // read a conversation it references: such a message waits, like a file.\n const hasReferences = Boolean(conversationReferences) && referencedConversations(conversationReferences?.refs ?? NO_REFS, inputValue).length > 0;\n // Show the accent Send button NEXT to Stop while generating: text-only\n // sends can steer the running agent. With attachments selected the send\n // must wait for the current response, so only Stop is shown.\n const showSteerSend = isLoading && canSteer && Boolean(inputValue.trim()) && !hasAttachments && !hasReferences;\n\n // Every way of sending goes through here, and only when the matching button\n // would be enabled: Enter must not send while files upload, nor end a\n // dictation that nothing was sent from. Dictation is cancelled, not stopped:\n // a phrase still being recognised would land in the composer just emptied.\n const send = () => {\n if (!(isLoading ? showSteerSend : canSend)) return;\n dictation.cancel();\n onSend();\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // The menu's keys first (arrows, Enter / Tab, Escape) while it is open.\n if (referenceMenu.onKeyDown(e)) return;\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n send();\n }\n if (e.key === 'Escape' && isLoading) {\n e.preventDefault();\n onStop();\n }\n };\n\n const footerText =\n isLoading && canSteer && !hasAttachments && !hasReferences\n ? t('Enter to send now · Esc to stop')\n : isLoading && hasAttachments\n ? t('Attachments wait for the current response')\n : isLoading && hasReferences\n ? t('Referenced conversations wait for the current response')\n : t('Uses AI. Verify results.');\n\n return (\n <div\n className={`px-4 py-3 border-t border-gray-200 dark:border-white/10 ${mode === 'floating' ? 'rounded-b-xl' : ''}`}\n style={separatorColor ? { borderTopColor: separatorColor, borderTopWidth: 1 } : undefined}\n >\n {isFileManagementEnabled && attachedFiles.length > 0 && (\n <div className=\"flex gap-1.5 flex-wrap mb-2\">\n {attachedFiles.map((f, i) => (\n <span\n key={i}\n className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] ${\n f.uploadStatus === 'error'\n ? 'border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400'\n : f.uploadStatus === 'pending'\n ? 'border-gray-200 dark:border-white/10 text-gray-400 dark:text-white/40'\n : 'border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60'\n }`}\n >\n {f.uploadStatus === 'pending' ? (\n <span className=\"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin\" />\n ) : (\n <FileIcon size={14} />\n )}\n {f.name}\n {f.uploadStatus === 'error' && <span className=\"text-red-400 text-[0.6rem]\">✕</span>}\n <button\n type=\"button\"\n onClick={() => onFileRemove?.(i)}\n className=\"ml-0.5 text-gray-400 dark:text-white/30 hover:text-gray-600 dark:hover:text-white/60\"\n >\n ×\n </button>\n </span>\n ))}\n </div>\n )}\n\n {/* items-end keeps the buttons on the last line once the field grows.\n `relative` anchors the @ menu, which opens above the field. */}\n <div\n className={`relative flex items-end border rounded-xl px-2 py-1 transition-colors ${\n dictation.listening ? 'border-red-500/50' : 'border-gray-200 dark:border-white/10 focus-within:border-[var(--chat-accent)]'\n } ${isLoading ? 'filigran-chat-active-border' : ''}`}\n >\n {isFileManagementEnabled && (\n <>\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n hidden\n onChange={(e) => {\n onFileAdd?.(e.target.files);\n e.target.value = '';\n }}\n />\n <button\n type=\"button\"\n onClick={() => fileInputRef.current?.click()}\n className=\"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 mr-0.5 transition-colors\"\n >\n <AttachFileIcon size={18} />\n </button>\n </>\n )}\n <textarea\n ref={textareaRef}\n placeholder={dictation.listening ? t('Listening...') : t('Ask a question...')}\n value={inputValue}\n onChange={(e) => onInputChange(e.target.value)}\n onKeyDown={handleKeyDown}\n // The caret moved without the text changing: the @ menu follows it.\n onKeyUp={referenceMenu.sync}\n onClick={referenceMenu.sync}\n onFocus={referenceMenu.sync}\n onBlur={referenceMenu.close}\n {...referenceMenu.textareaAria}\n onPaste={onPaste}\n rows={1}\n className=\"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 filigran-chat-scrollable\"\n style={{ maxHeight: MAX_TEXTAREA_HEIGHT }}\n />\n <ConversationReferenceMenu\n view={referenceMenu.view}\n activeIndex={referenceMenu.activeIndex}\n listboxId={referenceMenu.listboxId}\n optionId={referenceMenu.optionId}\n onHover={referenceMenu.setActiveIndex}\n onPick={referenceMenu.pick}\n t={t}\n />\n {dictation.supported && (\n <Tooltip title={dictation.listening ? t('Stop dictation') : t('Dictate a message')}>\n <button\n type=\"button\"\n onClick={dictation.toggle}\n aria-label={t('Dictate a message')}\n aria-pressed={dictation.listening}\n className={`relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors ${\n dictation.listening\n ? 'text-red-500 bg-red-500/10 hover:bg-red-500/20'\n : 'text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10'\n }`}\n >\n {dictation.listening ? <MicOffIcon size={18} /> : <MicIcon size={18} />}\n {dictation.listening && <span className=\"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse\" />}\n </button>\n </Tooltip>\n )}\n {showSteerSend && (\n <Tooltip title={t('Send now')}>\n <button\n type=\"button\"\n onClick={send}\n aria-label={t('Send now')}\n className=\"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20\"\n >\n <SendIcon size={18} />\n </button>\n </Tooltip>\n )}\n <Tooltip title={isLoading ? t('Stop generating') : hasFilesUploading ? t('Files uploading...') : ''}>\n <button\n type=\"button\"\n onClick={isLoading ? onStop : send}\n disabled={!isLoading && !canSend}\n className={`p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 ${\n isLoading\n ? 'text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5'\n : canSend\n ? 'text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20'\n : 'text-gray-300 dark:text-white/20 cursor-not-allowed'\n }`}\n >\n {isLoading ? <StopCircleIcon size={18} /> : <SendIcon size={18} />}\n </button>\n </Tooltip>\n </div>\n\n {hasToolbar && (\n <div className=\"flex items-center gap-1.5 mt-1.5 px-0.5\">\n {prompts && prompts.length > 0 && <PromptPicker prompts={prompts} onPick={handlePromptPick} t={t} />}\n {composerToolbar}\n {/* Status readouts sit last and pushed right, together: they are not\n controls, so neither should ever land between two clickable\n things. Context before quota — \"how full is this chat\" is the one\n the user can still act on by starting a new one. */}\n {(contextUsage || quota) && (\n <span className=\"ml-auto flex items-center gap-2.5\">\n {contextUsage && <ContextUsageIndicator usage={contextUsage} t={t} />}\n {quota && <QuotaIndicator quota={quota} t={t} />}\n </span>\n )}\n </div>\n )}\n\n {/* Words heard but not yet final take the footer's place, so the preview\n never shifts the composer's height. */}\n {dictation.interim ? (\n <p className=\"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5\">\n <span className=\"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse\" />\n <span className=\"truncate\">{dictation.interim}</span>\n </p>\n ) : (\n <p className=\"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70\">{footerText}</p>\n )}\n </div>\n );\n};\n","import { useCallback, useInsertionEffect, useRef, useState } from 'react';\nimport type { ChatMessage, MessageFeedback, Translate } from '../types';\nimport { normalizeFeedbackComment, ratingOf, submitFeedback } from '../utils/feedback';\n\n/** What the user did to one answer's rating in this session. */\nexport interface FeedbackEntry {\n /** Identifies the last change: a request answered after a newer one is ignored. */\n seq: number;\n value: MessageFeedback | null;\n comment: string | null;\n /** A request is on its way; the thumbs wait for it. */\n pending: boolean;\n /** The translated reason the last request failed, shown under the answer. */\n error: string | null;\n /** The optional comment asked for after a thumbs down. */\n commentOpen: boolean;\n}\n\n/**\n * The key an answer's rating is kept under. Not `id` alone: a restore renames\n * every row (`restored-<n>`), and one runs right after the first turn of a new\n * conversation - the persisted id is what stays the same.\n */\nexport const feedbackKeyOf = (msg: ChatMessage): string => msg.serverId ?? msg.id;\n\ninterface Options {\n /** `{apiBaseUrl}{feedback}` when the panel stores ratings itself (`feedbackBaseUrl`). */\n feedbackUrl?: string | null;\n conversationId?: string | null;\n requestHeaders?: Record<string, string>;\n onMessageFeedback?: (messageId: string, feedback: MessageFeedback | null, message: ChatMessage) => void;\n t: Translate;\n}\n\n/**\n * The thumbs of every answer in the transcript. A rating shows at once and is\n * taken back if the backend refuses it; the callbacks keep their identity, so\n * the memoized rows do not re-render when the panel does.\n *\n * Every action is handed the answer's current entry by its row: a click is a\n * discrete event, so the row has rendered the previous one's outcome by then.\n */\nexport function useMessageFeedback({ feedbackUrl, conversationId, requestHeaders, onMessageFeedback, t }: Options) {\n const [state, setState] = useState<{ scope: string | null | undefined; entries: Record<string, FeedbackEntry> }>(() => ({\n scope: conversationId,\n entries: {},\n }));\n // Ratings belong to one conversation: another one starts from none, and a\n // request of the previous one answering late finds no entry to update.\n let entries = state.entries;\n if (state.scope !== conversationId) {\n entries = {};\n setState({ scope: conversationId, entries });\n }\n\n const latest = useRef({ feedbackUrl, conversationId, requestHeaders, onMessageFeedback, t });\n useInsertionEffect(() => {\n latest.current = { feedbackUrl, conversationId, requestHeaders, onMessageFeedback, t };\n });\n const seqRef = useRef(0);\n\n const put = useCallback((key: string, entry: FeedbackEntry) => setState((s) => ({ ...s, entries: { ...s.entries, [key]: entry } })), []);\n const patch = useCallback(\n (key: string, seq: number, change: (entry: FeedbackEntry) => FeedbackEntry) =>\n setState((s) => {\n const entry = s.entries[key];\n if (!entry || entry.seq !== seq) return s;\n return { ...s, entries: { ...s.entries, [key]: change(entry) } };\n }),\n [],\n );\n\n const rate = useCallback(\n async (msg: ChatMessage, next: MessageFeedback | null, current: FeedbackEntry | undefined) => {\n const { feedbackUrl: url, conversationId: convId, requestHeaders: headers, onMessageFeedback: notify, t: tr } = latest.current;\n const key = feedbackKeyOf(msg);\n const seq = ++seqRef.current;\n if (!url) {\n // The host stores it: nothing to wait for.\n put(key, { seq, value: next, comment: null, pending: false, error: null, commentOpen: false });\n notify?.(key, next, msg);\n return;\n }\n if (!convId || !msg.serverId) return;\n put(key, { seq, value: next, comment: null, pending: true, error: null, commentOpen: false });\n const stored = await submitFeedback(fetch, url, convId, msg.serverId, next ? { rating: ratingOf(next), comment: null } : null, headers);\n if (!stored) {\n const error = tr(next ? 'Could not submit feedback.' : 'Could not retract feedback.');\n patch(key, seq, () =>\n current\n ? { ...current, seq, pending: false, commentOpen: false, error }\n : { seq, value: null, comment: null, pending: false, error, commentOpen: false },\n );\n return;\n }\n // A thumbs down is worth a word on what went wrong - asked once it is\n // stored, so skipping the question loses nothing.\n patch(key, seq, (entry) => ({ ...entry, pending: false, commentOpen: next === 'down' }));\n latest.current.onMessageFeedback?.(key, next, msg);\n },\n [put, patch],\n );\n\n const saveComment = useCallback(\n async (msg: ChatMessage, text: string, current: FeedbackEntry) => {\n const { feedbackUrl: url, conversationId: convId, requestHeaders: headers, t: tr } = latest.current;\n const key = feedbackKeyOf(msg);\n const comment = normalizeFeedbackComment(text);\n if (!url || !convId || !msg.serverId || !comment) {\n put(key, { ...current, commentOpen: false, error: null });\n return;\n }\n const seq = ++seqRef.current;\n put(key, { ...current, seq, pending: true, error: null });\n const stored = await submitFeedback(fetch, url, convId, msg.serverId, { rating: 'negative', comment }, headers);\n patch(key, seq, (entry) =>\n stored\n ? { ...entry, comment, pending: false, commentOpen: false }\n : // The question stays open with what was typed, to try again.\n { ...entry, pending: false, error: tr('Could not submit feedback.') },\n );\n },\n [put, patch],\n );\n\n const skipComment = useCallback(\n (msg: ChatMessage, current: FeedbackEntry) => put(feedbackKeyOf(msg), { ...current, commentOpen: false, error: null }),\n [put],\n );\n\n return { entries, rate, saveComment, skipComment };\n}\n","import remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport { unified } from 'unified';\n\n/**\n * Reading an answer aloud through the browser's speech synthesis.\n *\n * What is spoken is the text a reader sees, never the markdown that draws it:\n * no `**`, no `#`, no table pipes, no code block, no image, and no bare URL\n * spelled out character by character. The text is parsed with the parser the\n * panel renders with (remark-parse + remark-gfm), so what counts as a heading,\n * a list or a link is what the screen shows. It reads the documents the\n * transcript renders (`answerMarkdownSources`), never the raw answer: the\n * renderer splits it at its file markers and repairs it first (`prepareMarkdown`).\n *\n * Kept free of local imports so `node --test` runs it as is.\n */\n\nconst parser = unified().use(remarkParse).use(remarkGfm).freeze();\n\ntype MdNode = { type: string; value?: string; url?: string; children?: MdNode[] };\n\n/** Blocks and inline nodes a listener has nothing to hear in. */\nconst SILENT = new Set(['code', 'html', 'image', 'imageReference', 'definition', 'footnoteDefinition', 'footnoteReference', 'thematicBreak']);\n\nfunction inlineText(node: MdNode): string {\n if (SILENT.has(node.type)) return '';\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? '';\n if (node.type === 'break') return ' ';\n const text = (node.children ?? []).map(inlineText).join('');\n // A link written as its own address (a bare URL, an autolink) is noise when\n // read out; a link with words says those words.\n if (node.type === 'link' && node.url && (text === node.url || `mailto:${text}` === node.url)) return '';\n return text;\n}\n\nfunction collectLines(node: MdNode, lines: string[]): void {\n if (SILENT.has(node.type)) return;\n switch (node.type) {\n case 'paragraph':\n case 'heading':\n lines.push(inlineText(node));\n return;\n case 'tableRow':\n lines.push(\n (node.children ?? [])\n .map(inlineText)\n .map((cell) => cell.trim())\n .filter(Boolean)\n .join(', '),\n );\n return;\n default:\n for (const child of node.children ?? []) collectLines(child, lines);\n }\n}\n\n/**\n * The words of an answer's markdown documents, one sentence-ending line per\n * block: a heading or a list item without its own punctuation gets a full\n * stop, so the voice pauses where the eye does. Each document is parsed on its own.\n */\nexport function speakableText(documents: readonly string[]): string {\n const lines: string[] = [];\n for (const markdown of documents) {\n if (markdown.trim()) collectLines(parser.parse(markdown) as MdNode, lines);\n }\n return lines\n .map((line) =>\n line\n .replace(/\\s+/g, ' ')\n .replace(/ ([.,!?;:])/g, '$1')\n .trim(),\n )\n .filter((line) => /[\\p{L}\\p{N}]/u.test(line))\n .map((line) => (/[.!?;:\\u3002\\uff01\\uff1f]$/.test(line) ? line : `${line}.`))\n .join('\\n');\n}\n\n/**\n * A fenced code block: a run of 3+ backticks or tildes, closed by a bare run of\n * the same character at least as long (`prepareMarkdown` lengthens the fence\n * around nested ones), or by the end of an answer cut short.\n */\nconst FENCED_BLOCK_RE = /^[ \\t]*((`|~)\\2{2,})[\\s\\S]*?(?:^[ \\t]*\\1\\2*[ \\t]*$|(?![\\s\\S]))/gm;\n\n/**\n * Whether an answer's markdown documents have words to read outside their code\n * blocks - what decides that it gets a \"Read aloud\" button. A cheap look rather\n * than `speakableText`: it runs for every message on screen, the full parse only on a click.\n */\nexport function hasSpeakableWords(documents: readonly string[]): boolean {\n return documents.some((markdown) => /[\\p{L}\\p{N}]/u.test(markdown.replace(FENCED_BLOCK_RE, '')));\n}\n\n/**\n * Longest utterance handed to the synthesiser. Chrome stops a single utterance\n * after roughly fifteen seconds without firing `end`, so a long answer is\n * queued as a series of short ones, cut between sentences.\n */\nexport const SPEECH_CHUNK_MAX_LENGTH = 220;\n\n/** `text` cut into utterances of at most `maxLength` characters, between sentences first, then between words. */\nexport function chunkSpeech(text: string, maxLength: number = SPEECH_CHUNK_MAX_LENGTH): string[] {\n const sentences = text\n .split(/\\n+|(?<=[.!?;:\\u3002\\uff01\\uff1f])\\s+/)\n .map((s) => s.trim())\n .filter(Boolean);\n const pieces: string[] = [];\n for (const sentence of sentences) {\n if (sentence.length <= maxLength) {\n pieces.push(sentence);\n continue;\n }\n let current = '';\n for (const word of sentence.split(' ')) {\n for (let start = 0; start < word.length; start += maxLength) {\n const part = word.slice(start, start + maxLength);\n if (!current) current = part;\n else if (current.length + 1 + part.length <= maxLength) current = `${current} ${part}`;\n else {\n pieces.push(current);\n current = part;\n }\n }\n }\n if (current) pieces.push(current);\n }\n const chunks: string[] = [];\n for (const piece of pieces) {\n const last = chunks.length - 1;\n if (last >= 0 && chunks[last].length + 1 + piece.length <= maxLength) chunks[last] = `${chunks[last]} ${piece}`;\n else chunks.push(piece);\n }\n return chunks;\n}\n\n/** The part of `window.speechSynthesis` the controller uses. */\nexport interface SpeechSynthesisLike<U> {\n speak(utterance: U): void;\n cancel(): void;\n}\n\n/** Builds one utterance; `window.SpeechSynthesisUtterance` in the browser. */\nexport type CreateUtterance<U> = (text: string, options: { lang?: string; onEnd: () => void; onError: () => void }) => U;\n\nexport interface SpeechController {\n /**\n * Reads `chunks` as the message `id`, stopping whatever was being read.\n * Returns false, and reads nothing, when there is nothing to read.\n */\n speak(id: string, chunks: string[], lang?: string): boolean;\n /** Stops reading. A no-op when nothing is being read. */\n stop(): void;\n /** The message being read, or null. */\n readonly speakingId: string | null;\n}\n\n/**\n * One reader for the whole transcript: starting a message stops the previous\n * one, and `onChange` reports which message is being read (null once it ended,\n * failed or was stopped). The synthesiser reports the end of an utterance\n * asynchronously and, on `cancel()`, fails every queued one: each reading\n * carries a generation, and only the current one's events count.\n */\nexport function createSpeechController<U>(\n synth: SpeechSynthesisLike<U>,\n createUtterance: CreateUtterance<U>,\n onChange: (id: string | null) => void,\n): SpeechController {\n let generation = 0;\n let speakingId: string | null = null;\n\n const finish = (gen: number) => {\n if (gen !== generation || speakingId === null) return;\n generation += 1;\n speakingId = null;\n onChange(null);\n };\n\n // Nothing of ours being read, nothing is cancelled: the synthesiser is the\n // page's, and the host may be using it.\n const stop = () => {\n if (speakingId === null) return;\n generation += 1;\n speakingId = null;\n synth.cancel();\n onChange(null);\n };\n\n const speak = (id: string, chunks: string[], lang?: string) => {\n stop();\n const parts = chunks.filter((c) => c.trim());\n if (!parts.length) return false;\n const gen = generation;\n speakingId = id;\n onChange(id);\n parts.forEach((part, index) => {\n const last = index === parts.length - 1;\n const utterance = createUtterance(part, {\n lang,\n onEnd: () => {\n if (last) finish(gen);\n },\n onError: () => {\n if (gen !== generation) return;\n // Ends the reading before cancelling the rest of its queue, whose\n // failures then belong to a past generation.\n finish(gen);\n synth.cancel();\n },\n });\n synth.speak(utterance);\n });\n return true;\n };\n\n return {\n speak,\n stop,\n get speakingId() {\n return speakingId;\n },\n };\n}\n","import { useCallback, useEffect, useInsertionEffect, useRef, useState } from 'react';\nimport { chunkSpeech, createSpeechController, speakableText, type SpeechController } from '../utils/speech';\n\nconst speechSupported = (): boolean =>\n typeof window !== 'undefined' && !!window.speechSynthesis && typeof window.SpeechSynthesisUtterance === 'function';\n\n/**\n * Reads answers aloud through the browser's speech synthesis, one at a time,\n * in `locale` (the browser's voice when unset). `supported` is false where the\n * browser has no synthesiser: the panel then offers no button at all.\n *\n * Whatever is being read stops when the transcript unmounts.\n */\nexport function useSpeechReader(locale?: string) {\n const [supported] = useState(speechSupported);\n const [speakingId, setSpeakingId] = useState<string | null>(null);\n const controllerRef = useRef<SpeechController | null>(null);\n const localeRef = useRef(locale);\n useInsertionEffect(() => {\n localeRef.current = locale;\n });\n\n const controller = useCallback((): SpeechController | null => {\n if (!supported) return null;\n controllerRef.current ??= createSpeechController<SpeechSynthesisUtterance>(\n window.speechSynthesis,\n (text, { lang, onEnd, onError }) => {\n const utterance = new SpeechSynthesisUtterance(text);\n if (lang) utterance.lang = lang;\n utterance.onend = onEnd;\n utterance.onerror = onError;\n return utterance;\n },\n setSpeakingId,\n );\n return controllerRef.current;\n }, [supported]);\n\n /**\n * Reads the message `id` from the markdown documents the transcript renders it\n * from (`answerMarkdownSources`), or stops it when it is the one being read.\n */\n const toggle = useCallback(\n (id: string, documents: readonly string[]) => {\n const reader = controller();\n if (!reader) return;\n if (reader.speakingId === id) reader.stop();\n else reader.speak(id, chunkSpeech(speakableText(documents)), localeRef.current);\n },\n [controller],\n );\n\n const stop = useCallback(() => controllerRef.current?.stop(), []);\n\n useEffect(() => () => controllerRef.current?.stop(), []);\n\n return { supported, speakingId, toggle, stop };\n}\n","/**\n * The time shown under a chat message.\n *\n * A message from today reads as its time alone (`14:05`); an older one leads\n * with a short date (`29 Sept, 14:05`), and one from another year carries the\n * year, so a restored conversation says when each answer was given without\n * anyone having to hover. The tooltip spells the whole date out.\n *\n * Kept free of local imports so `node --test` runs it as is.\n */\n\nexport interface MessageTime {\n /** What the footer shows. */\n label: string;\n /** The complete date and time, for the tooltip. */\n full: string;\n /** Machine-readable, for the `dateTime` attribute of a `<time>` element. */\n iso: string;\n}\n\ntype FormatKind = 'time' | 'date' | 'dateWithYear' | 'full';\n\nconst FORMAT_OPTIONS: Record<FormatKind, Intl.DateTimeFormatOptions> = {\n time: { hour: '2-digit', minute: '2-digit' },\n date: { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' },\n dateWithYear: { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' },\n full: { dateStyle: 'full', timeStyle: 'short' },\n};\n\n// Every row of a transcript formats with the same few formatters, and building\n// one costs far more than using it.\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction formatter(locale: string | undefined, kind: FormatKind): Intl.DateTimeFormat {\n const key = `${locale ?? ''}|${kind}`;\n let cached = formatters.get(key);\n if (!cached) {\n try {\n cached = new Intl.DateTimeFormat(locale || undefined, FORMAT_OPTIONS[kind]);\n } catch {\n // A malformed tag throws a RangeError: fall back to the browser's own\n // language rather than losing the time.\n cached = new Intl.DateTimeFormat(undefined, FORMAT_OPTIONS[kind]);\n }\n formatters.set(key, cached);\n }\n return cached;\n}\n\nfunction sameDay(a: Date, b: Date): boolean {\n return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();\n}\n\n/**\n * The footer time of a message sent at `date`, in `locale` (browser default\n * when absent), read against `now`. `null` for a date that is not one, so a\n * backend sending an unparseable `created_at` loses the time, not the row.\n */\nexport function formatMessageTime(date: Date, locale?: string, now: Date = new Date()): MessageTime | null {\n if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;\n const kind: FormatKind = sameDay(date, now) ? 'time' : date.getFullYear() === now.getFullYear() ? 'date' : 'dateWithYear';\n return {\n label: formatter(locale, kind).format(date),\n full: formatter(locale, 'full').format(date),\n iso: date.toISOString(),\n };\n}\n","/**\n * How the thread keeps the end of the conversation in view as it grows.\n *\n * The view follows the conversation while the reader is at the bottom, stops\n * once they scroll up to read back, and follows again when they come back down\n * or send a message. While following, each streamed frame jumps to the end at\n * once: a smooth scroll restarted on every frame lags behind the text. A\n * message just sent and a conversation just opened are scrolled to smoothly,\n * and since any other scroll aborts a smooth one, the frames streamed in the\n * meantime wait for it to arrive and the view then catches up with them.\n *\n * The reader's gestures toward the top (a wheel, a swipe, a key, a press on\n * the scrollbar) stop the follow before the scroll they cause, read by the\n * predicates below. A scroll event that moved nothing changes nothing: it is\n * the event of a jump of ours, delivered a frame late, and right after such a\n * gesture it would re-arm the follow the gesture just ended. Each move is read\n * against the last position that moved more than 1 px, so a slow drift of\n * sub-pixel steps adds up to a move instead of reading as none at every step.\n */\n\n/** How near the bottom a reader scrolling down must come for the view to follow again. */\nexport const FOLLOW_THRESHOLD_PX = 100;\n\n/** How far (px) a finger must travel down the screen before the swipe counts as scrolling up. */\nexport const TOUCH_SLOP_PX = 4;\n\n/**\n * The longest a smooth scroll of ours is waited for. Browsers finish one well\n * within it; past it the view catches up anyway, since a smooth scroll cut\n * short by another one (a prompt scrolling itself into view) never reaches\n * where it was going.\n */\nconst SMOOTH_SCROLL_TIMEOUT_MS = 1000;\n\n/** The scroll container, as far as following the conversation needs it. */\nexport interface ScrollBox {\n readonly scrollTop: number;\n readonly scrollHeight: number;\n readonly clientHeight: number;\n scrollTo(options: ScrollToOptions): void;\n}\n\nexport interface ScrollFollowTimers {\n set: (callback: () => void, ms: number) => unknown;\n clear: (handle: unknown) => void;\n}\n\nexport interface ScrollFollower {\n /** Whether the view follows the conversation as it grows. */\n readonly following: boolean;\n /** Scroll smoothly to the end and follow again: a message just sent, a conversation just opened. */\n reveal: () => void;\n /** The conversation grew: keep its end in view while the view follows. */\n keepUp: () => void;\n /** The container scrolled. */\n onScroll: () => void;\n /**\n * The reader is scrolling toward the top (a wheel, a swipe, a key, the scrollbar). Stops the follow\n * at once: the scroll event only comes with the next frame, and a streamed\n * frame committed before it would pull the view back down first.\n */\n leave: () => void;\n}\n\nconst browserTimers: ScrollFollowTimers = {\n set: (callback, ms) => setTimeout(callback, ms),\n clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n\nexport function createScrollFollower(getBox: () => ScrollBox | null, timers: ScrollFollowTimers = browserTimers): ScrollFollower {\n let following = true;\n // Where the view was last seen, which tells the reader scrolling up apart\n // from the view being moved down by a scroll of ours.\n let lastTop = 0;\n // A smooth scroll of ours still running: where it lands, and the timer that\n // stops waiting for it.\n let smooth: { target: number; timer: unknown } | null = null;\n\n // 'instant' rather than 'auto': a `scroll-behavior: smooth` stylesheet would\n // turn 'auto' smooth again.\n const jumpToEnd = (box: ScrollBox) => {\n box.scrollTo({ top: box.scrollHeight, behavior: 'instant' });\n lastTop = box.scrollTop;\n };\n\n const stopWaiting = () => {\n if (!smooth) return;\n timers.clear(smooth.timer);\n smooth = null;\n };\n\n // The smooth scroll is over: catch up with what streamed in while it ran.\n const arrived = () => {\n stopWaiting();\n const box = getBox();\n if (box && following) jumpToEnd(box);\n };\n\n return {\n get following() {\n return following;\n },\n reveal: () => {\n const box = getBox();\n if (!box) return;\n following = true;\n stopWaiting();\n const target = Math.max(0, box.scrollHeight - box.clientHeight);\n box.scrollTo({ top: box.scrollHeight, behavior: 'smooth' });\n lastTop = box.scrollTop;\n // Already at the end, or moved there at once (smooth scrolling turned off).\n if (lastTop >= target - 1) return;\n smooth = { target, timer: timers.set(arrived, SMOOTH_SCROLL_TIMEOUT_MS) };\n },\n keepUp: () => {\n const box = getBox();\n // A jump now would cut the smooth scroll short: it catches up on arrival.\n if (box && following && !smooth) jumpToEnd(box);\n },\n onScroll: () => {\n const box = getBox();\n if (!box) return;\n const top = box.scrollTop;\n const movedUp = top < lastTop - 1;\n const movedDown = top > lastTop + 1;\n if (movedUp || movedDown) lastTop = top;\n const distance = box.scrollHeight - top - box.clientHeight;\n if (movedUp) {\n // The reader scrolled up — or the browser moved the view to the new end\n // of a list that got shorter, which leaves it at the bottom.\n following = distance <= 1;\n } else if (movedDown && distance <= FOLLOW_THRESHOLD_PX) {\n following = true;\n }\n // Ours only goes down: it is over once the view reaches where it was sent\n // or the end, and a move up is the reader taking over.\n if (smooth && (movedUp || top >= smooth.target - 1 || distance <= 1)) arrived();\n },\n leave: () => {\n const box = getBox();\n // With nothing above to scroll to (a thread that fits), the reader is\n // still at the end whatever the gesture.\n if (!box || box.scrollTop <= 0) return;\n following = false;\n stopWaiting();\n },\n };\n}\n\n/** A wheel turned toward the top. A pinch (ctrl + wheel) zooms, and a mostly sideways one pans a code block or a table. */\nexport function wheelScrollsUp(event: { deltaX: number; deltaY: number; ctrlKey: boolean }): boolean {\n return !event.ctrlKey && event.deltaY < 0 && Math.abs(event.deltaY) > Math.abs(event.deltaX);\n}\n\nconst KEYS_TOWARD_TOP = new Set(['ArrowUp', 'PageUp', 'Home']);\n\n/** A key that scrolls a focused thread toward its top. */\nexport function keyScrollsUp(event: { key: string; shiftKey: boolean; altKey: boolean }): boolean {\n if (event.altKey) return false;\n return KEYS_TOWARD_TOP.has(event.key) || (event.key === ' ' && event.shiftKey);\n}\n\n/**\n * A finger moving DOWN the screen (the content follows it toward the top),\n * measured from the highest point of the touch so far, so a tap's jitter is\n * not a swipe.\n */\nexport function swipeScrollsUp(anchorY: number, y: number): boolean {\n return y - anchorY > TOUCH_SLOP_PX;\n}\n\n/**\n * Where the one finger on the screen is. `null` while two or more are down: a\n * pinch zooms and a first finger can travel down past the slop without the\n * thread scrolling at all.\n */\nexport function singleTouchY(touches: ArrayLike<{ clientY: number }>): number | null {\n return touches.length === 1 ? touches[0].clientY : null;\n}\n\n/**\n * The swipe anchor after a `touchmove` that found the finger at `y`: none\n * during a pinch, the finger's own position on its first move after one (no\n * `touchstart` marks the finger left on the screen), else the highest point.\n */\nexport function nextTouchAnchor(anchor: number | null, y: number | null): number | null {\n if (y === null) return null;\n return anchor === null ? y : Math.min(anchor, y);\n}\n\n/** A pointer press on the thread, `x` / `y` measured from its padding box. */\nexport interface ScrollPress {\n button: number;\n /** The press landed on the container itself, not on its content. */\n onContainer: boolean;\n /** The press landed on a link, a button or a field. */\n onControl: boolean;\n x: number;\n y: number;\n clientWidth: number;\n clientHeight: number;\n scrollTop: number;\n scrollHeight: number;\n}\n\n/**\n * A press that hands the view to the reader: the middle button away from a\n * control, which starts the browser's autoscroll on Windows and Linux (on a\n * link it opens a tab), or the thread's own scrollbar (`x` past its content\n * box) on the thumb or above it. The track below the thumb pages DOWN, toward\n * the end the view follows.\n */\nexport function pressTakesScrollbar(press: ScrollPress): boolean {\n if (press.button === 1) return !press.onControl;\n if (press.button !== 0 || !press.onContainer || press.x < press.clientWidth) return false;\n const thumbBottom = ((press.scrollTop + press.clientHeight) / press.scrollHeight) * press.clientHeight;\n return press.y <= thumbBottom;\n}\n\n/** What `innerBoxScrollsUp` reads of an element. */\nexport interface ScrollNode {\n readonly scrollTop: number;\n readonly scrollHeight: number;\n readonly clientHeight: number;\n}\n\nconst SCROLLING_OVERFLOW = new Set(['auto', 'scroll', 'overlay']);\n\n/**\n * Whether a gesture toward the top at `target` scrolls a box INSIDE the thread\n * instead of the thread: the browser moves the innermost box under it that can\n * still go up, and the thread only once that box is at its top. A box that\n * only clips (`overflow: hidden` — the reasoning window, pinned to its own\n * end) is not one: the gesture goes through it.\n */\nexport function innerBoxScrollsUp<T extends ScrollNode>(\n target: T | null,\n container: T,\n parentOf: (node: T) => T | null,\n overflowY: (node: T) => string,\n): boolean {\n for (let node = target; node && node !== container; node = parentOf(node)) {\n if (node.scrollTop > 0 && node.scrollHeight > node.clientHeight && SCROLLING_OVERFLOW.has(overflowY(node))) {\n return true;\n }\n }\n return false;\n}\n","import { useEffect, useState } from 'react';\nimport type { ChatArtifact, ChatArtifactKind, Translate } from '../types';\nimport { artifactDownloadLabel, artifactFacts, artifactKindLabel, artifactLink, isRenderInProgress, translate, videoRenderLabel } from '../utils';\nimport { pollInTurn } from '../utils/polling';\nimport { ClapperboardIcon, DownloadIcon, ExternalLinkIcon, FileTextIcon, PresentationIcon } from './icons';\nimport { Spinner } from './Spinner';\n\n/** How often a card asks again about a video that is still rendering, and for how long. */\nconst REFRESH_INTERVAL_MS = 10_000;\nconst REFRESH_FOR_MS = 15 * 60_000;\n\nconst KIND_ICONS: Record<ChatArtifactKind, typeof PresentationIcon> = {\n presentation: PresentationIcon,\n report: FileTextIcon,\n video: ClapperboardIcon,\n};\n\nconst ACTION =\n 'inline-flex items-center gap-1 rounded-md border border-gray-200 dark:border-white/10 px-2 py-1 text-[0.7rem] text-gray-700 dark:text-white/70 transition-colors hover:border-[var(--chat-accent)] hover:text-[var(--chat-accent)] disabled:opacity-50 disabled:cursor-default outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]';\n\ninterface ArtifactCardProps {\n artifact: ChatArtifact;\n t: Translate;\n /** Downloads it in a format through the host's proxy; no download buttons without it. */\n onDownload?: (artifact: ChatArtifact, format: string) => Promise<void>;\n /** Describes it again; a video still rendering is followed with it. */\n onRefresh?: (kind: ChatArtifactKind, id: string) => Promise<ChatArtifact | undefined>;\n}\n\n/**\n * A deck, report or video an answer made: what it is, `Open in XTM One`, and\n * its downloads when the host proxies them. The panel cannot draw the deck or\n * play the film itself; XTM One's page does.\n */\nexport const ArtifactCard = ({ artifact, t, onDownload, onRefresh }: ArtifactCardProps) => {\n const [current, setCurrent] = useState(artifact);\n const [busyFormat, setBusyFormat] = useState<string | null>(null);\n const [gaveUp, setGaveUp] = useState(false);\n useEffect(() => setCurrent(artifact), [artifact]);\n\n const following = !!onRefresh && !gaveUp && isRenderInProgress(current);\n useEffect(() => {\n if (!following || !onRefresh) return undefined;\n let cancelled = false;\n const stop = pollInTurn(\n () =>\n onRefresh(current.kind, current.id).then((fresh) => {\n if (!cancelled && fresh) setCurrent(fresh);\n }),\n { intervalMs: REFRESH_INTERVAL_MS, forMs: REFRESH_FOR_MS, onGiveUp: () => setGaveUp(true) },\n );\n return () => {\n cancelled = true;\n stop();\n };\n }, [following, onRefresh, current.kind, current.id]);\n\n const Icon = KIND_ICONS[current.kind];\n const kindLabel = artifactKindLabel(current.kind, t);\n const title = current.title || kindLabel;\n const facts = artifactFacts(current, t);\n const renderLabel = videoRenderLabel(current, t);\n const link = artifactLink(current);\n const downloads = onDownload ? current.downloads : [];\n\n const download = async (format: string) => {\n if (!onDownload) return;\n setBusyFormat(format);\n try {\n await onDownload(current, format);\n } finally {\n setBusyFormat(null);\n }\n };\n\n return (\n <div\n role=\"group\"\n aria-label={`${kindLabel}: ${title}`}\n className=\"flex flex-col gap-2 w-full max-w-[90%] rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] px-3 py-2.5\"\n >\n <div className=\"flex items-start gap-2.5 min-w-0\">\n <span className=\"shrink-0 mt-0.5 text-[var(--chat-accent)]\">\n <Icon size={18} />\n </span>\n <span className=\"flex flex-col min-w-0 flex-1 gap-0.5\">\n <span className=\"truncate text-[0.8125rem] font-medium text-gray-900 dark:text-white\">{title}</span>\n {facts && <span className=\"text-[0.7rem] text-gray-500 dark:text-white/50\">{facts}</span>}\n {renderLabel && (\n <span className=\"flex items-center gap-1.5 text-[0.7rem] text-gray-500 dark:text-white/50\" aria-live=\"polite\">\n {following && <Spinner size={10} />}\n {renderLabel}\n </span>\n )}\n </span>\n </div>\n {(link || downloads.length > 0) && (\n <div className=\"flex flex-wrap items-center gap-1.5 pl-[28px]\">\n {link && (\n <a href={link} target=\"_blank\" rel=\"noopener noreferrer\" className={ACTION}>\n {t('Open in XTM One')}\n <ExternalLinkIcon size={12} />\n </a>\n )}\n {downloads.map((format) => {\n const label = artifactDownloadLabel(format, t);\n return (\n <button\n key={format}\n type=\"button\"\n className={ACTION}\n disabled={busyFormat !== null}\n aria-label={translate(t, 'Download {format}', { format: label })}\n onClick={() => void download(format)}\n >\n {busyFormat === format ? <Spinner size={11} /> : <DownloadIcon size={12} />}\n {label}\n </button>\n );\n })}\n </div>\n )}\n </div>\n );\n};\n","import type { IconProps } from '../../types';\n\nexport const PresentationIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M2 3h20\" />\n <path d=\"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3\" />\n <path d=\"m7 21 5-5 5 5\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const FileTextIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n <path d=\"M10 9H8\" />\n <path d=\"M16 13H8\" />\n <path d=\"M16 17H8\" />\n </svg>\n);\n","import type { IconProps } from '../../types';\n\nexport const ClapperboardIcon = ({ className, size = 24 }: IconProps) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={className}\n >\n <path d=\"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z\" />\n <path d=\"m6.2 5.3 3.1 3.9\" />\n <path d=\"m12.4 3.4 3.1 4\" />\n <path d=\"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z\" />\n </svg>\n);\n","/**\n * Calls *ask* every *intervalMs*, one call at a time: the next one waits for\n * the last to settle, so a slow answer can never land after a newer one. A\n * call that fails is followed by the next as usual. After *forMs* it stops for\n * good and calls *onGiveUp*, even with a call still unanswered; the returned\n * function stops it earlier.\n */\nexport function pollInTurn(\n ask: () => Promise<unknown>,\n { intervalMs, forMs, onGiveUp }: { intervalMs: number; forMs: number; onGiveUp?: () => void },\n): () => void {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const next = () => {\n timer = setTimeout(() => {\n ask()\n .catch(() => undefined)\n .finally(() => {\n if (!stopped) next();\n });\n }, intervalMs);\n };\n const deadline = setTimeout(() => {\n stopped = true;\n clearTimeout(timer);\n onGiveUp?.();\n }, forMs);\n next();\n return () => {\n stopped = true;\n clearTimeout(timer);\n clearTimeout(deadline);\n };\n}\n","import { useEffect, useId, useRef, useState } from 'react';\nimport type { ToolApprovalDecision, ToolApprovalProposal, ToolApprovalVerdict } from '../types';\nimport { translate } from '../utils';\nimport { AlertTriangleIcon, CheckIcon, WrenchIcon, XCircleIcon } from './icons';\n\ninterface ChatApprovalPromptProps {\n proposals: ToolApprovalProposal[];\n /** Sends one decision per proposal — the backend refuses a partial set. */\n onSubmit: (decisions: ToolApprovalDecision[]) => void;\n isSubmitting?: boolean;\n /** Why the last submission failed. Non-null re-arms the controls for a retry. */\n error?: string | null;\n t: (key: string) => string;\n}\n\n/** Shape of one argument as described by the tool's own JSON Schema. */\ninterface ArgumentSchema {\n description?: string;\n type?: string;\n}\n\n/**\n * Pull `{ description, type }` for one argument out of a JSON Schema, tolerating\n * a schema that is absent or shaped unexpectedly — an unlabelled argument still\n * renders, it just carries less.\n */\nfunction argumentSchema(inputSchema: Record<string, unknown> | undefined, name: string): ArgumentSchema {\n const properties = inputSchema?.properties;\n if (!properties || typeof properties !== 'object') return {};\n const entry = (properties as Record<string, unknown>)[name];\n if (!entry || typeof entry !== 'object') return {};\n const e = entry as Record<string, unknown>;\n return {\n description: typeof e.description === 'string' ? e.description : undefined,\n type: typeof e.type === 'string' ? e.type : undefined,\n };\n}\n\n/** Render an argument value as something a person can read. */\nfunction formatValue(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n // Cyclic or otherwise unstringifiable — the reviewer still needs to see\n // that the argument is there, so degrade rather than blank the card.\n return String(value);\n }\n}\n\n/**\n * Scroll `ref` into view when `active` becomes true, and on each later\n * transition into it.\n *\n * Every control here is revealed rather than always present: the prompt itself\n * arrives at the bottom of a thread that has just grown by a whole turn, \"No\"\n * opens a reason box under the card, and \"Yes, always\" opens a warning under the\n * list. In each case the click can look like it did nothing — and on a *paused*\n * turn a stalled reviewer stalls the agent too. rAF because the revealed node\n * must be laid out before it can be scrolled to.\n */\nfunction useRevealIntoView<T extends HTMLElement>(active: boolean) {\n const ref = useRef<T>(null);\n useEffect(() => {\n if (!active) return;\n const raf = requestAnimationFrame(() => {\n ref.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });\n });\n return () => cancelAnimationFrame(raf);\n }, [active]);\n return ref;\n}\n\nconst BUTTON_BASE =\n 'inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50';\n\ninterface ApprovalCardProps {\n proposal: ToolApprovalProposal;\n decision: ToolApprovalDecision | undefined;\n onDecide: (decision: ToolApprovalDecision) => void;\n disabled?: boolean;\n t: (key: string) => string;\n}\n\n/**\n * One proposed call: what the agent wants to run, what it does, and every\n * argument labelled with the tool's own description of it.\n *\n * Those descriptions are the difference between a control and a rubber stamp.\n * `cascade: true` is unjudgeable; \"cascade — also delete linked entities\" is a\n * decision someone can actually make.\n */\nconst ApprovalCard = ({ proposal, decision, onDecide, disabled, t }: ApprovalCardProps) => {\n // Declining asks why before it sends. With argument editing deliberately\n // absent, a rejection IS the correction channel — it is the agent's only\n // signal to adapt. Optional, so a reviewer with nothing to add just confirms.\n const [rejecting, setRejecting] = useState(false);\n const [reason, setReason] = useState('');\n // Every proposal in a batch renders its own reason box, so the association\n // needs an id unique to this card rather than a constant.\n const reasonId = useId();\n const rejectPanelRef = useRevealIntoView<HTMLDivElement>(rejecting);\n\n const verdict = decision?.verdict;\n const argumentNames = Object.keys(proposal.arguments ?? {});\n\n const decide = (next: ToolApprovalVerdict) => {\n onDecide({\n toolCallId: proposal.toolCallId,\n verdict: next,\n ...(next === 'reject' && reason.trim() ? { rejectionReason: reason.trim() } : {}),\n });\n };\n\n return (\n <div className=\"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2\">\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"min-w-0 flex items-start gap-2\">\n <WrenchIcon size={13} className=\"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400\" />\n <div className=\"min-w-0\">\n {/* An unnamed tool is a malformed proposal, not a tool called\n \"unknown tool\": the placeholder is the package's own text and\n therefore translated here, not in the parser. */}\n <p className=\"truncate font-mono text-xs text-gray-800 dark:text-white/85\">{proposal.toolName || t('unknown tool')}</p>\n {proposal.toolDescription && <p className=\"mt-0.5 text-[0.7rem] text-gray-600 dark:text-white/60\">{proposal.toolDescription}</p>}\n {proposal.source && <p className=\"mt-0.5 text-[0.65rem] text-gray-400 dark:text-white/35\">{proposal.source}</p>}\n </div>\n </div>\n {verdict && (\n <span\n className={\n 'shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium ' +\n (verdict === 'reject' ? 'bg-red-500/15 text-red-600 dark:text-red-300' : 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300')\n }\n >\n {verdict === 'reject' ? t('Declined') : verdict === 'approve_always' ? t('Always allowed') : t('Approved')}\n </span>\n )}\n </div>\n\n {argumentNames.length > 0 && (\n <div className=\"flex flex-col gap-1.5\">\n {argumentNames.map((name) => {\n const schema = argumentSchema(proposal.inputSchema, name);\n return (\n <div key={name} className=\"text-[0.7rem]\">\n <div className=\"flex flex-wrap items-baseline gap-1.5\">\n <span className=\"font-mono text-gray-700 dark:text-white/75\">{name}</span>\n {schema.description && <span className=\"text-gray-500 dark:text-white/45\">— {schema.description}</span>}\n </div>\n <pre className=\"mt-0.5 whitespace-pre-wrap break-all font-mono text-gray-600 dark:text-white/60\">\n {formatValue(proposal.arguments?.[name])}\n </pre>\n </div>\n );\n })}\n </div>\n )}\n\n {!verdict && rejecting && (\n <div ref={rejectPanelRef} className=\"flex flex-col gap-1.5\">\n <label htmlFor={reasonId} className=\"text-[0.7rem] text-gray-500 dark:text-white/45\">\n {t('Why not? The agent sees this and can adapt (optional)')}\n </label>\n <textarea\n id={reasonId}\n autoFocus\n rows={2}\n value={reason}\n onChange={(e) => setReason(e.target.value)}\n placeholder={t('e.g. wrong environment — use staging instead')}\n className=\"w-full resize-none rounded-md border border-gray-200 bg-white px-2 py-1 text-[0.7rem] text-gray-800 outline-none focus:border-[var(--chat-accent)]/50 dark:border-white/10 dark:bg-white/[0.03] dark:text-white/85\"\n />\n <div className=\"flex items-center gap-1.5\">\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => decide('reject')}\n className={`${BUTTON_BASE} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`}\n >\n <XCircleIcon size={13} />\n {t('Decline this call')}\n </button>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => {\n setRejecting(false);\n setReason('');\n }}\n className={`${BUTTON_BASE} text-gray-500 hover:bg-gray-100 dark:text-white/50 dark:hover:bg-white/5`}\n >\n {t('Back')}\n </button>\n </div>\n </div>\n )}\n\n {!verdict && !rejecting && (\n <div className=\"flex flex-wrap items-center gap-1.5\">\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => setRejecting(true)}\n className={`${BUTTON_BASE} text-red-600 hover:bg-red-500/10 dark:text-red-300`}\n >\n <XCircleIcon size={13} />\n {t('No')}\n </button>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => decide('approve')}\n className={`${BUTTON_BASE} bg-[var(--chat-accent)] text-white hover:opacity-90`}\n >\n <CheckIcon size={13} />\n {t('Yes')}\n </button>\n <button\n type=\"button\"\n disabled={disabled}\n onClick={() => decide('approve_always')}\n /* Disclosed on the control itself rather than buried in a tooltip:\n this is the one verdict whose effect outlives the turn. */\n title={t('Also applies to your scheduled runs, until you revoke it')}\n className={`${BUTTON_BASE} border border-gray-200 text-gray-700 hover:bg-gray-100 dark:border-white/15 dark:text-white/70 dark:hover:bg-white/5`}\n >\n {t('Yes, always')}\n </button>\n </div>\n )}\n </div>\n );\n};\n\n/**\n * Collects a verdict for every call a paused turn is waiting on.\n *\n * Submission is all-or-nothing because the backend requires it: resuming with\n * an undecided call would leave its `tool_use` block without a `tool_result`,\n * which the model providers reject outright. That condition is met the moment\n * the last card is decided, so the set submits itself there — a verdict is\n * final once clicked (a decided card shows a badge, not buttons), so a separate\n * confirm would gate work already committed to.\n *\n * \"Yes, always\" is the exception and the only click that earns a confirm step:\n * it saves a standing preference for this user that applies to unattended runs\n * too, and that has to be read before it is committed.\n */\nexport const ChatApprovalPrompt = ({ proposals, onSubmit, isSubmitting, error, t }: ChatApprovalPromptProps) => {\n const [decisions, setDecisions] = useState<Record<string, ToolApprovalDecision>>({});\n // Guards the auto-submit against a double fire: React may re-render between\n // the last verdict and the parent flipping `isSubmitting`, and answering the\n // same pause twice would decide a turn that is already resuming.\n const submitted = useRef(false);\n // The same fact as state, because a ref cannot re-render the footer button.\n const [sent, setSent] = useState(false);\n\n // A failed submission is the one case where the prompt survives its own send:\n // the turn is still paused, so the controls have to come back for a retry.\n useEffect(() => {\n if (!error) return;\n submitted.current = false;\n setSent(false);\n }, [error]);\n\n const busy = isSubmitting || sent;\n\n const submit = (all: ToolApprovalDecision[]) => {\n if (submitted.current || isSubmitting) return;\n submitted.current = true;\n setSent(true);\n onSubmit(all);\n };\n\n const decidedCount = proposals.filter((p) => decisions[p.toolCallId]).length;\n const allDecided = decidedCount === proposals.length && proposals.length > 0;\n const willRunAlways = Object.values(decisions).some((d) => d.verdict === 'approve_always');\n\n // The warning and the confirm sit *below* the cards, so an \"always\" click can\n // push them past the fold — exactly what must be read before confirming.\n const footerRef = useRevealIntoView<HTMLDivElement>(willRunAlways);\n // The prompt arrives at the bottom of a thread that just grew by a whole\n // turn. Always true: the mount is the reveal.\n const rootRef = useRevealIntoView<HTMLDivElement>(true);\n\n return (\n <div ref={rootRef} className=\"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3\">\n <p className=\"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300\">\n <AlertTriangleIcon size={13} className=\"mt-0.5 shrink-0\" />\n {proposals.length === 1 ? t('The agent needs your approval to run a tool:') : t('The agent needs your approval to run these tools:')}\n </p>\n\n {proposals.map((proposal) => (\n <ApprovalCard\n key={proposal.toolCallId}\n proposal={proposal}\n decision={decisions[proposal.toolCallId]}\n disabled={busy}\n t={t}\n onDecide={(decision) => {\n const next = { ...decisions, [decision.toolCallId]: decision };\n setDecisions(next);\n // Safe to read `decisions` from the closure: each verdict is its\n // own click, so this handler always sees the state the previous\n // one set.\n const all = proposals.map((p) => next[p.toolCallId]);\n if (all.every(Boolean) && !all.some((d) => d.verdict === 'approve_always')) {\n submit(all);\n }\n }}\n />\n ))}\n\n {willRunAlways && (\n <p className=\"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90\">\n <AlertTriangleIcon size={13} className=\"mt-0.5 shrink-0\" />\n {t(\n '“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.',\n )}\n </p>\n )}\n\n {error && <p className=\"text-[0.7rem] text-red-600 dark:text-red-300\">{error}</p>}\n\n <div ref={footerRef} className=\"flex items-center justify-between gap-2\">\n {/* The counter earns its place only when there is more than one thing\n to count; on a single proposal it reads as a progress bar for a\n one-step process. */}\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40\">\n {proposals.length > 1 ? translate(t, '{decided}/{total} decided', { decided: decidedCount, total: proposals.length }) : ''}\n </span>\n <button\n type=\"button\"\n disabled={!allDecided || busy}\n onClick={() => submit(proposals.map((p) => decisions[p.toolCallId]))}\n className={`${BUTTON_BASE} bg-[var(--chat-accent)] text-white hover:opacity-90`}\n >\n {busy ? t('Sending…') : t('Confirm')}\n </button>\n </div>\n </div>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CloseIcon, ImageIcon, MaximizeIcon } from './icons';\nimport { findChatbotRoot } from '../utils';\n\ninterface ImageLightboxProps {\n src: string;\n alt: string;\n onClose: () => void;\n t: (key: string) => string;\n}\n\n/**\n * Full-panel image viewer. Portalled into the chatbot root (not `document.body`)\n * so it inherits the panel's stacking context and can never be painted under —\n * or over — unrelated host chrome, matching the reasoning-details dialog.\n */\nconst ImageLightbox = ({ src, alt, onClose, t }: ImageLightboxProps) => {\n const hostRef = useRef<HTMLSpanElement>(null);\n const closeButtonRef = useRef<HTMLButtonElement>(null);\n const [root, setRoot] = useState<HTMLElement | null>(null);\n\n useEffect(() => {\n setRoot(findChatbotRoot(hostRef.current));\n }, []);\n\n useEffect(() => {\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') onClose();\n };\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [onClose]);\n\n // The overlay is the only interactive surface while open, so focus moves to\n // its close button and returns to the thumbnail on dismiss.\n useEffect(() => {\n if (!root) return;\n const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n closeButtonRef.current?.focus({ preventScroll: true });\n return () => previouslyFocused?.focus({ preventScroll: true });\n }, [root]);\n\n return (\n <span ref={hostRef} className=\"hidden\">\n {root &&\n createPortal(\n <div\n className=\"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4\"\n onClick={onClose}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={t('Image preview')}\n >\n <button\n ref={closeButtonRef}\n type=\"button\"\n onClick={onClose}\n aria-label={t('Close')}\n className=\"absolute top-4 right-4 rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20\"\n >\n <CloseIcon size={20} />\n </button>\n <img src={src} alt={alt} className=\"max-h-[90%] max-w-[90%] rounded-lg object-contain\" onClick={(e) => e.stopPropagation()} />\n </div>,\n root,\n )}\n </span>\n );\n};\n\n/**\n * True for a URL with no scheme — a host-relative path such as\n * `/api/v1/platform/chat/files/<id>/download`. Protocol-relative URLs (`//host`)\n * are excluded: they resolve to a different origin, so the host's auth headers\n * must not be attached to them.\n */\nconst isRelativeUrl = (src: string): boolean => !src.startsWith('//') && !/^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(src);\n\ninterface ChatImageProps {\n src: string;\n alt: string;\n /**\n * Auth headers the host attaches to chatbot API calls. When present and the\n * image is host-relative, the image is fetched as a blob with these headers\n * instead of being handed to `<img src>` — a browser never sends custom\n * headers on an `<img>` request, so a bearer-authenticated image endpoint\n * would otherwise return 401 and render as a broken image.\n */\n requestHeaders?: Record<string, string>;\n /** Cap the inline thumbnail height. Full size is always available via the lightbox. */\n maxHeightClass?: string;\n t: (key: string) => string;\n}\n\n/**\n * An image inside a chat message: click (or the hover affordance) opens a\n * full-panel lightbox. Handles the three shapes an agent produces — inline\n * `data:image/*` charts from a code interpreter, host-relative API-served\n * images needing auth headers, and ordinary absolute URLs.\n */\nexport const ChatImage = ({ src, alt, requestHeaders, maxHeightClass = 'max-h-[400px]', t }: ChatImageProps) => {\n const needsAuth = !!requestHeaders && Object.keys(requestHeaders).length > 0 && isRelativeUrl(src);\n const [blobUrl, setBlobUrl] = useState<string | null>(null);\n const [errored, setErrored] = useState(false);\n const [expanded, setExpanded] = useState(false);\n\n useEffect(() => {\n if (!needsAuth) return;\n let cancelled = false;\n let objectUrl: string | null = null;\n\n fetch(src, { credentials: 'include', headers: { ...requestHeaders } })\n .then((res) => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.blob();\n })\n .then((blob) => {\n if (cancelled) return;\n objectUrl = URL.createObjectURL(blob);\n setBlobUrl(objectUrl);\n })\n .catch(() => {\n if (!cancelled) setErrored(true);\n });\n\n return () => {\n cancelled = true;\n // Revoking on teardown (rather than on unmount only) keeps a src change\n // from leaking the previous blob.\n if (objectUrl) URL.revokeObjectURL(objectUrl);\n };\n }, [needsAuth, src, requestHeaders]);\n\n const displaySrc = needsAuth ? blobUrl : src;\n\n if (errored) {\n return <p className=\"my-2 text-[0.75rem] italic text-gray-400 dark:text-white/40\">{t('Image could not be loaded')}</p>;\n }\n\n if (!displaySrc) {\n return (\n <span className=\"my-3 inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 dark:border-white/10\">\n <ImageIcon size={14} className=\"shrink-0 animate-pulse text-[var(--chat-accent)]\" />\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40\">{t('Loading image…')}</span>\n </span>\n );\n }\n\n return (\n <>\n <span className=\"group/img relative my-3 inline-block max-w-full rounded-lg border border-gray-200 p-1 transition-colors hover:border-[var(--chat-accent)]/40 dark:border-white/10\">\n <img\n src={displaySrc}\n alt={alt}\n loading=\"lazy\"\n onClick={() => setExpanded(true)}\n onError={() => setErrored(true)}\n className={`max-w-full cursor-zoom-in rounded-md object-contain ${maxHeightClass}`}\n />\n <button\n type=\"button\"\n onClick={() => setExpanded(true)}\n aria-label={t('Expand image')}\n className=\"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100\"\n >\n <MaximizeIcon size={14} />\n </button>\n </span>\n {expanded && <ImageLightbox src={displaySrc} alt={alt} onClose={() => setExpanded(false)} t={t} />}\n </>\n );\n};\n","import { useEffect, useMemo, useState } from 'react';\nimport type { Translate } from '../types';\nimport { ExternalLinkIcon, GamepadIcon } from './icons';\n\n/**\n * Playful, rotating \"still working on it\" messages shown below the status\n * bubble during longer waits. Kept short and upbeat so they fit on one line in\n * the narrow floating panel and read as a sense of progress rather than noise.\n */\nconst defaultMessages = (t: Translate) => [\n t('Crunching the data'),\n t('Connecting the dots'),\n t('Consulting the sources'),\n t('Thinking it through'),\n t('Reticulating splines'),\n t('Analyzing the details'),\n t('Almost there'),\n t('Putting it together'),\n t('Polishing the answer'),\n t('Wrapping things up'),\n];\n\n/** Message rotation cadence. */\nconst ROTATE_MS = 2600;\n\n/**\n * Where the waiting game is played: XTM One's arcade, which `?arcade=play`\n * opens on any XTM One page, the chat being where it lives. `xtmOneUrl` is\n * host input that ends up in an href, so only an http(s) base is linked.\n */\nexport function waitingGameUrl(xtmOneUrl: string | undefined): string | null {\n const base = xtmOneUrl?.trim().replace(/\\/+$/, '');\n if (!base || !/^https?:\\/\\//i.test(base)) return null;\n return `${base}/chat?arcade=play`;\n}\n\nfunction usePrefersReducedMotion(): boolean {\n const [reduced, setReduced] = useState(() => {\n if (typeof window === 'undefined' || !window.matchMedia) return false;\n return window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n });\n useEffect(() => {\n if (typeof window === 'undefined' || !window.matchMedia) return;\n const mql = window.matchMedia('(prefers-reduced-motion: reduce)');\n const onChange = () => setReduced(mql.matches);\n // Older Safari/WebKit only expose the deprecated addListener/removeListener.\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', onChange);\n return () => mql.removeEventListener('change', onChange);\n }\n mql.addListener(onChange);\n return () => mql.removeListener(onChange);\n }, []);\n return reduced;\n}\n\ninterface ChatWaitingPanelProps {\n t: Translate;\n /** Host-level override; when false the panel is hidden entirely. */\n enabled?: boolean;\n /** Opens the arcade in place, for a host that runs it itself. Wins over `playUrl`. */\n onPlay?: () => void;\n /** Where the arcade is played, opened in a new tab. */\n playUrl?: string | null;\n /** The thread's follower: keeps its end in view while the reader is there. */\n keepEndInView: () => void;\n}\n\nconst PLAY_CLASS =\n 'inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100';\n\n/**\n * Waiting experience shown below the status bubble during longer waits:\n * rotating messages, and an invitation to play XTM One's Space Invaders arcade\n * while the agent works. The package ships no game of its own; without a way\n * to reach the arcade the messages stand alone.\n */\nexport const ChatWaitingPanel = ({ t, enabled = true, onPlay, playUrl, keepEndInView }: ChatWaitingPanelProps) => {\n const messages = useMemo(() => defaultMessages(t), [t]);\n const reducedMotion = usePrefersReducedMotion();\n const [msgIndex, setMsgIndex] = useState(0);\n\n // The panel mounts below the last message but, unlike streamed reasoning or\n // answer text (which auto-scrolls on length change), nothing else triggers a\n // scroll - so at the bottom it lands under the fold. It is revealed through\n // the thread's follower, which only moves a reader still following the end:\n // one who scrolled up stays where they went, however near the end.\n useEffect(() => {\n if (enabled) keepEndInView();\n }, [enabled, keepEndInView]);\n\n // A disabled host arms no timer; `enabled` is a dep so toggling it cleans up.\n useEffect(() => {\n if (!enabled) return;\n const id = window.setInterval(() => setMsgIndex((i) => (i + 1) % messages.length), ROTATE_MS);\n return () => window.clearInterval(id);\n }, [enabled, messages.length]);\n\n if (!enabled) return null;\n\n const current = messages[msgIndex % messages.length];\n\n return (\n <div className=\"ml-11 mt-2.5 max-w-[78%]\">\n {/* Keep the live region scoped to the announced text only: wrapping the\n play link too would re-announce it alongside each message change. */}\n <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {current}\n </span>\n {/* Every non-essential animation (fade-ins, the blinking caret) stops\n under prefers-reduced-motion; only the dimmed text rotates. */}\n <div\n className=\"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5\"\n style={reducedMotion ? undefined : { animation: 'chat-fade-in 0.5s ease-out' }}\n >\n <span\n key={current}\n aria-hidden\n className=\"text-xs text-gray-500 dark:text-white/45\"\n style={reducedMotion ? undefined : { animation: 'chat-fade-in 0.4s ease-out' }}\n >\n {current}\n <span className={`ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 ${reducedMotion ? '' : 'animate-pulse'}`} />\n </span>\n {onPlay ? (\n <button type=\"button\" onClick={onPlay} className={PLAY_CLASS}>\n <span aria-hidden className=\"inline-flex\">\n <GamepadIcon size={13} />\n </span>\n {t('Play Space Invaders')}\n </button>\n ) : playUrl ? (\n <a href={playUrl} target=\"_blank\" rel=\"noopener noreferrer\" className={PLAY_CLASS}>\n <span aria-hidden className=\"inline-flex\">\n <GamepadIcon size={13} />\n </span>\n {t('Play Space Invaders in XTM One')}\n <span aria-hidden className=\"inline-flex\">\n <ExternalLinkIcon size={11} />\n </span>\n </a>\n ) : null}\n </div>\n </div>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport type { AgentStatusState, IconProps, Translate } from '../types';\nimport {\n AlertTriangleIcon,\n BrainIcon,\n DatabaseIcon,\n ExternalLinkIcon,\n GlobeIcon,\n MailIcon,\n SearchIcon,\n SparklesIcon,\n TerminalIcon,\n UserPlusIcon,\n WrenchIcon,\n} from './icons';\nimport { translate } from '../utils';\nimport { ChatWaitingPanel } from './ChatWaitingPanel';\n\ninterface ChatThinkingProps {\n agentStatus: AgentStatusState | null;\n logoIcon?: React.ReactNode;\n t: Translate;\n /** Host-level override for the waiting panel (messages and the invitation to play). */\n miniGameEnabled?: boolean;\n /** Opens the XTM One arcade in place; wins over `waitingGameUrl`. */\n onPlayWaitingGame?: () => void;\n /** Where the XTM One arcade is played, opened in a new tab. */\n waitingGameUrl?: string | null;\n /** The thread's follower: keeps its end in view while the reader is there. */\n keepEndInView: () => void;\n}\n\ntype IconComponent = (props: IconProps) => React.JSX.Element;\n\ninterface StatusVisual {\n label: string;\n StatusIcon: IconComponent;\n showDots: boolean;\n}\n\n/**\n * Whole-sentence keys, one per plural branch: a lookup-only `t` cannot select a\n * plural form, so the branch is chosen here and the locale translates the\n * finished sentence — including where the count sits in it.\n */\nfunction delegatingLabel(count: number, t: Translate): string {\n return count > 1 ? translate(t, 'Delegating {count} tasks…', { count }) : t('Delegating one task…');\n}\n\nfunction pollingLabel(count: number, t: Translate): string {\n return count > 1 ? translate(t, 'Waiting for {count} background tasks…', { count }) : t('Waiting for one background task…');\n}\n\nfunction collectingLabel(count: number, t: Translate): string {\n return count > 1 ? translate(t, 'Collecting results from {count} tasks…', { count }) : t('Collecting results from one task…');\n}\n\nfunction resolveStatusVisual(agentStatus: AgentStatusState | null, t: Translate): StatusVisual {\n if (!agentStatus) {\n return { label: t('Thinking...'), StatusIcon: BrainIcon, showDots: false };\n }\n switch (agentStatus.status) {\n case 'tool_start': {\n const rawNames = agentStatus.tools ?? [];\n const lower = rawNames.map((n) => n.toLowerCase());\n\n // Delegation tools have dedicated statuses\n if (lower.some((n) => n === 'spawn_background_task')) {\n const count = rawNames.filter((n) => n === 'spawn_background_task').length;\n return { label: delegatingLabel(count, t), StatusIcon: UserPlusIcon, showDots: false };\n }\n if (lower.some((n) => n === 'check_task_status')) {\n const count = rawNames.filter((n) => n === 'check_task_status').length;\n return { label: pollingLabel(count, t), StatusIcon: SparklesIcon, showDots: false };\n }\n if (lower.some((n) => n === 'get_task_result')) {\n const count = rawNames.filter((n) => n === 'get_task_result').length;\n return { label: collectingLabel(count, t), StatusIcon: SparklesIcon, showDots: false };\n }\n\n let StatusIcon: IconComponent = WrenchIcon;\n if (lower.some((n) => n.includes('search') || n.includes('list'))) {\n StatusIcon = SearchIcon;\n } else if (lower.some((n) => n.includes('read') || n.includes('get') || n.includes('query'))) {\n StatusIcon = DatabaseIcon;\n } else if (lower.some((n) => n.includes('send') || n.includes('create') || n.includes('draft') || n.includes('reply') || n.includes('flag'))) {\n StatusIcon = MailIcon;\n } else if (lower.some((n) => n.includes('code') || n.includes('execute'))) {\n StatusIcon = TerminalIcon;\n } else if (lower.some((n) => n.includes('web') || n.includes('browse'))) {\n StatusIcon = GlobeIcon;\n }\n let label: string;\n if (rawNames.length > 0) {\n const display = rawNames.map((n) => n.replace(/_/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase()));\n const unique = Array.from(new Set(display));\n label = unique.length === 1 ? `${unique[0]}…` : translate(t, '{tool} (+{count} more)…', { tool: unique[0], count: unique.length - 1 });\n } else {\n label = t('Using tools…');\n }\n return { label, StatusIcon, showDots: false };\n }\n case 'awaiting_approval':\n // Not progress: the turn has stopped and the stream is held open while a\n // person decides. Shown only when the prompt itself is not rendered (a\n // host wiring `ChatMessages` without a decision handler) — otherwise the\n // prompt replaces this bubble entirely.\n return { label: t('Waiting for your approval…'), StatusIcon: AlertTriangleIcon, showDots: false };\n case 'acting_on_page':\n return { label: t('Acting on the page…'), StatusIcon: SparklesIcon, showDots: true };\n case 'analyzing':\n return { label: t('Analyzing results…'), StatusIcon: SparklesIcon, showDots: false };\n case 'steering':\n return { label: t('Incorporating your message…'), StatusIcon: SparklesIcon, showDots: true };\n case 'composing':\n return { label: t('Composing answer…'), StatusIcon: BrainIcon, showDots: true };\n case 'consulting': {\n const consultName = agentStatus.tools?.[0] ?? t('the agent');\n return { label: translate(t, 'Consulting {agent}…', { agent: consultName }), StatusIcon: UserPlusIcon, showDots: false };\n }\n case 'delegating': {\n const count = agentStatus.tools?.filter((n) => n === 'spawn_background_task').length ?? 0;\n return { label: delegatingLabel(count, t), StatusIcon: UserPlusIcon, showDots: false };\n }\n case 'polling': {\n const checkCount = agentStatus.tools?.filter((n) => n === 'check_task_status').length ?? 0;\n return { label: pollingLabel(checkCount, t), StatusIcon: SparklesIcon, showDots: false };\n }\n case 'collecting': {\n const fetchCount = agentStatus.tools?.filter((n) => n === 'get_task_result').length ?? 0;\n return { label: collectingLabel(fetchCount, t), StatusIcon: SparklesIcon, showDots: false };\n }\n case 'transferring': {\n const targetName = agentStatus.tools?.[0] ?? t('the agent');\n return { label: translate(t, 'Transferring to {agent}…', { agent: targetName }), StatusIcon: ExternalLinkIcon, showDots: false };\n }\n case 'thinking':\n default:\n return { label: t('Thinking...'), StatusIcon: BrainIcon, showDots: false };\n }\n}\n\n/**\n * Light markdown cleanup for reasoning prose. Preserves paragraph breaks so\n * multi-step reasoning stays readable inside the small scrolling window\n * instead of collapsing into one unbroken blob.\n */\nexport function cleanReasoningText(text: string): string {\n return text\n .replace(/```[\\s\\S]*?```/g, ' ')\n .replace(/`([^`]+)`/g, '$1')\n .replace(/\\*\\*(.+?)\\*\\*/g, '$1')\n .replace(/__(.+?)__/g, '$1')\n .replace(/#{1,6}\\s+/g, '')\n .replace(/^[ \\t]*[-*>]+[ \\t]*/gm, '')\n .replace(/[ \\t]+/g, ' ')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/**\n * Most characters of the turn's reasoning the window renders. The window is\n * pinned to its newest line and shows about eight lines, while a long turn\n * accumulates hundreds of KB: laying all of it out again on every streamed\n * chunk only re-flows text nobody can see.\n */\nconst REASONING_WINDOW_MAX_CHARS = 6000;\n\n/** Fewer visible characters than this is no reasoning to show. */\nconst MIN_REASONING_CHARS = 3;\n\n/**\n * The text the reasoning window shows: the cleaned tail of the prose between\n * the turn's fenced blocks, opened at a paragraph break when one is near.\n * Fences pair up from the start of the whole text, as `cleanReasoningText`\n * pairs them: paired inside a cut tail instead, a block the cut split or a\n * block still streaming shifts every pair and strips the newest prose.\n */\nfunction reasoningWindowText(content: string): string {\n if (content.length <= REASONING_WINDOW_MAX_CHARS) return cleanReasoningText(content);\n // [start, end) of the prose around each fenced block; an unclosed fence\n // stays prose, as `cleanReasoningText` leaves it.\n const prose: [number, number][] = [];\n let from = 0;\n for (let open = content.indexOf('```'); open !== -1; open = content.indexOf('```', from)) {\n const close = content.indexOf('```', open + 3);\n if (close === -1) break;\n prose.push([from, open]);\n from = close + 3;\n }\n prose.push([from, content.length]);\n const parts: string[] = [];\n let budget = REASONING_WINDOW_MAX_CHARS;\n for (let i = prose.length - 1; i >= 0 && budget > 0; i--) {\n const [start, end] = prose[i];\n const cut = Math.max(start, end - budget);\n parts.push(content.slice(cut, end));\n // + 1: each dropped block leaves a space, as in `cleanReasoningText`.\n budget -= end - cut + 1;\n }\n let tail = parts.reverse().join(' ');\n if (budget <= 0) {\n const paragraph = tail.indexOf('\\n\\n');\n if (paragraph !== -1 && paragraph < tail.length / 2) tail = tail.slice(paragraph + 2);\n }\n return cleanReasoningText(tail);\n}\n\n/**\n * Reasoning window — the model's reasoning prose rendered below the status\n * bubble while the agent works: smaller, dimmed text inside a capped-height\n * (max-h-40) window always pinned to the newest line, with a Cursor-style\n * top dissolve once full (soft gradient fade at the top only — the text reads\n * as scrolling up and dissolving; the bottom stays sharp) — framed by the\n * breathing accent left-border glow. The window is intentionally NOT\n * user-scrollable (overflow-hidden, no scrollbar): the prose is ambient\n * feedback that scrolls up and dissolves; the full accumulated reasoning\n * stays readable afterwards via the message's reasoning details. The window\n * (and the status bubble above it) disappears the moment the final answer\n * starts flowing. `text` comes cleaned and tail-bounded from\n * `reasoningWindowText`; the glow lives on `.filigran-chat-reasoning` so\n * reduced motion can stop it.\n */\nfunction ThinkingTextBubble({ text }: { text: string }) {\n const ref = useRef<HTMLDivElement>(null);\n const [isOverflowing, setIsOverflowing] = useState(false);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return;\n el.scrollTop = el.scrollHeight;\n setIsOverflowing(el.scrollHeight > el.clientHeight + 1);\n }, [text]);\n\n return (\n <div className=\"filigran-chat-reasoning ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3\">\n <div\n ref={ref}\n className={`max-h-40 overflow-hidden${\n isOverflowing\n ? // -webkit- twin first: Safari/WebKit ignores unprefixed mask-image\n // on older versions, which would silently drop the top dissolve.\n ' [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]' +\n ' [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]'\n : ''\n }`}\n >\n <p className=\"m-0 whitespace-pre-wrap break-words text-xs leading-5 text-gray-500 dark:text-white/45\">{text}</p>\n </div>\n </div>\n );\n}\n\n/** Render seconds as a compact elapsed label (e.g. `45s`, `3m 20s`). */\nfunction formatElapsed(seconds: number): string {\n // Floor at the boundary: `elapsed_s` comes from the backend and may be a\n // float, which would otherwise render as \"45.3s\" / \"3m 20.5s\".\n const total = Math.floor(seconds);\n if (total < 60) return `${total}s`;\n const m = Math.floor(total / 60);\n const s = total % 60;\n return s > 0 ? `${m}m ${s}s` : `${m}m`;\n}\n\n/**\n * Elapsed time is only surfaced once the current operation has been\n * running long enough that the user could wonder whether it is stuck.\n */\nconst ELAPSED_DISPLAY_THRESHOLD_S = 15;\n\n/**\n * How long a working turn with no reasoning to show waits before the waiting\n * panel fills the space, so a quick reply never flashes it.\n */\nconst WAITING_GAME_DELAY_MS = 5000;\n\n/**\n * How long reasoning already on screen must go without a new chunk before the\n * waiting panel takes its place: long enough to outlast an ordinary tool call,\n * so the window only gives way on a genuinely long wait.\n */\nconst QUIET_REASONING_GAME_DELAY_MS = 10_000;\n\n/**\n * True once `active` has held for `delayMs` with the same `key`; false the\n * moment either changes, in that very render (the timer that fired carries\n * the key it saw). Arms no timer while `active` is false, so a host that\n * disables the waiting panel schedules no timeouts or re-renders for it.\n */\nfunction useSustained(active: boolean, delayMs: number, key = 0): boolean {\n const [firedKey, setFiredKey] = useState<number | null>(null);\n useEffect(() => {\n setFiredKey(null);\n if (!active) return;\n const id = window.setTimeout(() => setFiredKey(key), delayMs);\n return () => window.clearTimeout(id);\n }, [active, delayMs, key]);\n return active && firedKey === key;\n}\n\nexport const ChatThinking = ({\n agentStatus,\n logoIcon,\n t,\n miniGameEnabled = true,\n onPlayWaitingGame,\n waitingGameUrl,\n keepEndInView,\n}: ChatThinkingProps) => {\n const { label, StatusIcon, showDots } = resolveStatusVisual(agentStatus, t);\n const thinkingContent = agentStatus?.thinkingContent;\n\n // Tick the elapsed counter every second. The backend only reports a fresh\n // value once every ~10s (`tool_heartbeat`), so rendering that integer\n // directly makes the timer sit still and then jump ~10s at a time. Each\n // heartbeat re-anchors `elapsedStartMs` (the instant elapsed was zero); the\n // displayed seconds are derived from that anchor plus a local 1s ticker, so\n // the number moves smoothly and self-corrects on every beat. The interval\n // only runs while an anchor is present, and this state is local to the\n // indicator so the tick never re-renders the surrounding message list.\n const elapsedStartMs = agentStatus?.elapsedStartMs;\n const [nowMs, setNowMs] = useState(() => Date.now());\n useEffect(() => {\n if (elapsedStartMs == null) return;\n setNowMs(Date.now());\n const id = window.setInterval(() => setNowMs(Date.now()), 1000);\n return () => window.clearInterval(id);\n }, [elapsedStartMs]);\n\n // Fall back to the raw heartbeat value for backends/protocols that report\n // `elapsedS` without an anchor.\n const elapsedS = elapsedStartMs != null ? Math.max(0, (nowMs - elapsedStartMs) / 1000) : agentStatus?.elapsedS;\n const showElapsed = typeof elapsedS === 'number' && elapsedS >= ELAPSED_DISPLAY_THRESHOLD_S;\n // Reasoning wins over the waiting panel: once the turn has reasoning to show,\n // the window stays through tool calls and short silences until the answer\n // streams. The panel fills a wait with no reasoning after 5 s, and takes over\n // from reasoning that has gone 10 s without a new chunk, until the next one.\n const reasoningText = useMemo(() => reasoningWindowText(thinkingContent ?? ''), [thinkingContent]);\n const showReasoning = reasoningText.length >= MIN_REASONING_CHARS;\n const waitedWithoutReasoning = useSustained(miniGameEnabled && !showReasoning, WAITING_GAME_DELAY_MS);\n const reasoningWentQuiet = useSustained(miniGameEnabled && showReasoning, QUIET_REASONING_GAME_DELAY_MS, thinkingContent?.length ?? 0);\n const showWaiting = showReasoning ? reasoningWentQuiet : waitedWithoutReasoning;\n\n return (\n <>\n <div className=\"flex gap-3 items-center justify-start\">\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5\">\n <span className=\"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4\">{logoIcon}</span>\n </div>\n <div className=\"filigran-chat-active-border rounded-lg bg-gray-50 dark:bg-white/[0.03] px-4 py-3 relative overflow-hidden\">\n <div className=\"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none\" />\n <div className=\"relative flex items-center gap-2.5\">\n {showDots ? (\n <div className=\"flex gap-[3px] items-center h-3.5 w-3.5 justify-center\">\n {[0, 0.15, 0.3].map((delay, i) => (\n <span\n key={i}\n className=\"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50\"\n style={{ animation: `chat-dot 1s ease-in-out infinite ${delay}s` }}\n />\n ))}\n </div>\n ) : (\n <StatusIcon size={14} className=\"text-[var(--chat-accent)] animate-pulse transition-all duration-300\" />\n )}\n <span className=\"text-sm text-gray-500 dark:text-white/50 transition-all duration-300\">{label}</span>\n {showElapsed && <span className=\"text-xs text-gray-400 dark:text-white/30 tabular-nums shrink-0\">{formatElapsed(elapsedS)}</span>}\n </div>\n </div>\n </div>\n {showWaiting ? (\n <ChatWaitingPanel t={t} enabled={miniGameEnabled} onPlay={onPlayWaitingGame} playUrl={waitingGameUrl} keepEndInView={keepEndInView} />\n ) : showReasoning ? (\n <ThinkingTextBubble text={reasoningText} />\n ) : null}\n </>\n );\n};\n","import remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport { unified } from 'unified';\n\n/**\n * The top-level blocks of a streamed markdown answer.\n *\n * The live answer is re-rendered every time the stream delivers text, and\n * parsing it whole costs ~14 ms at 8K characters and ~75 ms at 40K, on the\n * host application's main thread: past a few thousand characters its frames\n * go to re-parsing text that is already on screen. Rendered block by block\n * with a memoized renderer per block, only the blocks that can still change\n * are parsed again.\n *\n * The boundaries come from the parser the panel renders with (remark-parse +\n * remark-gfm; remark-breaks only rewrites line breaks inside a block), so\n * rendering the blocks one after the other produces what one parse of the\n * whole text produces. A block is final once a later top-level block starts\n * after a blank line with a complete first line: a blank line closes a\n * paragraph, and a written line after one cannot rejoin a list, a quote or an\n * indented block, whatever is appended to it. A block that starts without a\n * blank line before it stays open with its predecessor (`#` alone is a heading\n * that interrupts the paragraph above; `#x` is that paragraph's next line).\n * Link reference definitions and footnote definitions resolve across the whole\n * document, from a quote or a list item too, so a text holding one renders as\n * one block. They are read off the tree the split parses anyway rather than\n * matched by a line pattern: a pattern misses a label spanning lines, and\n * keeps whole a text that only looks like a definition (a TypeScript index\n * signature in a code block, a regex's `[^a-z]`).\n *\n * XTM One's web chat splits its streaming answer by the same rules; a fix to\n * one belongs in the other.\n */\n\nconst blockParser = unified().use(remarkParse).use(remarkGfm).freeze();\n\ntype BlockNode = ReturnType<typeof blockParser.parse>['children'][number];\n\nexport interface MarkdownBlocks {\n /** The text the blocks cover; `blocks.join('') === source`. */\n source: string;\n /** What to render: the top-level blocks, or the whole text when it holds a definition. */\n blocks: string[];\n /** Offset of each top-level block in `source`, kept when the text renders whole. */\n starts: number[];\n /** Top-level blocks `[0, settled)` are final while text is appended to `source`. */\n settled: number;\n /** The first top-level block holding a link reference or footnote definition, `-1` for none. */\n firstDefinition: number;\n}\n\n/** Whether *node* is or contains a link reference or footnote definition. */\nfunction holdsDefinition(node: BlockNode): boolean {\n switch (node.type) {\n case 'definition':\n case 'footnoteDefinition':\n return true;\n case 'blockquote':\n case 'list':\n case 'listItem':\n return node.children.some(holdsDefinition);\n default:\n return false;\n }\n}\n\nfunction lineStart(text: string, offset: number): number {\n return text.lastIndexOf('\\n', offset - 1) + 1;\n}\n\n/**\n * Whether the blocks before the one at *start* are final: it starts after a\n * blank line, and its first line is complete - while that line is still being\n * written it can turn into a continuation of the block above (`1` is a\n * paragraph, `10.` the next item of the ordered list before it).\n */\nfunction settlesBefore(text: string, start: number): boolean {\n if (start < 2 || text.indexOf('\\n', start) === -1) return false;\n const previousLine = text.slice(lineStart(text, start - 1), start - 1);\n return previousLine.trim() === '';\n}\n\n/**\n * Whether the region ends on an indented line (4 spaces or a tab). micromark\n * keeps an indented code block open across the blank lines after it and parses\n * the next line as if it interrupted it - `2. two` is text there and an ordered\n * list on its own - so the next block is rendered with it.\n */\nfunction endsIndented(text: string, start: number, end: number): boolean {\n const lines = text.slice(start, end).split('\\n');\n for (let index = lines.length - 1; index >= 0; index--) {\n if (lines[index].trim()) return /^(?: {4}|\\t)/.test(lines[index]);\n }\n return false;\n}\n\nfunction single(text: string): MarkdownBlocks {\n return { source: text, blocks: text ? [text] : [], starts: text ? [0] : [], settled: 0, firstDefinition: -1 };\n}\n\n/**\n * Split *text* into top-level markdown blocks.\n *\n * With *previous* - the split of a text that *text* extends - the settled\n * blocks are reused and only the rest is parsed again. Any other *previous* (a\n * retracted answer, a normalizer that rewrote earlier lines) is ignored.\n */\nexport function splitMarkdownBlocks(text: string, previous?: MarkdownBlocks | null): MarkdownBlocks {\n if (!text.trim()) return single(text);\n\n const reuse = previous && previous.settled > 0 && text.startsWith(previous.source) ? previous.settled : 0;\n const from = reuse ? previous!.starts[reuse] : 0;\n const tail = text.slice(from);\n\n const starts = previous && reuse ? previous.starts.slice(0, reuse) : [];\n // A definition in a settled block stays one; none there means the first one,\n // if any, is in the part parsed now.\n let firstDefinition = previous && reuse && previous.firstDefinition < reuse ? previous.firstDefinition : -1;\n starts.push(from);\n for (const node of blockParser.parse(tail).children) {\n const offset = node.position?.start.offset;\n if (offset !== undefined) {\n const start = from + lineStart(tail, offset);\n const last = starts[starts.length - 1];\n if (start > last && !endsIndented(text, last, start)) starts.push(start);\n }\n if (firstDefinition < 0 && holdsDefinition(node)) firstDefinition = starts.length - 1;\n }\n\n let settled = reuse;\n for (let index = starts.length - 1; index > reuse; index--) {\n if (settlesBefore(text, starts[index])) {\n settled = index;\n break;\n }\n }\n\n const blocks = firstDefinition < 0 ? starts.map((start, index) => text.slice(start, starts[index + 1] ?? text.length)) : [text];\n return { source: text, blocks, starts, settled, firstDefinition };\n}\n\n/**\n * {@link splitMarkdownBlocks} with the previous split kept between calls, so a\n * text that grows by a few characters per call is re-parsed from its last open\n * block only. Correctness never depends on the kept split: a text that does not\n * extend it is split from the start.\n */\nexport class MarkdownBlockSplitter {\n private last: MarkdownBlocks | null = null;\n\n split(text: string): string[] {\n if (this.last?.source !== text) this.last = splitMarkdownBlocks(text, this.last);\n return this.last.blocks;\n }\n}\n","import { createContext, memo, useCallback, useContext, useMemo, useState } from 'react';\nimport Markdown, { type Components } from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport remarkBreaks from 'remark-breaks';\nimport { CheckIcon, CopyIcon } from './icons';\nimport { ChatImage } from './ChatImage';\nimport { identity, markdownUrlTransform, prepareMarkdown } from '../utils';\nimport { MarkdownBlockSplitter } from '../utils/markdownBlocks';\nimport { isRelativeHref, toInternalHref } from '../utils/pageActions';\n\ninterface MarkdownMessageProps {\n content: string;\n /**\n * True while the message is still streaming: it is then rendered one\n * top-level block at a time, so a new chunk only re-parses the blocks it can\n * still change, and stays so once the stream ends. The markup is the one a\n * single parse of the finished message renders.\n */\n streaming?: boolean;\n onRelativeLinkClick?: (href: string) => void;\n /** Auth headers used to fetch host-relative images (see `ChatImage`). */\n requestHeaders?: Record<string, string>;\n t?: (key: string) => string;\n}\n\n\n/**\n * What the element renderers need from the message they render.\n *\n * react-markdown uses each renderer as an element TYPE, so a renderer must keep\n * its identity across renders: a new function is a new type, and React remounts\n * everything rendered with it. The renderers are therefore module-level and\n * read what varies per message from here — with renderers recreated on every\n * render, the streaming answer's DOM was rebuilt on every chunk, a selection in\n * it was lost, and each image in it was fetched again.\n */\ninterface MarkdownRenderContextValue {\n copiedBlock: string | null;\n onCopyCode: (code: string) => void;\n onRelativeLinkClick?: (href: string) => void;\n requestHeaders?: Record<string, string>;\n t: (key: string) => string;\n}\n\nconst MarkdownRenderContext = createContext<MarkdownRenderContextValue>({ copiedBlock: null, onCopyCode: () => undefined, t: identity });\n\nconst MarkdownCode = ({ className, children }: { className?: string; children?: React.ReactNode }) => {\n const { copiedBlock, onCopyCode, t } = useContext(MarkdownRenderContext);\n const match = /language-(\\w+)/.exec(className || '');\n const codeStr = String(children).replace(/\\n$/, '');\n // A fence with no info string (```\\n…\\n```) carries no `language-*`\n // class. Falling back to the multi-line test keeps it a block instead\n // of collapsing it into a single run of inline code.\n if (match || codeStr.includes('\\n')) {\n return (\n <div className=\"my-3 rounded-lg border border-gray-200 dark:border-white/10 overflow-hidden bg-gray-50 dark:bg-white/[0.03]\">\n <div className=\"flex items-center justify-between px-3 py-1.5 border-b border-gray-200 dark:border-white/10 bg-gray-100 dark:bg-white/[0.03]\">\n <span className=\"text-[0.7rem] text-gray-500 dark:text-white/40 font-mono\">{match?.[1] ?? 'plaintext'}</span>\n <button\n type=\"button\"\n onClick={() => onCopyCode(codeStr)}\n aria-label={copiedBlock === codeStr ? t('Copied') : t('Copy code')}\n className=\"p-0.5 rounded-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors\"\n >\n {copiedBlock === codeStr ? (\n <CheckIcon size={14} className=\"text-green-500\" />\n ) : (\n <CopyIcon size={14} className=\"text-gray-400 dark:text-white/40\" />\n )}\n </button>\n </div>\n <pre className=\"m-0 px-3 py-2 overflow-x-auto\">\n <code className=\"font-mono text-xs leading-[1.7] text-gray-800 dark:text-white/90 whitespace-pre\">{codeStr}</code>\n </pre>\n </div>\n );\n }\n return <code className=\"bg-gray-100 dark:bg-white/[0.08] px-1.5 py-0.5 rounded-sm font-mono text-xs text-[var(--chat-accent)]\">{children}</code>;\n};\n\nconst MarkdownLink = ({ href, children }: { href?: string; children?: React.ReactNode }) => {\n const { onRelativeLinkClick } = useContext(MarkdownRenderContext);\n const internalHref = toInternalHref(href);\n const routeInternally = internalHref !== null && !!onRelativeLinkClick;\n // A new tab unless the link was authored relative AND stays on this origin:\n // the second half keeps `/\\host` (which resolves off-site) out of this tab.\n const openInNewTab = !routeInternally && !(isRelativeHref(href) && internalHref !== null);\n const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {\n if (!routeInternally) return;\n event.preventDefault();\n onRelativeLinkClick!(internalHref!);\n };\n\n return (\n <a\n href={href}\n onClick={handleClick}\n target={openInNewTab ? '_blank' : undefined}\n rel={openInNewTab ? 'noopener noreferrer' : undefined}\n className=\"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125\"\n >\n {children}\n </a>\n );\n};\n\nconst MarkdownImage = ({ src, alt }: { src?: unknown; alt?: string }) => {\n const { requestHeaders, t } = useContext(MarkdownRenderContext);\n if (typeof src !== 'string' || !src) return null;\n // Keyed by its source: the image at a given place can change while the\n // message streams (a reference-style image resolves to each partial URL of\n // its definition as that line arrives), and a new source must not inherit the\n // previous one's fetched blob or its load error.\n return <ChatImage key={src} src={src} alt={alt || ''} requestHeaders={requestHeaders} t={t} />;\n};\n\nconst MARKDOWN_COMPONENTS: Components = {\n p: ({ children }) => <p className=\"mb-3 last:mb-0 leading-7 break-words text-[0.8125rem] text-gray-900 dark:text-white/90\">{children}</p>,\n // A fenced block renders as `<pre><code>`; the `code` override below\n // returns a `<div>` wrapper, which is not valid inside `<pre>`. Passing\n // the children straight through keeps the markup well-formed.\n pre: ({ children }) => <>{children}</>,\n code: MarkdownCode,\n // `list-disc` / `list-decimal` are required, not decorative: the\n // package's scoped preflight resets `list-style` inside the panel, so\n // without them every list renders as unmarked, indented prose.\n ul: ({ children }) => (\n <ul className=\"list-disc pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">\n {children}\n </ul>\n ),\n ol: ({ children }) => (\n <ol className=\"list-decimal pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">\n {children}\n </ol>\n ),\n li: ({ children }) => <li className=\"leading-7 break-words\">{children}</li>,\n strong: ({ children }) => <strong className=\"font-semibold text-gray-900 dark:text-white\">{children}</strong>,\n em: ({ children }) => <em className=\"italic\">{children}</em>,\n hr: () => <hr className=\"my-4 border-gray-200 dark:border-white/10\" />,\n blockquote: ({ children }) => (\n <blockquote className=\"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic text-gray-500 dark:text-white/60\">\n {children}\n </blockquote>\n ),\n a: MarkdownLink,\n img: MarkdownImage,\n h1: ({ children }) => <h1 className=\"mt-4 first:mt-0 mb-2 font-bold text-base text-gray-900 dark:text-white\">{children}</h1>,\n h2: ({ children }) => <h2 className=\"mt-3 first:mt-0 mb-2 font-bold text-[0.9rem] text-gray-900 dark:text-white\">{children}</h2>,\n h3: ({ children }) => <h3 className=\"mt-3 first:mt-0 mb-1.5 font-semibold text-[0.85rem] text-gray-900 dark:text-white\">{children}</h3>,\n table: ({ children }) => (\n <div className=\"my-3 overflow-x-auto rounded-lg border border-gray-200 dark:border-white/10\">\n <table className=\"w-full border-collapse text-xs\">{children}</table>\n </div>\n ),\n tr: ({ children }) => <tr className=\"transition-colors hover:bg-gray-50 dark:hover:bg-white/[0.02]\">{children}</tr>,\n th: ({ children }) => (\n <th className=\"px-3 py-2 text-left font-semibold bg-gray-50 dark:bg-white/[0.04] border-b border-gray-200 dark:border-white/10 text-gray-900 dark:text-white\">\n {children}\n </th>\n ),\n td: ({ children }) => <td className=\"px-3 py-2 border-b border-gray-200 dark:border-white/10 text-gray-700 dark:text-white/80\">{children}</td>,\n};\n\nconst REMARK_PLUGINS = [remarkGfm, remarkBreaks];\n\n/** One parse of `source`, run again only when the text itself changes. */\nconst MarkdownBody = memo(({ source }: { source: string }) => (\n <Markdown remarkPlugins={REMARK_PLUGINS} urlTransform={markdownUrlTransform} components={MARKDOWN_COMPONENTS}>\n {source}\n </Markdown>\n));\n\nMarkdownBody.displayName = 'MarkdownBody';\n\n/**\n * A streamed message, one top-level block per parse: a settled block keeps its\n * rendering, and a new chunk re-parses only the blocks it can still change.\n * The blocks render as siblings, which is the markup one parse of the whole\n * text produces.\n */\nconst StreamedMarkdownBody = ({ source }: { source: string }) => {\n const [splitter] = useState(() => new MarkdownBlockSplitter());\n const blocks = useMemo(() => splitter.split(source), [splitter, source]);\n return (\n <>\n {blocks.map((block, index) => (\n <MarkdownBody key={index} source={block} />\n ))}\n </>\n );\n};\n\n/**\n * Assistant prose renderer.\n *\n * Memoized because the message list re-renders on every streamed frame: without\n * it, each settled message in the thread would re-run the full remark parse on\n * every frame, which is the dominant source of streaming jank in long threads.\n * With it, only the live bubble re-parses — and only the blocks of it that can\n * still change.\n */\nexport const MarkdownMessage = memo(({ content, streaming = false, onRelativeLinkClick, requestHeaders, t = identity }: MarkdownMessageProps) => {\n const [copiedBlock, setCopiedBlock] = useState<string | null>(null);\n\n // Rendered by blocks once it has streamed: switching to one parse when the\n // stream ends would rebuild the whole message to produce the same markup,\n // fetching its images again behind their placeholders and dropping a\n // selection in it. A message first rendered finished (a restored thread, the\n // panel reopened) takes one parse.\n const [byBlocks, setByBlocks] = useState(streaming);\n if (streaming && !byBlocks) setByBlocks(true);\n\n // Preprocess once per `content`: every pass scans the whole message, so\n // memoizing keeps that work off the hot path for large messages.\n const processedContent = useMemo(() => prepareMarkdown(content), [content]);\n\n const onCopyCode = useCallback((code: string) => {\n navigator.clipboard.writeText(code);\n setCopiedBlock(code);\n setTimeout(() => setCopiedBlock(null), 2000);\n }, []);\n\n const renderContext = useMemo(\n () => ({ copiedBlock, onCopyCode, onRelativeLinkClick, requestHeaders, t }),\n [copiedBlock, onCopyCode, onRelativeLinkClick, requestHeaders, t],\n );\n\n return (\n <MarkdownRenderContext.Provider value={renderContext}>\n {byBlocks ? <StreamedMarkdownBody source={processedContent} /> : <MarkdownBody source={processedContent} />}\n </MarkdownRenderContext.Provider>\n );\n});\n\nMarkdownMessage.displayName = 'MarkdownMessage';\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { ChatMessage, ToolCallTraceEntry } from '../types';\nimport {\n AlertTriangleIcon,\n ArrowRightLeftIcon,\n BotIcon,\n BrainIcon,\n CheckCircleIcon,\n ChevronDownIcon,\n CloseIcon,\n WrenchIcon,\n XCircleIcon,\n} from './icons';\nimport { cleanReasoningText } from './ChatThinking';\nimport { findChatbotRoot, translate } from '../utils';\n\n/** Trace values longer than this are shown raw instead of pretty-printed JSON. */\nconst TRACE_PRETTY_LIMIT = 10_000;\n\n/**\n * Pretty-print a tool-call input/output when it is compact JSON; anything\n * else (plain text, oversized payloads, malformed JSON) is shown raw.\n */\nfunction prettyTraceValue(raw: string | undefined): string {\n if (!raw) return '';\n if (raw.length > TRACE_PRETTY_LIMIT) return raw;\n try {\n return JSON.stringify(JSON.parse(raw), null, 2);\n } catch {\n return raw;\n }\n}\n\nfunction toolDisplayName(name: string): string {\n return name.replace(/_/g, ' ');\n}\n\n/** Expandable row for a single tool call in the reasoning-details dialog. */\nconst ToolCallRow = ({ entry, index, t }: { entry: ToolCallTraceEntry; index: number; t: (key: string) => string }) => {\n const [expanded, setExpanded] = useState(false);\n\n const inputDisplay = useMemo(() => prettyTraceValue(entry.input), [entry.input]);\n const outputDisplay = useMemo(() => prettyTraceValue(entry.output), [entry.output]);\n const hasInput = !!inputDisplay && inputDisplay !== '{}';\n\n return (\n <div className=\"border border-gray-200 dark:border-white/[0.06] rounded-md overflow-hidden\">\n <button\n type=\"button\"\n onClick={() => setExpanded((v) => !v)}\n aria-expanded={expanded}\n className=\"w-full flex items-center gap-2.5 px-3 py-2 hover:bg-gray-50 dark:hover:bg-white/[0.03] transition-colors text-left\"\n >\n <span className=\"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]\">\n {index + 1}\n </span>\n {entry.success ? (\n <CheckCircleIcon size={12} className=\"shrink-0 text-emerald-500 dark:text-emerald-400\" />\n ) : (\n <XCircleIcon size={12} className=\"shrink-0 text-red-500 dark:text-red-400\" />\n )}\n <span className=\"flex-1 min-w-0 text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono\">{toolDisplayName(entry.name)}</span>\n <ChevronDownIcon\n size={14}\n className={`shrink-0 text-gray-400 dark:text-white/50 transition-transform duration-200 ${expanded ? 'rotate-180' : ''}`}\n />\n </button>\n\n {expanded && (\n <div className=\"border-t border-gray-200 dark:border-white/[0.06]\">\n {hasInput && (\n <div className=\"px-3 py-2 border-b border-gray-100 dark:border-white/[0.04] bg-gray-50/50 dark:bg-white/[0.01]\">\n <p className=\"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium\">{t('Input')}</p>\n <pre className=\"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable\">\n {inputDisplay}\n </pre>\n </div>\n )}\n <div className=\"px-3 py-2 bg-gray-50/50 dark:bg-white/[0.01]\">\n <p className=\"m-0 mb-1.5 text-[0.6rem] text-gray-500 dark:text-white/40 uppercase tracking-wider font-medium\">{t('Output')}</p>\n <pre className=\"m-0 text-[0.7rem] text-gray-600 dark:text-white/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable\">\n {outputDisplay || t('(no output)')}\n </pre>\n </div>\n </div>\n )}\n </div>\n );\n};\n\ninterface ReasoningDetailsDialogProps {\n msg: ChatMessage;\n onClose: () => void;\n t: (key: string) => string;\n}\n\n/**\n * Modal dialog with the full reasoning details of an assistant message —\n * mirrors the XTM One web chat dialog (truncation warning, model reasoning,\n * expandable per-tool-call trace, transfer chain). Rendered as an overlay\n * covering the chatbot panel so it works in every mode and host without\n * depending on the host app's stacking order.\n */\nexport const ReasoningDetailsDialog = ({ msg, onClose, t }: ReasoningDetailsDialogProps) => {\n const hostRef = useRef<HTMLSpanElement>(null);\n const closeButtonRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n const [root, setRoot] = useState<HTMLElement | null>(null);\n\n useEffect(() => {\n setRoot(findChatbotRoot(hostRef.current));\n }, []);\n\n useEffect(() => {\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n onClose();\n return;\n }\n // Focus trap: aria-modal promises focus stays inside the dialog, so\n // Tab/Shift+Tab cycle within it instead of escaping to the panel.\n if (e.key !== 'Tab') return;\n const dialog = dialogRef.current;\n if (!dialog) return;\n const focusable = dialog.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])');\n if (focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = document.activeElement;\n if (e.shiftKey) {\n if (active === first || !dialog.contains(active)) {\n e.preventDefault();\n last.focus();\n }\n } else if (active === last || !dialog.contains(active)) {\n e.preventDefault();\n first.focus();\n }\n };\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [onClose]);\n\n // Move initial keyboard focus into the modal (aria-modal) once the portal\n // is mounted, and hand it back to the trigger when the dialog closes.\n useEffect(() => {\n if (!root) return;\n const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n closeButtonRef.current?.focus({ preventScroll: true });\n return () => previouslyFocused?.focus({ preventScroll: true });\n }, [root]);\n\n // Prefer the backend's explicit count, then the detailed trace (what the\n // dialog body actually renders), then the flat tool-name list — keeps the\n // header summary consistent with the rows below.\n const totalCalls = msg.toolCallCount ?? msg.toolCallTrace?.length ?? msg.toolNames?.length ?? 0;\n const tools = msg.toolNames ?? [];\n const iterations = msg.iterations ?? 1;\n const transfers = msg.transferChain ?? [];\n const trace = msg.toolCallTrace ?? [];\n const reasoning = (msg.reasoning ?? '').trim();\n\n const summaryParts = [\n iterations > 1 ? translate(t, '{count} iterations', { count: iterations }) : '',\n totalCalls === 1 ? t('1 tool call') : translate(t, '{count} tool calls', { count: totalCalls }),\n transfers.length === 1 ? t('1 transfer') : transfers.length > 1 ? translate(t, '{count} transfers', { count: transfers.length }) : '',\n ].filter(Boolean);\n\n return (\n <span ref={hostRef} className=\"hidden\">\n {root &&\n createPortal(\n <div\n className=\"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4\"\n onClick={onClose}\n role=\"presentation\"\n >\n <div\n ref={dialogRef}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={t('Reasoning details')}\n onClick={(e) => e.stopPropagation()}\n className=\"w-full max-w-md max-h-full flex flex-col rounded-xl border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1e1e2e] shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]\"\n >\n <div className=\"px-4 pt-3.5 pb-2.5 border-b border-gray-200 dark:border-white/10\">\n <div className=\"flex items-center gap-2\">\n <WrenchIcon size={15} className=\"text-[var(--chat-accent)]\" />\n <span className=\"flex-1 text-[0.875rem] font-semibold text-gray-900 dark:text-white\">{t('Reasoning details')}</span>\n <button\n ref={closeButtonRef}\n type=\"button\"\n onClick={onClose}\n aria-label={t('Close')}\n className=\"w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 dark:text-white/40 hover:text-gray-700 dark:hover:text-white/70 transition-colors\"\n >\n <CloseIcon size={16} />\n </button>\n </div>\n <p className=\"m-0 mt-0.5 text-[0.72rem] text-gray-500 dark:text-white/40\">{summaryParts.join(' · ')}</p>\n </div>\n\n <div className=\"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3\">\n {msg.isTruncated && (\n <div className=\"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90\">\n <AlertTriangleIcon size={14} className=\"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400\" />\n <span>\n <span className=\"font-semibold\">{t('Turn limit reached.')}</span>{' '}\n {t(\n \"The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.\",\n )}\n </span>\n </div>\n )}\n\n {reasoning && (\n <div>\n <div className=\"flex items-center gap-1.5 mb-1.5\">\n <BrainIcon size={13} className=\"text-[var(--chat-accent)]/70\" />\n <span className=\"text-[0.72rem] font-medium text-gray-500 dark:text-white/50\">{t('Model reasoning')}</span>\n </div>\n <div className=\"rounded-md border border-gray-200 dark:border-white/[0.06] bg-gray-50/50 dark:bg-white/[0.01] px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable\">\n <p className=\"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 text-gray-500 dark:text-white/45\">\n {cleanReasoningText(reasoning)}\n </p>\n </div>\n </div>\n )}\n\n {trace.length > 0 ? (\n <div className=\"flex flex-col gap-1.5\">\n {trace.map((entry, i) => (\n <ToolCallRow key={`${entry.name}-${i}`} entry={entry} index={i} t={t} />\n ))}\n </div>\n ) : (\n tools.length > 0 && (\n // Fallback when no detailed trace is available (legacy\n // messages / backends without trace support).\n <div>\n {tools.map((tn, i) => (\n <div\n key={`${tn}-${i}`}\n className=\"flex items-center gap-3 py-2 border-b border-gray-100 dark:border-white/[0.04] last:border-0\"\n >\n <span className=\"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]\">\n {i + 1}\n </span>\n <WrenchIcon size={12} className=\"shrink-0 text-gray-400 dark:text-white/50\" />\n <span className=\"text-[0.8125rem] text-gray-700 dark:text-white/80 truncate font-mono\">{toolDisplayName(tn)}</span>\n </div>\n ))}\n </div>\n )\n )}\n\n {transfers.length > 0 && (\n <div>\n <div className=\"flex items-center gap-1.5 mb-1.5\">\n <ArrowRightLeftIcon size={13} className=\"text-[var(--chat-accent)]/70\" />\n <span className=\"text-[0.72rem] font-medium text-gray-500 dark:text-white/50\">{t('Transfer chain')}</span>\n </div>\n <div className=\"flex items-center gap-1.5 flex-wrap\">\n {transfers.map((tr, i) => (\n // Composite key: the same agent can appear twice in a\n // chain (A -> B -> A) and older payloads have no id.\n <div key={`${tr.agentId}-${i}`} className=\"flex items-center gap-1.5\">\n {i > 0 && <span className=\"text-gray-300 dark:text-white/30 text-[0.72rem]\">→</span>}\n <span className=\"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]\">\n <BotIcon size={12} />\n {tr.agentName}\n </span>\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n </div>\n </div>,\n root,\n )}\n </span>\n );\n};\n","import { memo, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type {\n AgentStatusState,\n ChatArtifact,\n ChatArtifactKind,\n ChatAttachment,\n ChatConversationRef,\n ChatMessage,\n MessageFeedback,\n ToolApprovalDecision,\n ToolApprovalProposal,\n} from '../types';\nimport { feedbackKeyOf, useMessageFeedback, type FeedbackEntry } from '../hooks/useMessageFeedback';\nimport { useSpeechReader } from '../hooks/useSpeechReader';\nimport { answerMarkdownSources, artifactKey, splitAnswerMarkers, stripAnswerMarkers } from '../utils';\nimport { FEEDBACK_COMMENT_MAX_LENGTH, feedbackModeOf, shownFeedback, type FeedbackMode } from '../utils/feedback';\nimport { formatMessageTime } from '../utils/messageTime';\nimport {\n createScrollFollower,\n innerBoxScrollsUp,\n keyScrollsUp,\n nextTouchAnchor,\n pressTakesScrollbar,\n singleTouchY,\n swipeScrollsUp,\n wheelScrollsUp,\n} from '../utils/scrollFollow';\nimport { hasSpeakableWords } from '../utils/speech';\nimport {\n AlertTriangleIcon,\n CheckIcon,\n ChevronDownIcon,\n CopyIcon,\n DownloadIcon,\n FileIcon,\n InfoIcon,\n MessageSquareIcon,\n ThumbsDownIcon,\n ThumbsUpIcon,\n VolumeIcon,\n VolumeOffIcon,\n} from './icons';\nimport { ArtifactCard } from './ArtifactCard';\nimport { ChatApprovalPrompt } from './ChatApprovalPrompt';\nimport { ChatImage } from './ChatImage';\nimport { ChatThinking } from './ChatThinking';\nimport { MarkdownMessage } from './MarkdownMessage';\nimport { ReasoningDetailsDialog } from './ReasoningDetailsDialog';\nimport { Tooltip } from './Tooltip';\n\n/**\n * Windowed thread rendering: only the most recent slice of the thread is\n * mounted, and \"Load earlier messages\" walks the window back a step at a time.\n * A long restored conversation would otherwise mount hundreds of markdown\n * subtrees at once, which stalls the panel on open and on every streamed frame.\n */\nconst INITIAL_RENDER_WINDOW = 150;\nconst RENDER_WINDOW_STEP = 50;\n\n/** How long the copy affordance stays in its confirmed state. */\nconst COPY_FEEDBACK_DELAY = 2000;\n\nconst parentOf = (node: Element) => node.parentElement;\nconst overflowYOf = (node: Element) => getComputedStyle(node).overflowY;\n\n/** Arrows and Page Up move the caret of a field (the feedback comment), not the thread. */\nfunction isTypingTarget(target: EventTarget): boolean {\n return target instanceof HTMLElement && (target.isContentEditable || !!target.closest('input, textarea, select'));\n}\n\nconst CONTROLS = 'a[href], button, summary, label, input, textarea, select, [role=\"button\"], [role=\"link\"]';\n\n/** A link, a button or a field: a middle click opens it, Shift+Space presses it. */\nfunction isControl(target: EventTarget): boolean {\n return target instanceof Element && !!target.closest(CONTROLS);\n}\n\ninterface ChatMessagesProps {\n messages: ChatMessage[];\n isLoading: boolean;\n agentStatus: AgentStatusState | null;\n agentName: string;\n logoIcon: React.ReactNode;\n onRelativeLinkClick?: (href: string) => void;\n /** Download an agent-generated file via the host app's backend proxy. */\n onDownloadFile?: (attachment: ChatAttachment) => void;\n /**\n * Resolve the host-proxied URL of an attachment, used to preview image\n * attachments inline. Attachments stay chips/cards when omitted.\n */\n resolveAttachmentUrl?: (attachment: ChatAttachment) => string | undefined;\n /** Download a deck, report or video through the host's proxy (`ApiEndpoints.artifacts`). */\n onDownloadArtifact?: (artifact: ChatArtifact, format: string) => Promise<void>;\n /** Describe one again, to follow a video that is still rendering. */\n onRefreshArtifact?: (kind: ChatArtifactKind, id: string) => Promise<ChatArtifact | undefined>;\n /** Auth headers used when fetching previewed images (see `ChatImage`). */\n requestHeaders?: Record<string, string>;\n /** Host-level override for the waiting panel (messages and the invitation to play). */\n miniGameEnabled?: boolean;\n /** Opens the XTM One arcade in place; wins over `waitingGameUrl`. */\n onPlayWaitingGame?: () => void;\n /** Where the XTM One arcade is played, opened in a new tab. */\n waitingGameUrl?: string | null;\n /** Enables the 👍/👎 affordance on completed assistant messages (see `feedbackUrl`). */\n onMessageFeedback?: (messageId: string, feedback: MessageFeedback | null, message: ChatMessage) => void;\n /**\n * Where the panel stores ratings itself (`feedbackBaseUrl`): shows the thumbs\n * on every answer the backend identified, whether or not `onMessageFeedback`\n * is passed.\n */\n feedbackUrl?: string | null;\n /** The conversation on screen; its ratings are stored against it. */\n conversationId?: string | null;\n /** BCP 47 tag the times are formatted in and answers are read aloud in. */\n locale?: string;\n /**\n * True while a turn answered after a reload is finishing without a stream.\n * Rendered as the ordinary working indicator: from the user's side nothing\n * about it is unusual, and a decision that visibly leads nowhere reads as a\n * broken button.\n */\n isResumingAfterDecision?: boolean;\n /**\n * Tool calls the running turn has paused on, awaiting a decision. Rendered\n * below the transcript, since the pause belongs to the turn rather than to\n * any one bubble.\n */\n pendingApprovals?: ToolApprovalProposal[] | null;\n onSubmitApprovalDecisions?: (decisions: ToolApprovalDecision[]) => void;\n isSubmittingApproval?: boolean;\n approvalError?: string | null;\n /**\n * The conversations the panel can open, by id: the loaded conversation list.\n * A referenced conversation's chip opens it through `onOpenConversation`\n * when it is there, and is a plain label otherwise.\n */\n openableConversationIds?: ReadonlySet<string>;\n onOpenConversation?: (conversationId: string) => void;\n t: (key: string) => string;\n}\n\nfunction formatFileSize(bytes?: number): string {\n if (!bytes || bytes <= 0) return '';\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Short uppercase extension label for a file chip (e.g. `report.pdf` → `PDF`). */\nfunction fileExtensionLabel(filename: string): string | undefined {\n const dot = filename.lastIndexOf('.');\n if (dot <= 0 || dot === filename.length - 1) return undefined;\n const ext = filename.slice(dot + 1);\n return ext.length <= 8 ? ext.toUpperCase() : undefined;\n}\n\nconst IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif']);\n\n/**\n * True when an attachment is worth previewing inline rather than showing as a\n * download card. The MIME type is authoritative; the short `type` label and the\n * filename extension are fallbacks for backends that omit it.\n */\nfunction isImageAttachment(att: ChatAttachment): boolean {\n if (att.contentType?.toLowerCase().startsWith('image/')) return true;\n const label = att.type?.toLowerCase();\n if (label && IMAGE_EXTENSIONS.has(label)) return true;\n const dot = att.filename.lastIndexOf('.');\n return dot > 0 && IMAGE_EXTENSIONS.has(att.filename.slice(dot + 1).toLowerCase());\n}\n\n/**\n * The footer's secondary controls show while the message is hovered or holds\n * the focus, and always where nothing hovers (a touch screen). A keyboard user\n * tabbing onto one sees it through `focus-visible` / `focus-within`.\n */\nconst SHOWN_ON_HOVER = 'group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100';\nconst FOOTER_BUTTON = 'p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]';\nconst ACCENT_ON_HOVER = 'hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]';\nconst REVEALED_BUTTON = `opacity-0 ${SHOWN_ON_HOVER} ${ACCENT_ON_HOVER}`;\n/**\n * The reasoning details button stays dimly in view, so a turn that reasoned is\n * noticed, and reads like its neighbours once they show.\n */\nconst DIMMED_BUTTON = `opacity-50 ${SHOWN_ON_HOVER} ${ACCENT_ON_HOVER}`;\n/** A control in its \"on\" state (the given rating, the message being read) stays in view. */\nconst ACTIVE_BUTTON = 'opacity-100 text-[var(--chat-accent)]';\n\n/** When the message was sent; the tooltip spells the date out. */\nconst MessageTime = ({ timestamp, locale }: { timestamp: Date; locale?: string }) => {\n const time = formatMessageTime(timestamp, locale);\n if (!time) return null;\n return (\n <Tooltip title={time.full}>\n <time dateTime={time.iso} className=\"px-1 text-[0.65rem] tabular-nums text-gray-400 dark:text-white/40 select-none\">\n <span aria-hidden=\"true\">{time.label}</span>\n <span className=\"sr-only\">{time.full}</span>\n </time>\n </Tooltip>\n );\n};\n\n/** Copies a message as plain text. Revealed on message hover. */\nconst MessageCopyButton = ({ text, label, t }: { text: string; label: string; t: (key: string) => string }) => {\n const [copied, setCopied] = useState(false);\n\n const handleCopy = async () => {\n try {\n await navigator.clipboard.writeText(text || '');\n setCopied(true);\n setTimeout(() => setCopied(false), COPY_FEEDBACK_DELAY);\n } catch {\n /* Clipboard unavailable (insecure context / denied permission) — the\n button simply doesn't confirm rather than throwing at the user. */\n }\n };\n\n const name = copied ? t('Copied!') : label;\n return (\n <Tooltip title={name}>\n <button\n type=\"button\"\n onClick={handleCopy}\n aria-label={name}\n className={`${FOOTER_BUTTON} ${copied ? 'opacity-100 text-green-500 dark:text-green-400' : REVEALED_BUTTON}`}\n >\n {copied ? <CheckIcon size={14} /> : <CopyIcon size={14} />}\n </button>\n </Tooltip>\n );\n};\n\n/**\n * 👍/👎 on a completed answer. Clicking the active value clears it. A rating\n * given before the conversation was reopened is final: only it is shown.\n */\nconst MessageFeedbackButtons = ({\n value,\n locked,\n pending,\n onChange,\n downRef,\n t,\n}: {\n value: MessageFeedback | null;\n locked: boolean;\n pending: boolean;\n onChange: (next: MessageFeedback | null) => void;\n downRef: React.RefObject<HTMLButtonElement | null>;\n t: (key: string) => string;\n}) => {\n const lockedId = useId();\n const inert = locked || pending;\n\n const button = (target: MessageFeedback, label: string) => {\n const active = value === target;\n if (locked && !active) return null;\n const Icon = target === 'up' ? ThumbsUpIcon : ThumbsDownIcon;\n return (\n <Tooltip title={locked ? t('Feedback already submitted') : label}>\n <button\n ref={target === 'down' ? downRef : undefined}\n type=\"button\"\n onClick={() => {\n if (!inert) onChange(active ? null : target);\n }}\n aria-label={label}\n aria-pressed={active}\n // Not `disabled`: a disabled button takes no focus and no hover, so\n // it could not say why it does not answer.\n aria-disabled={inert || undefined}\n aria-describedby={locked ? lockedId : undefined}\n className={`${FOOTER_BUTTON} ${active ? ACTIVE_BUTTON : REVEALED_BUTTON} ${inert ? 'cursor-default' : ''}`}\n >\n <Icon size={14} filled={active} />\n </button>\n </Tooltip>\n );\n };\n\n return (\n <>\n {button('up', t('Good response'))}\n {button('down', t('Bad response'))}\n {locked && (\n <span id={lockedId} className=\"sr-only\">\n {t('Feedback already submitted')}\n </span>\n )}\n </>\n );\n};\n\n/** The optional word on what went wrong, asked once a thumbs down is stored. */\nconst FeedbackComment = ({\n pending,\n onSave,\n onSkip,\n t,\n}: {\n pending: boolean;\n onSave: (text: string) => void;\n onSkip: () => void;\n t: (key: string) => string;\n}) => {\n const [text, setText] = useState('');\n const id = useId();\n const canSave = !pending && !!text.trim();\n\n return (\n <div className=\"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] p-2\">\n <label htmlFor={id} className=\"text-[0.7rem] text-gray-600 dark:text-white/60\">\n {t('Tell us what went wrong (optional)')}\n </label>\n <textarea\n id={id}\n // Opened by the user's own thumbs down, to be typed into.\n autoFocus\n rows={2}\n maxLength={FEEDBACK_COMMENT_MAX_LENGTH}\n value={text}\n // Read-only rather than disabled while saving, so the focus stays here.\n readOnly={pending}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n if (!pending) onSkip();\n } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {\n e.preventDefault();\n if (canSave) onSave(text);\n }\n }}\n placeholder={t('What could be improved?')}\n className=\"w-full resize-y rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-transparent px-2 py-1 text-[0.75rem] leading-5 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]\"\n />\n <div className=\"flex justify-end gap-1.5\">\n <button\n type=\"button\"\n onClick={() => {\n if (!pending) onSkip();\n }}\n aria-disabled={pending || undefined}\n className=\"rounded-md px-2 py-0.5 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]\"\n >\n {t('Skip')}\n </button>\n <button\n type=\"button\"\n onClick={() => {\n if (canSave) onSave(text);\n }}\n aria-disabled={!canSave || undefined}\n className={`rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] ${canSave ? 'hover:opacity-90' : 'opacity-50 cursor-default'}`}\n >\n {t('Save')}\n </button>\n </div>\n </div>\n );\n};\n\n/** Reads the answer aloud; the same button stops it. */\nconst ReadAloudButton = ({ speaking, onToggle, t }: { speaking: boolean; onToggle: () => void; t: (key: string) => string }) => {\n const name = speaking ? t('Stop reading') : t('Read aloud');\n return (\n <Tooltip title={name}>\n <button type=\"button\" onClick={onToggle} aria-label={name} className={`${FOOTER_BUTTON} ${speaking ? ACTIVE_BUTTON : REVEALED_BUTTON}`}>\n {speaking ? <VolumeOffIcon size={14} /> : <VolumeIcon size={14} />}\n </button>\n </Tooltip>\n );\n};\n\ninterface MessageRowProps {\n msg: ChatMessage;\n /** True only for the message currently being streamed. */\n isStreaming: boolean;\n agentName: string;\n logoIcon: React.ReactNode;\n onRelativeLinkClick?: (href: string) => void;\n onDownloadFile?: (attachment: ChatAttachment) => void;\n resolveAttachmentUrl?: (attachment: ChatAttachment) => string | undefined;\n onDownloadArtifact?: (artifact: ChatArtifact, format: string) => Promise<void>;\n onRefreshArtifact?: (kind: ChatArtifactKind, id: string) => Promise<ChatArtifact | undefined>;\n requestHeaders?: Record<string, string>;\n /** How this answer's thumbs work, or null for none (`feedbackModeOf`). */\n feedbackMode: FeedbackMode | null;\n /** What the user did to its rating in this session. */\n feedback: FeedbackEntry | undefined;\n onRate: (msg: ChatMessage, next: MessageFeedback | null, current: FeedbackEntry | undefined) => void;\n onSaveComment: (msg: ChatMessage, text: string, current: FeedbackEntry) => void;\n onSkipComment: (msg: ChatMessage, current: FeedbackEntry) => void;\n locale?: string;\n /** The browser can read aloud. */\n canSpeak: boolean;\n /** This message is being read aloud. */\n isSpeaking: boolean;\n onToggleSpeech: (id: string, documents: readonly string[]) => void;\n /** Given only to a message referencing conversations (see `ChatMessagesProps`). */\n openableConversationIds?: ReadonlySet<string>;\n onOpenConversation?: (conversationId: string) => void;\n t: (key: string) => string;\n}\n\n/**\n * One message in the thread.\n *\n * Memoized: the parent re-renders on every streamed frame, and without this\n * every settled message would re-run its markdown parse and re-mount its\n * attachment cards on each frame.\n */\nconst MessageRow = memo(\n ({\n msg,\n isStreaming,\n agentName,\n logoIcon,\n onRelativeLinkClick,\n onDownloadFile,\n resolveAttachmentUrl,\n onDownloadArtifact,\n onRefreshArtifact,\n requestHeaders,\n feedbackMode,\n feedback,\n onRate,\n onSaveComment,\n onSkipComment,\n locale,\n canSpeak,\n isSpeaking,\n onToggleSpeech,\n openableConversationIds,\n onOpenConversation,\n t,\n }: MessageRowProps) => {\n const [showReasoning, setShowReasoning] = useState(false);\n const isAssistant = msg.role === 'assistant';\n const isEmpty = !msg.content;\n const downRef = useRef<HTMLButtonElement>(null);\n\n // The comment question takes the focus when it opens; when it closes with\n // the focus still in it (the element is gone, so the page lost it), the\n // focus goes back to the thumb that opened it rather than to the page.\n const commentOpen = !!feedback?.commentOpen;\n const wasCommentOpen = useRef(commentOpen);\n useLayoutEffect(() => {\n const closed = wasCommentOpen.current && !commentOpen;\n wasCommentOpen.current = commentOpen;\n if (closed && (!document.activeElement || document.activeElement === document.body)) downRef.current?.focus();\n }, [commentOpen]);\n\n const renderAttachmentCard = (att: ChatAttachment, key: string) => {\n // An image the host can resolve a URL for is shown, not filed away.\n const previewUrl = resolveAttachmentUrl && isImageAttachment(att) ? resolveAttachmentUrl(att) : undefined;\n if (previewUrl) {\n return <ChatImage key={key} src={previewUrl} alt={att.filename} requestHeaders={requestHeaders} maxHeightClass=\"max-h-[200px]\" t={t} />;\n }\n\n const isWorking = att.fileTag === 'working_file';\n const sizeLabel = formatFileSize(att.size);\n return (\n <button\n key={key}\n type=\"button\"\n onClick={() => onDownloadFile?.(att)}\n title={t('Download')}\n className={`group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] ${\n isWorking\n ? 'border-gray-200 dark:border-white/10 bg-transparent'\n : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5'\n }`}\n >\n <span className={`shrink-0 ${isWorking ? 'text-gray-400 dark:text-white/40' : 'text-[var(--chat-accent)]'}`}>\n <FileIcon size={16} />\n </span>\n <span className=\"flex flex-col min-w-0 flex-1\">\n <span className=\"truncate text-[0.75rem] text-gray-900 dark:text-white\">{att.filename}</span>\n {(att.type || sizeLabel) && (\n <span className=\"text-[0.65rem] text-gray-400 dark:text-white/40 uppercase\">{[att.type, sizeLabel].filter(Boolean).join(' · ')}</span>\n )}\n </span>\n <span className=\"shrink-0 text-gray-400 dark:text-white/30 group-hover:text-[var(--chat-accent)]\">\n <DownloadIcon size={15} />\n </span>\n </button>\n );\n };\n\n // A user-uploaded file shown as a non-clickable chip — used while the upload\n // is still in flight (no server `fileId` yet) or when no download handler is\n // wired by the host.\n const renderFileChip = (name: string, key: string) => (\n <span\n key={key}\n className=\"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-white/60\"\n >\n <FileIcon size={14} />\n {name}\n </span>\n );\n\n const renderArtifactCard = (artifact: ChatArtifact, key: string) => (\n <ArtifactCard key={key} artifact={artifact} t={t} onDownload={onDownloadArtifact} onRefresh={onRefreshArtifact} />\n );\n\n // Render assistant content as an ordered interleave of prose segments and\n // cards, so a reply with markers like\n // `text [[FILE:a]] more text [[PRESENTATION:b]]` keeps the cards at their\n // source position. File cards only render when a download handler is wired\n // (`onDownloadFile`); a deck, report or video always renders, from its\n // descriptor. Attachments and artifacts whose marker isn't found in the\n // prose are appended as a fallback; a marker with no descriptor renders\n // nothing. During streaming neither is hydrated yet, so only prose (markers\n // stripped) renders.\n const buildAssistantBlocks = (): React.ReactNode[] => {\n const parts = splitAnswerMarkers(msg.content, isStreaming);\n const attByFileId = new Map((msg.attachments ?? []).map((a) => [a.fileId, a] as const));\n const artifactsByKey = new Map((msg.artifacts ?? []).map((a) => [artifactKey(a.kind, a.id), a] as const));\n const used = new Set<string>();\n const usedArtifacts = new Set<string>();\n const blocks: React.ReactNode[] = [];\n\n parts.forEach((part, i) => {\n if (part.type === 'text') {\n if (part.value.trim()) {\n blocks.push(\n <div key={`t-${i}`} className=\"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7\">\n <MarkdownMessage\n content={part.value}\n streaming={isStreaming}\n onRelativeLinkClick={onRelativeLinkClick}\n requestHeaders={requestHeaders}\n t={t}\n />\n </div>,\n );\n }\n } else if (part.type === 'artifact') {\n const key = artifactKey(part.kind, part.id);\n const artifact = artifactsByKey.get(key);\n if (artifact && !usedArtifacts.has(key)) {\n usedArtifacts.add(key);\n blocks.push(renderArtifactCard(artifact, `a-${key}-${i}`));\n }\n } else if (onDownloadFile) {\n const att = attByFileId.get(part.fileId);\n if (att) {\n used.add(part.fileId);\n blocks.push(renderAttachmentCard(att, `f-${part.fileId}-${i}`));\n }\n }\n });\n\n (msg.artifacts ?? []).forEach((artifact) => {\n const key = artifactKey(artifact.kind, artifact.id);\n if (!usedArtifacts.has(key)) {\n usedArtifacts.add(key);\n blocks.push(renderArtifactCard(artifact, `orphan-a-${key}`));\n }\n });\n\n if (onDownloadFile) {\n (msg.attachments ?? []).forEach((att) => {\n if (!used.has(att.fileId)) {\n blocks.push(renderAttachmentCard(att, `orphan-${att.fileId}`));\n }\n });\n }\n\n // An assistant reply that is *only* a file marker leaves no prose; show a\n // subtle ellipsis (not an empty padded bubble) when nothing else rendered\n // and we're not still streaming.\n if (blocks.length === 0 && !isStreaming) {\n blocks.push(\n <span key=\"empty\" className=\"pl-1 text-[0.8125rem] text-gray-400 dark:text-white/40 italic\">\n ...\n </span>,\n );\n }\n\n return blocks;\n };\n\n // Build the file cards shown on a user message. A successfully-uploaded file\n // carries a server `fileId`, so it renders as the same download card as an\n // agent-generated attachment (re-using the host download proxy via\n // `onDownloadFile`) — uploaded files must stay downloadable, not just\n // displayed. Files still uploading (no `fileId` / not `done`) or hosts\n // without a download handler fall back to a static chip. On conversation\n // restore the backend re-surfaces user uploads as `attachments` (there are\n // no live `files`), so those are rendered too.\n const buildUserFileBlocks = (): React.ReactNode[] => {\n const blocks: React.ReactNode[] = [];\n const seen = new Set<string>();\n\n (msg.files ?? []).forEach((f, i) => {\n const downloadable = !!(onDownloadFile && f.fileId && f.uploadStatus === 'done');\n if (downloadable && f.fileId) {\n seen.add(f.fileId);\n blocks.push(\n renderAttachmentCard(\n { fileId: f.fileId, filename: f.name, type: fileExtensionLabel(f.name), size: f.size, contentType: f.type },\n `file-${f.fileId}-${i}`,\n ),\n );\n } else {\n blocks.push(renderFileChip(f.name, `file-${i}`));\n }\n });\n\n (msg.attachments ?? []).forEach((att, i) => {\n if (seen.has(att.fileId)) return;\n seen.add(att.fileId);\n blocks.push(onDownloadFile ? renderAttachmentCard(att, `att-${att.fileId}-${i}`) : renderFileChip(att.filename, `att-${i}`));\n });\n\n return blocks;\n };\n\n // A conversation the message referenced with `@`: it opens in the panel\n // when the panel can open it, and otherwise just says what was referenced.\n const renderConversationRef = (ref: ChatConversationRef, i: number) => {\n const label = ref.title || (ref.key ? `@${ref.key}` : t('Untitled conversation'));\n const chip = 'inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]';\n const content = (\n <>\n <MessageSquareIcon size={13} className=\"shrink-0\" />\n <span className=\"truncate\">{label}</span>\n </>\n );\n if (onOpenConversation && openableConversationIds?.has(ref.conversationId)) {\n return (\n <Tooltip key={`ref-${ref.conversationId}-${i}`} title={t('Open conversation')}>\n <button\n type=\"button\"\n onClick={() => onOpenConversation(ref.conversationId)}\n className={`${chip} border-[var(--chat-accent-40)] text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]`}\n >\n {content}\n </button>\n </Tooltip>\n );\n }\n return (\n <Tooltip key={`ref-${ref.conversationId}-${i}`} title={ref.key ? `@${ref.key}` : ''}>\n <span className={`${chip} border-gray-200 dark:border-white/10 text-gray-600 dark:text-white/60`}>{content}</span>\n </Tooltip>\n );\n };\n\n const hasReasoningDetails =\n (msg.toolNames && msg.toolNames.length > 0) ||\n !!(msg.reasoning ?? '').trim() ||\n (msg.toolCallTrace && msg.toolCallTrace.length > 0) ||\n (msg.transferChain && msg.transferChain.length > 0) ||\n msg.isTruncated;\n\n // Actions only make sense on a finished answer, so they stay hidden while\n // the message is still streaming.\n const showActions = isAssistant && !isEmpty && !isStreaming;\n const plainText = stripAnswerMarkers(msg.content);\n const speechDocuments = useMemo(\n () => (showActions && canSpeak ? answerMarkdownSources(msg.content) : null),\n [showActions, canSpeak, msg.content],\n );\n const shown = shownFeedback(feedback, msg.feedback);\n const speechKey = feedbackKeyOf(msg);\n\n return (\n <div className={`group/msg flex flex-col ${isAssistant ? 'items-start' : 'items-end'}`}>\n {isAssistant && (\n <div className=\"flex items-center gap-1.5 mb-1\">\n <div className=\"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5\">\n <span className=\"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3\">{logoIcon}</span>\n </div>\n {/*\n The message's own agent wins over the panel-wide one. That name is\n whoever is selected right now, which is simply wrong for history —\n a thread that changed hands mid-way must keep each answer under\n the agent that wrote it.\n */}\n <span className=\"font-semibold text-xs text-gray-900 dark:text-white\">{msg.agentName ?? agentName}</span>\n </div>\n )}\n\n {!isAssistant && ((msg.files?.length ?? 0) > 0 || (msg.attachments?.length ?? 0) > 0) && (\n <div className=\"flex gap-1.5 flex-wrap mb-1.5 justify-end\">{buildUserFileBlocks()}</div>\n )}\n\n {!isAssistant && (msg.conversationRefs?.length ?? 0) > 0 && (\n <div className=\"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]\">{msg.conversationRefs!.map(renderConversationRef)}</div>\n )}\n\n {isAssistant ? (\n <div className=\"flex flex-col gap-1.5 w-full items-start\">\n {buildAssistantBlocks()}\n {!isEmpty && isStreaming && <span className=\"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse\" />}\n </div>\n ) : (\n <div className=\"max-w-[90%] px-3.5 py-2 rounded-[14px_14px_4px_14px] bg-[var(--chat-accent-dark)] text-white text-[0.8125rem] leading-6\">\n {msg.content}\n </div>\n )}\n\n {/* The user's side mirrors the answer's: the time hugs the bubble's edge. */}\n {!isAssistant && (\n <div className=\"mt-0.5 flex items-center justify-end gap-0.5 text-gray-400 dark:text-white/40\">\n {!!msg.content.trim() && <MessageCopyButton text={msg.content} label={t('Copy message')} t={t} />}\n {!msg.timestampUnknown && <MessageTime timestamp={msg.timestamp} locale={locale} />}\n </div>\n )}\n\n {showActions && (\n <div className=\"mt-0.5 flex flex-wrap items-center gap-0.5 text-gray-400 dark:text-white/40\">\n {!msg.timestampUnknown && <MessageTime timestamp={msg.timestamp} locale={locale} />}\n {hasReasoningDetails && (\n <Tooltip title={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}>\n <button\n type=\"button\"\n onClick={() => setShowReasoning((v) => !v)}\n className={`${FOOTER_BUTTON} ${\n msg.isTruncated\n ? // A truncated turn must be visible at a glance (not gated\n // on hover) so the user notices the warning — mirrors the\n // XTM One web chat affordance.\n 'opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300'\n : DIMMED_BUTTON\n }`}\n aria-label={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}\n aria-haspopup=\"dialog\"\n aria-expanded={showReasoning}\n >\n {msg.isTruncated ? <AlertTriangleIcon size={14} /> : <InfoIcon size={14} />}\n </button>\n </Tooltip>\n )}\n <MessageCopyButton text={plainText} label={t('Copy response')} t={t} />\n {feedbackMode && (\n <MessageFeedbackButtons\n value={shown.value}\n locked={shown.locked}\n pending={!!feedback?.pending}\n onChange={(next) => onRate(msg, next, feedback)}\n downRef={downRef}\n t={t}\n />\n )}\n {speechDocuments && hasSpeakableWords(speechDocuments) && (\n <ReadAloudButton speaking={isSpeaking} onToggle={() => onToggleSpeech(speechKey, speechDocuments)} t={t} />\n )}\n </div>\n )}\n {showActions && feedback?.commentOpen && (\n <FeedbackComment\n pending={feedback.pending}\n onSave={(text) => onSaveComment(msg, text, feedback)}\n onSkip={() => onSkipComment(msg, feedback)}\n t={t}\n />\n )}\n {showActions && feedback?.error && (\n <p role=\"alert\" className=\"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400\">\n {feedback.error}\n </p>\n )}\n {showReasoning && <ReasoningDetailsDialog msg={msg} onClose={() => setShowReasoning(false)} t={t} />}\n </div>\n );\n },\n);\n\nMessageRow.displayName = 'MessageRow';\n\nexport const ChatMessages = ({\n messages,\n isLoading,\n agentStatus,\n agentName,\n logoIcon,\n onRelativeLinkClick,\n onDownloadFile,\n resolveAttachmentUrl,\n onDownloadArtifact,\n onRefreshArtifact,\n requestHeaders,\n miniGameEnabled = true,\n onPlayWaitingGame,\n waitingGameUrl,\n onMessageFeedback,\n isResumingAfterDecision,\n pendingApprovals,\n onSubmitApprovalDecisions,\n isSubmittingApproval,\n approvalError,\n feedbackUrl,\n conversationId,\n locale,\n openableConversationIds,\n onOpenConversation,\n t,\n}: ChatMessagesProps) => {\n const scrollRef = useRef<HTMLDivElement>(null);\n const [renderWindow, setRenderWindow] = useState(INITIAL_RENDER_WINDOW);\n const {\n entries: feedbackEntries,\n rate,\n saveComment,\n skipComment,\n } = useMessageFeedback({\n feedbackUrl,\n conversationId,\n requestHeaders,\n onMessageFeedback,\n t,\n });\n const speech = useSpeechReader(locale);\n\n // Keeps the end of the conversation in view while the reader is at the\n // bottom (see `createScrollFollower`). It holds no React state: its timer\n // firing after unmount finds no container and does nothing.\n const [follower] = useState(() => createScrollFollower(() => scrollRef.current));\n // The highest point of the touch in progress: a swipe is measured from it,\n // so a finger that turns back down counts from where it turned.\n const touchAnchorRef = useRef<number | null>(null);\n\n // A gesture toward the top is the reader leaving the bottom — but only where\n // it moves the thread itself: an overlay portalled out of it (the image\n // lightbox) still bubbles its events here through React and scrolls nothing\n // of ours, and a box inside it that can still go up takes the gesture first.\n const leaveFrom = (container: HTMLDivElement, target: EventTarget) => {\n if (!(target instanceof Element) || !container.contains(target)) return;\n if (innerBoxScrollsUp<Element>(target, container, parentOf, overflowYOf)) return;\n follower.leave();\n };\n const handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {\n if (wheelScrollsUp(event)) leaveFrom(event.currentTarget, event.target);\n };\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.defaultPrevented || !keyScrollsUp(event) || isTypingTarget(event.target)) return;\n if (event.key === ' ' && isControl(event.target)) return;\n leaveFrom(event.currentTarget, event.target);\n };\n const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n const container = event.currentTarget;\n const rect = container.getBoundingClientRect();\n const press = {\n button: event.button,\n onContainer: event.target === container,\n onControl: isControl(event.target),\n x: event.clientX - rect.left - container.clientLeft,\n y: event.clientY - rect.top - container.clientTop,\n clientWidth: container.clientWidth,\n clientHeight: container.clientHeight,\n scrollTop: container.scrollTop,\n scrollHeight: container.scrollHeight,\n };\n if (pressTakesScrollbar(press)) leaveFrom(container, event.target);\n };\n // A second finger ends the swipe: a pinch is no scroll, and the swipe of\n // the finger left on the screen is measured afresh from its next move.\n const handleTouchStart = (event: React.TouchEvent) => {\n touchAnchorRef.current = singleTouchY(event.touches);\n };\n const handleTouchMove = (event: React.TouchEvent<HTMLDivElement>) => {\n const y = singleTouchY(event.touches);\n const anchor = touchAnchorRef.current;\n if (y !== null && anchor !== null && swipeScrollsUp(anchor, y)) leaveFrom(event.currentTarget, event.target);\n touchAnchorRef.current = nextTouchAnchor(anchor, y);\n };\n\n // Switching conversation (restore / new chat) replaces the whole array, so\n // the window must snap back to the tail instead of keeping a widened one.\n const firstMessageId = messages[0]?.id;\n useEffect(() => {\n setRenderWindow(INITIAL_RENDER_WINDOW);\n }, [firstMessageId]);\n\n // A message the user just sent (a steer included) and a conversation just\n // opened are scrolled into view smoothly, and the view follows again.\n // Anything else — mostly the streamed answer, which changes `messages` on\n // every frame — keeps the bottom in view only while the view follows, so a\n // reader who scrolled up stays where they are.\n let userMessageCount = 0;\n for (const m of messages) if (m.role === 'user') userMessageCount += 1;\n const seenRef = useRef<{ firstMessageId?: string; userMessageCount: number } | null>(null);\n useLayoutEffect(() => {\n const seen = seenRef.current;\n seenRef.current = { firstMessageId, userMessageCount };\n if (!seen || seen.firstMessageId !== firstMessageId || userMessageCount > seen.userMessageCount) {\n follower.reveal();\n } else {\n follower.keepUp();\n }\n }, [messages, firstMessageId, userMessageCount, follower]);\n\n // Keep the bottom in view while the reasoning window below the status\n // bubble grows: thinking prose streams in without any `messages` change,\n // so without this the growing window slides under the fold and the user\n // stops seeing the live reasoning.\n const thinkingLen = agentStatus?.thinkingContent?.length ?? 0;\n useLayoutEffect(() => {\n if (thinkingLen) follower.keepUp();\n }, [thinkingLen, follower]);\n\n const hasEarlierMessages = messages.length > renderWindow;\n const visibleMessages = useMemo(\n () => (hasEarlierMessages ? messages.slice(messages.length - renderWindow) : messages),\n [messages, renderWindow, hasEarlierMessages],\n );\n\n // Reading aloud is about the message on screen: it stops when the user\n // sends a new one, opens another conversation, or the message goes away.\n const { speakingId, stop: stopSpeech } = speech;\n const spokenStillShown = speakingId === null || messages.some((m) => feedbackKeyOf(m) === speakingId);\n const speechScope = useRef({ conversationId, userMessageCount });\n useEffect(() => {\n const previous = speechScope.current;\n speechScope.current = { conversationId, userMessageCount };\n if (previous.conversationId !== conversationId || userMessageCount > previous.userMessageCount || !spokenStillShown) stopSpeech();\n }, [conversationId, userMessageCount, spokenStillShown, stopSpeech]);\n\n // The streaming response is the LAST ASSISTANT message — not necessarily\n // the last message overall: a mid-run steering send appends an optimistic\n // user bubble after the assistant message that is still streaming. Gating\n // on `messages.length - 1` would then drop the live cursor / ChatThinking\n // state the moment the user steers.\n let streamingMessageId: string | null = null;\n if (isLoading) {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n streamingMessageId = messages[i].id;\n break;\n }\n }\n }\n\n // Only a prompt something can actually answer counts: without a submit\n // handler the controls would collect verdicts with nowhere to send them.\n const awaitingApproval = !!pendingApprovals?.length && !!onSubmitApprovalDecisions;\n\n // A tab stop of its own, so the keys scroll the thread (and are read as\n // leaving the bottom) without first focusing something inside it.\n return (\n <div\n ref={scrollRef}\n role=\"region\"\n aria-label={t('Conversation transcript')}\n tabIndex={0}\n onScroll={follower.onScroll}\n onWheel={handleWheel}\n onKeyDown={handleKeyDown}\n onPointerDown={handlePointerDown}\n onTouchStart={handleTouchStart}\n onTouchMove={handleTouchMove}\n className=\"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]\"\n >\n {hasEarlierMessages && (\n <div className=\"flex justify-center\">\n <button\n type=\"button\"\n onClick={() => setRenderWindow((w) => w + RENDER_WINDOW_STEP)}\n className=\"flex items-center gap-1.5 rounded-full border border-gray-200 dark:border-white/10 px-3 py-1 text-[0.7rem] text-gray-500 dark:text-white/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]\"\n >\n <ChevronDownIcon size={13} className=\"rotate-180\" />\n {t('Load earlier messages')}\n </button>\n </div>\n )}\n\n {visibleMessages.map((msg) => {\n const isStreamingMessage = msg.id === streamingMessageId;\n // An assistant message with no content yet is the \"agent is working\"\n // placeholder, replaced by the live status bubble.\n if (msg.role === 'assistant' && !msg.content && isStreamingMessage) {\n // A turn paused for approval is not working, it is waiting on the\n // person reading it — so the progress bubble (and the waiting game\n // it grows into) gives way to the prompt rendered below.\n if (awaitingApproval) return null;\n return (\n <div key={msg.id}>\n <ChatThinking\n agentStatus={agentStatus}\n logoIcon={logoIcon}\n t={t}\n miniGameEnabled={miniGameEnabled}\n onPlayWaitingGame={onPlayWaitingGame}\n waitingGameUrl={waitingGameUrl}\n keepEndInView={follower.keepUp}\n />\n </div>\n );\n }\n\n return (\n <MessageRow\n key={msg.id}\n msg={msg}\n isStreaming={isStreamingMessage}\n agentName={agentName}\n logoIcon={logoIcon}\n onRelativeLinkClick={onRelativeLinkClick}\n onDownloadFile={onDownloadFile}\n resolveAttachmentUrl={resolveAttachmentUrl}\n onDownloadArtifact={onDownloadArtifact}\n onRefreshArtifact={onRefreshArtifact}\n requestHeaders={requestHeaders}\n feedbackMode={msg.role === 'assistant' ? feedbackModeOf(msg.serverId, feedbackUrl, conversationId, !!onMessageFeedback) : null}\n feedback={feedbackEntries[feedbackKeyOf(msg)]}\n onRate={rate}\n onSaveComment={saveComment}\n onSkipComment={skipComment}\n locale={locale}\n canSpeak={speech.supported}\n isSpeaking={speakingId === feedbackKeyOf(msg)}\n onToggleSpeech={speech.toggle}\n // Only to a row that needs them: a new list of openable\n // conversations must not re-render every row of the thread.\n openableConversationIds={msg.conversationRefs?.length ? openableConversationIds : undefined}\n onOpenConversation={msg.conversationRefs?.length ? onOpenConversation : undefined}\n t={t}\n />\n );\n })}\n {/* Not tied to a placeholder message like the streaming indicator: a\n restore replaces the whole transcript on every poll, so there is no\n bubble of ours left to hang it on. */}\n {isResumingAfterDecision && !awaitingApproval && (\n <ChatThinking\n agentStatus={agentStatus}\n logoIcon={logoIcon}\n t={t}\n miniGameEnabled={miniGameEnabled}\n onPlayWaitingGame={onPlayWaitingGame}\n waitingGameUrl={waitingGameUrl}\n keepEndInView={follower.keepUp}\n />\n )}\n {awaitingApproval && (\n <ChatApprovalPrompt\n // A second pause in the same turn is a new question, not a continuation\n // of the answered one: remounting drops the verdicts and the\n // already-submitted guard the previous set left behind.\n key={pendingApprovals!.map((p) => p.toolCallId).join('|')}\n proposals={pendingApprovals!}\n onSubmit={onSubmitApprovalDecisions!}\n isSubmitting={isSubmittingApproval}\n error={approvalError}\n t={t}\n />\n )}\n {/* Holds the list's gap below its last item. */}\n <div />\n </div>\n );\n};\n","import type { Translate } from '../types';\nimport { translate, translateAround } from '../utils';\n\n/**\n * The greeting, as one sentence the locale owns end to end. The agent's name is\n * markup (it carries the accent colour), so it cannot be spliced into a string —\n * hence the split around its slot rather than three separate fragments.\n */\nconst Greeting = ({ firstName, agentName, t }: { firstName: string; agentName?: string; t: Translate }) => {\n if (!agentName) return <>{translate(t, 'How can I help you, {name}?', { name: firstName })}</>;\n const { before, after, hasSlot } = translateAround(t, 'How can {agent} help you, {name}?', 'agent', { name: firstName });\n return (\n <>\n {before}\n {hasSlot && <span className=\"text-[var(--chat-accent)]\">{agentName}</span>}\n {after}\n </>\n );\n};\n\ninterface ChatWelcomeProps {\n firstName: string;\n logoIcon: React.ReactNode;\n /** Already translated by the caller — see `ChatPanel`. */\n promptSuggestions: string[];\n onPromptClick: (prompt: string) => void;\n /** Selected agent, so the screen says who is about to answer. */\n agentName?: string;\n agentDescription?: string | null;\n /** True while agent-specific suggestions are being fetched. */\n suggestionsLoading?: boolean;\n t: Translate;\n}\n\nexport const ChatWelcome = ({\n firstName,\n logoIcon,\n promptSuggestions,\n onPromptClick,\n agentName,\n agentDescription,\n suggestionsLoading = false,\n t,\n}: ChatWelcomeProps) => (\n <div className=\"flex-1 flex flex-col items-center justify-center px-6 pb-8\">\n <span className=\"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]\">{logoIcon}</span>\n\n {/*\n Naming the agent here is the only confirmation that switching in the\n header actually took effect: the thread resets to this screen, so without\n it nothing tells you which agent the next message will reach.\n `key` on the heading restarts the fade whenever the agent changes, so the\n switch is visible rather than a silent text swap.\n */}\n <h2\n key={agentName ?? 'default'}\n className=\"text-xl font-medium mb-1 text-center text-gray-900 dark:text-white\"\n style={{ fontFamily: '\"Geologica\", sans-serif', animation: 'chat-fade-in 0.35s ease-out' }}\n >\n <Greeting firstName={firstName} agentName={agentName} t={t} />\n </h2>\n\n {agentDescription && (\n <p className=\"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 text-gray-500 dark:text-white/40\">{agentDescription}</p>\n )}\n {!agentDescription && <span className=\"mb-5\" />}\n\n {/* A host that passes no suggestions gets no section: the heading on its own\n used to sit above an empty gap. */}\n {(suggestionsLoading || promptSuggestions.length > 0) && (\n <div className=\"w-full max-w-[320px]\">\n <span className=\"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold\">\n {t('Suggestions')}\n </span>\n {suggestionsLoading ? (\n // Placeholder rows rather than an empty gap: the list is about to be\n // replaced by the new agent's own suggestions.\n <div aria-hidden className=\"space-y-1\">\n {[0, 1, 2].map((i) => (\n <div key={i} className=\"h-8 rounded-lg border border-gray-200 dark:border-white/10 bg-gray-100/50 dark:bg-white/[0.03] animate-pulse\" />\n ))}\n </div>\n ) : (\n promptSuggestions.map((prompt) => (\n <button\n key={prompt}\n type=\"button\"\n onClick={() => onPromptClick(prompt)}\n className=\"w-full text-left text-[0.8125rem] text-gray-800 dark:text-white py-1.5 px-3 mb-1 rounded-lg border border-gray-200 dark:border-white/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]\"\n >\n {prompt}\n </button>\n ))\n )}\n </div>\n )}\n </div>\n);\n","import { useEffect, useMemo, useRef, useState, type DragEvent, type ReactNode } from 'react';\nimport type { ChatConversationSummary, ChatWorkspace } from '../types';\nimport type { WorkspaceWriteResult } from '../hooks/useWorkspaces';\nimport { timeAgo } from '../utils';\nimport { fileableWorkspaces, groupCanToggle, groupConversations, groupIsOpen, isNoopMove, unfiledEmptyNote } from '../utils/workspaces';\nimport { Dropdown } from './Dropdown';\nimport {\n BotIcon,\n CheckIcon,\n ChevronRightIcon,\n CloseIcon,\n EditIcon,\n FolderIcon,\n FolderInputIcon,\n FolderPlusIcon,\n PencilIcon,\n SearchIcon,\n SidebarIcon,\n TrashIcon,\n} from './icons';\nimport { Spinner } from './Spinner';\nimport { Tooltip } from './Tooltip';\n\n/**\n * The workspaces the list is grouped by, and what the list may do with them.\n * Omitted when the host does not name `apiEndpoints.workspaces` or the backend\n * refuses the list: the sidebar is then the flat list it always was.\n */\nexport interface SidebarWorkspaces {\n list: ChatWorkspace[];\n /** The workspace the next conversation will be created in, if any. */\n pendingWorkspaceId: string | null;\n onCreate: (name: string) => Promise<WorkspaceWriteResult>;\n onRename: (id: string, name: string) => Promise<WorkspaceWriteResult>;\n onDelete: (id: string) => Promise<WorkspaceWriteResult>;\n /** Resolves to `null` on success, or the backend's reason. */\n onMove: (conversationId: string, workspaceId: string | null) => Promise<string | null>;\n onNewChat: (workspaceId: string) => void;\n}\n\ninterface ConversationSidebarProps {\n conversations: ChatConversationSummary[];\n loading: boolean;\n activeConversationId: string | null;\n collapsed: boolean;\n onToggleCollapsed: () => void;\n onSelect: (id: string) => void;\n onDelete: (id: string) => void;\n /** Omit to hide the rename affordance (backend without the route). */\n onRename?: (id: string, title: string) => void;\n onNewChat: () => void;\n workspaces?: SidebarWorkspaces;\n t: (key: string) => string;\n}\n\n/** Below this many conversations the list is quicker to scan than to filter. */\nconst SEARCH_THRESHOLD = 7;\n/** What a dragged conversation row carries. */\nconst DRAG_TYPE = 'application/x-filigran-conversation';\n/** Where the collapsed workspace groups are remembered, per browser. */\nconst COLLAPSED_KEY = 'filigran-chat-collapsed-workspaces';\n\nfunction readCollapsed(): Set<string> {\n try {\n const parsed: unknown = JSON.parse(localStorage.getItem(COLLAPSED_KEY) ?? '[]');\n return new Set(Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : []);\n } catch {\n return new Set();\n }\n}\n\nconst iconButton =\n 'p-1 rounded-md text-gray-400 dark:text-white/30 hover:bg-gray-200/60 dark:hover:bg-white/10 transition-colors disabled:opacity-40 disabled:pointer-events-none';\nconst sectionLabel = 'text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40';\n\n/**\n * Persistent conversation list for fullscreen mode, mirroring the XTM One web\n * chat's sidebar - grouped by workspace when the host offers workspaces, the\n * way a desktop assistant groups its projects: collapsible groups, a\n * conversation started inside one, and rows moved between them from their\n * menu or by dragging them onto a group.\n *\n * Fullscreen is the only mode with room for it: in floating and sidebar modes\n * the header's history menu remains the way in, since a permanent column there\n * would eat most of the panel.\n */\nexport const ConversationSidebar = ({\n conversations,\n loading,\n activeConversationId,\n collapsed,\n onToggleCollapsed,\n onSelect,\n onDelete,\n onRename,\n onNewChat,\n workspaces,\n t,\n}: ConversationSidebarProps) => {\n const [query, setQuery] = useState('');\n const [editingId, setEditingId] = useState<string | null>(null);\n const [draftTitle, setDraftTitle] = useState('');\n // Guards the input's onBlur: committing and then blurring would fire the\n // commit twice, and cancelling via Escape blurs too.\n const settledRef = useRef(false);\n const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(readCollapsed);\n const [creatingWorkspace, setCreatingWorkspace] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // A refusal is said, then goes: it is about the action just tried.\n useEffect(() => {\n if (!error) return;\n const timer = setTimeout(() => setError(null), 6000);\n return () => clearTimeout(timer);\n }, [error]);\n\n const startRename = (id: string, current: string) => {\n settledRef.current = false;\n setEditingId(id);\n setDraftTitle(current);\n };\n\n const commitRename = () => {\n if (settledRef.current) return;\n settledRef.current = true;\n const id = editingId;\n const next = draftTitle.trim();\n setEditingId(null);\n // Unchanged or emptied: leave the conversation alone rather than issuing a\n // request that would either no-op or wipe the title.\n if (id && next) onRename?.(id, next);\n };\n\n const cancelRename = () => {\n settledRef.current = true;\n setEditingId(null);\n };\n\n const toggleGroup = (key: string) => {\n setCollapsedGroups((prev) => {\n const next = new Set(prev);\n if (next.has(key)) next.delete(key);\n else next.add(key);\n try {\n localStorage.setItem(COLLAPSED_KEY, JSON.stringify([...next]));\n } catch {\n // Blocked storage: the groups simply open next time.\n }\n return next;\n });\n };\n\n const say = (reason: string | null, fallback: string) => setError(reason || t(fallback));\n\n const move = async (conversationId: string, workspaceId: string | null) => {\n // A drop on the group the row is already in (or an unfiled row on \"Not in\n // a workspace\") is no move: the row menu disables it, the drop ignores it.\n if (!workspaces || isNoopMove(conversations, conversationId, workspaceId)) return;\n const refusal = await workspaces.onMove(conversationId, workspaceId);\n if (refusal !== null) say(refusal, 'The conversation could not be moved');\n };\n\n const q = query.trim().toLowerCase();\n const matches = useMemo(() => (q ? (c: ChatConversationSummary) => (c.title || '').toLowerCase().includes(q) : undefined), [q]);\n const filtered = useMemo(() => (matches ? conversations.filter(matches) : conversations), [conversations, matches]);\n const grouped = useMemo(\n () => (workspaces ? groupConversations(conversations, workspaces.list, { matches }) : null),\n [conversations, workspaces, matches],\n );\n const fileable = workspaces ? fileableWorkspaces(workspaces.list) : [];\n const unfiledNote = grouped ? unfiledEmptyNote({ total: conversations.length, unfiled: grouped.unfiled.length, loading, searching: !!q }) : null;\n\n if (collapsed) {\n return (\n <div className=\"flex flex-col items-center gap-1 border-r border-gray-200 dark:border-white/10 px-2 py-3 shrink-0\">\n <Tooltip title={t('Show conversations')}>\n <button\n type=\"button\"\n onClick={onToggleCollapsed}\n aria-label={t('Show conversations')}\n aria-expanded={false}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <SidebarIcon size={17} />\n </button>\n </Tooltip>\n <Tooltip title={t('New conversation')}>\n <button\n type=\"button\"\n onClick={() => onNewChat()}\n aria-label={t('New conversation')}\n className=\"w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <EditIcon size={17} />\n </button>\n </Tooltip>\n </div>\n );\n }\n\n const renderRow = (c: ChatConversationSummary) => (\n <ConversationRow\n key={c.conversationId}\n conversation={c}\n isActive={c.conversationId === activeConversationId}\n isEditing={c.conversationId === editingId}\n draftTitle={draftTitle}\n onDraftTitleChange={setDraftTitle}\n onCommitRename={commitRename}\n onCancelRename={cancelRename}\n onStartRename={onRename ? startRename : undefined}\n onSelect={onSelect}\n onDelete={onDelete}\n fileable={workspaces ? fileable : undefined}\n onMove={move}\n t={t}\n />\n );\n\n return (\n <div className=\"w-64 shrink-0 flex flex-col border-r border-gray-200 dark:border-white/10\">\n <div className=\"flex items-center gap-1 px-3 py-3\">\n <button\n type=\"button\"\n onClick={() => onNewChat()}\n className=\"flex-1 flex items-center gap-2 rounded-lg border border-gray-200 dark:border-white/10 px-3 py-1.5 text-[0.8125rem] text-gray-700 dark:text-white/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors\"\n >\n <EditIcon size={15} />\n {t('New conversation')}\n </button>\n <Tooltip title={t('Hide conversations')}>\n <button\n type=\"button\"\n onClick={onToggleCollapsed}\n aria-label={t('Hide conversations')}\n aria-expanded\n className=\"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg text-gray-400 dark:text-white/30 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors\"\n >\n <SidebarIcon size={17} />\n </button>\n </Tooltip>\n </div>\n\n {conversations.length > SEARCH_THRESHOLD && (\n <div className=\"px-3 pb-2\">\n <div className=\"relative\">\n <SearchIcon size={12} className=\"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40\" />\n <input\n type=\"text\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') setQuery('');\n }}\n placeholder={t('Search conversations...')}\n aria-label={t('Search conversations...')}\n className=\"w-full h-7 pl-7 pr-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-[0.75rem] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]\"\n />\n </div>\n </div>\n )}\n\n <div className=\"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable\">\n {loading && conversations.length === 0 && (\n <div className=\"px-3 py-2\">\n <Spinner size={16} />\n </div>\n )}\n\n {grouped && workspaces ? (\n <>\n {!q && (\n <div className=\"flex items-center justify-between px-2 pb-1 pt-1\">\n <span className={sectionLabel}>{t('Workspaces')}</span>\n <Tooltip title={t('New workspace')}>\n <button type=\"button\" onClick={() => setCreatingWorkspace(true)} aria-label={t('New workspace')} className={iconButton}>\n <FolderPlusIcon size={14} />\n </button>\n </Tooltip>\n </div>\n )}\n {creatingWorkspace && (\n <NameField\n placeholder={t('Workspace name')}\n onSubmit={async (name) => {\n setCreatingWorkspace(false);\n if (!name) return;\n const result = await workspaces.onCreate(name);\n if (!result.ok) say(result.error, 'The workspace could not be created');\n }}\n onCancel={() => setCreatingWorkspace(false)}\n />\n )}\n {grouped.groups.map((group) => (\n <WorkspaceGroupSection\n key={group.key}\n workspace={group.workspace}\n count={group.conversations.length}\n open={groupIsOpen(group.key, collapsedGroups, group, activeConversationId, !!q)}\n toggleable={groupCanToggle(group, activeConversationId, !!q)}\n pending={!!group.workspace && workspaces.pendingWorkspaceId === group.workspace.id && !activeConversationId}\n onToggle={() => toggleGroup(group.key)}\n onNewChat={workspaces.onNewChat}\n onRename={async (id, name) => {\n const result = await workspaces.onRename(id, name);\n if (!result.ok) say(result.error, 'The workspace could not be renamed');\n }}\n onDelete={async (id) => {\n const result = await workspaces.onDelete(id);\n if (!result.ok) say(result.error, 'The workspace could not be deleted');\n }}\n onDropConversation={(conversationId) => group.workspace && void move(conversationId, group.workspace.id)}\n t={t}\n >\n {group.conversations.length > 0 ? (\n group.conversations.map(renderRow)\n ) : (\n <p className=\"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30\">{t('Drop a conversation here, or start one with +.')}</p>\n )}\n </WorkspaceGroupSection>\n ))}\n <DropZone onDropConversation={(conversationId) => void move(conversationId, null)} accepts>\n <div className=\"flex items-center justify-between px-2 pb-1 pt-3\">\n <span className={sectionLabel}>{t('Not in a workspace')}</span>\n <span className=\"text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30\">{grouped.unfiled.length}</span>\n </div>\n {grouped.unfiled.map(renderRow)}\n {unfiledNote && (\n <p className=\"px-3 py-1.5 text-[0.65rem] text-gray-400 dark:text-white/30\">\n {unfiledNote === 'none' ? t('No conversations yet') : t('Every conversation is in a workspace.')}\n </p>\n )}\n </DropZone>\n {q && grouped.groups.length === 0 && grouped.unfiled.length === 0 && (\n <p className=\"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversation matches')}</p>\n )}\n </>\n ) : (\n <>\n {!loading && conversations.length === 0 && (\n <p className=\"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversations yet')}</p>\n )}\n {conversations.length > 0 && filtered.length === 0 && (\n <p className=\"px-3 py-2 text-[0.75rem] text-gray-400 dark:text-white/40\">{t('No conversation matches')}</p>\n )}\n {filtered.map(renderRow)}\n </>\n )}\n </div>\n\n {error && (\n <p role=\"alert\" className=\"mx-3 mb-3 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[0.7rem] text-red-600 dark:text-red-400\">\n {error}\n </p>\n )}\n </div>\n );\n};\n\n/** An element conversations can be dropped onto. */\nconst DropZone = ({\n onDropConversation,\n accepts,\n children,\n className = '',\n}: {\n onDropConversation: (conversationId: string) => void;\n accepts: boolean;\n children: ReactNode;\n className?: string;\n}) => {\n const [over, setOver] = useState(false);\n const depth = useRef(0);\n const carries = (e: DragEvent) => e.dataTransfer.types.includes(DRAG_TYPE);\n return (\n <div\n className={`rounded-lg transition-colors ${over ? 'bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40' : ''} ${className}`}\n {...(accepts\n ? {\n onDragEnter: (e: DragEvent) => {\n if (!carries(e)) return;\n depth.current += 1;\n setOver(true);\n },\n onDragOver: (e: DragEvent) => {\n if (!carries(e)) return;\n e.preventDefault();\n e.dataTransfer.dropEffect = 'move';\n },\n onDragLeave: (e: DragEvent) => {\n if (!carries(e)) return;\n depth.current = Math.max(0, depth.current - 1);\n if (depth.current === 0) setOver(false);\n },\n onDrop: (e: DragEvent) => {\n if (!carries(e)) return;\n e.preventDefault();\n depth.current = 0;\n setOver(false);\n const id = e.dataTransfer.getData(DRAG_TYPE);\n if (id) onDropConversation(id);\n },\n }\n : {})}\n >\n {children}\n </div>\n );\n};\n\n/** A one-line name field: Enter commits, Escape or an empty blur cancels. */\nconst NameField = ({\n initial = '',\n placeholder,\n onSubmit,\n onCancel,\n}: {\n initial?: string;\n placeholder: string;\n onSubmit: (name: string) => void;\n onCancel: () => void;\n}) => {\n const [value, setValue] = useState(initial);\n const settled = useRef(false);\n const inputRef = useRef<HTMLInputElement>(null);\n useEffect(() => {\n inputRef.current?.focus();\n inputRef.current?.select();\n }, []);\n const commit = () => {\n if (settled.current) return;\n settled.current = true;\n onSubmit(value.trim());\n };\n return (\n <input\n ref={inputRef}\n value={value}\n maxLength={200}\n onChange={(e) => setValue(e.target.value)}\n onClick={(e) => e.stopPropagation()}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === 'Enter') commit();\n if (e.key === 'Escape') {\n settled.current = true;\n onCancel();\n }\n }}\n onBlur={commit}\n placeholder={placeholder}\n aria-label={placeholder}\n className=\"mx-2 mb-1 w-[calc(100%-1rem)] rounded-md bg-white dark:bg-white/10 px-2 py-1 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]\"\n />\n );\n};\n\nconst WorkspaceGroupSection = ({\n workspace,\n count,\n open,\n toggleable,\n pending,\n onToggle,\n onNewChat,\n onRename,\n onDelete,\n onDropConversation,\n t,\n children,\n}: {\n /** `null` for the conversations filed where the list does not reach. */\n workspace: ChatWorkspace | null;\n count: number;\n open: boolean;\n /** False while the group is held open (a search, the conversation on screen). */\n toggleable: boolean;\n /** A new conversation is about to be created in this workspace. */\n pending: boolean;\n onToggle: () => void;\n onNewChat: (workspaceId: string) => void;\n onRename: (id: string, name: string) => void;\n onDelete: (id: string) => void;\n onDropConversation: (conversationId: string) => void;\n t: (key: string) => string;\n children: ReactNode;\n}) => {\n const [renaming, setRenaming] = useState(false);\n const [confirmingDelete, setConfirmingDelete] = useState(false);\n const manageable = !!workspace?.canManage;\n const isMyDefault = !!workspace && workspace.isDefault && workspace.isOwn;\n\n return (\n <DropZone onDropConversation={onDropConversation} accepts={manageable} className=\"mb-0.5\">\n <div className=\"group/ws flex items-center gap-1 rounded-lg px-1.5 py-1 hover:bg-gray-100 dark:hover:bg-white/[0.06]\">\n {renaming && workspace ? (\n <NameField\n initial={workspace.name}\n placeholder={t('Workspace name')}\n onSubmit={(name) => {\n setRenaming(false);\n if (name && name !== workspace.name) onRename(workspace.id, name);\n }}\n onCancel={() => setRenaming(false)}\n />\n ) : (\n <button\n type=\"button\"\n onClick={onToggle}\n disabled={!toggleable}\n aria-expanded={open}\n className=\"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default\"\n >\n <ChevronRightIcon size={12} className={`shrink-0 text-gray-400 dark:text-white/30 transition-transform ${open ? 'rotate-90' : ''}`} />\n <FolderIcon size={14} className=\"shrink-0 text-[var(--chat-accent)]\" />\n <span className=\"truncate text-[0.8125rem] font-medium text-gray-800 dark:text-white/80\">\n {workspace ? workspace.name : t('Other workspaces')}\n </span>\n {isMyDefault && (\n <span className=\"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]\">{t('default')}</span>\n )}\n <span className=\"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums text-gray-400 dark:text-white/30\">{count}</span>\n </button>\n )}\n {workspace && manageable && !renaming && (\n <span className=\"flex shrink-0 items-center opacity-0 group-hover/ws:opacity-100 focus-within:opacity-100 transition-opacity\">\n {confirmingDelete ? (\n <>\n <span className=\"px-1 text-[0.65rem] text-red-600 dark:text-red-400\">{t('Delete?')}</span>\n <button\n type=\"button\"\n onClick={() => {\n setConfirmingDelete(false);\n onDelete(workspace.id);\n }}\n aria-label={t('Delete workspace')}\n className={`${iconButton} hover:text-red-500`}\n >\n <CheckIcon size={13} />\n </button>\n <button type=\"button\" onClick={() => setConfirmingDelete(false)} aria-label={t('Cancel')} className={iconButton}>\n <CloseIcon size={13} />\n </button>\n </>\n ) : (\n <>\n <Tooltip title={t('New conversation in this workspace')}>\n <button\n type=\"button\"\n onClick={() => onNewChat(workspace.id)}\n aria-label={t('New conversation in this workspace')}\n className={iconButton}\n >\n <EditIcon size={13} />\n </button>\n </Tooltip>\n <Tooltip title={t('Rename workspace')}>\n <button type=\"button\" onClick={() => setRenaming(true)} aria-label={t('Rename workspace')} className={iconButton}>\n <PencilIcon size={13} />\n </button>\n </Tooltip>\n {/* The default cannot be deleted: every person keeps one. */}\n {!workspace.isDefault && (\n <Tooltip title={t('Delete workspace')}>\n <button\n type=\"button\"\n onClick={() => setConfirmingDelete(true)}\n aria-label={t('Delete workspace')}\n className={`${iconButton} hover:text-red-500`}\n >\n <TrashIcon size={13} />\n </button>\n </Tooltip>\n )}\n </>\n )}\n </span>\n )}\n </div>\n {open && (\n <div className=\"space-y-0.5 pb-1 pl-3\">\n {pending && (\n <div className=\"flex items-center gap-2 rounded-lg bg-[var(--chat-accent)]/10 px-2.5 py-1.5 text-[0.75rem] text-[var(--chat-accent)]\">\n <EditIcon size={12} />\n {t('New conversation — send a message to start it')}\n </div>\n )}\n {children}\n </div>\n )}\n </DropZone>\n );\n};\n\nconst ConversationRow = ({\n conversation: c,\n isActive,\n isEditing,\n draftTitle,\n onDraftTitleChange,\n onCommitRename,\n onCancelRename,\n onStartRename,\n onSelect,\n onDelete,\n fileable,\n onMove,\n t,\n}: {\n conversation: ChatConversationSummary;\n isActive: boolean;\n isEditing: boolean;\n draftTitle: string;\n onDraftTitleChange: (title: string) => void;\n onCommitRename: () => void;\n onCancelRename: () => void;\n onStartRename?: (id: string, current: string) => void;\n onSelect: (id: string) => void;\n onDelete: (id: string) => void;\n /** Workspaces the row can be moved into; omitted when there are no workspaces. */\n fileable?: ChatWorkspace[];\n onMove: (conversationId: string, workspaceId: string | null) => void;\n t: (key: string) => string;\n}) => {\n const [moveOpen, setMoveOpen] = useState(false);\n const moveAnchor = useRef<HTMLButtonElement>(null);\n const movable = !!fileable && !isEditing;\n return (\n <div\n role=\"button\"\n tabIndex={0}\n aria-current={isActive}\n draggable={movable}\n onDragStart={\n movable\n ? (e) => {\n e.dataTransfer.setData(DRAG_TYPE, c.conversationId);\n e.dataTransfer.effectAllowed = 'move';\n }\n : undefined\n }\n onClick={() => onSelect(c.conversationId)}\n onKeyDown={(e) => {\n // Only the row's own keys: Enter or Space on the move, rename and\n // delete buttons inside it belongs to those buttons.\n if (e.target !== e.currentTarget) return;\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n onSelect(c.conversationId);\n }\n }}\n className={`group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors ${\n isActive ? 'bg-[var(--chat-accent)]/10' : 'hover:bg-gray-100 dark:hover:bg-white/[0.06]'\n }`}\n >\n <span\n className={`mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg ${\n isActive ? 'bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]' : 'bg-gray-100 dark:bg-white/[0.06] text-gray-400 dark:text-white/30'\n }`}\n >\n <BotIcon size={13} />\n </span>\n <span className=\"min-w-0 flex-1\">\n {isEditing ? (\n <input\n autoFocus\n value={draftTitle}\n onChange={(e) => onDraftTitleChange(e.target.value)}\n // The row selects on click and on Enter/Space; while editing\n // those belong to the field, not to navigation.\n onClick={(e) => e.stopPropagation()}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === 'Enter') onCommitRename();\n if (e.key === 'Escape') onCancelRename();\n }}\n onBlur={onCommitRename}\n aria-label={t('Conversation title')}\n className=\"w-full rounded-md bg-white dark:bg-white/10 px-1.5 py-0.5 text-[0.8125rem] text-gray-900 dark:text-white outline-hidden ring-1 ring-[var(--chat-accent)]\"\n />\n ) : (\n <span className={`block truncate text-[0.8125rem] ${isActive ? 'text-gray-900 dark:text-white' : 'text-gray-700 dark:text-white/70'}`}>\n {c.title || t('Untitled conversation')}\n </span>\n )}\n {/*\n Agent before time, on one line: which agent a thread is with\n is what tells two similarly-titled conversations apart, and\n knowing it before opening one is the point. Omitted entirely\n when the backend does not report it, rather than padded with\n a placeholder.\n */}\n {(c.agentName || c.updatedAt) && !isEditing && (\n <span className=\"block text-[0.65rem] text-gray-400 dark:text-white/30 truncate\">\n {c.agentName}\n {c.agentName && c.updatedAt ? ' · ' : ''}\n {c.updatedAt ? timeAgo(c.updatedAt, t) : ''}\n </span>\n )}\n </span>\n {!isEditing && (\n <span className=\"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity\">\n {movable && (\n <>\n <button\n ref={moveAnchor}\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n setMoveOpen((v) => !v);\n }}\n aria-label={t('Move to workspace')}\n title={t('Move to workspace')}\n aria-expanded={moveOpen}\n className=\"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]\"\n >\n <FolderInputIcon size={13} />\n </button>\n <Dropdown open={moveOpen} onClose={() => setMoveOpen(false)} anchorRef={moveAnchor} placement=\"bottom-end\" width={220}>\n <div className=\"py-1\" onClick={(e) => e.stopPropagation()}>\n <p className=\"px-3 pb-1 pt-1.5 text-[0.625rem] font-medium uppercase tracking-wide text-gray-400 dark:text-white/40\">\n {t('Move to workspace')}\n </p>\n {fileable.map((w) => (\n <button\n key={w.id}\n type=\"button\"\n disabled={w.id === c.workspaceId}\n onClick={() => {\n setMoveOpen(false);\n onMove(c.conversationId, w.id);\n }}\n className=\"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] text-gray-700 dark:text-white/80 hover:bg-gray-100 dark:hover:bg-white/10 disabled:opacity-40\"\n >\n <FolderIcon size={13} className=\"shrink-0 text-[var(--chat-accent)]\" />\n <span className=\"truncate\">{w.name}</span>\n {w.id === c.workspaceId && <CheckIcon size={12} className=\"ml-auto shrink-0\" />}\n </button>\n ))}\n <div className=\"my-1 h-px bg-gray-200 dark:bg-white/10\" />\n <button\n type=\"button\"\n disabled={!c.workspaceId}\n onClick={() => {\n setMoveOpen(false);\n onMove(c.conversationId, null);\n }}\n className=\"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] text-gray-700 dark:text-white/80 hover:bg-gray-100 dark:hover:bg-white/10 disabled:opacity-40\"\n >\n <CloseIcon size={13} className=\"shrink-0\" />\n {t('Remove from workspace')}\n </button>\n </div>\n </Dropdown>\n </>\n )}\n {onStartRename && (\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n onStartRename(c.conversationId, c.title || '');\n }}\n aria-label={t('Rename conversation')}\n title={t('Rename conversation')}\n className=\"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-[var(--chat-accent)]\"\n >\n <EditIcon size={13} />\n </button>\n )}\n <button\n type=\"button\"\n onClick={(e) => {\n // The row is the click target for selection, so deleting\n // must not also open the conversation on its way out.\n e.stopPropagation();\n onDelete(c.conversationId);\n }}\n aria-label={t('Delete conversation')}\n title={t('Delete conversation')}\n className=\"p-1 rounded-md text-gray-400 dark:text-white/30 hover:text-red-500 dark:hover:text-red-400\"\n >\n <TrashIcon size={13} />\n </button>\n </span>\n )}\n </div>\n );\n};\n","import { type FunctionComponent, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ChatArtifact, ChatArtifactKind, ChatAttachment, ChatPanelProps, Translate } from '../types';\nimport { artifactFileExtension, filenameFromContentDisposition, hexAlpha, identity } from '../utils';\nimport { feedbackBaseUrl } from '../utils/feedback';\nimport { conversationReferencesUrl } from '../utils/conversationRefs';\nimport { pendingWorkspaceStillFileable, returnRefreshDue } from '../utils/workspaces';\nimport { parseArtifact, parseContextUsage, parseRestoredMessages } from '../hooks/protocols/parseRestEvent';\nimport { useChat } from '../hooks/useChat';\nimport { useAgents } from '../hooks/useAgents';\nimport { useConversations } from '../hooks/useConversations';\nimport { useWorkspaces } from '../hooks/useWorkspaces';\nimport { useSidebarResize } from '../hooks/useSidebarResize';\nimport { useAwayCompletionNotice } from '../hooks/useAwayCompletionNotice';\nimport { useComposerExtras } from '../hooks/useComposerExtras';\nimport { useAgentSuggestions } from '../hooks/useAgentSuggestions';\nimport { useLatestCallback, useShallowStable } from '../hooks/useStableProps';\nimport { DefaultLogoIcon } from './icons';\nimport { ChatHeader } from './ChatHeader';\nimport { ChatInput } from './ChatInput';\nimport { ChatMessages } from './ChatMessages';\nimport { waitingGameUrl } from './ChatWaitingPanel';\nimport { ChatWelcome } from './ChatWelcome';\nimport { ConversationSidebar } from './ConversationSidebar';\n\nconst FLOATING_WIDTH = 380;\nconst FLOATING_HEIGHT = 560;\nconst SIDEBAR_GAP = 6;\n\n/**\n * Fallback suggestions, translated where they are written so extraction sees\n * the keys — the host's own list and the backend's are translated too (they may\n * be keys), but only these belong to the package.\n */\nconst defaultSuggestions = (t: Translate) => [\n t('Help me create a new simulation scenario'),\n t('What are the latest attack patterns?'),\n t('How do I configure detection rules?'),\n t('Summarize my recent findings'),\n];\n\nexport const ChatPanel: FunctionComponent<ChatPanelProps> = ({\n mode,\n onClose,\n onModeChange,\n topOffset = 0,\n apiBaseUrl,\n apiEndpoints: apiEndpointsProp,\n agentDashboardUrl,\n user,\n t = identity,\n accentColor = '#7b5cff',\n logoIcon,\n promptSuggestions: promptSuggestionsProp,\n draftBorderColor,\n resizable = false,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n disableFileManagement = false,\n onRelativeLinkClick: onRelativeLinkClickProp,\n onDownloadError: onDownloadErrorProp,\n maxFileCount,\n maxTotalSize,\n requestHeaders: requestHeadersProp,\n pageContext: pageContextProp,\n pushContentSelector,\n backendType = 'rest',\n miniGameEnabled = true,\n onPlayWaitingGame: onPlayWaitingGameProp,\n notifyOnComplete = true,\n onTaskComplete: onTaskCompleteProp,\n onMessageFeedback: onMessageFeedbackProp,\n locale,\n disableImagePreviews = false,\n contextUsageEnabled = true,\n composerToolbar,\n}) => {\n // Hosts tend to build these inline, so each host render hands the panel new\n // objects and functions with the same content. Held stable here, a host\n // render no longer re-renders every memoized message row, re-runs the effects\n // keyed on them (agent list, prompts, quota, suggestions, conversation list)\n // or refetches the images fetched with the headers. `t` passes through as is,\n // since a new one means new translations, and so do ReactNode props, which\n // cannot be compared.\n const apiEndpoints = useShallowStable(apiEndpointsProp);\n const requestHeaders = useShallowStable(requestHeadersProp);\n const pageContext = useShallowStable(pageContextProp);\n const promptSuggestions = useShallowStable(promptSuggestionsProp);\n const onRelativeLinkClick = useLatestCallback(onRelativeLinkClickProp);\n const onDownloadError = useLatestCallback(onDownloadErrorProp);\n const onPlayWaitingGame = useLatestCallback(onPlayWaitingGameProp);\n const onTaskComplete = useLatestCallback(onTaskCompleteProp);\n const onMessageFeedback = useLatestCallback(onMessageFeedbackProp);\n\n const [modeMenuOpen, setModeMenuOpen] = useState(false);\n\n const { agents, agentsLoading, agentsError, selectedAgent, agentMenuOpen, setAgentMenuOpen, handleSwitchAgent } = useAgents({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n\n const {\n messages,\n inputValue,\n setInputValue,\n isLoading,\n agentStatus,\n attachedFiles,\n conversationId,\n contextUsage,\n transferredAgent,\n canSteer,\n pendingApprovals,\n isSubmittingApproval,\n approvalError,\n submitApprovalDecisions,\n isResumingAfterDecision,\n historyReloadNonce,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n pendingWorkspaceId,\n clearPendingWorkspace,\n handleStopGenerating,\n conversationRefs,\n addConversationRef,\n setAttachedFiles,\n setMessages,\n setContextUsage,\n updateConversationId,\n handleSwitchConversation,\n } = useChat({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n agentSlug: selectedAgent?.slug,\n requestHeaders,\n pageContext,\n onRelativeLinkClick: onRelativeLinkClickProp ? onRelativeLinkClick : undefined,\n t,\n maxFileCount,\n maxTotalSize,\n });\n\n const { suggestions: agentSuggestions, loading: suggestionsLoading } = useAgentSuggestions({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n agentSlug: selectedAgent?.slug,\n });\n\n /**\n * Suggestions shown on the welcome screen, resolved to final text here rather\n * than in `ChatWelcome`: the backend's and the host's lists still go through\n * `t` (a host may well pass keys), while the package's own fallback is\n * translated at its definition so the keys stay extractable.\n */\n const suggestions = useMemo(\n () => (agentSuggestions ?? promptSuggestions)?.map((s) => t(s)) ?? defaultSuggestions(t),\n [agentSuggestions, promptSuggestions, t],\n );\n\n const { prompts, quota, refreshQuota } = useComposerExtras({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n\n const { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation, renameConversation, moveConversation } =\n useConversations({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n // Workspaces group the fullscreen list, when the host names their route.\n const { workspacesEnabled, workspaces, refreshWorkspaces, createWorkspace, renameWorkspace, deleteWorkspace } = useWorkspaces({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n // A pending workspace deleted, archived or unshared elsewhere leaves the\n // refreshed list: the next conversation must not be created in it.\n useEffect(() => {\n if (workspacesEnabled && pendingWorkspaceId && !pendingWorkspaceStillFileable(pendingWorkspaceId, workspaces)) {\n clearPendingWorkspace(pendingWorkspaceId);\n }\n }, [workspacesEnabled, workspaces, pendingWorkspaceId, clearPendingWorkspace]);\n const [historyMenuOpen, setHistoryMenuOpen] = useState(false);\n\n // Fullscreen shows the conversation list permanently, so it has to be\n // fetched on entry rather than lazily when a menu opens. Kept collapsible:\n // fullscreen is also the mode people use to read a long answer.\n const [sidebarCollapsed, setSidebarCollapsed] = useState(false);\n const showConversationSidebar = mode === 'fullscreen' && historyEnabled;\n\n // Re-read on entry AND whenever the active conversation changes, so a chat\n // created by the first send appears in the list. The header menu could fetch\n // lazily on open; a permanent list has no such moment, and a stale sidebar\n // that never shows the conversation you are in is worse than no sidebar.\n useEffect(() => {\n if (showConversationSidebar) void refreshConversations();\n }, [showConversationSidebar, conversationId, refreshConversations]);\n\n // The workspaces are also changed elsewhere (the XTM One web chat, another\n // tab): read on entry, after every write the sidebar makes (the hook\n // re-reads them), on each conversation switch, at the end of each turn and\n // on each return to the page - a group deleted there must not linger here.\n useEffect(() => {\n if (showConversationSidebar) void refreshWorkspaces();\n }, [showConversationSidebar, conversationId, refreshWorkspaces]);\n\n // Back to the page (from the XTM One tab, say): both lists may have moved.\n const lastReturnRefreshRef = useRef<number | null>(null);\n useEffect(() => {\n if (!showConversationSidebar) return;\n const onReturn = () => {\n if (document.visibilityState !== 'visible') return;\n const now = Date.now();\n if (!returnRefreshDue(now, lastReturnRefreshRef.current)) return;\n lastReturnRefreshRef.current = now;\n void refreshConversations();\n void refreshWorkspaces();\n };\n document.addEventListener('visibilitychange', onReturn);\n window.addEventListener('focus', onReturn);\n return () => {\n document.removeEventListener('visibilitychange', onReturn);\n window.removeEventListener('focus', onReturn);\n };\n }, [showConversationSidebar, refreshConversations, refreshWorkspaces]);\n\n // A finished turn has consumed allowance and may have retitled the chat.\n const wasLoadingRef = useRef(false);\n useEffect(() => {\n if (wasLoadingRef.current && !isLoading) {\n refreshQuota();\n // The backend titles a conversation from its first message, so the row\n // stays \"New conversation\" until the turn is read back. A conversation\n // that could not be created in its workspace (deleted elsewhere) is\n // read back unfiled: the workspaces are re-read with it.\n if (showConversationSidebar) {\n void refreshConversations();\n void refreshWorkspaces();\n }\n }\n wasLoadingRef.current = isLoading;\n }, [isLoading, refreshQuota, showConversationSidebar, refreshConversations, refreshWorkspaces]);\n\n const handleHistoryMenuToggle = () => {\n // Computed from the committed state in the event handler — NOT inside the\n // state updater, which must stay pure (StrictMode/concurrent rendering may\n // invoke updaters more than once, which would duplicate the fetch).\n const next = !historyMenuOpen;\n if (next) {\n // Fetch lazily on open so the list reflects the latest server state\n // (titles are rewritten by the backend after the first message).\n void refreshConversations();\n }\n setHistoryMenuOpen(next);\n };\n\n const handleSelectConversation = (id: string) => {\n setHistoryMenuOpen(false);\n handleSwitchConversation(id);\n };\n\n // The `@` conversation menu of the composer, when the host names its route.\n const conversationReferencesSearchUrl = conversationReferencesUrl(apiBaseUrl, apiEndpoints, backendType);\n\n // A referenced conversation's chip opens it in the panel when it is one the\n // conversation list holds, so the list is read as soon as the thread shows\n // a reference - not only once the history menu has been opened - and again\n // for each conversation switched to, whose chips may name newer ones.\n const openableConversationIds = useMemo(() => new Set(conversations.map((c) => c.conversationId)), [conversations]);\n const onOpenConversation = useLatestCallback(historyEnabled ? handleSelectConversation : undefined);\n const threadReferencesConversations = messages.some((m) => (m.conversationRefs?.length ?? 0) > 0);\n useEffect(() => {\n if (threadReferencesConversations && historyEnabled) void refreshConversations();\n }, [threadReferencesConversations, historyEnabled, refreshConversations, conversationId]);\n\n const handleDeleteConversation = async (id: string) => {\n const deleted = await deleteConversation(id);\n // Deleting the active conversation resets to a fresh chat so the next\n // message doesn't target a dead conversation id.\n if (deleted && id === conversationIdRef.current) {\n handleNewChat();\n }\n };\n\n const { sidebarWidth, handleResizeStart, defaultWidth, isResizing } = useSidebarResize({\n mode,\n resizable,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n });\n\n // Push content when sidebar mode is active using CSS variable\n useEffect(() => {\n const width = mode === 'sidebar' ? (resizable ? sidebarWidth : defaultWidth) : 0;\n const pushWidth = width > 0 ? width + SIDEBAR_GAP : 0;\n\n // Set CSS variable on :root for any component to use\n document.documentElement.style.setProperty('--chatbot-sidebar-width', `${pushWidth}px`);\n document.documentElement.style.setProperty('--chatbot-transition', isResizing ? 'none' : 'all 225ms cubic-bezier(0.4, 0, 0.2, 1)');\n\n // Also apply to pushContentSelector if provided (for simple cases)\n if (pushContentSelector) {\n const contentElement = document.querySelector<HTMLElement>(pushContentSelector);\n if (contentElement) {\n const originalPaddingRight = contentElement.style.paddingRight;\n const originalTransition = contentElement.style.transition;\n\n contentElement.style.paddingRight = pushWidth > 0 ? `${pushWidth}px` : '';\n contentElement.style.transition = isResizing ? 'none' : 'padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)';\n\n return () => {\n contentElement.style.paddingRight = originalPaddingRight;\n contentElement.style.transition = originalTransition;\n document.documentElement.style.setProperty('--chatbot-sidebar-width', '0px');\n };\n }\n }\n\n return () => {\n document.documentElement.style.setProperty('--chatbot-sidebar-width', '0px');\n };\n }, [pushContentSelector, mode, sidebarWidth, defaultWidth, resizable, isResizing]);\n\n // Stable across renders so the memoized message rows (which take it as a\n // prop) aren't invalidated on every streamed frame.\n const resolvedLogo = useMemo(() => logoIcon ?? <DefaultLogoIcon size={24} />, [logoIcon]);\n const playUrl = useMemo(() => waitingGameUrl(agentDashboardUrl), [agentDashboardUrl]);\n const firstName = user.firstName;\n /**\n * The agent a *restored* conversation belongs to, as the backend reports it.\n *\n * Sits between the live transfer and the menu selection on purpose. Reopening\n * a past thread used to relabel it — and its new replies — with whichever\n * agent was selected, while the backend went on routing the conversation to\n * its own stored agent. The label named someone who had not spoken. This is\n * the same agent that will answer, so the two now agree.\n */\n const [conversationAgentName, setConversationAgentName] = useState<string | null>(null);\n const agentName = transferredAgent?.name || conversationAgentName || selectedAgent?.name || t('Assistant');\n\n // \"Viewing the chat\" must mean the panel is on screen in the active tab —\n // NOT that an element inside it currently holds focus. In sidebar (and\n // floating) mode the user routinely reads a streamed answer while their focus\n // stays in the host app, so the previous focus-within test\n // (`document.activeElement.closest('.filigran-chatbot.fixed')`) wrongly\n // classified them as \"not viewing\" and fired a redundant completion toast for\n // an answer sitting right in front of them. The host mounts `<ChatPanel/>`\n // only while the widget is open, so a mounted + visible panel root means the\n // answer is visible to the user; the notifier still treats a hidden tab or an\n // unfocused window as \"away\" and notifies there. A host that keeps the panel\n // mounted but `display:none` while \"closed\" is likewise reported as not\n // viewing (checkVisibility() === false), so completion still notifies. The\n // `.fixed` qualifier targets the panel root, never the toggle button (which\n // carries `.filigran-chatbot` alone). Stable reference (useCallback) so the\n // notifier's effect doesn't re-run on every render — the panel re-renders\n // frequently while a response streams; the DOM is queried live on each call.\n const isViewingChat = useCallback(() => {\n if (typeof document === 'undefined') return false;\n const panel = document.querySelector('.filigran-chatbot.fixed') as (HTMLElement & { checkVisibility?: () => boolean }) | null;\n if (!panel) return false;\n if (typeof panel.checkVisibility === 'function') return panel.checkVisibility();\n // Fallback for browsers without Element.checkVisibility(): a display:none\n // panel generates no layout box, so an empty client-rect list means hidden\n // (works for the position:fixed root, whose offsetParent is null even when\n // shown). Erring toward \"not viewing\" keeps the documented closed/hidden\n // path notifying instead of silently swallowing the notice on older engines.\n return panel.getClientRects().length > 0;\n }, []);\n\n // Notify when a long turn finishes and the user is not watching the chat —\n // away (tab hidden / another window / panel closed-or-hidden). An open,\n // on-screen panel in the focused tab counts as watching, so no toast fires\n // for an answer the user can already see.\n useAwayCompletionNotice({\n isLoading,\n agentName,\n t,\n enabled: notifyOnComplete,\n onComplete: onTaskComplete,\n isViewingChat,\n });\n\n // Download an agent-generated file. The URL is resolved against the host\n // app's own backend proxy (apiBaseUrl), NOT the upstream chat service:\n // the proxy mints any upstream token server-side, so the user stays\n // authenticated to the host platform (e.g. OpenCTI / OpenAEV) only and\n // never logs in to the upstream service. Same-origin cookies +\n // requestHeaders (CSRF / draft context) carry the host-app auth.\n // Downloads need a path to build the URL from. Enabled for the REST\n // backend unless explicitly disabled (`download === null`). In\n // single-endpoint mode there is no per-path routing, so a download path\n // must be provided explicitly (e.g. an OpenCTI-style proxy route);\n // otherwise the default REST `/chat/files` path is used.\n const downloadPathProvided = apiEndpoints?.download !== null && apiEndpoints?.download !== undefined;\n const canDownload = backendType === 'rest' && apiEndpoints?.download !== null && (!apiEndpoints?.singleEndpoint || downloadPathProvided);\n\n // The host-proxied URL of an attachment. Shared by the download action and\n // the inline image preview so both resolve against the same proxy route.\n const resolveAttachmentUrl = useCallback(\n (att: ChatAttachment) => {\n const base = apiEndpoints?.download ?? '/chat/files';\n return `${apiBaseUrl}${base}/${encodeURIComponent(att.fileId)}/download`;\n },\n [apiBaseUrl, apiEndpoints],\n );\n\n const handleDownloadFile = useCallback(\n async (att: ChatAttachment) => {\n const url = resolveAttachmentUrl(att);\n try {\n const res = await fetch(url, {\n method: 'GET',\n credentials: 'include',\n headers: { ...(requestHeaders ?? {}) },\n });\n if (!res.ok) throw new Error(`Download failed: ${res.status}`);\n const blob = await res.blob();\n const objectUrl = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = objectUrl;\n link.download = att.filename || 'download';\n document.body.appendChild(link);\n link.click();\n link.remove();\n URL.revokeObjectURL(objectUrl);\n } catch (err) {\n // Surface the failure (403/404/5xx/network) to the host so it can\n // notify the user — the chatbot has no toast surface of its own.\n // If the host doesn't provide a handler the error is intentionally\n // not thrown further (a rejected click handler has nowhere to go).\n onDownloadError?.(err, att);\n }\n },\n [resolveAttachmentUrl, requestHeaders, onDownloadError],\n );\n\n // The decks, reports and videos an answer made are downloaded and followed\n // through the host's proxy too, once the host names the route\n // (`apiEndpoints.artifacts`, no default). Without it the cards still show\n // and link to XTM One.\n const artifactsBase = backendType === 'rest' && apiEndpoints?.artifacts ? `${apiBaseUrl}${apiEndpoints.artifacts}` : null;\n const artifactUrl = useCallback(\n (kind: ChatArtifactKind, id: string) => `${artifactsBase}/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`,\n [artifactsBase],\n );\n\n const handleDownloadArtifact = useCallback(\n async (artifact: ChatArtifact, format: string) => {\n const fallbackName = `${artifact.title || artifact.kind}.${artifactFileExtension(format)}`;\n try {\n const res = await fetch(`${artifactUrl(artifact.kind, artifact.id)}/download`, {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({ format }),\n });\n if (!res.ok) throw new Error(`Download failed: ${res.status}`);\n const blob = await res.blob();\n const objectUrl = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = objectUrl;\n link.download = filenameFromContentDisposition(res.headers.get('content-disposition')) ?? fallbackName;\n document.body.appendChild(link);\n link.click();\n link.remove();\n URL.revokeObjectURL(objectUrl);\n } catch (err) {\n // The host's notification path for a failed download, named after the\n // file the user asked for.\n onDownloadError?.(err, { fileId: artifact.id, filename: fallbackName, type: format.toUpperCase() });\n }\n },\n [artifactUrl, requestHeaders, onDownloadError],\n );\n\n const handleRefreshArtifact = useCallback(\n async (kind: ChatArtifactKind, id: string) => {\n const res = await fetch(artifactUrl(kind, id), { credentials: 'include', headers: { ...(requestHeaders ?? {}) } });\n if (!res.ok) return undefined;\n return parseArtifact(await res.json());\n },\n [artifactUrl, requestHeaders],\n );\n\n const cssVars = {\n '--chat-accent': accentColor,\n '--chat-accent-10': hexAlpha(accentColor, 0.1),\n '--chat-accent-40': hexAlpha(accentColor, 0.25),\n '--chat-accent-50': hexAlpha(accentColor, 0.5),\n '--chat-accent-dark': accentColor,\n } as React.CSSProperties;\n\n // Tracks whether this panel is still mounted. Flipped to false ONLY on a\n // real unmount (empty-deps cleanup) — never on the benign teardowns that an\n // inline `apiEndpoints` / `requestHeaders` prop churn or a StrictMode\n // double-invoke trigger. The restore effect below reads it so an in-flight\n // `/chat/sessions` response that outlives the panel — the host renders\n // `<ChatPanel />` conditionally and the user closes it mid-request — can't\n // call `setMessages` / `updateConversationId` after unmount, while a restore\n // merely interrupted by a re-render still lands. Re-set to true on setup so\n // StrictMode's mount → unmount → remount of the same instance leaves it true.\n const isMountedRef = useRef(true);\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n // Load conversation history when agent is selected\n useEffect(() => {\n // Skip session history if disabled, using single endpoint mode, or non-REST backend\n if (apiEndpoints?.sessions === null || apiEndpoints?.singleEndpoint || backendType === 'legacy' || backendType === 'ag-ui') return;\n // No conversation means a fresh chat — \"New conversation\", or an agent\n // switch, both of which null the id. Drop the restored thread's agent with\n // it, or the new chat would keep wearing the old one's name.\n if (!conversationId) {\n setConversationAgentName(null);\n return;\n }\n if (historyLoadedRef.current || !selectedAgent) return;\n historyLoadedRef.current = true;\n const sessionsUrl = `${apiBaseUrl}${apiEndpoints?.sessions ?? '/chat/sessions'}`;\n\n // The conversation this restore is being issued for. A host re-render that\n // churns an inline `apiEndpoints` / `requestHeaders` prop, or a React\n // StrictMode double-invoke, tears this effect down and re-runs it while the\n // request is still in flight — but the conversation itself hasn't changed.\n // We must NOT drop the restore in those benign cases (doing so left the\n // panel looking like a brand-new chat, randomly, on reload). Only a real\n // change — the user starting a new chat or switching agent, both of which\n // reset the id via `handleNewChat()` — should abandon the response, so it\n // can't resurrect a dead id or overwrite the freshly-started conversation.\n // Compare the live ref at apply time (not a blanket teardown flag) so the\n // legitimate restore always lands while a superseded one is still ignored —\n // and bail out entirely once the panel has actually unmounted, so a late\n // response can't write to localStorage / state after the panel is gone.\n const requestedConversationId = conversationId;\n const isStale = () => !isMountedRef.current || conversationIdRef.current !== requestedConversationId;\n\n fetch(sessionsUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...(requestHeaders ?? {}) },\n body: JSON.stringify({\n conversation_id: conversationId,\n agent_slug: selectedAgent.slug,\n supports_artifacts: true,\n }),\n })\n .then((res) => {\n if (isStale()) return null;\n if (!res.ok) {\n // Stale or invalid stored id (e.g. the platform was reset but the\n // browser kept an old id) — silently reset so a fresh conversation\n // is created on the next message instead of surfacing an error and\n // forcing the user to click \"New conversation\".\n updateConversationId(null);\n return null;\n }\n return res.json();\n })\n .then((data) => {\n if (!data || isStale()) return;\n // The backend resolves the session: it returns the same id when the\n // conversation still exists, or transparently creates a fresh one and\n // returns its NEW id when the stored id is stale. Adopt whatever id it\n // returns (and persist it) so we never send subsequent messages\n // against a dead conversation — which would 404 with\n // \"conversation does not exist\".\n if (typeof data.conversation_id === 'string' && data.conversation_id && data.conversation_id !== requestedConversationId) {\n updateConversationId(data.conversation_id);\n }\n // Null is meaningful and different from absent: it says the backend\n // knows this conversation has no agent (one predating per-conversation\n // routing), where a missing key means an older backend that cannot\n // tell us. Both land on the selected-agent fallback, but only the\n // first is a deliberate answer.\n setConversationAgentName(typeof data.agent_name === 'string' ? data.agent_name : null);\n if (!data.messages?.length) return;\n setMessages(parseRestoredMessages(data.messages));\n // The context gauge is conversation state, not per-message: the NEWEST\n // entry that carries a reading is the current occupancy. Scanned from\n // the end so a turn that predates the field (or a user message) falls\n // through to the last one that has it, rather than blanking the gauge.\n for (let i = data.messages.length - 1; i >= 0; i -= 1) {\n const usage = parseContextUsage(data.messages[i] as Record<string, unknown>);\n if (usage) {\n setContextUsage(usage);\n break;\n }\n }\n })\n .catch(() => {\n if (isStale()) return;\n updateConversationId(null);\n });\n }, [\n conversationId,\n selectedAgent,\n apiBaseUrl,\n apiEndpoints,\n backendType,\n // Re-runs the restore when the hook asks for one — the only way a turn\n // resumed without a stream can ever show its answer.\n historyReloadNonce,\n historyLoadedRef,\n conversationIdRef,\n isMountedRef,\n requestHeaders,\n setMessages,\n setContextUsage,\n updateConversationId,\n ]);\n\n const onSwitchAgent = (agent: typeof selectedAgent) => {\n if (!agent) return;\n handleSwitchAgent(agent, () => {\n handleNewChat();\n });\n };\n\n const containerClasses = (() => {\n const base = 'filigran-chatbot';\n switch (mode) {\n case 'sidebar':\n return `${base} fixed right-0 bottom-0 flex flex-col bg-white dark:bg-[#1e1e2e] border-l border-gray-200 dark:border-white/10 z-[1200]`;\n case 'floating':\n return `${base} fixed bottom-5 right-5 flex flex-col bg-white dark:bg-[#1e1e2e] rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border border-gray-200 dark:border-white/10`;\n case 'fullscreen':\n return `${base} fixed right-0 bottom-0 left-0 flex flex-col bg-gray-50 dark:bg-[#161622] z-[1400]`;\n default:\n return base;\n }\n })();\n\n const containerStyle: React.CSSProperties = {\n ...cssVars,\n ...(mode === 'sidebar'\n ? { top: topOffset, width: resizable ? sidebarWidth : defaultWidth }\n : mode === 'floating'\n ? { width: FLOATING_WIDTH, height: FLOATING_HEIGHT }\n : { top: topOffset }),\n };\n\n return (\n <div className={containerClasses} style={containerStyle}>\n {mode === 'sidebar' && resizable && (\n <div onMouseDown={handleResizeStart} className=\"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group\">\n <div className=\"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100\" />\n </div>\n )}\n <ChatHeader\n mode={mode}\n agentName={agentName}\n agents={agents}\n agentsLoading={agentsLoading}\n agentsError={agentsError}\n selectedAgent={selectedAgent}\n transferredFrom={transferredAgent ? selectedAgent?.name : undefined}\n agentMenuOpen={agentMenuOpen}\n onAgentMenuToggle={() => setAgentMenuOpen((p) => !p)}\n onAgentMenuClose={() => setAgentMenuOpen(false)}\n onSwitchAgent={onSwitchAgent}\n modeMenuOpen={modeMenuOpen}\n onModeMenuToggle={() => setModeMenuOpen((p) => !p)}\n onModeMenuClose={() => setModeMenuOpen(false)}\n onModeChange={onModeChange}\n onNewChat={handleNewChat}\n onClose={onClose}\n logoIcon={resolvedLogo}\n agentDashboardUrl={agentDashboardUrl}\n historyEnabled={historyEnabled && !showConversationSidebar}\n historyMenuOpen={historyMenuOpen}\n onHistoryMenuToggle={handleHistoryMenuToggle}\n onHistoryMenuClose={() => setHistoryMenuOpen(false)}\n conversations={conversations}\n conversationsLoading={conversationsLoading}\n activeConversationId={conversationId}\n onSelectConversation={handleSelectConversation}\n onDeleteConversation={(id) => void handleDeleteConversation(id)}\n t={t}\n />\n {/* Fullscreen puts the conversation list beside the thread. The header\n stays full width above both: it carries the agent picker, the mode\n switcher and close, which belong to the panel rather than to either\n column. `min-h-0` lets the thread scroll instead of growing the row. */}\n <div className={showConversationSidebar ? 'flex flex-1 min-h-0' : 'contents'}>\n {showConversationSidebar && (\n <ConversationSidebar\n conversations={conversations}\n loading={conversationsLoading}\n activeConversationId={conversationId}\n collapsed={sidebarCollapsed}\n onToggleCollapsed={() => setSidebarCollapsed((v) => !v)}\n onSelect={handleSelectConversation}\n onDelete={(id) => void handleDeleteConversation(id)}\n onRename={(id, title) => void renameConversation(id, title)}\n onNewChat={handleNewChat}\n workspaces={\n workspacesEnabled\n ? {\n list: workspaces,\n pendingWorkspaceId,\n onCreate: createWorkspace,\n onRename: renameWorkspace,\n onDelete: async (id) => {\n const result = await deleteWorkspace(id);\n if (result.ok) {\n // The next conversation must not be created in it.\n clearPendingWorkspace(id);\n // Its conversations are back in no workspace (`workspace_id: null`).\n void refreshConversations();\n }\n return result;\n },\n onMove: moveConversation,\n onNewChat: (workspaceId) => {\n handleNewChat(workspaceId);\n // Still there? Deleted elsewhere, the list drops it and\n // the pending workspace with it, before the first send.\n void refreshWorkspaces();\n },\n }\n : undefined\n }\n t={t}\n />\n )}\n <div className={showConversationSidebar ? 'flex flex-1 flex-col min-w-0' : 'contents'}>\n {messages.length === 0 ? (\n <ChatWelcome\n firstName={firstName}\n logoIcon={resolvedLogo}\n // The agent's own suggestions when the backend serves them, the\n // host's list otherwise, this package's list when there is neither —\n // never an empty section.\n promptSuggestions={suggestions}\n suggestionsLoading={suggestionsLoading}\n agentName={selectedAgent?.name}\n agentDescription={selectedAgent?.description}\n onPromptClick={setInputValue}\n t={t}\n />\n ) : (\n <ChatMessages\n messages={messages}\n isLoading={isLoading}\n agentStatus={agentStatus}\n agentName={agentName}\n logoIcon={resolvedLogo}\n onRelativeLinkClick={onRelativeLinkClick}\n onDownloadFile={canDownload ? handleDownloadFile : undefined}\n resolveAttachmentUrl={canDownload && !disableImagePreviews ? resolveAttachmentUrl : undefined}\n onDownloadArtifact={artifactsBase ? handleDownloadArtifact : undefined}\n onRefreshArtifact={artifactsBase ? handleRefreshArtifact : undefined}\n requestHeaders={requestHeaders}\n miniGameEnabled={miniGameEnabled}\n onPlayWaitingGame={onPlayWaitingGame}\n waitingGameUrl={playUrl}\n onMessageFeedback={onMessageFeedback}\n feedbackUrl={feedbackBaseUrl(apiBaseUrl, apiEndpoints, backendType)}\n conversationId={conversationId}\n locale={locale}\n isResumingAfterDecision={isResumingAfterDecision}\n pendingApprovals={pendingApprovals}\n onSubmitApprovalDecisions={submitApprovalDecisions}\n isSubmittingApproval={isSubmittingApproval}\n approvalError={approvalError}\n openableConversationIds={openableConversationIds}\n onOpenConversation={onOpenConversation}\n t={t}\n />\n )}\n <ChatInput\n inputValue={inputValue}\n onInputChange={setInputValue}\n onSend={handleSendMessage}\n onStop={handleStopGenerating}\n isLoading={isLoading}\n canSteer={canSteer}\n attachedFiles={disableFileManagement ? [] : attachedFiles}\n onFileAdd={disableFileManagement ? undefined : handleFileAdd}\n onFileRemove={disableFileManagement ? undefined : (i) => setAttachedFiles((prev) => prev.filter((_, j) => j !== i))}\n onPaste={disableFileManagement ? undefined : handlePaste}\n t={t}\n mode={mode}\n separatorColor={draftBorderColor}\n prompts={prompts}\n quota={quota}\n contextUsage={contextUsageEnabled ? contextUsage : null}\n composerToolbar={composerToolbar}\n conversationReferences={\n conversationReferencesSearchUrl\n ? { url: conversationReferencesSearchUrl, requestHeaders, conversationId, refs: conversationRefs, onPick: addConversationRef }\n : undefined\n }\n />\n </div>\n </div>\n </div>\n );\n};\n","import { useCallback, useRef, useState } from 'react';\nimport type { ApiEndpoints, BackendType, ChatWorkspace } from '../types';\nimport { isTransientListFailure, parseWorkspaces, refusalMessage } from '../utils/workspaces';\n\ninterface UseWorkspacesOptions {\n apiBaseUrl: string;\n apiEndpoints?: ApiEndpoints;\n backendType?: BackendType;\n requestHeaders?: Record<string, string>;\n}\n\n/** What a workspace write answered: done, or the backend's reason. */\nexport type WorkspaceWriteResult = { ok: true; workspace?: ChatWorkspace } | { ok: false; error: string | null };\n\ninterface UseWorkspacesReturn {\n /** The host named the route (`apiEndpoints.workspaces`) and the backend answered the list. */\n workspacesEnabled: boolean;\n workspaces: ChatWorkspace[];\n refreshWorkspaces: () => Promise<void>;\n createWorkspace: (name: string) => Promise<WorkspaceWriteResult>;\n renameWorkspace: (id: string, name: string) => Promise<WorkspaceWriteResult>;\n deleteWorkspace: (id: string) => Promise<WorkspaceWriteResult>;\n}\n\n/**\n * The caller's workspaces, which the conversation list is grouped by.\n *\n * Off unless the host names `apiEndpoints.workspaces` (see its doc: no\n * default). A backend that refuses the list - not licensed, an older proxy -\n * also leaves it off, so the history stays the flat list it always was.\n */\nexport function useWorkspaces({ apiBaseUrl, apiEndpoints, backendType = 'rest', requestHeaders }: UseWorkspacesOptions): UseWorkspacesReturn {\n const [workspaces, setWorkspaces] = useState<ChatWorkspace[]>([]);\n const [answered, setAnswered] = useState(false);\n // Refreshes overlap (after each write, on remount): only the latest answers.\n const latestRef = useRef(0);\n\n const path = apiEndpoints?.workspaces;\n const configured = backendType === 'rest' && !apiEndpoints?.singleEndpoint && typeof path === 'string' && path.length > 0;\n const url = configured ? `${apiBaseUrl}${path}` : null;\n\n const refreshWorkspaces = useCallback(async () => {\n if (!url) return;\n const ticket = ++latestRef.current;\n try {\n const res = await fetch(url, { method: 'GET', headers: { ...(requestHeaders ?? {}) } });\n if (ticket !== latestRef.current) return;\n if (!res.ok) {\n // A passing failure keeps the last list: emptying it would turn the\n // grouped history flat until remount. Only a refusal turns it off.\n if (!isTransientListFailure(res.status)) {\n setAnswered(false);\n setWorkspaces([]);\n }\n return;\n }\n const list = parseWorkspaces(await res.json());\n if (ticket !== latestRef.current) return;\n setWorkspaces(list);\n setAnswered(true);\n } catch {\n // A network failure or an unreadable body: keep the last list.\n }\n }, [url, requestHeaders]);\n\n const write = useCallback(\n async (method: 'POST' | 'PATCH' | 'DELETE', target: string, body?: Record<string, unknown>): Promise<WorkspaceWriteResult> => {\n try {\n const res = await fetch(target, {\n method,\n headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...(requestHeaders ?? {}) },\n ...(body ? { body: JSON.stringify(body) } : {}),\n });\n if (!res.ok) return { ok: false, error: await refusalMessage(res) };\n const created = res.status === 204 ? [] : parseWorkspaces([await res.json().catch(() => null)]);\n await refreshWorkspaces();\n return { ok: true, workspace: created[0] };\n } catch {\n return { ok: false, error: null };\n }\n },\n [requestHeaders, refreshWorkspaces],\n );\n\n const createWorkspace = useCallback(\n async (name: string) => (url ? write('POST', url, { name: name.trim() }) : { ok: false as const, error: null }),\n [url, write],\n );\n const renameWorkspace = useCallback(\n async (id: string, name: string) =>\n url ? write('PATCH', `${url}/${encodeURIComponent(id)}`, { name: name.trim() }) : { ok: false as const, error: null },\n [url, write],\n );\n const deleteWorkspace = useCallback(\n async (id: string) => (url ? write('DELETE', `${url}/${encodeURIComponent(id)}`) : { ok: false as const, error: null }),\n [url, write],\n );\n\n return {\n workspacesEnabled: configured && answered,\n workspaces,\n refreshWorkspaces,\n createWorkspace,\n renameWorkspace,\n deleteWorkspace,\n };\n}\n","import type { FunctionComponent } from 'react';\nimport type { ChatToggleButtonProps } from '../types';\nimport { hexAlpha, identity } from '../utils';\nimport { DefaultLogoIcon } from './icons';\n\nexport const ChatToggleButton: FunctionComponent<ChatToggleButtonProps> = ({\n isOpen,\n onToggle,\n label,\n accentColor = '#7b5cff',\n icon,\n t = identity,\n}) => {\n const resolvedIcon = icon ?? <DefaultLogoIcon size={16} />;\n\n return (\n <button\n type=\"button\"\n onClick={onToggle}\n className=\"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors\"\n style={{\n borderColor: isOpen ? accentColor : hexAlpha(accentColor, 0.5),\n color: accentColor,\n backgroundColor: isOpen ? hexAlpha(accentColor, 0.1) : 'transparent',\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.borderColor = accentColor;\n e.currentTarget.style.backgroundColor = hexAlpha(accentColor, 0.1);\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.borderColor = isOpen ? accentColor : hexAlpha(accentColor, 0.5);\n e.currentTarget.style.backgroundColor = isOpen ? hexAlpha(accentColor, 0.1) : 'transparent';\n }}\n >\n <span className=\"[&>svg]:w-4 [&>svg]:h-4\">{resolvedIcon}</span>\n {label ?? t('Ask Assistant')}\n </button>\n );\n};\n"],"names":["hexAlpha","hex","alpha","Math","round","toString","padStart","prepareMarkdown","content","raw","lines","split","fenceRe","markupLang","openerIdx","i","length","m","match","test","trim","fences","push","idx","run","bare","blankBetween","a","b","k","depth","maxRun","nestedCount","closerIdx","j","f","next","max","fence","repeat","om","cm","join","hardenNestedCodeFences","indexOf","splitCells","row","s","startsWith","slice","endsWith","cells","current","ch","isDelimiterRow","includes","alignOf","cell","c","left","right","fenceChar","fenceLen","listMarkerRe","fenceMatch","header","delim","markerMatch","offset","trimStart","indent","headerCols","delimCells","aligns","normalizeMarkdownTables","trimmed","JSON","parse","wrapBareJson","replace","_match","alt","url","SAFE_URL_PROTOCOLS","Set","markdownUrlTransform","colon","slash","question","hash","protocol","toLowerCase","has","identity","key","translate","t","values","slot","name","Object","hasOwn","String","findChatbotRoot","el","node","classList","contains","parentElement","document","body","compactCount","n","toFixed","timeAgo","iso","then","Date","getTime","Number","isNaN","diffMs","now","minutes","floor","count","hours","days","toLocaleDateString","undefined","month","day","ANSWER_MARKER_RE","PARTIAL_ANSWER_MARKER_RE","ANSWER_MARKER_HEADS","LONGEST_MARKER_HEAD","map","head","splitAnswerMarkers","streaming","parts","re","RegExp","source","lastIndex","exec","index","type","value","fileId","kind","id","slideRef","rest","tail","text","toUpperCase","some","withoutMarkerHead","artifactKey","artifactFacts","artifact","slideCount","sectionCount","sceneCount","duration","ms","total","formatVideoDuration","durationMs","ratingOf","feedbackModeOf","serverId","feedbackUrl","conversationId","hasCallback","normalizeFeedbackComment","comment","feedbackBaseUrl","apiBaseUrl","apiEndpoints","backendType","singleEndpoint","feedback","async","submitFeedback","fetchImpl","baseUrl","messageId","rating","requestHeaders","init","encodeURIComponent","method","credentials","headers","stringify","feedbackRequest","ok","isKeyChar","KEY_RE","referenceTokens","tokens","pruneConversationRefs","refs","kept","filter","r","referencedConversations","out","token","ref","parseReferenceCandidates","data","list","Array","isArray","conversations","o","title","updatedAt","updated_at","isOwn","is_own","conversationReferencesUrl","path","conversationReferences","EMPTY_REFERENCE_SEARCH","query","items","failed","rememberCandidates","seen","every","item","sameCandidate","ids","refAsCandidate","referenceMenuView","options","trigger","dismissed","search","referenced","exclude","known","local","candidate","q","words","Boolean","w","referenceMatches","merged","parseWorkspaces","workspaces","is_archived","isDefault","is_default","canManage","can_manage","sortWorkspaces","mine","sort","localeCompare","groupIsOpen","collapsed","group","activeConversationId","searching","groupCanToggle","refusalMessage","res","json","detail","BREAKDOWN_KEYS","parseContextUsage","evt","used","context_tokens","limit","context_window","isFinite","breakdown","src","any","wireKey","field","parseBreakdown","context_breakdown","parseAttachments","file_id","filename","size","contentType","content_type","fileTag","file_tag","ARTIFACT_KINDS","countOf","parseArtifact","find","slide_ref","slide_count","section_count","scene_count","duration_ms","status","progress","downloads","parseArtifacts","parseToolCallTrace","e","input","output","success","parseConversationRefs","conversation_id","parseTransferChain","agent_name","agentId","agent_id","agentName","parseToolApprovalProposals","p","toolCallId","tool_call_id","args","arguments","schema","input_schema","toolName","tool_name","toolDescription","tool_description","inputSchema","parseRestEvent","ctx","action","st","thinkingContent","hasUsedTools","tools","event","action_id","pageAction","requested","str","v","parsePageAction","actionId","elapsedS","elapsed_s","contextUsage","proposals","toolNames","tool_names","toolCallCount","tool_call_count","iterations","transferAgentId","transfer_agent_id","transferAgentName","transfer_agent_name","attachments","artifacts","reasoning","toolCallTrace","tool_call_trace","transferChain","transfer_chain","isTruncated","is_truncated","message_id","parsePersistedFeedback","parseLegacyEvent","eventType","nodeId","activeNodeId","usedTools","tool","chatId","parseAgUiEvent","message","stepName","delta","toolCallName","createSessionGate","generation","pending","controller","request","started","own","AbortController","promise","signal","catch","finally","abandon","abort","hostTakesPageActions","approveUrl","onNavigate","baseHref","doc","defaultView","location","href","window","toInternalHref","base","from","URL","origin","pathname","insidePanel","closest","SECRET_AUTOCOMPLETE","hover","view","ownerDocument","bubbles","cancelable","pointerType","Pointer","PointerEvent","MouseEvent","Mouse","dispatchEvent","withoutDefault","types","act","suppress","preventDefault","addEventListener","removeEventListener","clickOrRoute","matches","target","getAttribute","error","internal","focus","anchor","inAnchor","cancels","checkable","before","checked","click","Event","visible","details","summary","children","tagName","hidden","hasAttribute","style","getComputedStyle","display","visibility","menuShowing","expanded","menu","getElementById","openMenu","statesItself","Promise","resolve","tick","setTimeout","Observer","MutationObserver","globalThis","observer","records","addedNodes","disconnect","clearTimeout","timer","observe","documentElement","subtree","childList","addsContent","aborted","SEARCH_WORDS","performPageAction","get","isConnected","fieldset","legend","isDisabled","isTypeable","readOnly","isReadOnly","isSecretField","HTMLInputElement","HTMLTextAreaElement","proto","prototype","getOwnPropertyDescriptor","set","call","textContent","setValue","attr","form","querySelectorAll","entersSearch","Keyboard","KeyboardEvent","code","keyCode","which","down","defaultPrevented","requestSubmit","pressEnter","err","Error","TRUNCATION_MARKER","EXPLICIT_ROLES","wrapsControls","child","actionableRole","explicit","tag","headingLevel","spacedText","childNodes","nodeType","isSecret","clean","NAMED_BY_CONTENT","accessibleName","role","labelledBy","fromAttr","label","getElementsByTagName","l","htmlFor","querySelector","contents","placeholder","quote","states","disabledByFieldset","destination","loc","STORAGE_KEY","LEGACY_CHAT_ID_KEY","draftKey","persistDraft","sessionStorage","setItem","removeItem","draftRefsKey","loadDraftRefs","parsed","getItem","persistDraftRefs","loadDraftState","loadDraft","DEFAULT_MAX_TOTAL_SIZE","useChat","agentSlug","pageContext","onRelativeLinkClick","maxFileCount","maxTotalSize","isLegacy","messages","setMessages","useState","isLoading","setIsLoading","agentStatus","setAgentStatus","setConversationId","localStorage","initialDraft","inputValue","setInputValue","conversationRefs","setConversationRefs","attachedFiles","setAttachedFiles","transferredAgent","setTransferredAgent","setContextUsage","pendingApprovals","setPendingApprovals","isSubmittingApproval","setIsSubmittingApproval","approvalError","setApprovalError","isResumingAfterDecision","setIsResumingAfterDecision","historyReloadNonce","setHistoryReloadNonce","resumeTick","setResumeTick","legacyChatId","setLegacyChatId","historyLoadedRef","useRef","abortControllerRef","pageActionControllerRef","streamDeltasRef","hasUsedToolsRef","conversationIdRef","isLoadingRef","pageContextRef","pageRefsRef","Map","onRelativeLinkClickRef","requestHeadersRef","approvalConversationIdRef","approvalDetachedRef","probedConversationRef","resumeDeadlineRef","sessionGate","pendingWorkspaceRef","pendingWorkspaceId","setPendingWorkspaceId","uploadAbortRef","effectiveMaxFileCount","effectiveMaxTotalSize","useEffect","prev","addConversationRef","useCallback","withConversationRef","pick","getSteerUrl","steer","getApproveUrl","approve","getApproveUrlRef","getPendingApprovalsUrl","convId","readPendingApprovals","fetch","turnRunning","turn","reloadHistory","getUploadUrl","upload","updateConversationId","ensureConversation","slug","sessionsUrl","sessions","isCurrent","workspaceId","agent_slug","workspace_id","uploadSingleFile","file","uploadUrl","formData","FormData","append","uploadHeaders","fromEntries","entries","file_ids","handleFileAdd","fileList","candidates","tempId","crypto","randomUUID","accepted","currentCount","currentSize","reduce","sum","slotsAvailable","sizeLeft","filtered","newEntries","rawFile","uploadStatus","DOMException","answerPageAction","conversationIdHint","refuse","page_action","snapshot","result","quietMs","maxMs","quiet","done","cap","attributes","characterData","waitForDomSettle","page","snapshotError","maxChars","budget","truncated","walk","level","line","takePageSnapshot","handleNewChat","workspace","close","draftFlushRef","state","setInterval","clearInterval","cancelled","canSteer","submitApprovalDecisions","decisions","d","decision","verdict","rejectionReason","rejection_reason","handlePaste","files","clipboardData","handleSendMessage","steerText","sentRefs","steerUrl","optimistic","timestamp","steerMessage","userMsg","turnGeneration","assistantId","currentAssistantId","accumulated","doneReceived","deltas","apply","textChanged","thinking","frame","closed","cancelFrame","cancelAnimationFrame","flush","changed","chunk","schedule","requestAnimationFrame","createStreamDeltas","segId","pageActions","fileIds","created","requestBody","opts","threadId","runId","context","forwardedProps","supportsToolApproval","supports_tool_approval","referencedConversationIds","referenced_conversation_ids","supportsPageActions","supports_page_actions","supports_artifacts","keys","serialized","buildRequestBody","parseEvent","getParser","reader","getReader","decoder","TextDecoder","buffer","ensureSegment","segmentId","read","decode","stream","pop","rawLine","jsonStr","elapsedStartMs","finalContent","completedAt","clearPendingWorkspace","handleStopGenerating","handleSwitchConversation","draft","STORAGE_AGENT_KEY","useAgents","agents","setAgents","agentsLoading","setAgentsLoading","agentsError","setAgentsError","selectedAgent","setSelectedAgent","agentMenuOpen","setAgentMenuOpen","agentsUrl","parseAgents","savedSlug","handleSwitchAgent","agent","onSwitch","parseConversation","created_at","messageCount","message_count","SIDEBAR_WIDTH","SIDEBAR_WIDTH_STORAGE_KEY","flashTimer","originalTitle","activeHooks","stopTitleFlash","useAwayCompletionNotice","enabled","onComplete","isViewingChat","wasLoadingRef","startRef","clearOnReturn","hasFocus","wasLoading","unfocused","away","viewingChat","showMessage","startTitleFlash","Notification","permission","notifyOS","useComposerExtras","prompts","setPrompts","quota","setQuota","restLike","promptsPath","quotaPath","promptsUrl","quotaUrl","rawList","description","parsePrompts","quotaNonce","setQuotaNonce","refreshQuota","period","scope","parseQuota","useAgentSuggestions","suggestions","setSuggestions","loading","setLoading","prompt","parseSuggestions","useShallowStable","is","hasOwnProperty","shallowEqual","useLatestCallback","callback","useInsertionEffect","stable","AlertTriangleIcon","className","_jsxs","xmlns","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","_jsx","ArrowRightLeftIcon","AttachFileIcon","BotIcon","x","y","rx","BrainIcon","CheckCircleIcon","cx","cy","CheckIcon","ChevronDownIcon","ChevronRightIcon","CloseIcon","CopyIcon","ry","DatabaseIcon","DefaultLogoIcon","DownloadIcon","points","x1","x2","y1","y2","EditIcon","ExternalLinkIcon","FileIcon","FloatingIcon","FolderIcon","FolderInputIcon","FolderPlusIcon","FullscreenExitIcon","FullscreenIcon","GamepadIcon","GlobeIcon","HistoryIcon","ImageIcon","InfoIcon","MailIcon","MaximizeIcon","MessageSquareIcon","MicIcon","MicOffIcon","PencilIcon","SearchIcon","SendIcon","SidebarIcon","SparklesIcon","StopCircleIcon","TerminalIcon","ThumbsDownIcon","filled","ThumbsUpIcon","TrashIcon","UserPlusIcon","SPEAKER","VolumeIcon","VolumeOffIcon","WrenchIcon","XCircleIcon","Dropdown","open","onClose","anchorRef","placement","panelRef","pos","setPos","top","stableOnClose","handler","active","listener","useClickOutside","useLayoutEffect","rect","getBoundingClientRect","panelHeight","offsetHeight","spaceBelow","innerHeight","bottom","spaceAbove","preferredLeft","min","innerWidth","portalTarget","createPortal","Spinner","tooltipMaxWidth","opening","maxRight","minLeft","Tooltip","tipRef","setOpening","setPlacement","below","shift","center","minTop","placeTooltip","panel","viewportWidth","tooltipOpening","onMouseEnter","onMouseLeave","onFocus","onBlur","maxWidth","modeOptions","mode","getIcon","ChatHeader","transferredFrom","onAgentMenuToggle","onAgentMenuClose","onSwitchAgent","modeMenuOpen","onModeMenuToggle","onModeMenuClose","onModeChange","onNewChat","logoIcon","agentDashboardUrl","historyEnabled","historyMenuOpen","onHistoryMenuToggle","onHistoryMenuClose","conversationsLoading","onSelectConversation","onDeleteConversation","agentAnchorRef","modeAnchorRef","historyAnchorRef","agentQuery","setAgentQuery","filteredAgents","useMemo","showAgentSearch","CurrentModeIcon","onClick","autoFocus","onChange","onKeyDown","_Fragment","conv","isActive","when","opt","useConversationReferenceSearch","setState","params","URLSearchParams","referenceSearchUrl","useConversationReferenceMenu","onTextChange","textareaRef","onPick","setTrigger","dismissedAnchor","setDismissedAnchor","activeIndex","setActiveIndex","pendingCaretRef","listboxId","useId","optionId","sync","activeElement","selectionStart","selectionEnd","textBeforeCaret","referenceTrigger","caret","setSelectionRange","setSeen","listed","complete","rememberAnswer","inserted","after","insertConversationReference","textareaAria","nativeEvent","isComposing","step","shiftKey","createDictationController","recognition","events","phase","startQueued","disposed","reported","isOn","report","onListeningChange","tryStart","start","onresult","finalText","interimText","resultIndex","results","isFinal","transcript","phrase","onFinal","onInterim","onerror","onend","toggle","stop","cancel","dispose","getSpeechRecognition","SpeechRecognition","webkitSpeechRecognition","SIZE","CIRCUMFERENCE","PI","ROWS","color","ContextUsageIndicator","usage","setOpen","ratio","pruning","compacting","ringColor","textColor","percent","counts","headline","rows","expandable","gauge","strokeDasharray","strokeDashoffset","transform","backgroundColor","borderRadius","ConversationReferenceMenu","onHover","listRef","scrollIntoView","block","heading","onMouseDown","onMouseMove","PromptPicker","setQuery","QuotaIndicator","quotaPeriodLabel","withScope","compact","exhausted","nearLimit","barColor","NO_REFS","ChatInput","onInputChange","onSend","onStop","onFileAdd","onFileRemove","onPaste","separatorColor","composerToolbar","fileInputRef","referenceMenu","revealEndRef","dictation","onFinalText","listening","setListening","interim","setInterim","controllerRef","onFinalTextRef","supported","Ctor","continuous","interimResults","lang","navigator","language","useDictation","trimEnd","scrollHeight","scrollTop","hasToolbar","isFileManagementEnabled","hasContent","hasFilesUploading","canSend","hasAttachments","hasReferences","showSteerSend","send","footerText","borderTopColor","borderTopWidth","multiple","onKeyUp","maxHeight","disabled","feedbackKeyOf","msg","parser","unified","use","remarkParse","remarkGfm","freeze","SILENT","inlineText","collectLines","FENCED_BLOCK_RE","speechSupported","speechSynthesis","SpeechSynthesisUtterance","useSpeechReader","locale","speakingId","setSpeakingId","localeRef","synth","createUtterance","finish","gen","speak","chunks","forEach","part","last","utterance","onEnd","onError","createSpeechController","documents","maxLength","sentences","pieces","sentence","word","piece","chunkSpeech","markdown","speakableText","FORMAT_OPTIONS","time","hour","minute","date","dateWithYear","year","full","dateStyle","timeStyle","formatters","formatter","cached","Intl","DateTimeFormat","browserTimers","clear","handle","KEYS_TOWARD_TOP","singleTouchY","touches","clientY","SCROLLING_OVERFLOW","KIND_ICONS","presentation","video","ACTION","ArtifactCard","onDownload","onRefresh","setCurrent","busyFormat","setBusyFormat","gaveUp","setGaveUp","following","isRenderInProgress","ask","intervalMs","forMs","onGiveUp","stopped","deadline","pollInTurn","fresh","Icon","kindLabel","artifactKindLabel","facts","renderLabel","videoRenderLabel","link","artifactLink","rel","format","artifactDownloadLabel","download","formatValue","useRevealIntoView","raf","behavior","inline","BUTTON_BASE","ApprovalCard","proposal","onDecide","rejecting","setRejecting","reason","setReason","reasonId","rejectPanelRef","argumentNames","decide","properties","entry","argumentSchema","ChatApprovalPrompt","onSubmit","isSubmitting","setDecisions","submitted","sent","setSent","busy","submit","all","decidedCount","allDecided","willRunAlways","footerRef","rootRef","decided","ImageLightbox","hostRef","closeButtonRef","root","setRoot","previouslyFocused","HTMLElement","preventScroll","stopPropagation","ChatImage","maxHeightClass","needsAuth","isRelativeUrl","blobUrl","setBlobUrl","errored","setErrored","setExpanded","objectUrl","blob","createObjectURL","revokeObjectURL","displaySrc","PLAY_CLASS","ChatWaitingPanel","onPlay","playUrl","keepEndInView","defaultMessages","reducedMotion","reduced","setReduced","matchMedia","mql","addListener","removeListener","usePrefersReducedMotion","msgIndex","setMsgIndex","animation","delegatingLabel","pollingLabel","collectingLabel","cleanReasoningText","ThinkingTextBubble","isOverflowing","setIsOverflowing","clientHeight","formatElapsed","seconds","useSustained","delayMs","firedKey","setFiredKey","ChatThinking","miniGameEnabled","onPlayWaitingGame","waitingGameUrl","StatusIcon","showDots","rawNames","lower","unique","consultName","targetName","resolveStatusVisual","nowMs","setNowMs","showElapsed","reasoningText","prose","end","cut","reverse","paragraph","reasoningWindowText","showReasoning","waitedWithoutReasoning","reasoningWentQuiet","showWaiting","delay","blockParser","holdsDefinition","lineStart","lastIndexOf","settlesBefore","endsIndented","MarkdownBlockSplitter","this","previous","blocks","starts","settled","firstDefinition","single","reuse","position","splitMarkdownBlocks","MarkdownRenderContext","createContext","copiedBlock","onCopyCode","MARKDOWN_COMPONENTS","pre","useContext","codeStr","ul","ol","li","strong","em","hr","blockquote","internalHref","routeInternally","openInNewTab","isRelativeHref","img","h1","h2","h3","table","tr","th","td","REMARK_PLUGINS","remarkBreaks","MarkdownBody","memo","Markdown","remarkPlugins","urlTransform","components","displayName","StreamedMarkdownBody","splitter","MarkdownMessage","setCopiedBlock","byBlocks","setByBlocks","processedContent","clipboard","writeText","renderContext","Provider","prettyTraceValue","toolDisplayName","ToolCallRow","inputDisplay","outputDisplay","hasInput","ReasoningDetailsDialog","dialogRef","dialog","focusable","first","totalCalls","transfers","trace","summaryParts","tn","parentOf","overflowYOf","overflowY","isControl","Element","fileExtensionLabel","dot","ext","IMAGE_EXTENSIONS","SHOWN_ON_HOVER","FOOTER_BUTTON","ACCENT_ON_HOVER","REVEALED_BUTTON","DIMMED_BUTTON","ACTIVE_BUTTON","MessageTime","getFullYear","getMonth","getDate","toISOString","formatMessageTime","dateTime","MessageCopyButton","copied","setCopied","MessageFeedbackButtons","locked","downRef","lockedId","inert","button","FeedbackComment","onSave","onSkip","setText","canSave","ctrlKey","metaKey","ReadAloudButton","speaking","onToggle","MessageRow","isStreaming","onDownloadFile","resolveAttachmentUrl","onDownloadArtifact","onRefreshArtifact","feedbackMode","onRate","onSaveComment","onSkipComment","canSpeak","isSpeaking","onToggleSpeech","openableConversationIds","onOpenConversation","setShowReasoning","isAssistant","isEmpty","commentOpen","wasCommentOpen","renderAttachmentCard","att","previewUrl","isImageAttachment","isWorking","sizeLabel","bytes","renderFileChip","renderArtifactCard","hasReasoningDetails","showActions","plainText","stripped","stripAnswerMarkers","speechDocuments","sources","answerMarkdownSources","shown","session","stored","speechKey","add","buildUserFileBlocks","chip","attByFileId","artifactsByKey","usedArtifacts","buildAssistantBlocks","timestampUnknown","ChatMessages","onMessageFeedback","onSubmitApprovalDecisions","scrollRef","renderWindow","setRenderWindow","feedbackEntries","rate","saveComment","skipComment","latest","seqRef","put","patch","seq","change","notify","useMessageFeedback","speech","follower","getBox","timers","lastTop","smooth","jumpToEnd","box","scrollTo","stopWaiting","arrived","reveal","keepUp","onScroll","movedUp","movedDown","distance","leave","createScrollFollower","touchAnchorRef","leaveFrom","container","innerBoxScrollsUp","firstMessageId","userMessageCount","seenRef","thinkingLen","hasEarlierMessages","visibleMessages","stopSpeech","spokenStillShown","speechScope","streamingMessageId","awaitingApproval","tabIndex","onWheel","deltaY","abs","deltaX","wheelScrollsUp","currentTarget","altKey","keyScrollsUp","isContentEditable","onPointerDown","press","onControl","onContainer","clientWidth","thumbBottom","pressTakesScrollbar","clientX","clientLeft","clientTop","onTouchStart","onTouchMove","anchorY","swipeScrollsUp","nextTouchAnchor","isStreamingMessage","Greeting","firstName","hasSlot","at","translateAround","ChatWelcome","promptSuggestions","onPromptClick","agentDescription","suggestionsLoading","fontFamily","DRAG_TYPE","COLLAPSED_KEY","readCollapsed","iconButton","sectionLabel","ConversationSidebar","onToggleCollapsed","onSelect","onDelete","onRename","editingId","setEditingId","draftTitle","setDraftTitle","settledRef","collapsedGroups","setCollapsedGroups","creatingWorkspace","setCreatingWorkspace","setError","startRename","commitRename","cancelRename","say","fallback","move","isNoopMove","refusal","onMove","grouped","held","byWorkspace","elsewhere","unfiled","groups","inside","groupConversations","fileable","fileableWorkspaces","unfiledNote","unfiledEmptyNote","renderRow","ConversationRow","conversation","isEditing","onDraftTitleChange","onCommitRename","onCancelRename","onStartRename","NameField","onCreate","onCancel","WorkspaceGroupSection","toggleable","toggleGroup","delete","onDropConversation","DropZone","accepts","over","setOver","carries","dataTransfer","onDragEnter","onDragOver","dropEffect","onDragLeave","onDrop","getData","initial","inputRef","select","commit","renaming","setRenaming","confirmingDelete","setConfirmingDelete","manageable","isMyDefault","moveOpen","setMoveOpen","moveAnchor","movable","draggable","onDragStart","setData","effectAllowed","ChatPanel","topOffset","apiEndpointsProp","user","accentColor","promptSuggestionsProp","draftBorderColor","resizable","onWidthChange","onResizeStart","onResizeEnd","disableFileManagement","onRelativeLinkClickProp","onDownloadError","onDownloadErrorProp","requestHeadersProp","pageContextProp","pushContentSelector","onPlayWaitingGameProp","notifyOnComplete","onTaskComplete","onTaskCompleteProp","onMessageFeedbackProp","disableImagePreviews","contextUsageEnabled","setModeMenuOpen","agentSuggestions","defaultSuggestions","refreshConversations","deleteConversation","renameConversation","moveConversation","setConversations","setConversationsLoading","history","revert","findIndex","revertMove","useConversations","workspacesEnabled","refreshWorkspaces","createWorkspace","renameWorkspace","deleteWorkspace","setWorkspaces","answered","setAnswered","latestRef","configured","ticket","write","useWorkspaces","pendingId","pendingWorkspaceStillFileable","setHistoryMenuOpen","sidebarCollapsed","setSidebarCollapsed","showConversationSidebar","lastReturnRefreshRef","onReturn","visibilityState","returnRefreshDue","handleSelectConversation","conversationReferencesSearchUrl","threadReferencesConversations","handleDeleteConversation","sidebarWidth","handleResizeStart","defaultWidth","isResizing","setSidebarWidth","parseInt","setIsResizing","isResizingRef","sidebarWidthRef","onWidthChangeRef","onResizeEndRef","handleMouseMove","newWidth","clamped","handleMouseUp","cursor","userSelect","handleWindowResize","useSidebarResize","pushWidth","setProperty","contentElement","originalPaddingRight","paddingRight","originalTransition","transition","resolvedLogo","xtmOneUrl","conversationAgentName","setConversationAgentName","checkVisibility","getClientRects","downloadPathProvided","canDownload","handleDownloadFile","createElement","appendChild","remove","artifactsBase","artifactUrl","handleDownloadArtifact","fallbackName","artifactFileExtension","extended","decodeURIComponent","plain","filenameFromContentDisposition","handleRefreshArtifact","cssVars","isMountedRef","requestedConversationId","isStale","createdAt","sentAt","conversation_refs","parseRestoredMessages","containerClasses","containerStyle","_","ChatToggleButton","isOpen","icon","resolvedIcon","borderColor"],"mappings":"2bAEM,SAAUA,EAASC,EAAaC,GAIpC,MAAO,GAAGD,IAHAE,KAAKC,MAAc,IAARF,GAClBG,SAAS,IACTC,SAAS,EAAG,MAEjB,CA+PM,SAAUC,EAAgBC,GAC9B,OA3OI,SAAiCC,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