@filigran/chatbot 3.5.2 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/utils/index.ts","../../src/hooks/protocols/parseRestEvent.ts","../../src/hooks/protocols/parseLegacyEvent.ts","../../src/hooks/protocols/parseAgUiEvent.ts","../../src/hooks/useChat.ts","../../src/hooks/useAgents.ts","../../src/hooks/useSidebarResize.ts","../../src/components/icons/AttachFileIcon.tsx","../../src/components/icons/BrainIcon.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/GlobeIcon.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/UserPlusIcon.tsx","../../src/components/icons/WrenchIcon.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/ChatThinking.tsx","../../src/components/MarkdownMessage.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\nexport const identity = (key: string) => key;\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 } 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 * 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 === '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 };\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 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\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 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 const handleSendMessage = async () => {\n if ((!inputValue.trim() && attachedFiles.length === 0) || isLoading) 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 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 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 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 === assistantId ? { ...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 {\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 accumulated += parsed.content;\n setAgentStatus((prev) => ({ status: 'streaming', thinkingContent: prev?.thinkingContent }));\n setMessages((prev) => prev.map((m) => (m.id === assistantId ? { ...m, content: accumulated } : m)));\n break;\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 setMessages((prev) =>\n prev.map((m) =>\n m.id === assistantId\n ? {\n ...m,\n content: parsed.content || accumulated,\n toolNames: parsed.toolNames,\n toolCallCount: parsed.toolCallCount,\n iterations: parsed.iterations,\n attachments: parsed.attachments,\n }\n : m,\n ),\n );\n break;\n\n case 'error':\n setMessages((prev) =>\n prev.map((m) =>\n m.id === assistantId ? { ...m, content: parsed.content || t('Unable to connect. Please check the configuration.') } : m,\n ),\n );\n return;\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 setMessages((prev) => prev.map((m) => (m.id === assistantId ? { ...m, content: accumulated || 'No response.' } : m)));\n }\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') return;\n setMessages((prev) => prev.map((m) => (m.id === assistantId ? { ...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 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 return {\n messages,\n inputValue,\n setInputValue,\n isLoading,\n agentStatus,\n attachedFiles,\n conversationId,\n transferredAgent,\n historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\n updateConversationId,\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 { 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 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 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 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 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 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 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 { useCallback, useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useClickOutside } from '../hooks/useClickOutside';\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\nfunction 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\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';\n\ninterface TooltipProps {\n title: string;\n children: React.ReactElement;\n}\n\nfunction 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\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\n if (!title) return children;\n\n const handleEnter = () => {\n if (!ref.current) return;\n const rect = ref.current.getBoundingClientRect();\n setPos({\n top: 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 -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 { ChatMode, XtmAgent } from '../types';\nimport {\n ChevronDownIcon,\n CloseIcon,\n EditIcon,\n ExternalLinkIcon,\n FloatingIcon,\n FullscreenExitIcon,\n FullscreenIcon,\n SidebarIcon,\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 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 t,\n}: ChatHeaderProps) => {\n const agentAnchorRef = useRef<HTMLButtonElement>(null);\n const modeAnchorRef = 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 <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 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 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 };\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\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 <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'\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\">{t('Uses AI. Verify results.')}</p>\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';\n\ninterface ChatThinkingProps {\n agentStatus: AgentStatusState | null;\n logoIcon?: React.ReactNode;\n t: (key: string) => string;\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 '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 */\nfunction 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/** A scroll position within this distance of the bottom counts as \"pinned\". */\nconst REASONING_PIN_THRESHOLD_PX = 24;\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) scrolling window 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. Scrolling up detaches the pin so\n * earlier reasoning can be read while tokens keep streaming; scrolling back\n * to the bottom re-pins. The window (and the status bubble above it)\n * disappears the moment the final answer starts flowing.\n */\nexport function ThinkingTextBubble({ content }: { content: string }) {\n const ref = useRef<HTMLDivElement>(null);\n const [isOverflowing, setIsOverflowing] = useState(false);\n const pinnedRef = useRef(true);\n const cleaned = cleanReasoningText(content);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (pinnedRef.current) 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 onScroll={() => {\n const el = ref.current;\n if (!el) return;\n pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < REASONING_PIN_THRESHOLD_PX;\n }}\n className={`max-h-40 overflow-y-auto overscroll-contain [scrollbar-width:none] [&::-webkit-scrollbar]: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\nexport const ChatThinking = ({ agentStatus, logoIcon, t }: ChatThinkingProps) => {\n const { label, StatusIcon, showDots } = resolveStatusVisual(agentStatus, t);\n const thinkingContent = agentStatus?.thinkingContent;\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 </div>\n </div>\n </div>\n {thinkingContent && <ThinkingTextBubble content={thinkingContent} />}\n </>\n );\n};\n","import { useState } from 'react';\nimport Markdown from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport { CheckIcon, CopyIcon } from './icons';\nimport { hardenNestedCodeFences } 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\nexport const MarkdownMessage = ({ content, onRelativeLinkClick }: MarkdownMessageProps) => {\n const [copiedBlock, setCopiedBlock] = useState<string | null>(null);\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 openInNewTab = !isRelativeHref(href);\n const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {\n if (!href || !isRelativeHref(href) || !onRelativeLinkClick) return;\n event.preventDefault();\n onRelativeLinkClick(href);\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 {hardenNestedCodeFences(content)}\n </Markdown>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { AgentStatusState, ChatAttachment, ChatMessage } from '../types';\nimport { splitFileMarkers } from '../utils';\nimport { DownloadIcon, FileIcon, InfoIcon } from './icons';\nimport { ChatThinking } from './ChatThinking';\nimport { MarkdownMessage } from './MarkdownMessage';\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 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 = ({ messages, isLoading, agentStatus, agentName, logoIcon, onRelativeLinkClick, onDownloadFile, t }: 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 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\">\n {[att.type, sizeLabel].filter(Boolean).join(' · ')}\n </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 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 streaming response is always the last message, so the live\n // cursor / thinking bubble / ChatThinking state — and, conversely, the\n // hiding of the completed-message affordances (the reasoning \"i\"\n // button) — must be gated on it. Gating those on the global\n // `isLoading` instead made the blinking cursor leak onto every prior\n // assistant message and the \"i\" button vanish from all of them while a\n // *later* response was streaming.\n const isStreamingMessage = isLoading && index === messages.length - 1;\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} />\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 && !isEmpty && !isStreamingMessage && msg.toolNames && msg.toolNames.length > 0 && (\n <>\n <button\n type=\"button\"\n onClick={() => setToolDetailMsgId(toolDetailMsgId === msg.id ? null : msg.id)}\n className=\"mt-0.5 p-1 rounded-lg opacity-50 hover:opacity-100 hover:text-[var(--chat-accent)] transition-opacity\"\n title={t('Reasoning details')}\n >\n <InfoIcon size={14} />\n </button>\n {toolDetailMsgId === msg.id && (\n <div className=\"mt-1.5 p-3 rounded-lg bg-gray-50 dark:bg-white/[0.04] border border-gray-200 dark:border-white/10\">\n <p className=\"text-[0.7rem] text-gray-500 dark:text-white/40 mb-1.5\">\n {msg.iterations && msg.iterations > 1 ? `${msg.iterations} iterations · ` : ''}\n {msg.toolCallCount ?? msg.toolNames.length}{' '}\n {(msg.toolCallCount ?? msg.toolNames.length) === 1 ? t('tool call') : t('tool calls')}\n </p>\n <div className=\"flex flex-wrap gap-1\">\n {Array.from(new Set(msg.toolNames)).map((tn) => (\n <span\n key={tn}\n className=\"inline-flex items-center px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.68rem] font-mono text-gray-500 dark:text-white/40\"\n >\n {tn.replace(/_/g, ' ')}\n </span>\n ))}\n </div>\n </div>\n )}\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 } from '../hooks/protocols/parseRestEvent';\nimport { useChat } from '../hooks/useChat';\nimport { useAgents } from '../hooks/useAgents';\nimport { useSidebarResize } from '../hooks/useSidebarResize';\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}) => {\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 historyLoadedRef,\n conversationIdRef,\n handleFileAdd,\n handlePaste,\n handleSendMessage,\n handleNewChat,\n handleStopGenerating,\n setAttachedFiles,\n setMessages,\n updateConversationId,\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 { 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 // 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 =\n apiEndpoints?.download !== null && apiEndpoints?.download !== undefined;\n const canDownload =\n backendType === 'rest' &&\n apiEndpoints?.download !== null &&\n (!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 (m: { role: string; content: string; attachments?: unknown }, i: number) => ({\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 }),\n );\n setMessages(restored);\n })\n .catch(() => {\n if (isStale()) return;\n updateConversationId(null);\n });\n }, [conversationId, selectedAgent, apiBaseUrl, apiEndpoints, backendType, historyLoadedRef, conversationIdRef, isMountedRef, requestHeaders, setMessages, updateConversationId]);\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 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 t={t}\n />\n )}\n <ChatInput\n inputValue={inputValue}\n onInputChange={setInputValue}\n onSend={handleSendMessage}\n onStop={handleStopGenerating}\n isLoading={isLoading}\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","hardenNestedCodeFences","raw","lines","split","fenceRe","markupLang","openerIdx","i","length","m","match","test","trim","maxRun","nestedCount","lastBareFence","max","fence","repeat","om","cm","join","identity","key","PARTIAL_FILE_MARKER_RE","parseAttachments","Array","isArray","out","item","a","fileId","file_id","push","filename","type","undefined","size","contentType","content_type","fileTag","file_tag","parseRestEvent","evt","ctx","action","content","st","status","thinkingContent","hasUsedTools","tools","conversationId","conversation_id","toolNames","tool_names","toolCallCount","tool_call_count","iterations","transferAgentId","transfer_agent_id","transferAgentName","transfer_agent_name","attachments","parseLegacyEvent","eventType","event","data","nodeId","activeNodeId","replace","reasoning","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","getUploadUrl","singleEndpoint","upload","updateConversationId","useCallback","id","setItem","removeItem","ensureConversation","async","slug","sessionsUrl","sessions","promise","res","fetch","method","headers","body","JSON","stringify","agent_slug","ok","json","convId","uploadSingleFile","file","signal","uploadUrl","formData","FormData","append","name","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","handlePaste","e","files","clipboardData","preventDefault","handleSendMessage","userMsg","role","timestamp","Date","assistantId","controller","fileIds","requestBody","opts","question","streaming","threadId","runId","context","state","forwardedProps","keys","serialized","buildRequestBody","parseEvent","getParser","reader","getReader","decoder","TextDecoder","buffer","accumulated","doneReceived","done","value","read","decode","stream","pop","rawLine","line","startsWith","jsonStr","parsed","parse","handleNewChat","abort","handleStopGenerating","STORAGE_AGENT_KEY","SIDEBAR_WIDTH","SIDEBAR_WIDTH_STORAGE_KEY","AttachFileIcon","className","_jsx","xmlns","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","children","d","BrainIcon","_jsxs","CheckIcon","ChevronDownIcon","CloseIcon","CopyIcon","x","y","rx","ry","DatabaseIcon","cx","cy","DefaultLogoIcon","DownloadIcon","points","x1","x2","y1","y2","EditIcon","ExternalLinkIcon","FileIcon","FloatingIcon","FullscreenExitIcon","FullscreenIcon","GlobeIcon","r","InfoIcon","MailIcon","SearchIcon","SendIcon","SidebarIcon","SparklesIcon","StopCircleIcon","TerminalIcon","UserPlusIcon","WrenchIcon","Dropdown","open","onClose","anchorRef","placement","panelRef","pos","setPos","top","left","ref","handler","active","useEffect","listener","contains","target","document","addEventListener","removeEventListener","useClickOutside","rect","getBoundingClientRect","right","bottom","portalTarget","el","node","classList","parentElement","findChatbotRoot","createPortal","style","Spinner","Tooltip","title","show","setShow","onMouseEnter","onMouseLeave","modeOptions","mode","label","getIcon","ChatHeader","agentName","agents","selectedAgent","transferredFrom","agentMenuOpen","onAgentMenuToggle","onAgentMenuClose","onSwitchAgent","modeMenuOpen","onModeMenuToggle","onModeMenuClose","onModeChange","onNewChat","logoIcon","agentDashboardUrl","agentAnchorRef","modeAnchorRef","CurrentModeIcon","onClick","agent","description","opt","ChatInput","onInputChange","onSend","onStop","onFileAdd","onFileRemove","onPaste","separatorColor","fileInputRef","textareaRef","isFileManagementEnabled","Boolean","hasContent","hasFilesUploading","some","canSend","borderTopColor","borderTopWidth","multiple","hidden","onChange","click","placeholder","min","scrollHeight","onKeyDown","shiftKey","rows","maxHeight","disabled","ThinkingTextBubble","isOverflowing","setIsOverflowing","pinnedRef","cleaned","scrollTop","clientHeight","animation","onScroll","ChatThinking","StatusIcon","showDots","rawNames","lower","n","count","includes","display","toUpperCase","unique","Set","consultName","checkCount","fetchCount","targetName","resolveStatusVisual","_Fragment","delay","isRelativeHref","href","MarkdownMessage","onRelativeLinkClick","copiedBlock","setCopiedBlock","Markdown","remarkPlugins","remarkGfm","components","code","exec","codeStr","String","handleCopyCode","navigator","clipboard","writeText","ul","ol","blockquote","openInNewTab","rel","h1","h2","h3","table","th","td","fileExtensionLabel","dot","lastIndexOf","ext","ChatMessages","onDownloadFile","messagesEndRef","toolDetailMsgId","setToolDetailMsgId","scrollIntoView","behavior","renderAttachmentCard","att","isWorking","sizeLabel","bytes","toFixed","buildAssistantBlocks","msg","loading","parts","re","lastIndex","index","tail","splitFileMarkers","attByFileId","Map","used","blocks","forEach","part","get","add","has","renderFileChip","buildUserFileBlocks","seen","isAssistant","isEmpty","isStreamingMessage","tn","ChatWelcome","firstName","promptSuggestions","onPromptClick","fontFamily","prompt","DEFAULT_SUGGESTIONS","ChatPanel","topOffset","user","accentColor","draftBorderColor","resizable","onWidthChange","onResizeStart","onResizeEnd","disableFileManagement","onDownloadError","pushContentSelector","setModeMenuOpen","setAgentMenuOpen","handleSwitchAgent","setAgents","setSelectedAgent","then","savedSlug","find","catch","onSwitch","useAgents","sidebarWidth","handleResizeStart","defaultWidth","isResizing","setSidebarWidth","stored","parseInt","isNaN","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","downloadPathProvided","download","canDownload","handleDownloadFile","url","encodeURIComponent","credentials","blob","objectUrl","URL","createObjectURL","link","createElement","appendChild","remove","revokeObjectURL","cssVars","isMountedRef","requestedConversationId","isStale","restored","containerClasses","base","containerStyle","onMouseDown","_","j","ChatToggleButton","isOpen","onToggle","icon","resolvedIcon","borderColor","color","backgroundColor","currentTarget"],"mappings":"8OAAM,SAAUA,EAASC,EAAaC,GAIpC,MAAO,GAAGD,IAHAE,KAAKC,MAAc,IAARF,GAClBG,SAAS,IACTC,SAAS,EAAG,MAEjB,CAqBM,SAAUC,EAAuBC,GACrC,IAAKA,EAAK,OAAOA,EACjB,MAAMC,EAAQD,EAAIE,MAAM,MAClBC,EAAU,qBACVC,EAAa,+BAEnB,IAAI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ogB,EAAa,IACjFrT,EAAE8Y,cAAcvQ,MAAMsQ,gBAAkBN,EAAStlB,EAASogB,EAAa,IAAO,eAC/EtP,SAAA,CAEDV,EAAA,OAAA,CAAMD,UAAU,0BAAyBW,SAAE2U,IAC1CzP"}
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/components/icons/AttachFileIcon.tsx","../../src/components/icons/BrainIcon.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/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/Dropdown.tsx","../../src/hooks/useClickOutside.ts","../../src/components/Spinner.tsx","../../src/components/Tooltip.tsx","../../src/components/ChatHeader.tsx","../../src/components/ChatInput.tsx","../../src/components/ChatThinking.tsx","../../src/components/MarkdownMessage.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\nexport const identity = (key: string) => key;\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 } 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 * 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 };\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 }\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 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 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 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 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 { useCallback, useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useClickOutside } from '../hooks/useClickOutside';\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\nfunction 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\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';\n\ninterface TooltipProps {\n title: string;\n children: React.ReactElement;\n}\n\nfunction 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\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\n if (!title) return children;\n\n const handleEnter = () => {\n if (!ref.current) return;\n const rect = ref.current.getBoundingClientRect();\n setPos({\n top: 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 -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, 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';\n\ninterface ChatThinkingProps {\n agentStatus: AgentStatusState | null;\n logoIcon?: React.ReactNode;\n t: (key: string) => string;\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\nexport const ChatThinking = ({ agentStatus, logoIcon, t }: 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\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 && <ThinkingTextBubble content={thinkingContent} />}\n </>\n );\n};\n","import { useState } from 'react';\nimport Markdown from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport { CheckIcon, CopyIcon } from './icons';\nimport { hardenNestedCodeFences } 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 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 {hardenNestedCodeFences(content)}\n </Markdown>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { AgentStatusState, ChatAttachment, ChatMessage } from '../types';\nimport { splitFileMarkers } from '../utils';\nimport { BrainIcon, DownloadIcon, FileIcon, InfoIcon, WrenchIcon } from './icons';\nimport { ChatThinking, cleanReasoningText } from './ChatThinking';\nimport { MarkdownMessage } from './MarkdownMessage';\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 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 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} />\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 && !isEmpty && !isStreamingMessage && ((msg.toolNames && msg.toolNames.length > 0) || (msg.reasoning ?? '').trim()) && (\n <>\n <button\n type=\"button\"\n onClick={() => setToolDetailMsgId(toolDetailMsgId === msg.id ? null : msg.id)}\n className=\"mt-0.5 p-1 rounded-lg opacity-50 hover:opacity-100 hover:text-[var(--chat-accent)] transition-opacity\"\n title={t('Reasoning details')}\n >\n <InfoIcon size={14} />\n </button>\n {toolDetailMsgId === msg.id && (\n <div className=\"mt-1.5 p-3 rounded-lg bg-gray-50 dark:bg-white/[0.04] border border-gray-200 dark:border-white/10 max-w-[90%]\">\n {/* Header — mirrors the XTM One web chat \"Reasoning details\"\n dialog (title + iterations/calls summary) so the embedded\n chatbot and the native web chat read the same. */}\n <div className=\"flex items-center gap-1.5 mb-1\">\n <WrenchIcon size={13} className=\"text-[var(--chat-accent)]\" />\n <span className=\"text-[0.75rem] font-semibold text-gray-900 dark:text-white\">{t('Reasoning details')}</span>\n </div>\n <p className=\"text-[0.7rem] text-gray-500 dark:text-white/40 mb-1.5\">\n {msg.iterations && msg.iterations > 1 ? `${msg.iterations} ${t('iterations')} · ` : ''}\n {msg.toolCallCount ?? msg.toolNames?.length ?? 0}{' '}\n {(msg.toolCallCount ?? msg.toolNames?.length ?? 0) === 1 ? t('tool call') : t('tool calls')}\n </p>\n {(msg.reasoning ?? '').trim() && (\n <div className=\"mb-2\">\n <div className=\"flex items-center gap-1.5 mb-1\">\n <BrainIcon size={13} className=\"text-[var(--chat-accent)]/70\" />\n <span className=\"text-[0.7rem] 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-white dark:bg-white/[0.01] px-2.5 py-2 max-h-44 overflow-y-auto\">\n <p className=\"m-0 whitespace-pre-wrap break-words text-[0.7rem] leading-5 text-gray-500 dark:text-white/45\">\n {cleanReasoningText(msg.reasoning!)}\n </p>\n </div>\n </div>\n )}\n {msg.toolNames && msg.toolNames.length > 0 && (\n <div className=\"flex flex-wrap gap-1\">\n {Array.from(new Set(msg.toolNames)).map((tn) => (\n <span\n key={tn}\n className=\"inline-flex items-center px-2 py-0.5 rounded-full border border-gray-200 dark:border-white/10 text-[0.68rem] font-mono text-gray-500 dark:text-white/40\"\n >\n {tn.replace(/_/g, ' ')}\n </span>\n ))}\n </div>\n )}\n </div>\n )}\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 } 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 { 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}) => {\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 // 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 },\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 }),\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 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","hardenNestedCodeFences","raw","lines","split","fenceRe","markupLang","openerIdx","i","length","m","match","test","trim","maxRun","nestedCount","lastBareFence","max","fence","repeat","om","cm","join","identity","key","PARTIAL_FILE_MARKER_RE","parseAttachments","Array","isArray","out","item","a","fileId","file_id","push","filename","type","undefined","size","contentType","content_type","fileTag","file_tag","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","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","body","JSON","stringify","agent_slug","ok","json","convId","uploadSingleFile","file","signal","uploadUrl","formData","FormData","append","name","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","e","files","clipboardData","preventDefault","handleSendMessage","steerText","steerUrl","optimistic","role","timestamp","Date","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","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","AttachFileIcon","className","_jsx","xmlns","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","children","d","BrainIcon","_jsxs","CheckIcon","ChevronDownIcon","CloseIcon","CopyIcon","x","y","rx","ry","DatabaseIcon","cx","cy","DefaultLogoIcon","DownloadIcon","points","x1","x2","y1","y2","EditIcon","ExternalLinkIcon","FileIcon","FloatingIcon","FullscreenExitIcon","FullscreenIcon","GlobeIcon","r","HistoryIcon","InfoIcon","MailIcon","SearchIcon","SendIcon","SidebarIcon","SparklesIcon","StopCircleIcon","TerminalIcon","TrashIcon","UserPlusIcon","WrenchIcon","Dropdown","open","onClose","anchorRef","placement","panelRef","pos","setPos","top","left","ref","handler","active","useEffect","listener","contains","target","document","addEventListener","removeEventListener","useClickOutside","rect","getBoundingClientRect","right","bottom","portalTarget","el","node","classList","parentElement","findChatbotRoot","createPortal","style","Spinner","Tooltip","show","setShow","onMouseEnter","onMouseLeave","modeOptions","mode","label","getIcon","ChatHeader","agentName","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","now","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","multiple","hidden","onChange","click","placeholder","min","scrollHeight","onKeyDown","shiftKey","rows","maxHeight","disabled","cleanReasoningText","ThinkingTextBubble","isOverflowing","setIsOverflowing","cleaned","scrollTop","clientHeight","animation","formatElapsed","seconds","total","s","ChatThinking","StatusIcon","showDots","rawNames","lower","n","count","includes","display","toUpperCase","unique","Set","consultName","checkCount","fetchCount","targetName","resolveStatusVisual","showElapsed","delay","isRelativeHref","href","MarkdownMessage","onRelativeLinkClick","copiedBlock","setCopiedBlock","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","fileExtensionLabel","dot","lastIndexOf","ext","ChatMessages","onDownloadFile","messagesEndRef","toolDetailMsgId","setToolDetailMsgId","scrollIntoView","behavior","thinkingLen","renderAttachmentCard","att","isWorking","sizeLabel","bytes","toFixed","buildAssistantBlocks","msg","loading","parts","re","lastIndex","index","tail","splitFileMarkers","attByFileId","Map","used","blocks","forEach","part","get","add","has","renderFileChip","buildUserFileBlocks","seen","lastAssistantIndex","isAssistant","isEmpty","isStreamingMessage","tn","ChatWelcome","firstName","promptSuggestions","onPromptClick","fontFamily","prompt","DEFAULT_SUGGESTIONS","ChatPanel","topOffset","user","accentColor","draftBorderColor","resizable","onWidthChange","onResizeStart","onResizeEnd","disableFileManagement","onDownloadError","pushContentSelector","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","downloadPathProvided","download","canDownload","handleDownloadFile","credentials","blob","objectUrl","createObjectURL","link","createElement","appendChild","remove","revokeObjectURL","cssVars","isMountedRef","requestedConversationId","isStale","restored","containerClasses","base","containerStyle","onMouseDown","next","handleDeleteConversation","_","j","ChatToggleButton","isOpen","onToggle","icon","resolvedIcon","borderColor","color","backgroundColor","currentTarget"],"mappings":"8OAAM,SAAUA,EAASC,EAAaC,GAIpC,MAAO,GAAGD,IAHAE,KAAKC,MAAc,IAARF,GAClBG,SAAS,IACTC,SAAS,EAAG,MAEjB,CAqBM,SAAUC,EAAuBC,GACrC,IAAKA,EAAK,OAAOA,EACjB,MAAMC,EAAQD,EAAIE,MAAM,MAClBC,EAAU,qBACVC,EAAa,+BAEnB,IAAIC,GAAY,EAChB,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAMM,OAAQD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