@filigran/chatbot 3.7.2 → 3.7.4

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/hooks/protocols/parseRestEvent.ts","../../src/hooks/protocols/parseLegacyEvent.ts","../../src/hooks/protocols/parseAgUiEvent.ts","../../src/hooks/useChat.ts","../../src/hooks/useAgents.ts","../../src/hooks/useConversations.ts","../../src/hooks/useSidebarResize.ts","../../src/hooks/useAwayCompletionNotice.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/InfoIcon.tsx","../../src/components/icons/MailIcon.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/TrashIcon.tsx","../../src/components/icons/UserPlusIcon.tsx","../../src/components/icons/WrenchIcon.tsx","../../src/components/icons/XCircleIcon.tsx","../../src/components/Dropdown.tsx","../../src/hooks/useClickOutside.ts","../../src/components/Spinner.tsx","../../src/components/Tooltip.tsx","../../src/components/ChatHeader.tsx","../../src/components/ChatInput.tsx","../../src/components/ChatWaitingGame.tsx","../../src/components/ChatThinking.tsx","../../src/components/MarkdownMessage.tsx","../../src/components/ReasoningDetailsDialog.tsx","../../src/components/ChatMessages.tsx","../../src/components/ChatWelcome.tsx","../../src/components/ChatPanel.tsx","../../src/components/ChatToggleButton.tsx"],"sourcesContent":["export 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 let maxRun = 3;\n let nestedCount = 0;\n let lastBareFence = -1;\n for (let i = openerIdx + 1; i < lines.length; i++) {\n const m = lines[i].match(fenceRe);\n if (!m) continue;\n nestedCount++;\n maxRun = Math.max(maxRun, m[2].length);\n if (m[3].trim() === '') lastBareFence = i;\n }\n if (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 if (lastBareFence > openerIdx) {\n const cm = lines[lastBareFence].match(fenceRe)!;\n lines[lastBareFence] = `${cm[1]}${fence}`;\n }\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\nexport const identity = (key: string) => key;\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 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: (key: string) => string): 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 `${minutes}${t('m ago')}`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}${t('h ago')}`;\n const days = Math.floor(hours / 24);\n if (days < 7) return `${days}${t('d ago')}`;\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","import type { ChatAttachment, ToolCallTraceEntry, TransferChainEntry } from '../../types';\nimport type { ParsedAction, ProtocolContext } from './types';\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 * 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 if (st === 'thinking' && ctx.hasUsedTools) {\n return { action: 'status', status: 'analyzing' };\n }\n return { action: 'status', status: st, tools: evt.tools as string[] | undefined };\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 };\n }\n\n return { action: 'noop' };\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 return { action: 'error', content: (evt.message as string) || 'Unknown error' };\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, useRef, useState } from 'react';\nimport type { AgentStatusState, ApiEndpoints, BackendType, ChatFile, ChatMessage } from '../types';\nimport type { ParsedAction, ProtocolContext } from './protocols';\nimport { parseAgUiEvent, parseLegacyEvent, parseRestEvent } from './protocols';\n\nconst STORAGE_KEY = 'filigranChatConversationId';\nconst LEGACY_CHAT_ID_KEY = 'filigranChatLegacyChatId';\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 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 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 * 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 },\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 // 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 [inputValue, setInputValue] = useState('');\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 const [attachedFiles, setAttachedFiles] = useState<ChatFile[]>([]);\n const [transferredAgent, setTransferredAgent] = useState<TransferredAgent | null>(null);\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 const hasUsedToolsRef = useRef(false);\n // Ref mirror of conversationId — always current across async boundaries\n const conversationIdRef = useRef(conversationId);\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 // 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 // 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 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\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 });\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 let accumulated = '';\n let doneReceived = false;\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 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 if (parsed.status === 'tool_start') hasUsedToolsRef.current = true;\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 === 'thinking_text') {\n setAgentStatus((prev) => ({\n ...prev,\n status: prev?.status ?? 'thinking',\n thinkingContent: (prev?.thinkingContent ?? '') + (parsed.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 setAgentStatus((prev) =>\n prev ? { ...prev, elapsedS: parsed.elapsedS } : { status: 'tool_start', tools: parsed.tools, elapsedS: parsed.elapsedS },\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 // 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 break;\n }\n\n case 'done': {\n doneReceived = true;\n if (parsed.conversationId) {\n updateConversationId(parsed.conversationId);\n }\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 setMessages((prev) =>\n prev.map((m) =>\n m.id === segId\n ? {\n ...m,\n content: finalContent,\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 }\n : m,\n ),\n );\n break;\n }\n\n case 'error': {\n ensureSegment();\n const segId = currentAssistantId;\n setMessages((prev) =>\n prev.map((m) =>\n m.id === segId ? { ...m, content: parsed.content || t('Unable to connect. Please check the configuration.') } : 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 if (accumulated && !doneReceived) {\n const segId = currentAssistantId;\n const text = accumulated;\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: text || 'No response.' } : m)));\n }\n } catch (err) {\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 abortControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n }\n };\n\n const handleNewChat = () => {\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 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 }\n };\n\n const handleStopGenerating = () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.content)));\n };\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 transferredAgent,\n canSteer,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\n updateConversationId,\n handleSwitchConversation,\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 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\nexport function useAgents({ apiBaseUrl, apiEndpoints, backendType = 'rest', requestHeaders }: UseAgentsOptions): UseAgentsReturn {\n const [agents, setAgents] = useState<XtmAgent[]>([]);\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 fetch(agentsUrl, { headers: requestHeaders })\n .then((res) => (res.ok ? res.json() : []))\n .then((data: XtmAgent[]) => {\n setAgents(data);\n if (data.length > 0 && !selectedAgent) {\n const savedSlug = localStorage.getItem(STORAGE_AGENT_KEY);\n const match = savedSlug ? data.find((a) => a.slug === savedSlug) : null;\n setSelectedAgent(match || data[0]);\n }\n })\n .catch(() => {});\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 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}\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 return { conversationId: id, title, updatedAt, messageCount };\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 return { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation };\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';\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 * but focused elsewhere. Lets the host raise its own in-app toast (the\n * chatbot has no toast surface of its own). Receives the translated strings.\n */\n onComplete?: (title: string, body: string) => void;\n /**\n * Returns true when the user's focus is within the chat surface. When\n * provided, the toast also fires if the user is in the app but looking\n * elsewhere (panel open in a corner while they work in the main app). When\n * omitted, only the away case 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 * - **In-app but elsewhere** (window focused, focus outside the chat — only\n * when `isViewingChat` is supplied): host toast only.\n * - **Actively watching**: nothing — the streamed answer is 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 ? `${agentName} ${t('has finished')}` : 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 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 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 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 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\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, useEffect, 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\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 useEffect(() => {\n if (!open || !anchorRef.current) return;\n const rect = anchorRef.current.getBoundingClientRect();\n const left = placement === 'bottom-end' ? rect.right - width : rect.left;\n setPos({ top: rect.bottom + 4, left });\n }, [open, anchorRef, placement, width]);\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","import { useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { findChatbotRoot } from '../utils';\n\ninterface TooltipProps {\n title: string;\n children: React.ReactElement;\n}\n\n// Approximate rendered tooltip height (text-xs + py-1) plus the 4px gap.\n// Used to decide whether a top-placed tooltip would overflow the panel.\nconst TOOLTIP_CLEARANCE = 28;\n\nexport const Tooltip = ({ title, children }: TooltipProps) => {\n const ref = useRef<HTMLSpanElement>(null);\n const [show, setShow] = useState(false);\n const [pos, setPos] = useState({ top: 0, left: 0 });\n const [below, setBelow] = useState(false);\n\n if (!title) return children;\n\n const handleEnter = () => {\n if (!ref.current) return;\n const rect = ref.current.getBoundingClientRect();\n // Flip below the anchor when a top-placed tooltip would extend above the\n // chatbot panel's top edge. The tooltip lives inside the panel's stacking\n // context (z-[1200] in sidebar mode), so anything drawn above the panel\n // lands in the host app's top-bar zone and is hidden whenever the host\n // bar stacks higher (e.g. OpenAEV's AppBar at theme.zIndex.drawer + 1).\n const rootTop = findChatbotRoot(ref.current).getBoundingClientRect().top;\n const flip = rect.top - rootTop < TOOLTIP_CLEARANCE;\n setBelow(flip);\n setPos({\n top: flip ? rect.bottom + 4 : rect.top - 4,\n left: rect.left + rect.width / 2,\n });\n setShow(true);\n };\n\n return (\n <span ref={ref} className=\"inline-flex\" onMouseEnter={handleEnter} onMouseLeave={() => setShow(false)}>\n {children}\n {show &&\n createPortal(\n <span\n className={`pointer-events-none fixed z-[10001] -translate-x-1/2 ${below ? '' : '-translate-y-full'} whitespace-nowrap 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={{ top: pos.top, left: pos.left }}\n role=\"tooltip\"\n >\n {title}\n </span>,\n findChatbotRoot(ref.current),\n )}\n </span>\n );\n};\n","import { useRef } from 'react';\nimport type { ChatConversationSummary, ChatMode, XtmAgent } from '../types';\nimport { timeAgo } from '../utils';\nimport {\n ChevronDownIcon,\n CloseIcon,\n EditIcon,\n ExternalLinkIcon,\n FloatingIcon,\n FullscreenExitIcon,\n FullscreenIcon,\n HistoryIcon,\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 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: (key: string) => string;\n}\n\nconst modeOptions: { mode: ChatMode; label: string; getIcon: (p: { size: number; className: string }) => React.ReactNode }[] = [\n { mode: 'floating', label: 'Floating', getIcon: (p) => <FloatingIcon {...p} /> },\n { mode: 'sidebar', label: 'Sidebar', getIcon: (p) => <SidebarIcon {...p} /> },\n { mode: 'fullscreen', label: 'Full screen', getIcon: (p) => <FullscreenIcon {...p} /> },\n];\n\nexport const ChatHeader = ({\n mode,\n agentName,\n agents,\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 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 {t('Transferred from')} {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 {agents.length === 0 && (\n <div className=\"px-4 py-2\">\n <Spinner size={16} />\n </div>\n )}\n <div>\n {agents.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\">{t(opt.label)}</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 { useRef, type KeyboardEvent } from 'react';\nimport type { ChatFile, ChatMode } from '../types';\nimport { AttachFileIcon, FileIcon, SendIcon, StopCircleIcon } from './icons';\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}\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}: ChatInputProps) => {\n const fileInputRef = useRef<HTMLInputElement>(null);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n onSend();\n }\n if (e.key === 'Escape' && isLoading) {\n e.preventDefault();\n onStop();\n }\n };\n\n const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n onInputChange(e.target.value);\n const el = e.target;\n el.style.height = 'auto';\n el.style.height = `${Math.min(el.scrollHeight, 120)}px`;\n };\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 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 <div className=\"flex items-center border border-gray-200 dark:border-white/10 rounded-xl px-2 py-1 transition-colors focus-within:border-[var(--chat-accent)]\">\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={t('Ask a question...')}\n value={inputValue}\n onChange={handleInput}\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: 120 }}\n />\n {showSteerSend && (\n <Tooltip title={t('Send now')}>\n <button\n type=\"button\"\n onClick={onSend}\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 : onSend}\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 <p className=\"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70\">{footerText}</p>\n </div>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { GamepadIcon } from './icons';\n\n/**\n * Playful, rotating \"still working on it\" messages shown below the status\n * bubble during longer waits. They double as the Space Invader's targets:\n * the little invader ship erases them letter by letter, then the next one\n * fades in. Kept short and upbeat so they fit on one line in the narrow\n * floating panel and read as a sense of progress rather than noise.\n */\nconst DEFAULT_MESSAGES = [\n 'Crunching the data',\n 'Connecting the dots',\n 'Consulting the sources',\n 'Thinking it through',\n 'Reticulating splines',\n 'Analyzing the details',\n 'Almost there',\n 'Putting it together',\n 'Polishing the answer',\n 'Wrapping things up',\n];\n\n/** localStorage key for the per-browser mini-game preference (on by default). */\nconst PREF_KEY = 'filigranChatMiniGame';\n\n/** Plain (no-game) message rotation cadence. */\nconst PLAIN_ROTATE_MS = 2600;\n\n/** Canvas height in CSS px — room for the target row + the gliding ship. */\nconst GAME_HEIGHT = 70;\n\n/** Chunky monospace for the retro arcade feel + even letter spacing. */\nconst arcadeFont = (px: number): string => `700 ${px}px 'Courier New', ui-monospace, monospace`;\n\n/**\n * Classic 11x8 \"crab\" invader, two leg frames toggled while it glides — the\n * silhouette reads instantly as a Space Invader. `1` = filled pixel.\n */\nconst INVADER_FRAMES: string[][] = [\n ['00100000100', '00010001000', '00111111100', '01101110110', '11111111111', '10111111101', '10100000101', '00011011000'],\n ['00100000100', '10010001001', '10111111101', '11101110111', '11111111111', '00111111100', '00100000100', '01000000010'],\n];\n\nfunction readPref(): boolean {\n if (typeof window === 'undefined') return true;\n try {\n return window.localStorage.getItem(PREF_KEY) !== 'off';\n } catch {\n return true;\n }\n}\n\nfunction writePref(on: boolean): void {\n try {\n window.localStorage.setItem(PREF_KEY, on ? 'on' : 'off');\n } catch {\n /* private mode / disabled storage — fall back to in-memory state only */\n }\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 Letter {\n char: string;\n x: number;\n w: number;\n alive: boolean;\n}\n\ninterface Bullet {\n x: number;\n y: number;\n}\n\ninterface Particle {\n x: number;\n y: number;\n vx: number;\n vy: number;\n life: number;\n}\n\n/**\n * Self-contained canvas mini-game. Owns its own rAF loop, resize handling and\n * lifecycle; the only thing it reports back is the index of the message it is\n * currently destroying, so the host can keep an accessible text mirror in sync.\n * Returns a teardown function.\n */\nfunction createInvaderGame(canvas: HTMLCanvasElement, messages: string[], onMessage: (index: number) => void): () => void {\n const maybeCtx = canvas.getContext('2d');\n if (!maybeCtx) return () => {};\n const ctx: CanvasRenderingContext2D = maybeCtx;\n\n let raf = 0;\n let cssW = 0;\n const cssH = GAME_HEIGHT;\n let fontPx = 13;\n let accent = '#7b5cff';\n\n let msgIndex = 0;\n let letters: Letter[] = [];\n let targetIndex = -1;\n let bullets: Bullet[] = [];\n let particles: Particle[] = [];\n let shipX = 0;\n let cooldown = 0;\n let clearedAt = 0;\n let legFrame = 0;\n let legTimer = 0;\n let last = performance.now();\n\n const PX = 2;\n const SPRITE_W = 11 * PX;\n const SPRITE_H = 8 * PX;\n const shipTop = cssH - SPRITE_H - 4;\n const letterY = Math.round(cssH * 0.42);\n\n function resolveAccent(): void {\n const v = getComputedStyle(canvas).getPropertyValue('--chat-accent').trim();\n if (v) accent = v;\n }\n\n function firstAlive(from: number): number {\n for (let i = from; i < letters.length; i++) {\n if (letters[i].alive) return i;\n }\n return -1;\n }\n\n function layout(): void {\n if (cssW <= 0) return;\n const text = messages[msgIndex % messages.length] || '';\n onMessage(msgIndex % messages.length);\n\n // Shrink the font until the message fits the available width.\n fontPx = 13;\n for (; fontPx >= 8; fontPx--) {\n ctx.font = arcadeFont(fontPx);\n if (ctx.measureText(text).width <= cssW - 16) break;\n }\n ctx.font = arcadeFont(fontPx);\n\n const widths = Array.from(text).map((ch) => ctx.measureText(ch).width);\n const total = widths.reduce((a, b) => a + b, 0);\n let x = (cssW - total) / 2;\n letters = Array.from(text).map((ch, i) => {\n const lx = x;\n x += widths[i];\n return { char: ch, x: lx, w: widths[i], alive: ch.trim().length > 0 };\n });\n targetIndex = firstAlive(0);\n bullets = [];\n particles = [];\n cooldown = 0;\n clearedAt = 0;\n if (shipX <= 0) shipX = cssW / 2;\n }\n\n function letterCenter(i: number): number {\n return letters[i].x + letters[i].w / 2;\n }\n\n function update(dt: number): void {\n const dtf = Math.min(dt / 16.6667, 3);\n\n legTimer += dt;\n if (legTimer > 320) {\n legTimer = 0;\n legFrame ^= 1;\n }\n\n if (targetIndex === -1) {\n // Message fully cleared — brief pause, then load the next one.\n if (clearedAt === 0) clearedAt = performance.now();\n else if (performance.now() - clearedAt > 650) {\n msgIndex++;\n layout();\n }\n } else {\n const targetX = letterCenter(targetIndex);\n shipX += (targetX - shipX) * Math.min(0.16 * dtf, 1);\n cooldown -= dt;\n if (bullets.length === 0 && cooldown <= 0 && Math.abs(shipX - targetX) < 4) {\n bullets.push({ x: shipX, y: shipTop });\n cooldown = 130;\n }\n }\n\n for (let i = bullets.length - 1; i >= 0; i--) {\n bullets[i].y -= 2.6 * dtf;\n if (bullets[i].y <= letterY) {\n // Hit: detonate the current target letter and advance.\n if (targetIndex !== -1) {\n const cx = letterCenter(targetIndex);\n letters[targetIndex].alive = false;\n for (let p = 0; p < 7; p++) {\n const ang = (Math.PI * 2 * p) / 7 + Math.random();\n const spd = 0.6 + Math.random() * 1.4;\n particles.push({ x: cx, y: letterY, vx: Math.cos(ang) * spd, vy: Math.sin(ang) * spd, life: 1 });\n }\n targetIndex = firstAlive(targetIndex + 1);\n }\n bullets.splice(i, 1);\n }\n }\n\n for (let i = particles.length - 1; i >= 0; i--) {\n const p = particles[i];\n p.x += p.vx * dtf;\n p.y += p.vy * dtf;\n p.life -= 0.045 * dtf;\n if (p.life <= 0) particles.splice(i, 1);\n }\n }\n\n function draw(): void {\n ctx.clearRect(0, 0, cssW, cssH);\n\n // Single solid fill colour throughout; vary opacity via globalAlpha rather\n // than CSS color-mix() strings, which are not reliably accepted as a canvas\n // fillStyle on every browser (some fall back to opaque black).\n ctx.fillStyle = accent;\n\n ctx.font = arcadeFont(fontPx);\n ctx.textBaseline = 'middle';\n ctx.globalAlpha = 0.85;\n for (const l of letters) {\n if (l.alive) ctx.fillText(l.char, l.x, letterY);\n }\n\n ctx.globalAlpha = 1;\n for (const b of bullets) {\n ctx.fillRect(b.x - 1, b.y, 2, 7);\n }\n\n for (const p of particles) {\n ctx.globalAlpha = Math.max(p.life, 0) * 0.9;\n ctx.fillRect(p.x - 1.5, p.y - 1.5, 3, 3);\n }\n\n ctx.globalAlpha = 1;\n const frame = INVADER_FRAMES[legFrame];\n const ox = Math.round(shipX - SPRITE_W / 2);\n for (let r = 0; r < frame.length; r++) {\n const row = frame[r];\n for (let c = 0; c < row.length; c++) {\n if (row[c] === '1') ctx.fillRect(ox + c * PX, shipTop + r * PX, PX, PX);\n }\n }\n }\n\n function loop(now: number): void {\n const dt = now - last;\n last = now;\n if (!document.hidden && cssW > 0) {\n update(dt);\n draw();\n }\n raf = requestAnimationFrame(loop);\n }\n\n function applySize(): void {\n const rect = canvas.getBoundingClientRect();\n const dpr = window.devicePixelRatio || 1;\n cssW = rect.width;\n canvas.width = Math.max(1, Math.round(cssW * dpr));\n canvas.height = Math.round(cssH * dpr);\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n resolveAccent();\n layout();\n }\n\n // Prefer ResizeObserver; fall back to a window resize listener on older\n // browsers / embedded webviews where it is unavailable (an unguarded\n // `new ResizeObserver(...)` would throw and break the waiting experience).\n let ro: ResizeObserver | null = null;\n if (typeof ResizeObserver !== 'undefined') {\n ro = new ResizeObserver(applySize);\n ro.observe(canvas);\n } else {\n window.addEventListener('resize', applySize);\n }\n applySize();\n raf = requestAnimationFrame(loop);\n\n return () => {\n cancelAnimationFrame(raf);\n if (ro) ro.disconnect();\n else window.removeEventListener('resize', applySize);\n };\n}\n\ninterface ChatWaitingGameProps {\n t: (key: string) => string;\n /** Host-level override; when false the feature is hidden entirely. */\n enabled?: boolean;\n}\n\n/**\n * Waiting experience shown below the status bubble during longer waits:\n * dynamic rotating messages with an optional Space Invader mini-game that\n * shoots the message letters away one by one. The game can be toggled off\n * per browser (preference persisted in localStorage); when off — or when the\n * OS requests reduced motion — the messages simply rotate as plain dimmed\n * text, so the \"dynamic loading messages\" feedback always stands on its own.\n */\nexport const ChatWaitingGame = ({ t, enabled = true }: ChatWaitingGameProps) => {\n const messages = useMemo(() => DEFAULT_MESSAGES.map((m) => t(m)), [t]);\n const reducedMotion = usePrefersReducedMotion();\n const [minigameOn, setMinigameOn] = useState(readPref);\n const [msgIndex, setMsgIndex] = useState(0);\n const canvasRef = useRef<HTMLCanvasElement>(null);\n\n const playMode = enabled && minigameOn && !reducedMotion;\n\n // Plain-text rotation when the game is off / reduced motion. Skipped while the\n // game drives the index, and entirely when the feature is disabled (so a\n // disabled host arms no timer); `enabled` is a dep so toggling it cleans up.\n useEffect(() => {\n if (playMode || !enabled) return;\n const id = window.setInterval(() => setMsgIndex((i) => (i + 1) % messages.length), PLAIN_ROTATE_MS);\n return () => window.clearInterval(id);\n }, [playMode, enabled, messages.length]);\n\n // Canvas engine when the game is on.\n useEffect(() => {\n if (!playMode) return;\n const canvas = canvasRef.current;\n if (!canvas) return;\n return createInvaderGame(canvas, messages, setMsgIndex);\n }, [playMode, messages]);\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 whole UI (including the toggle button) made screen readers re-announce\n the control alongside each message change. */}\n <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {current}\n </span>\n {/* Suppress every non-essential animation (fade-ins, the blinking caret)\n under prefers-reduced-motion, so the reduced-motion path really is\n motion-free — only the plain dimmed text rotates. */}\n <div\n className=\"relative overflow-hidden rounded-md bg-[var(--chat-accent)]/[0.03]\"\n style={reducedMotion ? undefined : { animation: 'chat-fade-in 0.5s ease-out' }}\n >\n {playMode ? (\n <canvas ref={canvasRef} aria-hidden className=\"block w-full\" style={{ height: GAME_HEIGHT }} />\n ) : (\n <div className=\"flex items-center\" style={{ height: GAME_HEIGHT }}>\n <span\n key={current}\n className=\"px-3 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 </div>\n )}\n {!reducedMotion && (\n <button\n type=\"button\"\n onClick={() => {\n const next = !minigameOn;\n setMinigameOn(next);\n writePref(next);\n }}\n aria-pressed={minigameOn}\n aria-label={minigameOn ? t('Turn off the waiting mini-game') : t('Turn on the waiting mini-game')}\n title={minigameOn ? t('Turn off the waiting mini-game') : t('Turn on the waiting mini-game')}\n className={`absolute top-1 right-1 rounded p-1 transition-opacity ${\n minigameOn ? 'text-[var(--chat-accent)] opacity-50 hover:opacity-100' : 'text-gray-400 dark:text-white/40 opacity-40 hover:opacity-90'\n }`}\n >\n <GamepadIcon size={13} />\n </button>\n )}\n </div>\n </div>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { AgentStatusState, IconProps } from '../types';\nimport {\n BrainIcon,\n DatabaseIcon,\n ExternalLinkIcon,\n GlobeIcon,\n MailIcon,\n SearchIcon,\n SparklesIcon,\n TerminalIcon,\n UserPlusIcon,\n WrenchIcon,\n} from './icons';\nimport { ChatWaitingGame } from './ChatWaitingGame';\n\ninterface ChatThinkingProps {\n agentStatus: AgentStatusState | null;\n logoIcon?: React.ReactNode;\n t: (key: string) => string;\n /** Host-level override for the waiting mini-game / dynamic messages. */\n miniGameEnabled?: boolean;\n}\n\ntype IconComponent = (props: IconProps) => React.JSX.Element;\n\ninterface StatusVisual {\n label: string;\n StatusIcon: IconComponent;\n showDots: boolean;\n}\n\nfunction resolveStatusVisual(agentStatus: AgentStatusState | null, t: (key: string) => string): 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 const label = count > 1 ? `${t('Delegating')} ${count} ${t('tasks')}…` : `${t('Delegating task')}…`;\n return { label, 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 const target = count > 1 ? `${count} ${t('background tasks')}` : t('background task');\n return { label: `${t('Waiting for')} ${target}…`, 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 const from = count > 1 ? `${count} ${t('tasks')}` : t('task');\n return { label: `${t('Collecting results from')} ${from}…`, 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]}…` : `${unique[0]} (+${unique.length - 1} more)…`;\n } else {\n label = t('Using tools…');\n }\n return { label, StatusIcon, showDots: false };\n }\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] ?? 'agent';\n return { label: `${t('Consulting')} ${consultName}…`, StatusIcon: UserPlusIcon, showDots: false };\n }\n case 'delegating': {\n const count = agentStatus.tools?.filter((n) => n === 'spawn_background_task').length ?? 0;\n return {\n label: count > 1 ? `${t('Delegating')} ${count} ${t('tasks')}…` : `${t('Delegating task')}…`,\n StatusIcon: UserPlusIcon,\n showDots: false,\n };\n }\n case 'polling': {\n const checkCount = agentStatus.tools?.filter((n) => n === 'check_task_status').length ?? 0;\n const target = checkCount > 1 ? `${checkCount} ${t('background tasks')}` : t('background task');\n return { label: `${t('Waiting for')} ${target}…`, StatusIcon: SparklesIcon, showDots: false };\n }\n case 'collecting': {\n const fetchCount = agentStatus.tools?.filter((n) => n === 'get_task_result').length ?? 0;\n const from = fetchCount > 1 ? `${fetchCount} ${t('tasks')}` : t('task');\n return { label: `${t('Collecting results from')} ${from}…`, StatusIcon: SparklesIcon, showDots: false };\n }\n case 'transferring': {\n const targetName = agentStatus.tools?.[0] ?? 'agent';\n return { label: `${t('Transferring to')} ${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 * 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.\n */\nexport function ThinkingTextBubble({ content }: { content: string }) {\n const ref = useRef<HTMLDivElement>(null);\n const [isOverflowing, setIsOverflowing] = useState(false);\n const cleaned = cleanReasoningText(content);\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 }, [cleaned]);\n\n if (cleaned.length < 3) return null;\n\n return (\n <div\n className=\"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 style={{ animation: 'reasoningGlow 3s ease-in-out infinite, chat-fade-in 0.5s ease-out' }}\n >\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\">{cleaned}</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 * The reasoning window flips to the waiting game once nothing has progressed\n * for this long — i.e. no reasoning at all, or a reasoning stream that stalled.\n */\nconst STALL_DELAY_MS = 5000;\n\n/**\n * True once `signal` has stayed unchanged for `delayMs`. Re-arms whenever the\n * signal changes, so resumed reasoning clears the flag immediately. Used to\n * detect a stalled (or absent) reasoning stream so we can show the waiting game\n * in the meantime and flip back to the reasoning the moment it resumes. Arms no\n * timer (and never flips) while `enabled` is false, so a host that disables the\n * waiting game schedules no timeouts or re-renders for it.\n */\nfunction useStalled(signal: number, delayMs: number, enabled: boolean): boolean {\n const [stalled, setStalled] = useState(false);\n const prevSignalRef = useRef(signal);\n\n // Did the signal change since the last settled render? When it did, reasoning\n // has just resumed, so we report \"not stalled\" for this very render without a\n // render-phase state update (discouraged in React / brittle under StrictMode\n // and concurrent rendering). The effect below then resets the flag and re-arms\n // the timer — deriving the value here keeps the flip back to the reasoning\n // window free of the one-frame lag a clear-in-effect alone would leave.\n const signalChanged = prevSignalRef.current !== signal;\n\n useEffect(() => {\n prevSignalRef.current = signal;\n setStalled(false);\n if (!enabled) return;\n const id = window.setTimeout(() => setStalled(true), delayMs);\n return () => window.clearTimeout(id);\n }, [signal, delayMs, enabled]);\n\n return enabled && stalled && !signalChanged;\n}\n\nexport const ChatThinking = ({ agentStatus, logoIcon, t, miniGameEnabled = true }: ChatThinkingProps) => {\n const { label, StatusIcon, showDots } = resolveStatusVisual(agentStatus, t);\n const thinkingContent = agentStatus?.thinkingContent;\n const elapsedS = agentStatus?.elapsedS;\n const showElapsed = typeof elapsedS === 'number' && elapsedS >= ELAPSED_DISPLAY_THRESHOLD_S;\n // Show the waiting game when reasoning is absent or has stalled for 5s; flip\n // back to the reasoning window the moment new reasoning text resumes (the\n // accumulated content carries the continuation).\n const stalled = useStalled(thinkingContent?.length ?? 0, STALL_DELAY_MS, miniGameEnabled);\n const showGame = miniGameEnabled && stalled;\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 {thinkingContent && !showGame ? (\n <ThinkingTextBubble content={thinkingContent} />\n ) : showGame ? (\n <ChatWaitingGame t={t} enabled={miniGameEnabled} />\n ) : null}\n </>\n );\n};\n","import { useMemo, useState } from 'react';\nimport Markdown from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport { CheckIcon, CopyIcon } from './icons';\nimport { hardenNestedCodeFences, normalizeMarkdownTables } from '../utils';\n\ninterface MarkdownMessageProps {\n content: string;\n onRelativeLinkClick?: (href: string) => void;\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\nexport const MarkdownMessage = ({ content, onRelativeLinkClick }: MarkdownMessageProps) => {\n const [copiedBlock, setCopiedBlock] = useState<string | null>(null);\n\n // Preprocess once per `content`: this component re-renders on UI-only state\n // (e.g. `copiedBlock`), and both passes scan the whole message, so memoizing\n // keeps that work off the hot path for large messages.\n const processedContent = useMemo(() => normalizeMarkdownTables(hardenNestedCodeFences(content)), [content]);\n\n const handleCopyCode = (code: string) => {\n navigator.clipboard.writeText(code);\n setCopiedBlock(code);\n setTimeout(() => setCopiedBlock(null), 2000);\n };\n\n return (\n <Markdown\n remarkPlugins={[remarkGfm]}\n 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 code: ({ className, children }) => {\n const match = /language-(\\w+)/.exec(className || '');\n const codeStr = String(children).replace(/\\n$/, '');\n if (match) {\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]}</span>\n <button\n type=\"button\"\n onClick={() => handleCopyCode(codeStr)}\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 (\n <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 },\n ul: ({ children }) => (\n <ul className=\"pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">{children}</ul>\n ),\n ol: ({ children }) => (\n <ol className=\"pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">{children}</ol>\n ),\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: ({ href, children }) => {\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 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 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 }) => (\n <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 }}\n >\n {processedContent}\n </Markdown>\n );\n};\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 } 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 ? `${iterations} ${t('iterations')}` : '',\n `${totalCalls} ${totalCalls === 1 ? t('tool call') : t('tool calls')}`,\n transfers.length > 0 ? `${transfers.length} ${transfers.length === 1 ? t('transfer') : t('transfers')}` : '',\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 { useEffect, useRef, useState } from 'react';\nimport type { AgentStatusState, ChatAttachment, ChatMessage } from '../types';\nimport { splitFileMarkers } from '../utils';\nimport { AlertTriangleIcon, DownloadIcon, FileIcon, InfoIcon } from './icons';\nimport { ChatThinking } from './ChatThinking';\nimport { MarkdownMessage } from './MarkdownMessage';\nimport { ReasoningDetailsDialog } from './ReasoningDetailsDialog';\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 /** Host-level override for the waiting mini-game / dynamic messages. */\n miniGameEnabled?: boolean;\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\nexport const ChatMessages = ({\n messages,\n isLoading,\n agentStatus,\n agentName,\n logoIcon,\n onRelativeLinkClick,\n onDownloadFile,\n miniGameEnabled = true,\n t,\n}: ChatMessagesProps) => {\n const messagesEndRef = useRef<HTMLDivElement>(null);\n const [toolDetailMsgId, setToolDetailMsgId] = useState<string | null>(null);\n\n useEffect(() => {\n messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });\n }, [messages]);\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. `behavior: 'instant'` (CSSOM View,\n // Baseline-supported) forces a non-animated jump — this fires on every\n // reasoning chunk and smooth animations would queue up; 'auto' would not\n // do, since a `scroll-behavior: smooth` ancestor turns it smooth again.\n const thinkingLen = agentStatus?.thinkingContent?.length ?? 0;\n useEffect(() => {\n if (!thinkingLen) return;\n messagesEndRef.current?.scrollIntoView({ behavior: 'instant' });\n }, [thinkingLen]);\n\n const renderAttachmentCard = (att: ChatAttachment, key: string) => {\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 // 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 = (msg: ChatMessage, loading: boolean): 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 content={part.value} onRelativeLinkClick={onRelativeLinkClick} />\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 && !loading) {\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 // 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 // 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 = (msg: ChatMessage): 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 // 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 lastAssistantIndex = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n lastAssistantIndex = i;\n break;\n }\n }\n\n return (\n <div className=\"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable\">\n {messages.map((msg, index) => {\n const isAssistant = msg.role === 'assistant';\n const isEmpty = !msg.content;\n // The live cursor / thinking bubble / ChatThinking state — and,\n // conversely, the hiding of the completed-message affordances (the\n // reasoning \"i\" button) — must be gated on the streaming message.\n // Gating those on the global `isLoading` instead made the blinking\n // cursor leak onto every prior assistant message and the \"i\" button\n // vanish from all of them while a *later* response was streaming.\n const isStreamingMessage = isLoading && index === lastAssistantIndex;\n const isThinking = isAssistant && isEmpty && isStreamingMessage;\n\n if (isThinking) {\n return (\n <div key={msg.id}>\n <ChatThinking agentStatus={agentStatus} logoIcon={logoIcon} t={t} miniGameEnabled={miniGameEnabled} />\n </div>\n );\n }\n\n return (\n <div key={msg.id} className={`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 <span className=\"font-semibold text-xs text-gray-900 dark:text-white\">{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(msg)}</div>\n )}\n\n {isAssistant ? (\n <div className=\"flex flex-col gap-1.5 w-full items-start\">\n {buildAssistantBlocks(msg, isStreamingMessage)}\n {!isEmpty && isStreamingMessage && (\n <span className=\"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse\" />\n )}\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 {isAssistant &&\n !isEmpty &&\n !isStreamingMessage &&\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 <button\n type=\"button\"\n onClick={() => setToolDetailMsgId(toolDetailMsgId === msg.id ? null : msg.id)}\n className={`mt-0.5 p-1 rounded-lg transition-opacity ${\n msg.isTruncated\n ? // A truncated turn must be visible at a glance (not\n // gated on hover) so the user notices the warning —\n // mirrors the 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 : 'opacity-50 hover:opacity-100 hover:text-[var(--chat-accent)]'\n }`}\n title={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}\n aria-label={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}\n aria-haspopup=\"dialog\"\n aria-expanded={toolDetailMsgId === msg.id}\n >\n {msg.isTruncated ? <AlertTriangleIcon size={14} /> : <InfoIcon size={14} />}\n </button>\n {toolDetailMsgId === msg.id && <ReasoningDetailsDialog msg={msg} onClose={() => setToolDetailMsgId(null)} t={t} />}\n </>\n )}\n </div>\n );\n })}\n <div ref={messagesEndRef} />\n </div>\n );\n};\n","interface ChatWelcomeProps {\n firstName: string;\n logoIcon: React.ReactNode;\n promptSuggestions: string[];\n onPromptClick: (prompt: string) => void;\n t: (key: string) => string;\n}\n\nexport const ChatWelcome = ({ firstName, logoIcon, promptSuggestions, onPromptClick, t }: 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 <h2 className=\"text-xl font-medium mb-6 text-center text-gray-900 dark:text-white\" style={{ fontFamily: '\"Geologica\", sans-serif' }}>\n {t('How can I help you, ')}\n {firstName}?\n </h2>\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 {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 {t(prompt)}\n </button>\n ))}\n </div>\n </div>\n);\n","import { type FunctionComponent, useCallback, useEffect, useRef, useState } from 'react';\nimport type { ChatAttachment, ChatMessage, ChatPanelProps } from '../types';\nimport { hexAlpha, identity } from '../utils';\nimport { parseAttachments, parseToolCallTrace, parseTransferChain } 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 { DefaultLogoIcon } from './icons';\nimport { ChatHeader } from './ChatHeader';\nimport { ChatInput } from './ChatInput';\nimport { ChatMessages } from './ChatMessages';\nimport { ChatWelcome } from './ChatWelcome';\n\nconst FLOATING_WIDTH = 380;\nconst FLOATING_HEIGHT = 560;\nconst SIDEBAR_GAP = 6;\n\nconst DEFAULT_SUGGESTIONS = [\n 'Help me create a new simulation scenario',\n 'What are the latest attack patterns?',\n 'How do I configure detection rules?',\n 'Summarize my recent findings',\n];\n\nexport const ChatPanel: FunctionComponent<ChatPanelProps> = ({\n mode,\n onClose,\n onModeChange,\n topOffset = 0,\n apiBaseUrl,\n apiEndpoints,\n agentDashboardUrl,\n user,\n t = identity,\n accentColor = '#7b5cff',\n logoIcon,\n promptSuggestions = DEFAULT_SUGGESTIONS,\n draftBorderColor,\n resizable = false,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n disableFileManagement = false,\n onRelativeLinkClick,\n onDownloadError,\n maxFileCount,\n maxTotalSize,\n requestHeaders,\n pageContext,\n pushContentSelector,\n backendType = 'rest',\n miniGameEnabled = true,\n notifyOnComplete = true,\n onTaskComplete,\n}) => {\n const [modeMenuOpen, setModeMenuOpen] = useState(false);\n\n const { agents, 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 transferredAgent,\n canSteer,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\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 { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation } = useConversations({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n const [historyMenuOpen, setHistoryMenuOpen] = useState(false);\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 const resolvedLogo = logoIcon ?? <DefaultLogoIcon size={24} />;\n const firstName = user.firstName;\n const agentName = transferredAgent?.name || selectedAgent?.name || 'Assistant';\n\n // Key on `.filigran-chatbot.fixed` (the panel root carries both in every\n // mode) rather than `.filigran-chatbot` alone, which the toggle button also\n // uses — otherwise focusing the toggle would be mistaken for viewing the chat.\n // Stable reference (useCallback) so the notifier's effect doesn't re-run on\n // every render — the panel re-renders frequently while a response streams.\n const isViewingChat = useCallback(() => typeof document !== 'undefined' && !!document.activeElement?.closest('.filigran-chatbot.fixed'), []);\n\n // Notify when a long turn finishes and the user is not watching the chat —\n // away (tab hidden / another window) or in-app but focused outside the panel.\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 const handleDownloadFile = useCallback(\n async (att: ChatAttachment) => {\n const base = apiEndpoints?.download ?? '/chat/files';\n const url = `${apiBaseUrl}${base}/${encodeURIComponent(att.fileId)}/download`;\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 [apiBaseUrl, apiEndpoints, 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 if (!conversationId || 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 if (!data.messages?.length) return;\n const restored: ChatMessage[] = data.messages.map(\n (\n m: {\n role: string;\n content: string;\n attachments?: unknown;\n tool_names?: unknown;\n tool_call_count?: unknown;\n iterations?: unknown;\n reasoning?: unknown;\n tool_call_trace?: unknown;\n transfer_chain?: unknown;\n is_truncated?: unknown;\n },\n i: number,\n ) => ({\n id: `restored-${i}`,\n role: m.role as 'user' | 'assistant',\n content: m.content,\n timestamp: new Date(),\n // Re-surface downloadable file chips on conversation restore for\n // both roles: agent-generated deliverables on assistant messages\n // (the [[FILE:…]] markers in content are stripped at render time by\n // ChatMessages) and user-uploaded files on user messages (so an\n // upload stays downloadable after a page reload, not just in the\n // live session where it is carried on `files`).\n attachments: parseAttachments(m.attachments),\n // Re-surface the reasoning-details affordance (\"i\" button) on\n // restored assistant messages — 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 setMessages(restored);\n })\n .catch(() => {\n if (isStale()) return;\n updateConversationId(null);\n });\n }, [\n conversationId,\n selectedAgent,\n apiBaseUrl,\n apiEndpoints,\n backendType,\n historyLoadedRef,\n conversationIdRef,\n isMountedRef,\n requestHeaders,\n setMessages,\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 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}\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 {messages.length === 0 ? (\n <ChatWelcome firstName={firstName} logoIcon={resolvedLogo} promptSuggestions={promptSuggestions} onPromptClick={setInputValue} t={t} />\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 miniGameEnabled={miniGameEnabled}\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 />\n </div>\n );\n};\n","import type { FunctionComponent } from 'react';\nimport type { ChatToggleButtonProps } from '../types';\nimport { hexAlpha } from '../utils';\nimport { DefaultLogoIcon } from './icons';\n\nexport const ChatToggleButton: FunctionComponent<ChatToggleButtonProps> = ({\n isOpen,\n onToggle,\n label = 'Ask Assistant',\n accentColor = '#7b5cff',\n icon,\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}\n </button>\n );\n};\n"],"names":["hexAlpha","hex","alpha","Math","round","toString","padStart","identity","key","findChatbotRoot","el","node","classList","contains","parentElement","document","body","PARTIAL_FILE_MARKER_RE","parseAttachments","raw","Array","isArray","out","item","a","fileId","file_id","push","filename","type","undefined","size","contentType","content_type","fileTag","file_tag","length","parseToolCallTrace","e","name","input","output","success","parseTransferChain","agent_name","agentId","agent_id","agentName","parseRestEvent","evt","ctx","action","content","st","status","thinkingContent","hasUsedTools","tools","elapsedS","elapsed_s","conversationId","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","parseLegacyEvent","eventType","event","data","nodeId","activeNodeId","replace","usedTools","map","t","tool","chatId","parseAgUiEvent","message","stepName","delta","toolName","toolCallName","STORAGE_KEY","LEGACY_CHAT_ID_KEY","DEFAULT_MAX_TOTAL_SIZE","useChat","apiBaseUrl","apiEndpoints","backendType","agentSlug","requestHeaders","pageContext","maxFileCount","maxTotalSize","isLegacy","messages","setMessages","useState","inputValue","setInputValue","isLoading","setIsLoading","agentStatus","setAgentStatus","setConversationId","window","localStorage","getItem","attachedFiles","setAttachedFiles","transferredAgent","setTransferredAgent","legacyChatId","setLegacyChatId","historyLoadedRef","useRef","abortControllerRef","hasUsedToolsRef","conversationIdRef","pageContextRef","current","creatingSessionRef","uploadAbortRef","AbortController","effectiveMaxFileCount","Number","isFinite","floor","effectiveMaxTotalSize","getSteerUrl","singleEndpoint","steer","getUploadUrl","upload","updateConversationId","useCallback","id","setItem","removeItem","ensureConversation","async","slug","sessionsUrl","sessions","promise","res","fetch","method","headers","JSON","stringify","agent_slug","ok","json","convId","uploadSingleFile","file","signal","uploadUrl","formData","FormData","append","uploadHeaders","Object","fromEntries","entries","filter","k","toLowerCase","Error","ids","file_ids","handleFileAdd","fileList","candidates","from","tempId","crypto","randomUUID","accepted","prev","currentCount","currentSize","reduce","sum","f","slotsAvailable","sizeLeft","filtered","c","slice","newEntries","rawFile","uploadStatus","setTimeout","p","err","DOMException","handleNewChat","abort","canSteer","handlePaste","files","clipboardData","preventDefault","handleSendMessage","steerText","trim","steerUrl","optimistic","role","timestamp","Date","m","steerMessage","userMsg","assistantId","currentAssistantId","controller","fileIds","requestBody","opts","question","streaming","threadId","runId","context","state","forwardedProps","keys","serialized","buildRequestBody","parseEvent","getParser","reader","getReader","decoder","TextDecoder","buffer","accumulated","doneReceived","ensureSegment","segmentId","done","value","read","decode","stream","lines","split","pop","rawLine","line","startsWith","jsonStr","parsed","parse","segId","text","finalContent","handleStopGenerating","handleSwitchConversation","STORAGE_AGENT_KEY","parseConversation","title","updatedAt","updated_at","created_at","messageCount","message_count","SIDEBAR_WIDTH","SIDEBAR_WIDTH_STORAGE_KEY","flashTimer","originalTitle","activeHooks","stopTitleFlash","clearInterval","useAwayCompletionNotice","enabled","onComplete","isViewingChat","wasLoadingRef","startRef","useEffect","clearOnReturn","hidden","hasFocus","addEventListener","removeEventListener","max","wasLoading","now","unfocused","away","viewingChat","showMessage","setInterval","startTitleFlash","Notification","permission","tag","notifyOS","AlertTriangleIcon","className","_jsxs","xmlns","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","children","_jsx","d","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","InfoIcon","MailIcon","SearchIcon","SendIcon","SidebarIcon","SparklesIcon","StopCircleIcon","TerminalIcon","TrashIcon","UserPlusIcon","WrenchIcon","XCircleIcon","Dropdown","open","onClose","anchorRef","placement","panelRef","pos","setPos","top","left","ref","handler","active","listener","target","useClickOutside","rect","getBoundingClientRect","right","bottom","portalTarget","createPortal","style","Spinner","Tooltip","show","setShow","below","setBelow","onMouseEnter","rootTop","flip","onMouseLeave","modeOptions","mode","label","getIcon","ChatHeader","agents","selectedAgent","transferredFrom","agentMenuOpen","onAgentMenuToggle","onAgentMenuClose","onSwitchAgent","modeMenuOpen","onModeMenuToggle","onModeMenuClose","onModeChange","onNewChat","logoIcon","agentDashboardUrl","historyEnabled","historyMenuOpen","onHistoryMenuToggle","onHistoryMenuClose","conversations","conversationsLoading","activeConversationId","onSelectConversation","onDeleteConversation","agentAnchorRef","modeAnchorRef","historyAnchorRef","CurrentModeIcon","onClick","agent","description","_Fragment","conv","isActive","when","iso","then","getTime","isNaN","diffMs","minutes","hours","days","toLocaleDateString","month","day","timeAgo","opt","ChatInput","onInputChange","onSend","onStop","onFileAdd","onFileRemove","onPaste","separatorColor","fileInputRef","textareaRef","isFileManagementEnabled","Boolean","hasContent","hasFilesUploading","some","canSend","hasAttachments","showSteerSend","footerText","borderTopColor","borderTopWidth","i","multiple","onChange","click","placeholder","min","scrollHeight","onKeyDown","shiftKey","rows","maxHeight","disabled","DEFAULT_MESSAGES","PREF_KEY","arcadeFont","px","INVADER_FRAMES","readPref","createInvaderGame","canvas","onMessage","maybeCtx","getContext","raf","cssW","fontPx","accent","msgIndex","letters","targetIndex","bullets","particles","shipX","cooldown","clearedAt","legFrame","legTimer","last","performance","letterY","cssH","firstAlive","alive","layout","font","measureText","widths","ch","total","b","lx","char","w","letterCenter","applySize","dpr","devicePixelRatio","setTransform","v","getComputedStyle","getPropertyValue","resolveAccent","ro","ResizeObserver","observe","requestAnimationFrame","loop","dt","dtf","targetX","abs","ang","PI","random","spd","vx","cos","vy","sin","life","splice","update","clearRect","fillStyle","textBaseline","globalAlpha","l","fillText","fillRect","frame","ox","SPRITE_W","row","draw","cancelAnimationFrame","disconnect","ChatWaitingGame","useMemo","reducedMotion","reduced","setReduced","matchMedia","matches","mql","addListener","removeListener","usePrefersReducedMotion","minigameOn","setMinigameOn","setMsgIndex","canvasRef","playMode","animation","next","on","writePref","cleanReasoningText","ThinkingTextBubble","isOverflowing","setIsOverflowing","cleaned","scrollTop","clientHeight","formatElapsed","seconds","s","ChatThinking","miniGameEnabled","StatusIcon","showDots","rawNames","lower","n","count","includes","display","toUpperCase","unique","Set","consultName","checkCount","fetchCount","targetName","resolveStatusVisual","showElapsed","stalled","delayMs","setStalled","prevSignalRef","signalChanged","clearTimeout","useStalled","showGame","delay","isRelativeHref","href","test","MarkdownMessage","onRelativeLinkClick","copiedBlock","setCopiedBlock","processedContent","indexOf","splitCells","endsWith","cells","isDelimiterRow","alignOf","cell","fenceRe","fenceChar","fenceLen","listMarkerRe","fenceMatch","match","run","header","delim","markerMatch","offset","trimStart","indent","repeat","headerCols","delimCells","aligns","join","normalizeMarkdownTables","markupLang","openerIdx","maxRun","nestedCount","lastBareFence","fence","om","cm","hardenNestedCodeFences","Markdown","remarkPlugins","remarkGfm","components","code","exec","codeStr","String","handleCopyCode","navigator","clipboard","writeText","ul","ol","blockquote","internalHref","url","URL","location","protocol","origin","pathname","search","hash","toInternalHref","routeInternally","openInNewTab","rel","h1","h2","h3","table","th","td","prettyTraceValue","toolDisplayName","ToolCallRow","entry","index","expanded","setExpanded","inputDisplay","outputDisplay","hasInput","ReasoningDetailsDialog","msg","hostRef","closeButtonRef","dialogRef","root","setRoot","dialog","focusable","querySelectorAll","first","activeElement","focus","previouslyFocused","HTMLElement","preventScroll","totalCalls","transfers","trace","summaryParts","stopPropagation","tn","tr","fileExtensionLabel","dot","lastIndexOf","ext","ChatMessages","onDownloadFile","messagesEndRef","toolDetailMsgId","setToolDetailMsgId","scrollIntoView","behavior","thinkingLen","renderAttachmentCard","att","isWorking","sizeLabel","bytes","toFixed","buildAssistantBlocks","loading","parts","re","lastIndex","tail","splitFileMarkers","attByFileId","Map","used","blocks","forEach","part","get","add","has","renderFileChip","buildUserFileBlocks","seen","lastAssistantIndex","isAssistant","isEmpty","isStreamingMessage","ChatWelcome","firstName","promptSuggestions","onPromptClick","fontFamily","prompt","DEFAULT_SUGGESTIONS","ChatPanel","topOffset","user","accentColor","draftBorderColor","resizable","onWidthChange","onResizeStart","onResizeEnd","disableFileManagement","onDownloadError","pushContentSelector","notifyOnComplete","onTaskComplete","setModeMenuOpen","setAgentMenuOpen","handleSwitchAgent","setAgents","setSelectedAgent","savedSlug","find","catch","onSwitch","useAgents","refreshConversations","deleteConversation","setConversations","setConversationsLoading","history","rawList","encodeURIComponent","useConversations","setHistoryMenuOpen","sidebarWidth","handleResizeStart","defaultWidth","isResizing","setSidebarWidth","stored","parseInt","setIsResizing","isResizingRef","sidebarWidthRef","onWidthChangeRef","onResizeEndRef","handleMouseMove","newWidth","innerWidth","clientX","maxWidth","clamped","handleMouseUp","cursor","userSelect","handleWindowResize","useSidebarResize","pushWidth","documentElement","setProperty","contentElement","querySelector","originalPaddingRight","paddingRight","originalTransition","transition","resolvedLogo","closest","downloadPathProvided","download","canDownload","handleDownloadFile","credentials","blob","objectUrl","createObjectURL","link","createElement","appendChild","remove","revokeObjectURL","cssVars","isMountedRef","requestedConversationId","isStale","restored","containerClasses","base","containerStyle","onMouseDown","handleDeleteConversation","_","j","ChatToggleButton","isOpen","onToggle","icon","resolvedIcon","borderColor","color","backgroundColor","currentTarget"],"mappings":"2PAAM,SAAUA,EAASC,EAAaC,GAIpC,MAAO,GAAGD,IAHAE,KAAKC,MAAc,IAARF,GAClBG,SAAS,IACTC,SAAS,EAAG,MAEjB,CAmKO,MAAMC,EAAYC,GAAgBA,EAQnC,SAAUC,EAAgBC,GAC9B,IAAIC,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S8xB,EAAa,IACjFxvB,EAAEy1B,cAAchf,MAAM+e,gBAAkBN,EAASx3B,EAAS8xB,EAAa,IAAO,eAC/Erd,SAAA,CAEDC,EAAA,OAAA,CAAMZ,UAAU,0BAAyBW,SAAEkjB,IAC1C/d"}
1
+ {"version":3,"file":"index.js","sources":["../../src/utils/index.ts","../../src/hooks/protocols/parseRestEvent.ts","../../src/hooks/protocols/parseLegacyEvent.ts","../../src/hooks/protocols/parseAgUiEvent.ts","../../src/hooks/useChat.ts","../../src/hooks/useAgents.ts","../../src/hooks/useConversations.ts","../../src/hooks/useSidebarResize.ts","../../src/hooks/useAwayCompletionNotice.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/InfoIcon.tsx","../../src/components/icons/MailIcon.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/TrashIcon.tsx","../../src/components/icons/UserPlusIcon.tsx","../../src/components/icons/WrenchIcon.tsx","../../src/components/icons/XCircleIcon.tsx","../../src/components/Dropdown.tsx","../../src/hooks/useClickOutside.ts","../../src/components/Spinner.tsx","../../src/components/Tooltip.tsx","../../src/components/ChatHeader.tsx","../../src/components/ChatInput.tsx","../../src/components/ChatWaitingGame.tsx","../../src/components/ChatThinking.tsx","../../src/components/MarkdownMessage.tsx","../../src/components/ReasoningDetailsDialog.tsx","../../src/components/ChatMessages.tsx","../../src/components/ChatWelcome.tsx","../../src/components/ChatPanel.tsx","../../src/components/ChatToggleButton.tsx"],"sourcesContent":["export 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 let maxRun = 3;\n let nestedCount = 0;\n let lastBareFence = -1;\n for (let i = openerIdx + 1; i < lines.length; i++) {\n const m = lines[i].match(fenceRe);\n if (!m) continue;\n nestedCount++;\n maxRun = Math.max(maxRun, m[2].length);\n if (m[3].trim() === '') lastBareFence = i;\n }\n if (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 if (lastBareFence > openerIdx) {\n const cm = lines[lastBareFence].match(fenceRe)!;\n lines[lastBareFence] = `${cm[1]}${fence}`;\n }\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\nexport const identity = (key: string) => key;\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 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: (key: string) => string): 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 `${minutes}${t('m ago')}`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}${t('h ago')}`;\n const days = Math.floor(hours / 24);\n if (days < 7) return `${days}${t('d ago')}`;\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","import type { ChatAttachment, ToolCallTraceEntry, TransferChainEntry } from '../../types';\nimport type { ParsedAction, ProtocolContext } from './types';\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 * 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 if (st === 'thinking' && ctx.hasUsedTools) {\n return { action: 'status', status: 'analyzing' };\n }\n return { action: 'status', status: st, tools: evt.tools as string[] | undefined };\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 };\n }\n\n return { action: 'noop' };\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 return { action: 'error', content: (evt.message as string) || 'Unknown error' };\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, useRef, useState } from 'react';\nimport type { AgentStatusState, ApiEndpoints, BackendType, ChatFile, ChatMessage } from '../types';\nimport type { ParsedAction, ProtocolContext } from './protocols';\nimport { parseAgUiEvent, parseLegacyEvent, parseRestEvent } from './protocols';\n\nconst STORAGE_KEY = 'filigranChatConversationId';\nconst LEGACY_CHAT_ID_KEY = 'filigranChatLegacyChatId';\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 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 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 * 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 },\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 // 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 [inputValue, setInputValue] = useState('');\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 const [attachedFiles, setAttachedFiles] = useState<ChatFile[]>([]);\n const [transferredAgent, setTransferredAgent] = useState<TransferredAgent | null>(null);\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 const hasUsedToolsRef = useRef(false);\n // Ref mirror of conversationId — always current across async boundaries\n const conversationIdRef = useRef(conversationId);\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 // 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 // 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 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\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 });\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 let accumulated = '';\n let doneReceived = false;\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 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 if (parsed.status === 'tool_start') hasUsedToolsRef.current = true;\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 === 'thinking_text') {\n setAgentStatus((prev) => ({\n ...prev,\n status: prev?.status ?? 'thinking',\n thinkingContent: (prev?.thinkingContent ?? '') + (parsed.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 setAgentStatus((prev) =>\n prev ? { ...prev, elapsedS: parsed.elapsedS } : { status: 'tool_start', tools: parsed.tools, elapsedS: parsed.elapsedS },\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 // 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 break;\n }\n\n case 'done': {\n doneReceived = true;\n if (parsed.conversationId) {\n updateConversationId(parsed.conversationId);\n }\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 setMessages((prev) =>\n prev.map((m) =>\n m.id === segId\n ? {\n ...m,\n content: finalContent,\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 }\n : m,\n ),\n );\n break;\n }\n\n case 'error': {\n ensureSegment();\n const segId = currentAssistantId;\n setMessages((prev) =>\n prev.map((m) =>\n m.id === segId ? { ...m, content: parsed.content || t('Unable to connect. Please check the configuration.') } : 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 if (accumulated && !doneReceived) {\n const segId = currentAssistantId;\n const text = accumulated;\n setMessages((prev) => prev.map((m) => (m.id === segId ? { ...m, content: text || 'No response.' } : m)));\n }\n } catch (err) {\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 abortControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n }\n };\n\n const handleNewChat = () => {\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 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 }\n };\n\n const handleStopGenerating = () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = null;\n setIsLoading(false);\n setAgentStatus(null);\n hasUsedToolsRef.current = false;\n setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.content)));\n };\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 transferredAgent,\n canSteer,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\n updateConversationId,\n handleSwitchConversation,\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 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\nexport function useAgents({ apiBaseUrl, apiEndpoints, backendType = 'rest', requestHeaders }: UseAgentsOptions): UseAgentsReturn {\n const [agents, setAgents] = useState<XtmAgent[]>([]);\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 fetch(agentsUrl, { headers: requestHeaders })\n .then((res) => (res.ok ? res.json() : []))\n .then((data: XtmAgent[]) => {\n setAgents(data);\n if (data.length > 0 && !selectedAgent) {\n const savedSlug = localStorage.getItem(STORAGE_AGENT_KEY);\n const match = savedSlug ? data.find((a) => a.slug === savedSlug) : null;\n setSelectedAgent(match || data[0]);\n }\n })\n .catch(() => {});\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 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}\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 return { conversationId: id, title, updatedAt, messageCount };\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 return { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation };\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';\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 ? `${agentName} ${t('has finished')}` : 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 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 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 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 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\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, useEffect, 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\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 useEffect(() => {\n if (!open || !anchorRef.current) return;\n const rect = anchorRef.current.getBoundingClientRect();\n const left = placement === 'bottom-end' ? rect.right - width : rect.left;\n setPos({ top: rect.bottom + 4, left });\n }, [open, anchorRef, placement, width]);\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","import { useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { findChatbotRoot } from '../utils';\n\ninterface TooltipProps {\n title: string;\n children: React.ReactElement;\n}\n\n// Approximate rendered tooltip height (text-xs + py-1) plus the 4px gap.\n// Used to decide whether a top-placed tooltip would overflow the panel.\nconst TOOLTIP_CLEARANCE = 28;\n\nexport const Tooltip = ({ title, children }: TooltipProps) => {\n const ref = useRef<HTMLSpanElement>(null);\n const [show, setShow] = useState(false);\n const [pos, setPos] = useState({ top: 0, left: 0 });\n const [below, setBelow] = useState(false);\n\n if (!title) return children;\n\n const handleEnter = () => {\n if (!ref.current) return;\n const rect = ref.current.getBoundingClientRect();\n // Flip below the anchor when a top-placed tooltip would extend above the\n // chatbot panel's top edge. The tooltip lives inside the panel's stacking\n // context (z-[1200] in sidebar mode), so anything drawn above the panel\n // lands in the host app's top-bar zone and is hidden whenever the host\n // bar stacks higher (e.g. OpenAEV's AppBar at theme.zIndex.drawer + 1).\n const rootTop = findChatbotRoot(ref.current).getBoundingClientRect().top;\n const flip = rect.top - rootTop < TOOLTIP_CLEARANCE;\n setBelow(flip);\n setPos({\n top: flip ? rect.bottom + 4 : rect.top - 4,\n left: rect.left + rect.width / 2,\n });\n setShow(true);\n };\n\n return (\n <span ref={ref} className=\"inline-flex\" onMouseEnter={handleEnter} onMouseLeave={() => setShow(false)}>\n {children}\n {show &&\n createPortal(\n <span\n className={`pointer-events-none fixed z-[10001] -translate-x-1/2 ${below ? '' : '-translate-y-full'} whitespace-nowrap 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={{ top: pos.top, left: pos.left }}\n role=\"tooltip\"\n >\n {title}\n </span>,\n findChatbotRoot(ref.current),\n )}\n </span>\n );\n};\n","import { useRef } from 'react';\nimport type { ChatConversationSummary, ChatMode, XtmAgent } from '../types';\nimport { timeAgo } from '../utils';\nimport {\n ChevronDownIcon,\n CloseIcon,\n EditIcon,\n ExternalLinkIcon,\n FloatingIcon,\n FullscreenExitIcon,\n FullscreenIcon,\n HistoryIcon,\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 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: (key: string) => string;\n}\n\nconst modeOptions: { mode: ChatMode; label: string; getIcon: (p: { size: number; className: string }) => React.ReactNode }[] = [\n { mode: 'floating', label: 'Floating', getIcon: (p) => <FloatingIcon {...p} /> },\n { mode: 'sidebar', label: 'Sidebar', getIcon: (p) => <SidebarIcon {...p} /> },\n { mode: 'fullscreen', label: 'Full screen', getIcon: (p) => <FullscreenIcon {...p} /> },\n];\n\nexport const ChatHeader = ({\n mode,\n agentName,\n agents,\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 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 {t('Transferred from')} {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 {agents.length === 0 && (\n <div className=\"px-4 py-2\">\n <Spinner size={16} />\n </div>\n )}\n <div>\n {agents.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\">{t(opt.label)}</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 { useRef, type KeyboardEvent } from 'react';\nimport type { ChatFile, ChatMode } from '../types';\nimport { AttachFileIcon, FileIcon, SendIcon, StopCircleIcon } from './icons';\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}\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}: ChatInputProps) => {\n const fileInputRef = useRef<HTMLInputElement>(null);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n onSend();\n }\n if (e.key === 'Escape' && isLoading) {\n e.preventDefault();\n onStop();\n }\n };\n\n const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n onInputChange(e.target.value);\n const el = e.target;\n el.style.height = 'auto';\n el.style.height = `${Math.min(el.scrollHeight, 120)}px`;\n };\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 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 <div className=\"flex items-center border border-gray-200 dark:border-white/10 rounded-xl px-2 py-1 transition-colors focus-within:border-[var(--chat-accent)]\">\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={t('Ask a question...')}\n value={inputValue}\n onChange={handleInput}\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: 120 }}\n />\n {showSteerSend && (\n <Tooltip title={t('Send now')}>\n <button\n type=\"button\"\n onClick={onSend}\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 : onSend}\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 <p className=\"text-center text-[0.65rem] text-gray-400 dark:text-white/30 mt-1.5 opacity-70\">{footerText}</p>\n </div>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { GamepadIcon } from './icons';\n\n/**\n * Playful, rotating \"still working on it\" messages shown below the status\n * bubble during longer waits. They double as the Space Invader's targets:\n * the little invader ship erases them letter by letter, then the next one\n * fades in. Kept short and upbeat so they fit on one line in the narrow\n * floating panel and read as a sense of progress rather than noise.\n */\nconst DEFAULT_MESSAGES = [\n 'Crunching the data',\n 'Connecting the dots',\n 'Consulting the sources',\n 'Thinking it through',\n 'Reticulating splines',\n 'Analyzing the details',\n 'Almost there',\n 'Putting it together',\n 'Polishing the answer',\n 'Wrapping things up',\n];\n\n/** localStorage key for the per-browser mini-game preference (on by default). */\nconst PREF_KEY = 'filigranChatMiniGame';\n\n/** Plain (no-game) message rotation cadence. */\nconst PLAIN_ROTATE_MS = 2600;\n\n/** Canvas height in CSS px — room for the target row + the gliding ship. */\nconst GAME_HEIGHT = 70;\n\n/** Chunky monospace for the retro arcade feel + even letter spacing. */\nconst arcadeFont = (px: number): string => `700 ${px}px 'Courier New', ui-monospace, monospace`;\n\n/**\n * Classic 11x8 \"crab\" invader, two leg frames toggled while it glides — the\n * silhouette reads instantly as a Space Invader. `1` = filled pixel.\n */\nconst INVADER_FRAMES: string[][] = [\n ['00100000100', '00010001000', '00111111100', '01101110110', '11111111111', '10111111101', '10100000101', '00011011000'],\n ['00100000100', '10010001001', '10111111101', '11101110111', '11111111111', '00111111100', '00100000100', '01000000010'],\n];\n\nfunction readPref(): boolean {\n if (typeof window === 'undefined') return true;\n try {\n return window.localStorage.getItem(PREF_KEY) !== 'off';\n } catch {\n return true;\n }\n}\n\nfunction writePref(on: boolean): void {\n try {\n window.localStorage.setItem(PREF_KEY, on ? 'on' : 'off');\n } catch {\n /* private mode / disabled storage — fall back to in-memory state only */\n }\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\n/** Px-from-bottom within which the user is considered \"still following\". */\nconst FOLLOW_THRESHOLD_PX = 140;\n\n/** Nearest vertically-scrollable ancestor of `el`, or null. */\nfunction findScrollParent(el: HTMLElement | null): HTMLElement | null {\n let node = el?.parentElement ?? null;\n while (node) {\n const oy = getComputedStyle(node).overflowY;\n if ((oy === 'auto' || oy === 'scroll') && node.scrollHeight > node.clientHeight) {\n return node;\n }\n node = node.parentElement;\n }\n return null;\n}\n\ninterface Letter {\n char: string;\n x: number;\n w: number;\n alive: boolean;\n}\n\ninterface Bullet {\n x: number;\n y: number;\n}\n\ninterface Particle {\n x: number;\n y: number;\n vx: number;\n vy: number;\n life: number;\n}\n\n/**\n * Self-contained canvas mini-game. Owns its own rAF loop, resize handling and\n * lifecycle; the only thing it reports back is the index of the message it is\n * currently destroying, so the host can keep an accessible text mirror in sync.\n * Returns a teardown function.\n */\nfunction createInvaderGame(canvas: HTMLCanvasElement, messages: string[], onMessage: (index: number) => void): () => void {\n const maybeCtx = canvas.getContext('2d');\n if (!maybeCtx) return () => {};\n const ctx: CanvasRenderingContext2D = maybeCtx;\n\n let raf = 0;\n let cssW = 0;\n const cssH = GAME_HEIGHT;\n let fontPx = 13;\n let accent = '#7b5cff';\n\n let msgIndex = 0;\n let letters: Letter[] = [];\n let targetIndex = -1;\n let bullets: Bullet[] = [];\n let particles: Particle[] = [];\n let shipX = 0;\n let cooldown = 0;\n let clearedAt = 0;\n let legFrame = 0;\n let legTimer = 0;\n let last = performance.now();\n\n const PX = 2;\n const SPRITE_W = 11 * PX;\n const SPRITE_H = 8 * PX;\n const shipTop = cssH - SPRITE_H - 4;\n const letterY = Math.round(cssH * 0.42);\n\n function resolveAccent(): void {\n const v = getComputedStyle(canvas).getPropertyValue('--chat-accent').trim();\n if (v) accent = v;\n }\n\n function firstAlive(from: number): number {\n for (let i = from; i < letters.length; i++) {\n if (letters[i].alive) return i;\n }\n return -1;\n }\n\n function layout(): void {\n if (cssW <= 0) return;\n const text = messages[msgIndex % messages.length] || '';\n onMessage(msgIndex % messages.length);\n\n // Shrink the font until the message fits the available width.\n fontPx = 13;\n for (; fontPx >= 8; fontPx--) {\n ctx.font = arcadeFont(fontPx);\n if (ctx.measureText(text).width <= cssW - 16) break;\n }\n ctx.font = arcadeFont(fontPx);\n\n const widths = Array.from(text).map((ch) => ctx.measureText(ch).width);\n const total = widths.reduce((a, b) => a + b, 0);\n let x = (cssW - total) / 2;\n letters = Array.from(text).map((ch, i) => {\n const lx = x;\n x += widths[i];\n return { char: ch, x: lx, w: widths[i], alive: ch.trim().length > 0 };\n });\n targetIndex = firstAlive(0);\n bullets = [];\n particles = [];\n cooldown = 0;\n clearedAt = 0;\n if (shipX <= 0) shipX = cssW / 2;\n }\n\n function letterCenter(i: number): number {\n return letters[i].x + letters[i].w / 2;\n }\n\n function update(dt: number): void {\n const dtf = Math.min(dt / 16.6667, 3);\n\n legTimer += dt;\n if (legTimer > 320) {\n legTimer = 0;\n legFrame ^= 1;\n }\n\n if (targetIndex === -1) {\n // Message fully cleared — brief pause, then load the next one.\n if (clearedAt === 0) clearedAt = performance.now();\n else if (performance.now() - clearedAt > 650) {\n msgIndex++;\n layout();\n }\n } else {\n const targetX = letterCenter(targetIndex);\n shipX += (targetX - shipX) * Math.min(0.16 * dtf, 1);\n cooldown -= dt;\n if (bullets.length === 0 && cooldown <= 0 && Math.abs(shipX - targetX) < 4) {\n bullets.push({ x: shipX, y: shipTop });\n cooldown = 130;\n }\n }\n\n for (let i = bullets.length - 1; i >= 0; i--) {\n bullets[i].y -= 2.6 * dtf;\n if (bullets[i].y <= letterY) {\n // Hit: detonate the current target letter and advance.\n if (targetIndex !== -1) {\n const cx = letterCenter(targetIndex);\n letters[targetIndex].alive = false;\n for (let p = 0; p < 7; p++) {\n const ang = (Math.PI * 2 * p) / 7 + Math.random();\n const spd = 0.6 + Math.random() * 1.4;\n particles.push({ x: cx, y: letterY, vx: Math.cos(ang) * spd, vy: Math.sin(ang) * spd, life: 1 });\n }\n targetIndex = firstAlive(targetIndex + 1);\n }\n bullets.splice(i, 1);\n }\n }\n\n for (let i = particles.length - 1; i >= 0; i--) {\n const p = particles[i];\n p.x += p.vx * dtf;\n p.y += p.vy * dtf;\n p.life -= 0.045 * dtf;\n if (p.life <= 0) particles.splice(i, 1);\n }\n }\n\n function draw(): void {\n ctx.clearRect(0, 0, cssW, cssH);\n\n // Single solid fill colour throughout; vary opacity via globalAlpha rather\n // than CSS color-mix() strings, which are not reliably accepted as a canvas\n // fillStyle on every browser (some fall back to opaque black).\n ctx.fillStyle = accent;\n\n ctx.font = arcadeFont(fontPx);\n ctx.textBaseline = 'middle';\n ctx.globalAlpha = 0.85;\n for (const l of letters) {\n if (l.alive) ctx.fillText(l.char, l.x, letterY);\n }\n\n ctx.globalAlpha = 1;\n for (const b of bullets) {\n ctx.fillRect(b.x - 1, b.y, 2, 7);\n }\n\n for (const p of particles) {\n ctx.globalAlpha = Math.max(p.life, 0) * 0.9;\n ctx.fillRect(p.x - 1.5, p.y - 1.5, 3, 3);\n }\n\n ctx.globalAlpha = 1;\n const frame = INVADER_FRAMES[legFrame];\n const ox = Math.round(shipX - SPRITE_W / 2);\n for (let r = 0; r < frame.length; r++) {\n const row = frame[r];\n for (let c = 0; c < row.length; c++) {\n if (row[c] === '1') ctx.fillRect(ox + c * PX, shipTop + r * PX, PX, PX);\n }\n }\n }\n\n function loop(now: number): void {\n const dt = now - last;\n last = now;\n if (!document.hidden && cssW > 0) {\n update(dt);\n draw();\n }\n raf = requestAnimationFrame(loop);\n }\n\n function applySize(): void {\n const rect = canvas.getBoundingClientRect();\n const dpr = window.devicePixelRatio || 1;\n cssW = rect.width;\n canvas.width = Math.max(1, Math.round(cssW * dpr));\n canvas.height = Math.round(cssH * dpr);\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n resolveAccent();\n layout();\n }\n\n // Prefer ResizeObserver; fall back to a window resize listener on older\n // browsers / embedded webviews where it is unavailable (an unguarded\n // `new ResizeObserver(...)` would throw and break the waiting experience).\n let ro: ResizeObserver | null = null;\n if (typeof ResizeObserver !== 'undefined') {\n ro = new ResizeObserver(applySize);\n ro.observe(canvas);\n } else {\n window.addEventListener('resize', applySize);\n }\n applySize();\n raf = requestAnimationFrame(loop);\n\n return () => {\n cancelAnimationFrame(raf);\n if (ro) ro.disconnect();\n else window.removeEventListener('resize', applySize);\n };\n}\n\ninterface ChatWaitingGameProps {\n t: (key: string) => string;\n /** Host-level override; when false the feature is hidden entirely. */\n enabled?: boolean;\n}\n\n/**\n * Waiting experience shown below the status bubble during longer waits:\n * dynamic rotating messages with an optional Space Invader mini-game that\n * shoots the message letters away one by one. The game can be toggled off\n * per browser (preference persisted in localStorage); when off — or when the\n * OS requests reduced motion — the messages simply rotate as plain dimmed\n * text, so the \"dynamic loading messages\" feedback always stands on its own.\n */\nexport const ChatWaitingGame = ({ t, enabled = true }: ChatWaitingGameProps) => {\n const messages = useMemo(() => DEFAULT_MESSAGES.map((m) => t(m)), [t]);\n const reducedMotion = usePrefersReducedMotion();\n const [minigameOn, setMinigameOn] = useState(readPref);\n const [msgIndex, setMsgIndex] = useState(0);\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const rootRef = useRef<HTMLDivElement>(null);\n\n const playMode = enabled && minigameOn && !reducedMotion;\n\n // The game mounts below the last message but, unlike streamed reasoning/answer\n // text (which auto-scrolls on length change), nothing else triggers a scroll —\n // so at the bottom it lands under the fold. Reveal it on mount IF the user is\n // still following the bottom; if they scrolled up to read history, leave them.\n useEffect(() => {\n const scroller = findScrollParent(rootRef.current);\n if (!scroller) return;\n const distance = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;\n if (distance <= FOLLOW_THRESHOLD_PX) {\n scroller.scrollTop = scroller.scrollHeight;\n }\n }, []);\n\n // Plain-text rotation when the game is off / reduced motion. Skipped while the\n // game drives the index, and entirely when the feature is disabled (so a\n // disabled host arms no timer); `enabled` is a dep so toggling it cleans up.\n useEffect(() => {\n if (playMode || !enabled) return;\n const id = window.setInterval(() => setMsgIndex((i) => (i + 1) % messages.length), PLAIN_ROTATE_MS);\n return () => window.clearInterval(id);\n }, [playMode, enabled, messages.length]);\n\n // Canvas engine when the game is on.\n useEffect(() => {\n if (!playMode) return;\n const canvas = canvasRef.current;\n if (!canvas) return;\n return createInvaderGame(canvas, messages, setMsgIndex);\n }, [playMode, messages]);\n\n if (!enabled) return null;\n\n const current = messages[msgIndex % messages.length];\n\n return (\n <div ref={rootRef} className=\"ml-11 mt-2.5 max-w-[78%]\">\n {/* Keep the live region scoped to the announced text only — wrapping the\n whole UI (including the toggle button) made screen readers re-announce\n the control alongside each message change. */}\n <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {current}\n </span>\n {/* Suppress every non-essential animation (fade-ins, the blinking caret)\n under prefers-reduced-motion, so the reduced-motion path really is\n motion-free — only the plain dimmed text rotates. */}\n <div\n className=\"relative overflow-hidden rounded-md bg-[var(--chat-accent)]/[0.03]\"\n style={reducedMotion ? undefined : { animation: 'chat-fade-in 0.5s ease-out' }}\n >\n {playMode ? (\n <canvas ref={canvasRef} aria-hidden className=\"block w-full\" style={{ height: GAME_HEIGHT }} />\n ) : (\n <div className=\"flex items-center\" style={{ height: GAME_HEIGHT }}>\n <span\n key={current}\n className=\"px-3 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 </div>\n )}\n {!reducedMotion && (\n <button\n type=\"button\"\n onClick={() => {\n const next = !minigameOn;\n setMinigameOn(next);\n writePref(next);\n }}\n aria-pressed={minigameOn}\n aria-label={minigameOn ? t('Turn off the waiting mini-game') : t('Turn on the waiting mini-game')}\n title={minigameOn ? t('Turn off the waiting mini-game') : t('Turn on the waiting mini-game')}\n className={`absolute top-1 right-1 rounded p-1 transition-opacity ${\n minigameOn ? 'text-[var(--chat-accent)] opacity-50 hover:opacity-100' : 'text-gray-400 dark:text-white/40 opacity-40 hover:opacity-90'\n }`}\n >\n <GamepadIcon size={13} />\n </button>\n )}\n </div>\n </div>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { AgentStatusState, IconProps } from '../types';\nimport {\n BrainIcon,\n DatabaseIcon,\n ExternalLinkIcon,\n GlobeIcon,\n MailIcon,\n SearchIcon,\n SparklesIcon,\n TerminalIcon,\n UserPlusIcon,\n WrenchIcon,\n} from './icons';\nimport { ChatWaitingGame } from './ChatWaitingGame';\n\ninterface ChatThinkingProps {\n agentStatus: AgentStatusState | null;\n logoIcon?: React.ReactNode;\n t: (key: string) => string;\n /** Host-level override for the waiting mini-game / dynamic messages. */\n miniGameEnabled?: boolean;\n}\n\ntype IconComponent = (props: IconProps) => React.JSX.Element;\n\ninterface StatusVisual {\n label: string;\n StatusIcon: IconComponent;\n showDots: boolean;\n}\n\nfunction resolveStatusVisual(agentStatus: AgentStatusState | null, t: (key: string) => string): 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 const label = count > 1 ? `${t('Delegating')} ${count} ${t('tasks')}…` : `${t('Delegating task')}…`;\n return { label, 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 const target = count > 1 ? `${count} ${t('background tasks')}` : t('background task');\n return { label: `${t('Waiting for')} ${target}…`, 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 const from = count > 1 ? `${count} ${t('tasks')}` : t('task');\n return { label: `${t('Collecting results from')} ${from}…`, 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]}…` : `${unique[0]} (+${unique.length - 1} more)…`;\n } else {\n label = t('Using tools…');\n }\n return { label, StatusIcon, showDots: false };\n }\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] ?? 'agent';\n return { label: `${t('Consulting')} ${consultName}…`, StatusIcon: UserPlusIcon, showDots: false };\n }\n case 'delegating': {\n const count = agentStatus.tools?.filter((n) => n === 'spawn_background_task').length ?? 0;\n return {\n label: count > 1 ? `${t('Delegating')} ${count} ${t('tasks')}…` : `${t('Delegating task')}…`,\n StatusIcon: UserPlusIcon,\n showDots: false,\n };\n }\n case 'polling': {\n const checkCount = agentStatus.tools?.filter((n) => n === 'check_task_status').length ?? 0;\n const target = checkCount > 1 ? `${checkCount} ${t('background tasks')}` : t('background task');\n return { label: `${t('Waiting for')} ${target}…`, StatusIcon: SparklesIcon, showDots: false };\n }\n case 'collecting': {\n const fetchCount = agentStatus.tools?.filter((n) => n === 'get_task_result').length ?? 0;\n const from = fetchCount > 1 ? `${fetchCount} ${t('tasks')}` : t('task');\n return { label: `${t('Collecting results from')} ${from}…`, StatusIcon: SparklesIcon, showDots: false };\n }\n case 'transferring': {\n const targetName = agentStatus.tools?.[0] ?? 'agent';\n return { label: `${t('Transferring to')} ${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 * 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.\n */\nexport function ThinkingTextBubble({ content }: { content: string }) {\n const ref = useRef<HTMLDivElement>(null);\n const [isOverflowing, setIsOverflowing] = useState(false);\n const cleaned = cleanReasoningText(content);\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 }, [cleaned]);\n\n if (cleaned.length < 3) return null;\n\n return (\n <div\n className=\"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 style={{ animation: 'reasoningGlow 3s ease-in-out infinite, chat-fade-in 0.5s ease-out' }}\n >\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\">{cleaned}</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 * The reasoning window flips to the waiting game once nothing has progressed\n * for this long — i.e. no reasoning at all, or a reasoning stream that stalled.\n */\nconst STALL_DELAY_MS = 5000;\n\n/**\n * True once `signal` has stayed unchanged for `delayMs`. Re-arms whenever the\n * signal changes, so resumed reasoning clears the flag immediately. Used to\n * detect a stalled (or absent) reasoning stream so we can show the waiting game\n * in the meantime and flip back to the reasoning the moment it resumes. Arms no\n * timer (and never flips) while `enabled` is false, so a host that disables the\n * waiting game schedules no timeouts or re-renders for it.\n */\nfunction useStalled(signal: number, delayMs: number, enabled: boolean): boolean {\n const [stalled, setStalled] = useState(false);\n const prevSignalRef = useRef(signal);\n\n // Did the signal change since the last settled render? When it did, reasoning\n // has just resumed, so we report \"not stalled\" for this very render without a\n // render-phase state update (discouraged in React / brittle under StrictMode\n // and concurrent rendering). The effect below then resets the flag and re-arms\n // the timer — deriving the value here keeps the flip back to the reasoning\n // window free of the one-frame lag a clear-in-effect alone would leave.\n const signalChanged = prevSignalRef.current !== signal;\n\n useEffect(() => {\n prevSignalRef.current = signal;\n setStalled(false);\n if (!enabled) return;\n const id = window.setTimeout(() => setStalled(true), delayMs);\n return () => window.clearTimeout(id);\n }, [signal, delayMs, enabled]);\n\n return enabled && stalled && !signalChanged;\n}\n\nexport const ChatThinking = ({ agentStatus, logoIcon, t, miniGameEnabled = true }: ChatThinkingProps) => {\n const { label, StatusIcon, showDots } = resolveStatusVisual(agentStatus, t);\n const thinkingContent = agentStatus?.thinkingContent;\n const elapsedS = agentStatus?.elapsedS;\n const showElapsed = typeof elapsedS === 'number' && elapsedS >= ELAPSED_DISPLAY_THRESHOLD_S;\n // Show the waiting game when reasoning is absent or has stalled for 5s; flip\n // back to the reasoning window the moment new reasoning text resumes (the\n // accumulated content carries the continuation).\n const stalled = useStalled(thinkingContent?.length ?? 0, STALL_DELAY_MS, miniGameEnabled);\n const showGame = miniGameEnabled && stalled;\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 {thinkingContent && !showGame ? (\n <ThinkingTextBubble content={thinkingContent} />\n ) : showGame ? (\n <ChatWaitingGame t={t} enabled={miniGameEnabled} />\n ) : null}\n </>\n );\n};\n","import { useMemo, useState } from 'react';\nimport Markdown from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport { CheckIcon, CopyIcon } from './icons';\nimport { hardenNestedCodeFences, normalizeMarkdownTables } from '../utils';\n\ninterface MarkdownMessageProps {\n content: string;\n onRelativeLinkClick?: (href: string) => void;\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\nexport const MarkdownMessage = ({ content, onRelativeLinkClick }: MarkdownMessageProps) => {\n const [copiedBlock, setCopiedBlock] = useState<string | null>(null);\n\n // Preprocess once per `content`: this component re-renders on UI-only state\n // (e.g. `copiedBlock`), and both passes scan the whole message, so memoizing\n // keeps that work off the hot path for large messages.\n const processedContent = useMemo(() => normalizeMarkdownTables(hardenNestedCodeFences(content)), [content]);\n\n const handleCopyCode = (code: string) => {\n navigator.clipboard.writeText(code);\n setCopiedBlock(code);\n setTimeout(() => setCopiedBlock(null), 2000);\n };\n\n return (\n <Markdown\n remarkPlugins={[remarkGfm]}\n 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 code: ({ className, children }) => {\n const match = /language-(\\w+)/.exec(className || '');\n const codeStr = String(children).replace(/\\n$/, '');\n if (match) {\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]}</span>\n <button\n type=\"button\"\n onClick={() => handleCopyCode(codeStr)}\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 (\n <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 },\n ul: ({ children }) => (\n <ul className=\"pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">{children}</ul>\n ),\n ol: ({ children }) => (\n <ol className=\"pl-5 mb-3 text-[0.8125rem] text-gray-900 dark:text-white/90 [&_li]:mb-1 marker:text-[var(--chat-accent)]/50\">{children}</ol>\n ),\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: ({ href, children }) => {\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 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 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 }) => (\n <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 }}\n >\n {processedContent}\n </Markdown>\n );\n};\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 } 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 ? `${iterations} ${t('iterations')}` : '',\n `${totalCalls} ${totalCalls === 1 ? t('tool call') : t('tool calls')}`,\n transfers.length > 0 ? `${transfers.length} ${transfers.length === 1 ? t('transfer') : t('transfers')}` : '',\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 { useEffect, useRef, useState } from 'react';\nimport type { AgentStatusState, ChatAttachment, ChatMessage } from '../types';\nimport { splitFileMarkers } from '../utils';\nimport { AlertTriangleIcon, DownloadIcon, FileIcon, InfoIcon } from './icons';\nimport { ChatThinking } from './ChatThinking';\nimport { MarkdownMessage } from './MarkdownMessage';\nimport { ReasoningDetailsDialog } from './ReasoningDetailsDialog';\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 /** Host-level override for the waiting mini-game / dynamic messages. */\n miniGameEnabled?: boolean;\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\nexport const ChatMessages = ({\n messages,\n isLoading,\n agentStatus,\n agentName,\n logoIcon,\n onRelativeLinkClick,\n onDownloadFile,\n miniGameEnabled = true,\n t,\n}: ChatMessagesProps) => {\n const messagesEndRef = useRef<HTMLDivElement>(null);\n const [toolDetailMsgId, setToolDetailMsgId] = useState<string | null>(null);\n\n useEffect(() => {\n messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });\n }, [messages]);\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. `behavior: 'instant'` (CSSOM View,\n // Baseline-supported) forces a non-animated jump — this fires on every\n // reasoning chunk and smooth animations would queue up; 'auto' would not\n // do, since a `scroll-behavior: smooth` ancestor turns it smooth again.\n const thinkingLen = agentStatus?.thinkingContent?.length ?? 0;\n useEffect(() => {\n if (!thinkingLen) return;\n messagesEndRef.current?.scrollIntoView({ behavior: 'instant' });\n }, [thinkingLen]);\n\n const renderAttachmentCard = (att: ChatAttachment, key: string) => {\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 // 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 = (msg: ChatMessage, loading: boolean): 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 content={part.value} onRelativeLinkClick={onRelativeLinkClick} />\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 && !loading) {\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 // 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 // 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 = (msg: ChatMessage): 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 // 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 lastAssistantIndex = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n lastAssistantIndex = i;\n break;\n }\n }\n\n return (\n <div className=\"flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable\">\n {messages.map((msg, index) => {\n const isAssistant = msg.role === 'assistant';\n const isEmpty = !msg.content;\n // The live cursor / thinking bubble / ChatThinking state — and,\n // conversely, the hiding of the completed-message affordances (the\n // reasoning \"i\" button) — must be gated on the streaming message.\n // Gating those on the global `isLoading` instead made the blinking\n // cursor leak onto every prior assistant message and the \"i\" button\n // vanish from all of them while a *later* response was streaming.\n const isStreamingMessage = isLoading && index === lastAssistantIndex;\n const isThinking = isAssistant && isEmpty && isStreamingMessage;\n\n if (isThinking) {\n return (\n <div key={msg.id}>\n <ChatThinking agentStatus={agentStatus} logoIcon={logoIcon} t={t} miniGameEnabled={miniGameEnabled} />\n </div>\n );\n }\n\n return (\n <div key={msg.id} className={`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 <span className=\"font-semibold text-xs text-gray-900 dark:text-white\">{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(msg)}</div>\n )}\n\n {isAssistant ? (\n <div className=\"flex flex-col gap-1.5 w-full items-start\">\n {buildAssistantBlocks(msg, isStreamingMessage)}\n {!isEmpty && isStreamingMessage && (\n <span className=\"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse\" />\n )}\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 {isAssistant &&\n !isEmpty &&\n !isStreamingMessage &&\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 <button\n type=\"button\"\n onClick={() => setToolDetailMsgId(toolDetailMsgId === msg.id ? null : msg.id)}\n className={`mt-0.5 p-1 rounded-lg transition-opacity ${\n msg.isTruncated\n ? // A truncated turn must be visible at a glance (not\n // gated on hover) so the user notices the warning —\n // mirrors the 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 : 'opacity-50 hover:opacity-100 hover:text-[var(--chat-accent)]'\n }`}\n title={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}\n aria-label={msg.isTruncated ? t('Reasoning details — turn limit reached') : t('Reasoning details')}\n aria-haspopup=\"dialog\"\n aria-expanded={toolDetailMsgId === msg.id}\n >\n {msg.isTruncated ? <AlertTriangleIcon size={14} /> : <InfoIcon size={14} />}\n </button>\n {toolDetailMsgId === msg.id && <ReasoningDetailsDialog msg={msg} onClose={() => setToolDetailMsgId(null)} t={t} />}\n </>\n )}\n </div>\n );\n })}\n <div ref={messagesEndRef} />\n </div>\n );\n};\n","interface ChatWelcomeProps {\n firstName: string;\n logoIcon: React.ReactNode;\n promptSuggestions: string[];\n onPromptClick: (prompt: string) => void;\n t: (key: string) => string;\n}\n\nexport const ChatWelcome = ({ firstName, logoIcon, promptSuggestions, onPromptClick, t }: 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 <h2 className=\"text-xl font-medium mb-6 text-center text-gray-900 dark:text-white\" style={{ fontFamily: '\"Geologica\", sans-serif' }}>\n {t('How can I help you, ')}\n {firstName}?\n </h2>\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 {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 {t(prompt)}\n </button>\n ))}\n </div>\n </div>\n);\n","import { type FunctionComponent, useCallback, useEffect, useRef, useState } from 'react';\nimport type { ChatAttachment, ChatMessage, ChatPanelProps } from '../types';\nimport { hexAlpha, identity } from '../utils';\nimport { parseAttachments, parseToolCallTrace, parseTransferChain } 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 { DefaultLogoIcon } from './icons';\nimport { ChatHeader } from './ChatHeader';\nimport { ChatInput } from './ChatInput';\nimport { ChatMessages } from './ChatMessages';\nimport { ChatWelcome } from './ChatWelcome';\n\nconst FLOATING_WIDTH = 380;\nconst FLOATING_HEIGHT = 560;\nconst SIDEBAR_GAP = 6;\n\nconst DEFAULT_SUGGESTIONS = [\n 'Help me create a new simulation scenario',\n 'What are the latest attack patterns?',\n 'How do I configure detection rules?',\n 'Summarize my recent findings',\n];\n\nexport const ChatPanel: FunctionComponent<ChatPanelProps> = ({\n mode,\n onClose,\n onModeChange,\n topOffset = 0,\n apiBaseUrl,\n apiEndpoints,\n agentDashboardUrl,\n user,\n t = identity,\n accentColor = '#7b5cff',\n logoIcon,\n promptSuggestions = DEFAULT_SUGGESTIONS,\n draftBorderColor,\n resizable = false,\n onWidthChange,\n onResizeStart,\n onResizeEnd,\n disableFileManagement = false,\n onRelativeLinkClick,\n onDownloadError,\n maxFileCount,\n maxTotalSize,\n requestHeaders,\n pageContext,\n pushContentSelector,\n backendType = 'rest',\n miniGameEnabled = true,\n notifyOnComplete = true,\n onTaskComplete,\n}) => {\n const [modeMenuOpen, setModeMenuOpen] = useState(false);\n\n const { agents, 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 transferredAgent,\n canSteer,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\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 { historyEnabled, conversations, conversationsLoading, refreshConversations, deleteConversation } = useConversations({\n apiBaseUrl,\n apiEndpoints,\n backendType,\n requestHeaders,\n });\n const [historyMenuOpen, setHistoryMenuOpen] = useState(false);\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 const resolvedLogo = logoIcon ?? <DefaultLogoIcon size={24} />;\n const firstName = user.firstName;\n const agentName = transferredAgent?.name || selectedAgent?.name || '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 const handleDownloadFile = useCallback(\n async (att: ChatAttachment) => {\n const base = apiEndpoints?.download ?? '/chat/files';\n const url = `${apiBaseUrl}${base}/${encodeURIComponent(att.fileId)}/download`;\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 [apiBaseUrl, apiEndpoints, 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 if (!conversationId || 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 if (!data.messages?.length) return;\n const restored: ChatMessage[] = data.messages.map(\n (\n m: {\n role: string;\n content: string;\n attachments?: unknown;\n tool_names?: unknown;\n tool_call_count?: unknown;\n iterations?: unknown;\n reasoning?: unknown;\n tool_call_trace?: unknown;\n transfer_chain?: unknown;\n is_truncated?: unknown;\n },\n i: number,\n ) => ({\n id: `restored-${i}`,\n role: m.role as 'user' | 'assistant',\n content: m.content,\n timestamp: new Date(),\n // Re-surface downloadable file chips on conversation restore for\n // both roles: agent-generated deliverables on assistant messages\n // (the [[FILE:…]] markers in content are stripped at render time by\n // ChatMessages) and user-uploaded files on user messages (so an\n // upload stays downloadable after a page reload, not just in the\n // live session where it is carried on `files`).\n attachments: parseAttachments(m.attachments),\n // Re-surface the reasoning-details affordance (\"i\" button) on\n // restored assistant messages — 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 setMessages(restored);\n })\n .catch(() => {\n if (isStale()) return;\n updateConversationId(null);\n });\n }, [\n conversationId,\n selectedAgent,\n apiBaseUrl,\n apiEndpoints,\n backendType,\n historyLoadedRef,\n conversationIdRef,\n isMountedRef,\n requestHeaders,\n setMessages,\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 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}\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 {messages.length === 0 ? (\n <ChatWelcome firstName={firstName} logoIcon={resolvedLogo} promptSuggestions={promptSuggestions} onPromptClick={setInputValue} t={t} />\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 miniGameEnabled={miniGameEnabled}\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 />\n </div>\n );\n};\n","import type { FunctionComponent } from 'react';\nimport type { ChatToggleButtonProps } from '../types';\nimport { hexAlpha } from '../utils';\nimport { DefaultLogoIcon } from './icons';\n\nexport const ChatToggleButton: FunctionComponent<ChatToggleButtonProps> = ({\n isOpen,\n onToggle,\n label = 'Ask Assistant',\n accentColor = '#7b5cff',\n icon,\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}\n </button>\n );\n};\n"],"names":["hexAlpha","hex","alpha","Math","round","toString","padStart","identity","key","findChatbotRoot","el","node","classList","contains","parentElement","document","body","PARTIAL_FILE_MARKER_RE","parseAttachments","raw","Array","isArray","out","item","a","fileId","file_id","push","filename","type","undefined","size","contentType","content_type","fileTag","file_tag","length","parseToolCallTrace","e","name","input","output","success","parseTransferChain","agent_name","agentId","agent_id","agentName","parseRestEvent","evt","ctx","action","content","st","status","thinkingContent","hasUsedTools","tools","elapsedS","elapsed_s","conversationId","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","parseLegacyEvent","eventType","event","data","nodeId","activeNodeId","replace","usedTools","map","t","tool","chatId","parseAgUiEvent","message","stepName","delta","toolName","toolCallName","STORAGE_KEY","LEGACY_CHAT_ID_KEY","DEFAULT_MAX_TOTAL_SIZE","useChat","apiBaseUrl","apiEndpoints","backendType","agentSlug","requestHeaders","pageContext","maxFileCount","maxTotalSize","isLegacy","messages","setMessages","useState","inputValue","setInputValue","isLoading","setIsLoading","agentStatus","setAgentStatus","setConversationId","window","localStorage","getItem","attachedFiles","setAttachedFiles","transferredAgent","setTransferredAgent","legacyChatId","setLegacyChatId","historyLoadedRef","useRef","abortControllerRef","hasUsedToolsRef","conversationIdRef","pageContextRef","current","creatingSessionRef","uploadAbortRef","AbortController","effectiveMaxFileCount","Number","isFinite","floor","effectiveMaxTotalSize","getSteerUrl","singleEndpoint","steer","getUploadUrl","upload","updateConversationId","useCallback","id","setItem","removeItem","ensureConversation","async","slug","sessionsUrl","sessions","promise","res","fetch","method","headers","JSON","stringify","agent_slug","ok","json","convId","uploadSingleFile","file","signal","uploadUrl","formData","FormData","append","uploadHeaders","Object","fromEntries","entries","filter","k","toLowerCase","Error","ids","file_ids","handleFileAdd","fileList","candidates","from","tempId","crypto","randomUUID","accepted","prev","currentCount","currentSize","reduce","sum","f","slotsAvailable","sizeLeft","filtered","c","slice","newEntries","rawFile","uploadStatus","setTimeout","p","err","DOMException","handleNewChat","abort","canSteer","handlePaste","files","clipboardData","preventDefault","handleSendMessage","steerText","trim","steerUrl","optimistic","role","timestamp","Date","m","steerMessage","userMsg","assistantId","currentAssistantId","controller","fileIds","requestBody","opts","question","streaming","threadId","runId","context","state","forwardedProps","keys","serialized","buildRequestBody","parseEvent","getParser","reader","getReader","decoder","TextDecoder","buffer","accumulated","doneReceived","ensureSegment","segmentId","done","value","read","decode","stream","lines","split","pop","rawLine","line","startsWith","jsonStr","parsed","parse","segId","text","finalContent","handleStopGenerating","handleSwitchConversation","STORAGE_AGENT_KEY","parseConversation","title","updatedAt","updated_at","created_at","messageCount","message_count","SIDEBAR_WIDTH","SIDEBAR_WIDTH_STORAGE_KEY","flashTimer","originalTitle","activeHooks","stopTitleFlash","clearInterval","useAwayCompletionNotice","enabled","onComplete","isViewingChat","wasLoadingRef","startRef","useEffect","clearOnReturn","hidden","hasFocus","addEventListener","removeEventListener","max","wasLoading","now","unfocused","away","viewingChat","showMessage","setInterval","startTitleFlash","Notification","permission","tag","notifyOS","AlertTriangleIcon","className","_jsxs","xmlns","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","children","_jsx","d","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","InfoIcon","MailIcon","SearchIcon","SendIcon","SidebarIcon","SparklesIcon","StopCircleIcon","TerminalIcon","TrashIcon","UserPlusIcon","WrenchIcon","XCircleIcon","Dropdown","open","onClose","anchorRef","placement","panelRef","pos","setPos","top","left","ref","handler","active","listener","target","useClickOutside","rect","getBoundingClientRect","right","bottom","portalTarget","createPortal","style","Spinner","Tooltip","show","setShow","below","setBelow","onMouseEnter","rootTop","flip","onMouseLeave","modeOptions","mode","label","getIcon","ChatHeader","agents","selectedAgent","transferredFrom","agentMenuOpen","onAgentMenuToggle","onAgentMenuClose","onSwitchAgent","modeMenuOpen","onModeMenuToggle","onModeMenuClose","onModeChange","onNewChat","logoIcon","agentDashboardUrl","historyEnabled","historyMenuOpen","onHistoryMenuToggle","onHistoryMenuClose","conversations","conversationsLoading","activeConversationId","onSelectConversation","onDeleteConversation","agentAnchorRef","modeAnchorRef","historyAnchorRef","CurrentModeIcon","onClick","agent","description","_Fragment","conv","isActive","when","iso","then","getTime","isNaN","diffMs","minutes","hours","days","toLocaleDateString","month","day","timeAgo","opt","ChatInput","onInputChange","onSend","onStop","onFileAdd","onFileRemove","onPaste","separatorColor","fileInputRef","textareaRef","isFileManagementEnabled","Boolean","hasContent","hasFilesUploading","some","canSend","hasAttachments","showSteerSend","footerText","borderTopColor","borderTopWidth","i","multiple","onChange","click","placeholder","min","scrollHeight","onKeyDown","shiftKey","rows","maxHeight","disabled","DEFAULT_MESSAGES","PREF_KEY","arcadeFont","px","INVADER_FRAMES","readPref","createInvaderGame","canvas","onMessage","maybeCtx","getContext","raf","cssW","fontPx","accent","msgIndex","letters","targetIndex","bullets","particles","shipX","cooldown","clearedAt","legFrame","legTimer","last","performance","letterY","cssH","firstAlive","alive","layout","font","measureText","widths","ch","total","b","lx","char","w","letterCenter","applySize","dpr","devicePixelRatio","setTransform","v","getComputedStyle","getPropertyValue","resolveAccent","ro","ResizeObserver","observe","requestAnimationFrame","loop","dt","dtf","targetX","abs","ang","PI","random","spd","vx","cos","vy","sin","life","splice","update","clearRect","fillStyle","textBaseline","globalAlpha","l","fillText","fillRect","frame","ox","SPRITE_W","row","draw","cancelAnimationFrame","disconnect","ChatWaitingGame","useMemo","reducedMotion","reduced","setReduced","matchMedia","matches","mql","addListener","removeListener","usePrefersReducedMotion","minigameOn","setMinigameOn","setMsgIndex","canvasRef","rootRef","playMode","scroller","oy","overflowY","clientHeight","findScrollParent","scrollTop","animation","next","on","writePref","cleanReasoningText","ThinkingTextBubble","isOverflowing","setIsOverflowing","cleaned","formatElapsed","seconds","s","ChatThinking","miniGameEnabled","StatusIcon","showDots","rawNames","lower","n","count","includes","display","toUpperCase","unique","Set","consultName","checkCount","fetchCount","targetName","resolveStatusVisual","showElapsed","stalled","delayMs","setStalled","prevSignalRef","signalChanged","clearTimeout","useStalled","showGame","delay","isRelativeHref","href","test","MarkdownMessage","onRelativeLinkClick","copiedBlock","setCopiedBlock","processedContent","indexOf","splitCells","endsWith","cells","isDelimiterRow","alignOf","cell","fenceRe","fenceChar","fenceLen","listMarkerRe","fenceMatch","match","run","header","delim","markerMatch","offset","trimStart","indent","repeat","headerCols","delimCells","aligns","join","normalizeMarkdownTables","markupLang","openerIdx","maxRun","nestedCount","lastBareFence","fence","om","cm","hardenNestedCodeFences","Markdown","remarkPlugins","remarkGfm","components","code","exec","codeStr","String","handleCopyCode","navigator","clipboard","writeText","ul","ol","blockquote","internalHref","url","URL","location","protocol","origin","pathname","search","hash","toInternalHref","routeInternally","openInNewTab","rel","h1","h2","h3","table","th","td","prettyTraceValue","toolDisplayName","ToolCallRow","entry","index","expanded","setExpanded","inputDisplay","outputDisplay","hasInput","ReasoningDetailsDialog","msg","hostRef","closeButtonRef","dialogRef","root","setRoot","dialog","focusable","querySelectorAll","first","activeElement","focus","previouslyFocused","HTMLElement","preventScroll","totalCalls","transfers","trace","summaryParts","stopPropagation","tn","tr","fileExtensionLabel","dot","lastIndexOf","ext","ChatMessages","onDownloadFile","messagesEndRef","toolDetailMsgId","setToolDetailMsgId","scrollIntoView","behavior","thinkingLen","renderAttachmentCard","att","isWorking","sizeLabel","bytes","toFixed","buildAssistantBlocks","loading","parts","re","lastIndex","tail","splitFileMarkers","attByFileId","Map","used","blocks","forEach","part","get","add","has","renderFileChip","buildUserFileBlocks","seen","lastAssistantIndex","isAssistant","isEmpty","isStreamingMessage","ChatWelcome","firstName","promptSuggestions","onPromptClick","fontFamily","prompt","DEFAULT_SUGGESTIONS","ChatPanel","topOffset","user","accentColor","draftBorderColor","resizable","onWidthChange","onResizeStart","onResizeEnd","disableFileManagement","onDownloadError","pushContentSelector","notifyOnComplete","onTaskComplete","setModeMenuOpen","setAgentMenuOpen","handleSwitchAgent","setAgents","setSelectedAgent","savedSlug","find","catch","onSwitch","useAgents","refreshConversations","deleteConversation","setConversations","setConversationsLoading","history","rawList","encodeURIComponent","useConversations","setHistoryMenuOpen","sidebarWidth","handleResizeStart","defaultWidth","isResizing","setSidebarWidth","stored","parseInt","setIsResizing","isResizingRef","sidebarWidthRef","onWidthChangeRef","onResizeEndRef","handleMouseMove","newWidth","innerWidth","clientX","maxWidth","clamped","handleMouseUp","cursor","userSelect","handleWindowResize","useSidebarResize","pushWidth","documentElement","setProperty","contentElement","querySelector","originalPaddingRight","paddingRight","originalTransition","transition","resolvedLogo","panel","checkVisibility","getClientRects","downloadPathProvided","download","canDownload","handleDownloadFile","credentials","blob","objectUrl","createObjectURL","link","createElement","appendChild","remove","revokeObjectURL","cssVars","isMountedRef","requestedConversationId","isStale","restored","containerClasses","base","containerStyle","onMouseDown","handleDeleteConversation","_","j","ChatToggleButton","isOpen","onToggle","icon","resolvedIcon","borderColor","color","backgroundColor","currentTarget"],"mappings":"2PAAM,SAAUA,EAASC,EAAaC,GAIpC,MAAO,GAAGD,IAHAE,KAAKC,MAAc,IAARF,GAClBG,SAAS,IACTC,SAAS,EAAG,MAEjB,CAmKO,MAAMC,EAAYC,GAAgBA,EAQnC,SAAUC,EAAgBC,GAC9B,IAAIC,EAAOD,EACX,KAAOC,GAAM,CACX,GAAIA,EAAKC,UAAUC,SAAS,oBAAqB,OAAOF,EACxDA,EAAOA,EAAKG,aACd,CACA,OAAOC,SAASC,IAClB,CAiCA,MAAMC,EAAyB,2BC/MzB,SAAUC,EAAiBC,GAC/B,IAAKC,MAAMC,QAAQF,GAAM,OACzB,MAAMG,EAAwB,GAC9B,IAAK,MAAMC,KAAQJ,EAAK,CACtB,IAAKI,GAAwB,iBAATA,EAAmB,SACvC,MAAMC,EAAID,EACJE,EAASD,EAAEE,QACK,iBAAXD,GAAwBA,GACnCH,EAAIK,KAAK,CACPF,SACAG,SAAgC,iBAAfJ,EAAEI,SAAwBJ,EAAEI,SAAW,OACxDC,KAAwB,iBAAXL,EAAEK,KAAoBL,EAAEK,UAAOC,EAC5CC,KAAwB,iBAAXP,EAAEO,KAAoBP,EAAEO,UAAOD,EAC5CE,YAAuC,iBAAnBR,EAAES,aAA4BT,EAAES,kBAAeH,EACnEI,QAAwB,iBAAfV,EAAEW,SAA8B,eAAiB,iBAE9D,CACA,OAAOb,EAAIc,OAAS,EAAId,OAAMQ,CAChC,CAQM,SAAUO,EAAmBlB,GACjC,IAAKC,MAAMC,QAAQF,GAAM,OACzB,MAAMG,EAA4B,GAClC,IAAK,MAAMC,KAAQJ,EAAK,CACtB,IAAKI,GAAwB,iBAATA,EAAmB,SACvC,MAAMe,EAAIf,EACY,iBAAXe,E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