@hsafa/ui-sdk 0.2.5 → 0.3.1

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 CHANGED
@@ -1,39 +1,43 @@
1
- import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {Maximize2,Plus,History,ChevronRight,File,Eye,X,Loader2,Paperclip,Link,Square,ArrowUp,Trash2,CheckCircle,Download}from'lucide-react';import Bt,{createContext,useState,useCallback,useRef,useEffect,useMemo,useContext}from'react';import {createPortal}from'react-dom';var st={};var Yr=({variant:t="primary",size:n="md",loading:e=false,disabled:r,children:a,className:s,...o})=>{let i=[st.button,st[t],st[n],e&&st.loading,s].filter(Boolean).join(" ");return jsxs("button",{className:i,disabled:r||e,...o,children:[e&&jsx("span",{className:st.spinner}),jsx("span",{className:e?st.hiddenText:void 0,children:a})]})};function Te(t){if(!t||Number.isNaN(t))return "0 B";let n=["B","KB","MB","GB","TB"],e=Math.min(n.length-1,Math.floor(Math.log(t)/Math.log(1024)));return `${(t/Math.pow(1024,e)).toFixed(e===0?0:1)} ${n[e]}`}function ve({attachment:t,resolvedColors:n,mode:e,onRemove:r,maxWidth:a="200px"}){let s=t.mimeType?.startsWith("image/"),o=e==="editable"||e==="input",i=e==="viewable",f={display:"flex",alignItems:"center",gap:e==="input"?"8px":"6px",padding:e==="input"?"8px 12px":"6px 10px",backgroundColor:n.inputBackground,borderRadius:e==="input"?"10px":"8px",border:`1px solid ${n.borderColor}`,fontSize:e==="input"?"12px":"11px",color:n.textColor,transition:"all 0.2s ease-out",cursor:i?"pointer":"default",maxWidth:e==="input"?"140px":a,position:"relative"},y=jsxs(Fragment,{children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:e==="input"?"20px":"16px",height:e==="input"?"20px":"16px",borderRadius:e==="input"?"4px":"3px",backgroundColor:s?"transparent":n.accentColor,flexShrink:0},children:[s?jsx("img",{src:t.url,alt:t.name,style:{width:e==="input"?"20px":"16px",height:e==="input"?"20px":"16px",borderRadius:e==="input"?"4px":"3px",objectFit:"cover"},onError:l=>{l.target.style.display="none";let b=l.target.nextElementSibling;b&&(b.style.display="block");}}):null,jsx(File,{size:e==="input"?14:10,strokeWidth:"2",style:{display:s?"none":"block",color:n.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:t.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:t.name}),jsx("span",{style:{fontSize:e==="input"?"10px":"9px",color:n.mutedTextColor,marginTop:e==="input"?"2px":"1px"},children:Te(t.size)})]}),e==="input"&&s&&jsx("button",{onClick:l=>{l.stopPropagation(),window.open(t.url,"_blank");},style:{background:"none",border:"none",color:n.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:l=>{l.currentTarget.style.backgroundColor=n.hoverBackground,l.currentTarget.style.color=n.textColor;},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="transparent",l.currentTarget.style.color=n.mutedTextColor;},children:jsx(Eye,{size:"12",strokeWidth:"2"})}),o&&r&&jsx("button",{onClick:l=>{l.stopPropagation(),r(t.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:e==="input"?"auto":"16px",height:e==="input"?"auto":"16px",padding:e==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:n.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:l=>{l.currentTarget.style.backgroundColor="#ef444420",l.currentTarget.style.color="#ef4444";},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="transparent",l.currentTarget.style.color=n.mutedTextColor;},children:jsx(X,{size:"12",strokeWidth:"2"})}),i&&jsx(Download,{size:"10",strokeWidth:"2",style:{color:n.mutedTextColor,flexShrink:0}})]});return i?jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",style:{...f,textDecoration:"none"},onMouseEnter:l=>{l.currentTarget.style.backgroundColor=n.hoverBackground,l.currentTarget.style.borderColor=n.primaryColor;},onMouseLeave:l=>{l.currentTarget.style.backgroundColor=n.inputBackground,l.currentTarget.style.borderColor=n.borderColor;},children:y}):jsx("div",{style:f,children:y})}function Et({attachments:t,resolvedColors:n,onRemove:e}){if(!Array.isArray(t)||t.length===0)return null;let r=typeof e=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:t.map(a=>jsx(ve,{attachment:a,resolvedColors:n,mode:r,onRemove:e},a.id))})}function we({messageId:t,initialText:n,editingText:e,onEditingTextChange:r,onCancel:a,onSave:s,streaming:o,resolvedColors:i,attachments:f,onRemoveAttachment:y,onAddAttachments:l,uploading:b,t:c}){let M=Bt.useRef(null),h=x=>{x.key==="Escape"?a():x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),o||s(t,e||n));},k=x=>{let d=x.target.files;d&&d.length>0&&l&&l(d),M.current&&(M.current.value="");};return jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${i.primaryColor}`,backgroundColor:i.accentColor,color:i.textColor},children:[jsx("textarea",{autoFocus:true,style:{width:"100%",resize:"none",backgroundColor:"transparent",padding:"8px",lineHeight:"1.6",outline:"none",border:"none",color:"inherit",fontFamily:"inherit",fontSize:"inherit"},rows:Math.max(2,Math.min(10,Math.ceil((e||n).length/60))),value:e,onChange:x=>r(x.target.value),onKeyDown:h}),f&&f.length>0&&jsx("div",{style:{padding:"8px"},children:jsx(Et,{attachments:f,resolvedColors:i,onRemove:y})}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",padding:"8px 8px 8px 0"},children:[l&&jsxs("div",{children:[jsx("input",{ref:M,type:"file",multiple:true,onChange:k,style:{display:"none"}}),jsx("button",{onClick:()=>M.current?.click(),disabled:b||o,title:c(b?"input.uploadingFiles":"input.attachFiles"),style:{display:"flex",margin:"0 10px",alignItems:"center",justifyContent:"center",borderRadius:"50%",width:"28px",height:"28px",transition:"all 0.2s",border:`1px solid ${i.borderColor}`,color:i.mutedTextColor,backgroundColor:"transparent",cursor:b||o?"not-allowed":"pointer",opacity:b||o?.5:1},onMouseEnter:x=>{!b&&!o&&(x.currentTarget.style.backgroundColor=i.inputBackground,x.currentTarget.style.borderColor=i.primaryColor);},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="transparent",x.currentTarget.style.borderColor=i.borderColor;},children:jsx(Plus,{size:16,strokeWidth:2})})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${i.borderColor}`,color:i.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:x=>x.currentTarget.style.backgroundColor=i.inputBackground,onMouseLeave:x=>x.currentTarget.style.backgroundColor="transparent",onClick:a,children:c("editor.cancel")}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${i.borderColor}`,backgroundColor:i.cardBackground,color:i.textColor,cursor:"pointer"},onMouseEnter:x=>x.currentTarget.style.borderColor=i.primaryColor,onMouseLeave:x=>x.currentTarget.style.borderColor=i.borderColor,onClick:()=>{o||s(t,e||n);},children:c("editor.saveAndRegenerate")})]})]})]})}function Kn(t){return t.mimeType.startsWith("image/")?{type:"image",image:new URL(t.url),mediaType:t.mimeType}:{type:"file",data:t.url,mediaType:t.mimeType,name:t.name}}function Yt(t,n){let e=(t||"").trim();if(!n||n.length===0)return e;let r=[];e&&r.push({type:"text",text:e});for(let a of n)r.push(Kn(a));return r}function Se(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(`
2
- `):""}function Re(t){if(typeof t=="string"||!Array.isArray(t))return [];let n=[];for(let e of t)if(e.type==="image"){let r=typeof e.image=="string"?e.image:e.image.toString();n.push({id:`img_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:"image",url:r,mimeType:e.mediaType||"image/jpeg",size:0});}else if(e.type==="file"){let r=typeof e.data=="string"?e.data:e.data.toString();n.push({id:`file_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:e.name||"file",url:r,mimeType:e.mediaType,size:0});}return n}function Gt(t){return t.role==="user"?t.text?t.text:Se(t.content):""}function gt(t){return t.role==="user"?t.attachments?t.attachments:Re(t.content):[]}function $e(t,n=[]){let e=Yt(t,n),r=Date.now();return {id:`user_${r}_${Math.random().toString(36).slice(2)}`,role:"user",content:e,createdAt:r,text:t,attachments:n.length>0?n:void 0}}function Qt(t=false){let n=Date.now();return {id:`assistant_${n}_${Math.random().toString(36).slice(2)}`,role:"assistant",items:[],reasoning:"",reasoningOpen:t,mainAgentActions:[],createdAt:n}}function Ie(t){let n=[];for(let e of t)if(e.role==="user")n.push({role:e.role,content:e.content});else if(e.role==="assistant"){let r=[];if(e.firstAgentMessage&&r.push({type:"text",text:e.firstAgentMessage}),e.mainAgentActions&&e.mainAgentActions.length>0){for(let a of e.mainAgentActions)if(a.type==="reasoning"&&a.reasoning)r.push({type:"reasoning",text:a.reasoning});else if(a.type==="tool-call"&&a.toolName){let s=a.toolCallId||(typeof a.startDate=="number"&&a.toolName?`${a.toolName}_${a.startDate}`:`call_${a.toolName||"tool"}_${Math.abs(a.durationMs||0)}`);r.push({type:"tool-call",toolCallId:s,toolName:a.toolName,input:a.input||{}}),a.output!==void 0&&n.push({role:"tool",content:[{type:"tool-result",toolCallId:s,toolName:a.toolName,output:a.output,isError:a.status==="error"}]});}}if(e.items&&e.items.length>0){let a=JSON.stringify(e.items,null,2);r.push({type:"text",text:a});}r.length>0&&n.push({role:e.role,content:r});}return n}function Fe(t,n,e){let r=e??gt(t),a=Yt(n,r);return {...t,content:a,text:n,attachments:r.length>0?r:void 0}}function De(t){if(t.role==="user"){let n=Gt(t),e=gt(t);return e.length>0?`${n} [${e.length} attachment${e.length>1?"s":""}]`:n}else if(t.role==="assistant"){let e=(t.items||[]).filter(r=>r.type==="text");return e.length>0?e.map(r=>r.text||"").join(" ").slice(0,100):"Assistant response"}return ""}function ze({message:t,isEditing:n,editingText:e,editingAttachments:r,onEditingTextChange:a,onStartEdit:s,onCancelEdit:o,onSaveEdit:i,onRemoveAttachment:f,onAddAttachments:y,uploading:l,streaming:b,resolvedColors:c,t:M}){let h=Gt(t),k=gt(t);return n?jsx(we,{messageId:t.id,initialText:h,editingText:e,onEditingTextChange:a,onCancel:o,onSave:i,streaming:b,resolvedColors:c,attachments:r||k,onRemoveAttachment:f,onAddAttachments:y,uploading:l,t:M}):jsxs("div",{title:M("editor.clickToEdit"),onClick:()=>{b||s(t.id,h);},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:c.accentColor,color:c.textColor},onMouseEnter:x=>x.currentTarget.style.backgroundColor=c.hoverBackground,onMouseLeave:x=>x.currentTarget.style.backgroundColor=c.accentColor,children:[h,jsx(Et,{attachments:k,resolvedColors:c})]})}function He({reasoning:t,reasoningOpen:n,onToggleReasoning:e,resolvedColors:r}){return t?jsxs("div",{style:{borderRadius:"12px",padding:"12px",cursor:"pointer",backgroundColor:r.inputBackground,border:`1px solid ${r.borderColor}`},onClick:e,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[jsx("div",{style:{fontSize:"12px",color:r.mutedTextColor},children:"Reasoning"}),jsx("button",{type:"button",style:{fontSize:"12px",transition:"color 0.2s",color:r.mutedTextColor,background:"none",border:"none",cursor:"pointer"},onMouseEnter:a=>a.currentTarget.style.color=r.textColor,onMouseLeave:a=>a.currentTarget.style.color=r.mutedTextColor,children:n?"Hide":"Show full"})]}),n?jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:t}):(()=>{let a=(t||"").trim().split(`
3
- `).filter(o=>o.trim()),s=a.length>0?a[a.length-1]:"";return jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:s||"\u2026"})})()]}):null}function _e({chart:t,theme:n}){let e=useRef(null),[r,a]=useState(null),[s,o]=useState(true);useEffect(()=>{let c=true;return (async()=>{try{o(!0),a(null);let h;try{h=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!c)return;if(h.default?.initialize({startOnLoad:!1,theme:n==="dark"?"dark":"default",themeVariables:{darkMode:n==="dark",primaryColor:n==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:n==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:n==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),e.current&&c){let k=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:x}=await h.default.render(k,t);if(e.current&&c){e.current.innerHTML=x;let d=e.current.querySelector("svg");d&&(d.style.maxWidth="100%",d.style.height="auto",d.style.display="block");}}}catch(h){c&&a(h instanceof Error?h.message:"Failed to render diagram");}finally{c&&o(false);}})(),()=>{c=false;}},[t,n]);let i=n==="dark"?"#374151":"#D1D5DB",f=n==="dark"?"#1F2937":"#F9FAFB",y=n==="dark"?"#7F1D1D":"#FEF2F2",l=n==="dark"?"#FCA5A5":"#DC2626",b=n==="dark"?"#9CA3AF":"#6B7280";return r?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:y,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:l,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:l,opacity:.8},children:r})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${i}`,backgroundColor:f,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[s&&jsx("div",{style:{fontSize:"14px",color:b,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:e,style:{display:s?"none":"block",textAlign:"center",minHeight:s?"0":"50px"}})]})}function G(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Lt(t){return t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),t=t.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),t=t.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),t}function Xn(t,n="dark"){let e=(t||"").replace(/\r\n/g,`
1
+ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import ot,{createContext,useRef,useEffect,useState,useCallback,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {useChat}from'@ai-sdk/react';import {DefaultChatTransport,lastAssistantMessageIsCompleteWithToolCalls}from'ai';import {Plus,History,ChevronRight,Trash2,File as File$1,Eye,X,Download}from'lucide-react';import {createRoot}from'react-dom/client';var Me={};var wo=({variant:e="primary",size:t="md",loading:n=false,disabled:o,children:r,className:l,...u})=>{let c=[Me.button,Me[e],Me[t],n&&Me.loading,l].filter(Boolean).join(" ");return jsxs("button",{className:c,disabled:o||n,...u,children:[n&&jsx("span",{className:Me.spinner}),jsx("span",{className:n?Me.hiddenText:void 0,children:r})]})};function Xt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:o}){if(!e)return null;let r={position:"fixed",bottom:typeof o.bottom=="number"?`${o.bottom}px`:o.bottom,right:o.right?typeof o.right=="number"?`${o.right}px`:o.right:void 0,top:o.top?typeof o.top=="number"?`${o.top}px`:o.top:void 0,left:o.left?typeof o.left=="number"?`${o.left}px`:o.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:t,style:{...r,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{l.currentTarget.style.borderColor=n.primaryColor,l.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:l=>{l.currentTarget.style.borderColor=n.borderColor,l.currentTarget.style.backgroundColor=n.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function Zt(e=true){let t=useRef(null),n=useRef(e);return useEffect(()=>{n.current=e;},[e]),useEffect(()=>{let o=t.current;if(!o)return;let r=new MutationObserver(()=>{n.current&&(o.scrollTop=o.scrollHeight);});return r.observe(o,{childList:true,subtree:true}),n.current&&(o.scrollTop=o.scrollHeight),()=>r.disconnect()},[]),t}function Qt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`;return `${n}${o}`}var At=25*1024*1024;function tn(e){let[t,n]=useState([]),[o,r]=useState(false),l=useRef(null),u=useCallback(f=>{if(!f||Number.isNaN(f))return "0 B";let b=["B","KB","MB","GB","TB"],g=Math.min(b.length-1,Math.floor(Math.log(f)/Math.log(1024)));return `${(f/Math.pow(1024,g)).toFixed(g===0?0:1)} ${b[g]}`},[]),c=useCallback(async f=>{let b=new FormData;b.append("file",f);let g=await fetch(Qt(e,"/api/uploads"),{method:"POST",body:b});if(!g.ok){let i=await g.text().catch(()=>"");throw new Error(i||`Failed to upload ${f.name}`)}let k=await g.json();return {id:k.id,name:k.name||f.name,url:k.url,mimeType:k.mimeType||f.type||"application/octet-stream",size:typeof k.size=="number"?k.size:f.size}},[e]),v=useCallback(f=>{n(b=>b.filter(g=>g.id!==f));},[]),S=useCallback(async(f,b)=>{if(!f)return;let g=Array.isArray(f)?f:Array.from(f);b(null),r(true);let k=[];try{for(let i of g){if(i.size>At){b(`"${i.name}" exceeds the ${u(At)} limit.`);continue}try{let m=await c(i);k.push(m);}catch(m){console.error("Failed to upload attachment:",m),b(String(m?.message??`Failed to upload ${i.name}`));}}k.length&&n(i=>[...i,...k]);}finally{r(false);}},[c,u]),a=useCallback((f,b)=>{let g=[],k=(f||"").trim();k&&g.push({type:"text",text:k});for(let i of b||[]){let m=i.mimeType||"application/octet-stream";m.startsWith("image/")?g.push({type:"image",image:new URL(i.url),mediaType:m}):g.push({type:"file",data:i.url,mediaType:m,name:i.name});}return g},[]),T=useCallback(()=>{n([]);},[]);return {attachments:t,uploading:o,fileInputRef:l,formatBytes:u,handleRemoveAttachment:v,handleFileSelection:S,buildUserContent:a,clearAttachments:T,MAX_UPLOAD_SIZE:At}}var nn=createContext(void 0);function lr({baseUrl:e,dir:t="ltr",theme:n="dark",children:o}){let[r,l]=useState(new Map),[u,c]=useState(new Map),[v,S]=useState(new Map),[a,T]=useState(new Map),f=useCallback((M,w)=>(l(y=>{let p=new Map(y);return p.set(String(M),w),p}),()=>{l(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});}),[]),b=useCallback((M,w)=>{l(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});},[]),g=useCallback((M,w)=>(c(y=>{let p=new Map(y);return p.set(String(M),w),p}),()=>{c(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});}),[]),k=useCallback((M,w)=>{c(y=>{let p=new Map(y),F=p.get(String(M));return (!w||F===w)&&p.delete(String(M)),p});},[]),i=useCallback((M,w)=>{S(y=>{let p=new Map(y);return w?p.set(M,true):p.delete(M),p});},[]),m=useCallback((M,w)=>{T(y=>{let p=new Map(y);return w?p.set(M,true):p.delete(M),p});},[]),h=useMemo(()=>Array.from(v.values()).some(M=>M),[v]),C=useMemo(()=>Array.from(a.values()).some(M=>M),[a]),E=useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:r,components:u,registerAction:f,unregisterAction:b,registerComponent:g,unregisterComponent:k,isAnyStreaming:h,setStreamingState:i,isAnyChatOpen:C,setChatOpenState:m}),[e,t,n,r,u,f,b,g,k,h,i,C,m]);return jsx(nn.Provider,{value:E,children:o})}function Le(){let e=useContext(nn);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function se({IconComponent:e,...t}){return ot.createElement(e,t)}function Rt({icon:e,onClick:t,ariaLabel:n,resolvedColors:o,disabled:r=false,title:l}){return jsx("button",{"aria-label":n,title:l,disabled:r,style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:u=>{r||(u.currentTarget.style.backgroundColor=o.hoverBackground,u.currentTarget.style.color=o.textColor);},onMouseLeave:u=>{u.currentTarget.style.backgroundColor="transparent",u.currentTarget.style.color=o.mutedTextColor;},onClick:t,children:e})}function on({title:e,alwaysOpen:t,streaming:n,dir:o,resolvedColors:r,onNew:l,onToggleHistory:u,onClose:c,historyBtnRef:v,t:S}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:o==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:e,style:{color:r.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:r.mutedTextColor},children:[jsx(Rt,{icon:jsx(se,{IconComponent:Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||l();},ariaLabel:S("header.new"),resolvedColors:r,disabled:n}),jsx("button",{ref:v,"aria-label":S("header.history"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:a=>{a.currentTarget.style.backgroundColor=r.hoverBackground,a.currentTarget.style.color=r.textColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=r.mutedTextColor;},onClick:u,children:jsx(se,{IconComponent:History,size:"20",strokeWidth:"2"})}),!t&&jsx(Rt,{icon:jsx(se,{IconComponent:ChevronRight,size:"20",strokeWidth:"2",style:{transform:o==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:S("header.close"),resolvedColors:r})]})]})}function ln({chart:e,theme:t}){let n=useRef(null),[o,r]=useState(null),[l,u]=useState(true);useEffect(()=>{let f=true;return (async()=>{try{u(!0),r(null);let g;try{g=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!f)return;if(g.default?.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:{darkMode:t==="dark",primaryColor:t==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:t==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:t==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&f){let k=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:i}=await g.default.render(k,e);if(n.current&&f){n.current.innerHTML=i;let m=n.current.querySelector("svg");m&&(m.style.maxWidth="100%",m.style.height="auto",m.style.display="block");}}}catch(g){f&&r(g instanceof Error?g.message:"Failed to render diagram");}finally{f&&u(false);}})(),()=>{f=false;}},[e,t]);let c=t==="dark"?"#374151":"#D1D5DB",v=t==="dark"?"#1F2937":"#F9FAFB",S=t==="dark"?"#7F1D1D":"#FEF2F2",a=t==="dark"?"#FCA5A5":"#DC2626",T=t==="dark"?"#9CA3AF":"#6B7280";return o?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:S,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:a,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:a,opacity:.8},children:o})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:v,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[l&&jsx("div",{style:{fontSize:"14px",color:T,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:l?"none":"block",textAlign:"center",minHeight:l?"0":"50px"}})]})}function le(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function He(e){return e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),e=e.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),e=e.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),e}function xr(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
4
2
  `).split(`
5
- `),r="",a=false,s="",o=[],i=false,f=false,y=false,l=n==="dark"?"#374151":"#D1D5DB",c=n==="dark"?"#111827":"#F3F4F6",M=n==="dark"?"#E5E7EB":"#374151",h=()=>{i&&(r+="</ul>",i=false),f&&(r+="</ol>",f=false);};for(let k=0;k<e.length;k++){let x=e[k],d=x.match(/^```\s*(\w+)?\s*$/);if(d){if(!a)h(),a=true,s=d[1]?String(d[1]):"",o=[];else {if(s==="mermaid"){y=true;let u=o.join(`
6
- `);r+=`<div class="mermaid-placeholder" data-mermaid="${G(u)}"></div>`;}else {let u=G(o.join(`
7
- `)),g=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${c}; color: ${M}; border: 1px solid ${l}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${g}">${u}</code></pre>`;}a=false,s="",o=[];}continue}if(a){o.push(x);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(x)){h(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let v=x.match(/^(#{1,6})\s+(.+)$/);if(v){h();let u=v[1].length,g=Lt(G(v[2].trim())),T=u<=2?"18px":u===3?"16px":"14px";r+=`<h${u} style="font-size: ${T}; font-weight: 600; margin: 8px 0 4px 0;">${g}</h${u}>`;continue}let m=x.match(/^\s*[-*]\s+(.+)$/),C=x.match(/^\s*\d+\.\s+(.+)$/);if(m){i||(h(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',i=true);let u=Lt(G(m[1]));r+=`<li style="margin: 2px 0;">${u}</li>`;continue}if(C){f||(h(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',f=true);let u=Lt(G(C[1]));r+=`<li style="margin: 2px 0;">${u}</li>`;continue}if(x.trim().length===0)h(),r+='<div style="height: 8px;"></div>';else {h();let u=Lt(G(x));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${u}</p>`;}}if(a)if(s==="mermaid"){y=true;let k=o.join(`
8
- `);r+=`<div class="mermaid-placeholder" data-mermaid="${G(k)}"></div>`;}else {let k=G(o.join(`
9
- `)),x=s?`language-${s}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${c}; color: ${M}; border: 1px solid ${l}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${x}">${k}</code></pre>`;}return i&&(r+="</ul>"),f&&(r+="</ol>"),{html:r,hasMermaid:y}}function mt({content:t,theme:n}){let{html:e,hasMermaid:r}=useMemo(()=>Xn(t,n),[t,n]);if(!r)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:e}});let a=e.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),s=[];return a.forEach((o,i)=>{if(o.includes("mermaid-placeholder")){let f=o.match(/data-mermaid="([^"]*)"/);if(f){let y=f[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");s.push(Bt.createElement(_e,{key:`mermaid-${i}`,chart:y,theme:n}));}}else o.trim()&&s.push(Bt.createElement("div",{key:`html-${i}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:o}}));}),Bt.createElement(Bt.Fragment,{},...s)}function We({mainAgentActions:t,reasoningOpen:n,onToggleReasoning:e,resolvedColors:r,streaming:a=false,theme:s="dark",hideReasoningContent:o=false}){if(!t||t.length===0)return null;let i=t.filter(b=>b.type==="reasoning"||b.type==="tool-call");if(i.length===0)return null;let f=[...i].reverse().find(b=>b.type==="reasoning"),y=t.some(b=>b.type==="response"),l=Gn(i);return jsxs("div",{style:{cursor:"pointer",padding:"0",maxWidth:"100%"},onClick:e,children:[n?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0",maxWidth:"100%",position:"relative"},children:[i.map((b,c)=>jsx(Qn,{action:b,resolvedColors:r,theme:s,isFirst:c===0,isLast:c===i.length-1,hideReasoningContent:o},c)),jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:"0",position:"relative",marginTop:"16px"},children:[jsx("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",width:"24px",flexShrink:0},children:y?jsx("div",{style:{width:"8px",height:"8px",marginTop:"6px",zIndex:1},children:jsx(CheckCircle,{size:10,color:r.borderColor})}):jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:r.borderColor,marginTop:"6px",zIndex:1}})}),jsx("div",{style:{flex:1,minWidth:0},children:y&&jsx("div",{style:{fontSize:"11px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:jsx("span",{children:"Done"})})})]})]}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",maxWidth:"100%",minWidth:0,overflow:"hidden"},children:[a&&!y?jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontStyle:"italic",display:"flex",alignItems:"center",gap:"6px",minWidth:0},children:[jsx("span",{children:"Thinking"}),jsxs("span",{className:"thinking-dots",style:{display:"inline-flex",gap:"2px"},children:[jsx("span",{style:{animation:"thinking-pulse 1.4s ease-in-out 0s infinite"},children:"."}),jsx("span",{style:{animation:"thinking-pulse 1.4s ease-in-out 0.2s infinite"},children:"."}),jsx("span",{style:{animation:"thinking-pulse 1.4s ease-in-out 0.4s infinite"},children:"."})]})]}):jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"4px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsx("span",{style:{opacity:.9,fontSize:"12px"},children:"Thought"}),jsxs("span",{style:{color:r.mutedTextColor,fontFamily:"monospace",fontSize:"12px",opacity:.5,letterSpacing:"0.1px"},children:["for ",Ne(l)]})]}),!o&&f?.type==="reasoning"&&!y&&jsx("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:jsx(mt,{content:f.reasoning,theme:s})})]}),jsx("style",{children:`
10
- @keyframes thinking-pulse {
11
- 0%, 60%, 100% { opacity: 0.3; }
12
- 30% { opacity: 1; }
13
- }
14
- `})]})}function Gn(t){return t.reduce((n,e)=>"startDate"in e&&"endDate"in e&&e.startDate&&e.endDate?n+(e.endDate-e.startDate):n,0)}function Ne(t){if(t<1e3)return `${Math.round(t)}ms`;if(t<6e4)return `${(t/1e3).toFixed(1)}s`;let n=Math.floor(t/6e4),e=Math.round(t%6e4/1e3);return `${n}m ${e}s`}function Qn({action:t,resolvedColors:n,theme:e,isFirst:r,isLast:a,hideReasoningContent:s=false}){let o="startDate"in t&&"endDate"in t&&t.startDate&&t.endDate?Ne(t.endDate-t.startDate):null,i=y=>{let l={input_streaming:{color:e==="dark"?"#eab308":"#d97706",text:"Inputting"},running:{color:e==="dark"?"#3b82f6":"#2563eb",text:"Running"},error:{color:e==="dark"?"#ef4444":"#dc2626",text:"Error"},finished:{color:e==="dark"?"#10b981":"#059669",text:"Called"}};return l[y.status]||l.finished},f=y=>jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",width:"24px",flexShrink:0},children:[jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:y,marginTop:"6px",zIndex:1}}),jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:e==="dark"?n.borderColor:n.mutedTextColor}})]});if(t.type==="reasoning")return jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[f(n.borderColor),jsxs("div",{style:{flex:1,minWidth:0},children:[jsxs("div",{style:{fontSize:"11px",color:n.mutedTextColor,marginBottom:"4px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{children:"Reasoning"}),o&&jsx("span",{style:{fontFamily:"monospace",fontSize:"10px"},children:o})]}),!s&&jsx("div",{style:{fontSize:"13px",color:n.mutedTextColor,lineHeight:"1.6",maxWidth:"100%",opacity:t.status==="streaming"?.8:1},children:jsx(mt,{content:t.reasoning,theme:e})})]})]});if(t.type==="tool-call"){let{color:y,text:l}=i(t);return jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[f(y),jsx("div",{style:{flex:1,minWidth:0},children:jsxs("div",{style:{fontSize:"12px",color:n.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsx("span",{style:{fontWeight:500,opacity:e==="dark"?.7:.6},children:l}),jsx("span",{style:{fontWeight:500},children:t.toolName||"tool"}),o&&jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",opacity:e==="dark"?.5:.6},children:o})]})})]})}return null}function Oe({mcpToolCalls:t,resolvedColors:n}){if(!t||t.length===0)return null;let e=new Map;t.forEach(s=>{let o=e.get(s.toolName);!o||o.status==="running"&&s.status==="completed"?e.set(s.toolName,{status:s.status||"pending",count:(o?.count||0)+1}):o&&o.count++;});let r=Array.from(e.values()).some(s=>s.status==="running"),a=Array.from(e.values()).filter(s=>s.status==="completed").length;return jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,fontSize:"12px",color:n.mutedTextColor},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:r?"#3b82f6":"#10b981"}}),jsx("span",{children:r?"Agent is using tools":a>0?`Agent used ${a} tool${a>1?"s":""}`:"Agent used tools"})]}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Array.from(e.entries()).map(([s,o])=>jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:n.inputBackground,border:`1px solid ${n.borderColor}`},children:[o.status==="running"?jsxs("svg",{style:{animation:"spin 1s linear infinite",height:"8px",width:"8px",flexShrink:0},xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{style:{opacity:.75},fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):jsx("span",{style:{display:"inline-block",height:"4px",width:"4px",borderRadius:"50%",backgroundColor:o.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:s}),o.count>1&&jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",o.count]})]},s))})]})}function Ue({items:t,mcpToolCalls:n,mcpToolResults:e,actionStatuses:r,components:a,theme:s,resolvedColors:o}){return !Array.isArray(t)||t.length===0?null:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.map((i,f)=>{let y=`it-${f}`;if(typeof i=="string")return jsx("div",{style:{padding:"0",color:o.textColor},children:jsx(mt,{content:i,theme:s})},y);if(i&&typeof i=="object"){if(i.type==="action"){let b=`${String(i.name??"action")}:${f}`,c=r.get(b);return jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsx("div",{style:{padding:"8px",fontSize:"12px",color:o.mutedTextColor},children:c==="executing"?jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxs("svg",{style:{animation:"spin 1s linear infinite",height:"12px",width:"12px"},xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{style:{opacity:.75},fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),String(i.name??"action")," is executing"]}):jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:"#10b981"}}),String(i.name??"action")," has executed"]})})},y)}if(i.type==="ui"){let b=String(i.component??"").trim(),c=b?a.get(b):void 0;return c?jsx("div",{style:{padding:"0"},children:jsx(c,{...i.props||{}})},y):jsxs("div",{style:{padding:"0"},children:[jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:o.mutedTextColor},children:[jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:o.accentColor,border:`1px solid ${o.borderColor}`},children:"UI"}),jsx("span",{children:b||"component"}),jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i.props??{},null,2)})]},y)}let l=i.text||i.content||i.message;return typeof l=="string"?jsx("div",{style:{padding:"0",color:o.textColor},children:jsx(mt,{content:l,theme:s})},y):jsx("div",{style:{padding:"0",fontSize:"14px"},children:jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i,null,2)})},y)}return null}),jsx(Oe,{mcpToolCalls:n,resolvedColors:o})]})}function je({message:t,streaming:n,isLastMessage:e,actionStatuses:r,components:a,theme:s,resolvedColors:o,onToggleReasoning:i,hideReasoningContent:f=false}){let y=t.mainAgentActions&&t.mainAgentActions.length>0;return jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.firstAgentMessage&&jsx("div",{style:{padding:"12px 0"},children:jsx("div",{style:{fontSize:"13px",color:o.textColor,lineHeight:"1.5"},children:t.firstAgentMessage})}),y?jsx(We,{mainAgentActions:t.mainAgentActions,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o,streaming:n&&e,theme:s,hideReasoningContent:f}):jsx(He,{reasoning:t.reasoning,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o}),jsx(Ue,{items:t.items,mcpToolCalls:t.mcpToolCalls,mcpToolResults:t.mcpToolResults,actionStatuses:r,components:a,theme:s,resolvedColors:o}),n&&e&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:o.mutedTextColor},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsx("span",{children:"Working\u2026"})]})]})}function qe({messages:t,streaming:n,editingMessageId:e,editingMessageText:r,editingAttachments:a,error:s,actionStatuses:o,components:i,theme:f,resolvedColors:y,onEditingTextChange:l,onRemoveAttachment:b,onAddAttachments:c,uploading:M,onStartEdit:h,onCancelEdit:k,onSaveEdit:x,onToggleReasoning:d,scrollAnchorRef:v,hideReasoningContent:m=false,t:C}){return jsxs("div",{className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth"},children:[s&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",backgroundColor:"rgba(239, 68, 68, 0.1)",color:"#fca5a5",border:"1px solid rgba(239, 68, 68, 0.3)",padding:"12px",fontSize:"14px"},children:s}),t.length===0&&!n&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${y.borderColor}`,backgroundColor:y.accentColor,color:y.mutedTextColor},children:C("messages.empty")}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:t.map((u,g)=>jsx("div",{style:{padding:"0 4px"},children:u.role==="user"?jsx(ze,{message:u,isEditing:e===u.id,editingText:r,editingAttachments:a,onEditingTextChange:l,onStartEdit:h,onCancelEdit:k,onSaveEdit:x,onRemoveAttachment:b,onAddAttachments:c,uploading:M,streaming:n,resolvedColors:y,t:C}):jsx(je,{message:u,streaming:n,isLastMessage:g===t.length-1,actionStatuses:o,components:i,theme:f,resolvedColors:y,onToggleReasoning:d,hideReasoningContent:m})},u.id))}),jsx("div",{ref:v})]})}function Je({show:t,onClick:n,resolvedColors:e,floatingButtonPosition:r}){if(!t)return null;let a={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsx("button",{"aria-label":"Open chat",onClick:n,style:{...a,borderColor:e.borderColor,backgroundColor:e.accentColor,color:e.textColor,borderRadius:"50%",border:`1px solid ${e.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:s=>{s.currentTarget.style.borderColor=e.primaryColor,s.currentTarget.style.backgroundColor=`${e.accentColor}dd`;},onMouseLeave:s=>{s.currentTarget.style.borderColor=e.borderColor,s.currentTarget.style.backgroundColor=e.accentColor;},children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function na(t=false){let[n,e]=useState(t),r=useCallback(()=>e(o=>!o),[]),a=useCallback(()=>e(true),[]),s=useCallback(()=>e(false),[]);return {on:n,toggle:r,setOn:e,setTrue:a,setFalse:s}}function aa(){let t=useRef(null);return useEffect(()=>{let n=t.current;if(!n)return;let e=new MutationObserver(()=>{n.scrollTop=n.scrollHeight;});return e.observe(n,{childList:true,subtree:true}),n.scrollTop=n.scrollHeight,()=>e.disconnect()},[]),t}var Ve=createContext(void 0);function ir({baseUrl:t,children:n}){let[e,r]=useState(new Map),[a,s]=useState(new Map),[o,i]=useState(new Map),[f,y]=useState(new Map),l=useCallback((m,C)=>(r(u=>{let g=new Map(u);return g.set(String(m),C),g}),()=>{r(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});}),[]),b=useCallback((m,C)=>{r(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});},[]),c=useCallback((m,C)=>(s(u=>{let g=new Map(u);return g.set(String(m),C),g}),()=>{s(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});}),[]),M=useCallback((m,C)=>{s(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});},[]),h=useCallback((m,C)=>{i(u=>{let g=new Map(u);return C?g.set(m,true):g.delete(m),g});},[]),k=useCallback((m,C)=>{y(u=>{let g=new Map(u);return C?g.set(m,true):g.delete(m),g});},[]),x=useMemo(()=>Array.from(o.values()).some(m=>m),[o]),d=useMemo(()=>Array.from(f.values()).some(m=>m),[f]),v=useMemo(()=>({baseUrl:t,actions:e,components:a,registerAction:l,unregisterAction:b,registerComponent:c,unregisterComponent:M,isAnyStreaming:x,setStreamingState:h,isAnyChatOpen:d,setChatOpenState:k}),[t,e,a,l,b,c,M,x,h,d,k]);return jsx(Ve.Provider,{value:v,children:n})}function Q(){let t=useContext(Ve);return t||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function ga(t,n){let{registerAction:e}=Q(),r=useRef(n);useEffect(()=>{r.current=n;});let a=useCallback((s,o)=>r.current(s,o),[]);useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaAction] Invalid action registration: name="${t}", handler type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function ya(t,n){let{registerComponent:e}=Q(),r=useRef(n);useEffect(()=>{r.current=n;});let a=useMemo(()=>{let s=o=>{let i=r.current;return Bt.createElement(i,o)};return s.displayName=`HsafaStable(${t})`,s},[]);useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaComponent] Invalid component registration: name="${t}", component type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function Ge(t){let n=`hsafaChat_${t}`,e=`${n}.chats`,r=u=>`${n}.chat.${u}`,a=`${n}.currentChatId`,s=`${n}.showChat`,[o,i]=useState(null),f=useRef(false),y=useRef(null),l=()=>{try{let u=localStorage.getItem(e);return u?JSON.parse(u):[]}catch{return []}},b=u=>{try{localStorage.setItem(e,JSON.stringify(u));}catch{}},c=u=>{try{let g=localStorage.getItem(r(u));return g?JSON.parse(g):null}catch{return null}},M=u=>{try{localStorage.setItem(r(u.id),JSON.stringify(u));}catch{}},h=u=>{let g=l(),T=g.findIndex(R=>R.id===u.id);T>=0?g[T]=u:g.unshift(u),b(g);},k=u=>{let T=l().filter(R=>R.id!==u);b(T);},x=u=>{try{localStorage.removeItem(r(u));}catch{}};return {currentChatId:o,setCurrentChatId:i,hasChatRecordRef:f,pendingFirstTitleRef:y,loadChatsIndex:l,loadChat:c,saveChat:M,deleteChat:(u,g)=>{x(u),k(u);let T=o===u;if(T){i(null),f.current=false,y.current=null;try{localStorage.removeItem(a);}catch{}}g?.(T);},loadChatPreferences:()=>{try{let u=localStorage.getItem(a);if(u){let g=c(u);if(g)return i(g.id),f.current=!0,g.messages||[]}}catch{}return []},persistChatData:u=>{if(!o||!f.current)return;M({id:o,messages:u,agentId:t});let T=u.find(H=>H.role==="user"),R=T?De(T):"New chat",L=(y.current||R).slice(0,80),$={id:o,title:L,createdAt:Date.now(),updatedAt:Date.now()};h($);try{localStorage.setItem(a,o);}catch{}},createNewChat:u=>{let g=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;i(g),f.current=true;let T=(u||"New chat").slice(0,80),R=Date.now();h({id:g,title:T,createdAt:R,updatedAt:R});try{localStorage.setItem(a,g);}catch{}return g},upsertChatMeta:h,showChatKey:s}}function Qe(){let[t,n]=useState(false),[e,r]=useState(null),a=useRef(null),s=useRef({}),o=useRef(void 0),i=useRef(new Set),f=useRef(new Map),y=useRef(new Map),[l,b]=useState(new Map),c=useCallback((d,v)=>{let m=f.current.get(d)||[],C=JSON.stringify(v);if(m.push(C),m.length>5&&m.shift(),f.current.set(d,m),m.length>=3){let u=m.slice(-3);return u.every(g=>g===u[0])}return false},[]),M=useCallback((d,v,m,C)=>{!Array.isArray(d)||d.length===0||d.forEach((u,g)=>{if(!(!u||typeof u!="object")&&u.type==="action"){let T=String(u.name??"").trim();if(!T)return;let R=m.get(T);if(!R){console.warn(`Action handler not found for: ${T}`);return}let L=!!s.current[T],$=`${o.current||"assist"}:${T}:${g}`,H=`${T}:${g}`;try{if(v==="partial"&&L){b(B=>new Map(B).set(H,"executing"));let j=setTimeout(()=>{Promise.resolve(R(u.params,{name:T,trigger:v,index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(B=>{console.error(`Error executing streaming action ${T}:`,B),b(I=>new Map(I).set(H,"executed"));});},50);y.current.set(`${H}_timeout`,j);}else if(v==="partial"&&!L){let j=c(H,u.params),B=y.current.get(H);j&&B!=="executed"?(y.current.set(H,"executed"),b(I=>new Map(I).set(H,"executed")),Promise.resolve(R(u.params,{name:T,trigger:"params_complete",index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(I=>{console.error(`Error executing stabilized action ${T}:`,I);})):B||(y.current.set(H,"executing"),b(I=>new Map(I).set(H,"executing")));}else if(v==="final"&&y.current.get(H)!=="executed"&&!i.current.has($)){i.current.add($);let B=y.current.get(`${H}_timeout`);B&&(clearTimeout(B),y.current.delete(`${H}_timeout`)),y.current.set(H,"executed"),b(I=>new Map(I).set(H,"executed")),Promise.resolve(R(u.params,{name:T,trigger:L?"final":"params_complete",index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(I=>{console.error(`Error executing final action ${T}:`,I);});}}catch(j){console.error(`Error processing action ${T}:`,j);}}});},[c]),h=useCallback(()=>{a.current&&(a.current.abort(),a.current=null),n(false),r("Request stopped by user");},[]),k=useCallback(()=>{i.current.clear(),f.current.clear(),y.current.clear(),b(new Map);},[]),x=useCallback(()=>{y.current.forEach((d,v)=>{v.endsWith("_timeout")&&clearTimeout(d);});},[]);return {streaming:t,setStreaming:n,error:e,setError:r,actionStatuses:l,setActionStatuses:b,abortControllerRef:a,actionExecMapRef:s,assistantMsgIdRef:o,calledFinalActionsRef:i,actionParamsHistoryRef:f,actionExecutionStatusRef:y,processActions:M,handleStop:h,resetActionTracking:k,cleanupTimeouts:x,hasActionParamsStabilized:c}}function tn(t,n){if(!t)return n;let e=t.endsWith("/")?t.slice(0,-1):t,r=n.startsWith("/")?n:`/${n}`;return `${e}${r}`}var oe=25*1024*1024;function nn(t){let[n,e]=useState([]),[r,a]=useState(false),s=useRef(null),o=useCallback(c=>{if(!c||Number.isNaN(c))return "0 B";let M=["B","KB","MB","GB","TB"],h=Math.min(M.length-1,Math.floor(Math.log(c)/Math.log(1024)));return `${(c/Math.pow(1024,h)).toFixed(h===0?0:1)} ${M[h]}`},[]),i=useCallback(async c=>{let M=new FormData;M.append("file",c);let h=await fetch(tn(t,"/api/uploads"),{method:"POST",body:M});if(!h.ok){let x=await h.text().catch(()=>"");throw new Error(x||`Failed to upload ${c.name}`)}let k=await h.json();return {id:k.id,name:k.name||c.name,url:k.url,mimeType:k.mimeType||c.type||"application/octet-stream",size:typeof k.size=="number"?k.size:c.size}},[t]),f=useCallback(c=>{e(M=>M.filter(h=>h.id!==c));},[]),y=useCallback(async(c,M)=>{if(!c)return;let h=Array.isArray(c)?c:Array.from(c);M(null),a(true);let k=[];try{for(let x of h){if(x.size>oe){M(`"${x.name}" exceeds the ${o(oe)} limit.`);continue}try{let d=await i(x);k.push(d);}catch(d){console.error("Failed to upload attachment:",d),M(String(d?.message??`Failed to upload ${x.name}`));}}k.length&&e(x=>[...x,...k]);}finally{a(false);}},[i,o]),l=useCallback((c,M)=>{let h=[],k=(c||"").trim();k&&h.push({type:"text",text:k});for(let x of M||[]){let d=x.mimeType||"application/octet-stream";d.startsWith("image/")?h.push({type:"image",image:new URL(x.url),mediaType:d}):h.push({type:"file",data:x.url,mediaType:d,name:x.name});}return h},[]),b=useCallback(()=>{e([]);},[]);return {attachments:n,uploading:r,fileInputRef:s,formatBytes:o,handleRemoveAttachment:f,handleFileSelection:y,buildUserContent:l,clearAttachments:b,MAX_UPLOAD_SIZE:oe}}function hr(t){return JSON.parse(JSON.stringify(t))}function rn(){let[t,n]=useState(false),[e,r]=useState(null),[a,s]=useState(null),o=useRef(null),i=useCallback(async({agentId:l,body:b,baseUrl:c,onUpdate:M,signal:h})=>{try{let $=function(){let I=hr(C);s(I),M?.(I);};var k=$;n(!0),r(null);let x;if(h)o.current=null,x=h;else {let I=new AbortController;o.current=I,x=I.signal;}let v=`${c?c.replace(/\/$/,""):""}/api/run/${encodeURIComponent(l)}`,m=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(b??{}),signal:x});if(!m.ok||!m.body){let I=await m.text().catch(()=>"");throw new Error(`Request failed: ${m.status} ${m.statusText} - ${I}`)}let C={first_agent:{message:"",continue:!1},main_agent:[]},u=null,g=null,T=null,R=null,L=!1,H=m.body.getReader(),j=new TextDecoder("utf-8"),B="";for($();;){let{value:I,done:Mt}=await H.read();if(Mt)break;B+=j.decode(I,{stream:!0});let et=B.indexOf(`
15
- `);for(;et!==-1;){let q=B.slice(0,et).trim();if(B=B.slice(et+1),q.length>0)try{let p=JSON.parse(q);switch(p?.type){case "start":break;case "first-agent-start":C.first_agent.startDate=p?.startDate,C.first_agent.durationMs=p?.durationMs,$();break;case "first-agent-partial":typeof p?.message=="string"&&(C.first_agent.message=p.message),typeof p?.continue=="boolean"&&(C.first_agent.continue=p.continue),typeof p?.durationMs=="number"&&(C.first_agent.durationMs=p.durationMs),$();break;case "first-agent-end":typeof p?.message=="string"&&(C.first_agent.message=p.message),typeof p?.continue=="boolean"&&(C.first_agent.continue=p.continue),C.first_agent.endDate=p?.endDate,C.first_agent.durationMs=p?.durationMs,$();break;case "main-agent-start":L=!1;break;case "main-agent-step-finish":{let S={type:"step",stepNumber:void 0,finishReason:p?.finishReason,usage:p?.usage,endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S),$();break}case "main-agent-skipped":L=!0;break;case "main-agent-reasoning-start":u={type:"reasoning",reasoning:"",status:"streaming",startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(u),$();break;case "main-agent-reasoning-delta":u&&typeof p?.text=="string"&&(u.reasoning+=p.text,u.durationMs=p?.durationMs,$());break;case "main-agent-reasoning-end":if(u){if(typeof p?.text=="string"&&p.text.length>0&&(u.reasoning+=p.text),u.status="finished",u.endDate=p?.endDate,u.durationMs=p?.durationMs,!u.reasoning||u.reasoning.trim().length===0){let S=C.main_agent.indexOf(u);S>-1&&C.main_agent.splice(S,1);}u=null,$();}else if(typeof p?.text=="string"&&p.text.length>0){let S={type:"reasoning",reasoning:p.text,status:"finished",endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S),$();}break;case "main-agent-tool-call-start":g={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,inputText:"",input:void 0,output:void 0,status:"input_streaming",startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(g),$();break;case "main-agent-tool-input-delta":let it=p?.delta||p?.argsTextDelta;g&&typeof it=="string"&&(g.inputText=(g.inputText||"")+it,g.durationMs=p?.durationMs,$());break;case "tool-call":case "main-agent-tool-call":if(g)g.input=p?.input,g.status="running",g.durationMs=p?.durationMs;else {let S=C.main_agent.find(vt=>vt.type==="tool-call"&&(vt.toolCallId===p?.toolCallId||vt.toolName===p?.toolName));S?(S.input=p?.input,S.status="running",S.durationMs=p?.durationMs,g=S):(g={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,input:p?.input,inputText:"",output:void 0,status:"running",durationMs:p?.durationMs},C.main_agent.push(g));}$();break;case "tool-result":case "main-agent-tool-result":let Y=g;if(Y||(Y=C.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===p?.toolCallId||S.toolName===p?.toolName))||null),Y)Y.output=p?.output,Y.status="finished",Y.endDate=p?.endDate,Y.durationMs=p?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,input:void 0,inputText:"",output:p?.output,status:"finished",endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S);}$();break;case "tool-error":case "main-agent-tool-error":let J=g;if(J||(J=C.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===p?.toolCallId||S.toolName===p?.toolName))||null),J)J.error=p?.error,J.status="error",J.endDate=p?.endDate,J.durationMs=p?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,input:void 0,inputText:"",output:void 0,error:p?.error,status:"error",endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S);}$();break;case "main-agent-response-partial":if(L)break;if(T||(T={type:"response",items:[],startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(T)),p?.value&&typeof p.value=="object"){let S=Array.isArray(p.value.items)?p.value.items:T.items;Object.assign(T,p.value),T.items=S,T.durationMs=p?.durationMs;}$();break;case "text-delta":case "main-agent-text-delta":typeof p?.text=="string"&&p.text&&(R||(R={type:"text",text:"",status:"streaming",startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(R)),R.text+=p.text,R.durationMs=p?.durationMs,$());break;case "text-end":R&&(R.status="finished",R.endDate=p?.endDate,R.durationMs=p?.durationMs,R=null,$());break;case "source":case "main-agent-source":let Tt={type:"source",source:p?.source,durationMs:p?.durationMs};C.main_agent.push(Tt),$();break;case "file":case "main-agent-file":let Kt={type:"file",file:p?.file,durationMs:p?.durationMs};C.main_agent.push(Kt),$();break;case "final":if(L)break;if(p?.value&&typeof p.value=="object"){T||(T={type:"response",items:[],endDate:p?.endDate,durationMs:p?.durationMs},C.main_agent.push(T));let S=Array.isArray(p.value.items)?p.value.items:T.items;Object.assign(T,p.value),T.items=S,T.endDate=p?.endDate,T.durationMs=p?.durationMs;}$();break;case "error":case "main-agent-error":throw new Error(p?.error||"Unknown agent error");default:break}}catch(p){console.warn("Failed to parse streaming line:",p);}et=B.indexOf(`
16
- `);}}try{H.releaseLock();}catch{}return n(!1),C}catch(x){return x.name==="AbortError"?r("Request was cancelled"):r(x?.message||"Request failed"),n(false),null}},[]),f=useCallback(()=>{o.current&&(o.current.abort(),o.current=null),n(false);},[]),y=useCallback(()=>{s(null),r(null),n(false);},[]);return {streaming:t,error:e,streamData:a,startStreaming:i,stopStreaming:f,reset:y}}var on={en:{"header.maximize":"Maximize","header.minimize":"Minimize","header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit","messages.empty":"Start by sending a message to the agent.","messages.error":"An error occurred","history.search":"Search","history.noChatsFound":"No chats found.","history.untitledChat":"Untitled chat","history.deleteChat":"Delete chat","general.agent":"Agent"},ar:{"header.maximize":"\u062A\u0643\u0628\u064A\u0631","header.minimize":"\u062A\u0635\u063A\u064A\u0631","header.new":"\u062C\u062F\u064A\u062F","header.history":"\u0627\u0644\u0633\u062C\u0644","header.close":"\u0625\u063A\u0644\u0627\u0642 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","input.placeholder":"\u0627\u0637\u0631\u062D \u0633\u0624\u0627\u0644\u0643...","input.attachFiles":"\u0625\u0631\u0641\u0627\u0642 \u0645\u0644\u0641\u0627\u062A","input.insertLink":"\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637","input.send":"\u0625\u0631\u0633\u0627\u0644","input.stop":"\u0625\u064A\u0642\u0627\u0641","input.uploadingFiles":"\u062C\u0627\u0631\u064A \u0631\u0641\u0639 \u0627\u0644\u0645\u0644\u0641\u0627\u062A...","input.previewImage":"\u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0635\u0648\u0631\u0629","input.removeFile":"\u062D\u0630\u0641 \u0627\u0644\u0645\u0644\u0641","editor.cancel":"\u0625\u0644\u063A\u0627\u0621","editor.saveAndRegenerate":"\u062D\u0641\u0638 \u0648\u0625\u0639\u0627\u062F\u0629 \u062A\u0648\u0644\u064A\u062F","editor.clickToEdit":"\u0627\u0646\u0642\u0631 \u0644\u0644\u062A\u0639\u062F\u064A\u0644","messages.empty":"\u0627\u0628\u062F\u0623 \u0628\u0625\u0631\u0633\u0627\u0644 \u0631\u0633\u0627\u0644\u0629 \u0625\u0644\u0649 \u0627\u0644\u0648\u0643\u064A\u0644.","messages.error":"\u062D\u062F\u062B \u062E\u0637\u0623","history.search":"\u0628\u062D\u062B","history.noChatsFound":"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u0645\u062D\u0627\u062F\u062B\u0627\u062A.","history.untitledChat":"\u0645\u062D\u0627\u062F\u062B\u0629 \u0628\u062F\u0648\u0646 \u0639\u0646\u0648\u0627\u0646","history.deleteChat":"\u062D\u0630\u0641 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","general.agent":"\u0627\u0644\u0648\u0643\u064A\u0644"}};function an(t,n){return on[t]?.[n]||on.en[n]||n}function sn(t="en"){return {t:useCallback(e=>an(t,e),[t]),language:t}}function cn({actions:t,currentChatId:n}){let e=useRef({}),r=useRef(void 0),a=useRef(new Set),[s,o]=useState(new Map);useEffect(()=>()=>{},[]);let i=useCallback((y,l)=>{if(!Array.isArray(y)||y.length===0){l==="final"&&o(b=>{let c=new Map(b);return c.forEach((M,h)=>c.set(h,"executed")),c});return}y.forEach((b,c)=>{if(!(!b||typeof b!="object")&&b.type==="action"){let M=String(b.name??"").trim();if(!M)return;let h=t.get(M);if(!h)return;let k=typeof b.executeOnStream=="boolean"?b.executeOnStream:!!e.current[M],x=`${r.current||"assist"}:${M}:${c}`,d=`${M}:${c}`;try{l==="partial"&&k?(o(v=>new Map(v).set(d,"executing")),Promise.resolve(h(b.params,{name:M,trigger:l,index:c,assistantMessageId:r.current,chatId:n||void 0})).then(()=>{o(v=>new Map(v).set(d,"executed"));}).catch(v=>{console.error(`[useActions] Error executing streaming action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));})):l==="partial"&&!k?o(v=>{if(v.get(d)==="executing")return v;let m=new Map(v);return m.set(d,"executing"),m}):l==="final"&&(!k&&!a.current.has(x)?(a.current.add(x),Promise.resolve(h(b.params,{name:M,trigger:"params_complete",index:c,assistantMessageId:r.current,chatId:n||void 0})).then(()=>{o(v=>new Map(v).set(d,"executed"));}).catch(v=>{console.error(`[useActions] Error executing final action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));})):k||o(v=>new Map(v).set(d,"executed")));}catch(v){console.error(`[useActions] Error processing action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));}}});},[t,n]),f=useCallback(()=>{a.current.clear(),o(new Map);},[]);return {actionExecMapRef:e,assistantMsgIdRef:r,actionStatuses:s,processActions:i,resetActionTracking:f}}function Wt({icon:t,onClick:n,ariaLabel:e,resolvedColors:r,disabled:a=false,title:s}){return jsx("button",{"aria-label":e,title:s,disabled:a,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:o=>{a||(o.currentTarget.style.backgroundColor=r.hoverBackground,o.currentTarget.style.color=r.textColor);},onMouseLeave:o=>{o.currentTarget.style.backgroundColor="transparent",o.currentTarget.style.color=r.mutedTextColor;},onClick:n,children:t})}function pn({title:t,expandable:n,alwaysOpen:e,maximized:r,streaming:a,dir:s,resolvedColors:o,onMaximize:i,onNew:f,onToggleHistory:y,onClose:l,historyBtnRef:b,t:c}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:s==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:t,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:t})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[n&&jsx(Wt,{icon:jsx(Maximize2,{size:"20",strokeWidth:"2"}),onClick:i,ariaLabel:c(r?"header.minimize":"header.maximize"),resolvedColors:o}),jsx(Wt,{icon:jsx(Plus,{size:"20",strokeWidth:"2"}),onClick:()=>{a||f();},ariaLabel:c("header.new"),resolvedColors:o,disabled:a}),jsx("button",{ref:b,"aria-label":c("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:M=>{M.currentTarget.style.backgroundColor=o.hoverBackground,M.currentTarget.style.color=o.textColor;},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="transparent",M.currentTarget.style.color=o.mutedTextColor;},onClick:y,children:jsx(History,{size:"20",strokeWidth:"2"})}),!e&&jsx(Wt,{icon:jsx(ChevronRight,{size:"20",strokeWidth:"2",style:{transform:s==="rtl"?"rotate(180deg)":"none"}}),onClick:l,ariaLabel:c("header.close"),resolvedColors:o})]})]})}function gn({value:t,onChange:n,onSend:e,onStop:r,streaming:a,placeholder:s,attachments:o,uploading:i,onRemoveAttachment:f,onFileInputClick:y,resolvedColors:l,formatBytes:b,textareaRef:c,fileInputRef:M,onFileSelection:h,t:k,dir:x="ltr"}){return Bt.useEffect(()=>{let d=c.current;if(d){d.style.height="24px",d.offsetHeight,d.style.height="auto";let v=Math.min(d.scrollHeight,200);d.style.height=`${v}px`;}},[t,c]),Bt.useEffect(()=>{let d=c.current;d&&!t&&(d.style.height="24px");},[c,t]),jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:l.backgroundColor},children:jsx("div",{style:{position:"relative",flex:"1"},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${l.borderColor}`,backgroundColor:l.accentColor},children:[o.length>0&&jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:o.map(d=>{let v=d.mimeType?.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:l.inputBackground,borderRadius:"10px",border:`1px solid ${l.borderColor}`,fontSize:"12px",color:l.textColor,transition:"all 0.2s ease-out",cursor:"pointer",position:"relative"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:v?"transparent":l.accentColor},children:[v?jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:m=>{m.target.style.display="none";let C=m.target.nextElementSibling;C&&(C.style.display="block");}}):null,jsx(File,{size:"14",strokeWidth:"2",style:{display:v?"none":"block",color:l.mutedTextColor}})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:d.name}),jsx("span",{style:{color:l.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:b(d.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[v&&jsx("button",{onClick:m=>{m.stopPropagation(),window.open(d.url,"_blank");},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:k("input.previewImage"),onMouseEnter:m=>{m.currentTarget.style.backgroundColor=l.hoverBackground,m.currentTarget.style.color=l.textColor;},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=l.mutedTextColor;},children:jsx(Eye,{size:"12",strokeWidth:"2"})}),jsx("button",{onClick:m=>{m.stopPropagation(),f(d.id);},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:k("input.removeFile"),onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.color="#ef4444";},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=l.mutedTextColor;},children:jsx(X,{size:"12",strokeWidth:"2"})})]})]},d.id)})}),i&&jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:l.mutedTextColor},children:[jsx(Loader2,{size:"14",strokeWidth:"2",style:{animation:"spin 1s linear infinite"}}),jsx("span",{children:k("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{"aria-label":"Prompt",rows:1,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:l.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:s,value:t,onChange:d=>n(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),a||e());},ref:c})}),jsxs("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:l.mutedTextColor},children:[jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,d.currentTarget.style.color=l.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=l.mutedTextColor;},"aria-label":k("input.attachFiles"),onClick:y,children:jsx(Paperclip,{size:"18",strokeWidth:"2"})}),jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,d.currentTarget.style.color=l.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=l.mutedTextColor;},"aria-label":k("input.insertLink"),children:jsx(Link,{size:"18",strokeWidth:"2"})})]}),jsx("input",{type:"file",ref:M,multiple:true,accept:"*/*",style:{display:"none"},onChange:d=>h(d.target.files)}),jsx("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{left:"8px"}:{right:"8px"}},children:jsx("button",{"aria-label":k(a?"input.stop":"input.send"),disabled:!a&&!t.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a?"#ef4444":l.borderColor}`,backgroundColor:a?"#ef444420":l.cardBackground,color:a?"#ef4444":l.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#dc2626",d.currentTarget.style.backgroundColor="#dc262630",d.currentTarget.style.color="#dc2626"):(d.currentTarget.style.borderColor=l.primaryColor,d.currentTarget.style.backgroundColor=l.hoverBackground,d.currentTarget.style.color=l.textColor));},onMouseLeave:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#ef4444",d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.color="#ef4444"):(d.currentTarget.style.borderColor=l.borderColor,d.currentTarget.style.backgroundColor=l.cardBackground,d.currentTarget.style.color=l.mutedTextColor));},onClick:()=>{a?r():e();},children:a?jsx(Square,{size:"18",strokeWidth:"2"}):jsx(ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function mn(t){let n=Date.now()-t,e=Math.max(1,Math.floor(n/1e3));if(e<60)return `${e}s`;let r=Math.floor(e/60);if(r<60)return `${r}m`;let a=Math.floor(r/60);if(a<24)return `${a}h`;let s=Math.floor(a/24);if(s<7)return `${s}d`;let o=Math.floor(s/7);if(o<4)return `${o}w`;let i=Math.floor(s/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function fn({isOpen:t,onClose:n,searchQuery:e,onSearchChange:r,chats:a,currentChatId:s,onChatSelect:o,onChatDelete:i,resolvedColors:f,t:y}){if(!t)return null;let l=e.trim()?a.filter(c=>(c.title||"").toLowerCase().includes(e.toLowerCase().trim())):a,b=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:n}),jsxs("div",{style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${f.borderColor}`,backgroundColor:`${f.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${f.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:e,onChange:c=>r(c.target.value),placeholder:y("history.search"),style:{width:"100%",borderRadius:"8px",backgroundColor:f.inputBackground,padding:"8px 12px",fontSize:"14px",color:f.textColor,border:`1px solid ${f.borderColor}`,outline:"none"},onFocus:c=>c.currentTarget.style.borderColor=f.primaryColor,onBlur:c=>c.currentTarget.style.borderColor=f.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:l.length===0?jsx("div",{style:{padding:"24px",color:f.mutedTextColor,textAlign:"center"},children:y("history.noChatsFound")}):jsx("div",{children:l.map((c,M)=>jsx("div",{style:{borderTop:M>0?`1px solid ${f.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:c.id===s?f.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:f.textColor},onMouseEnter:h=>h.currentTarget.style.backgroundColor=f.hoverBackground,onMouseLeave:h=>h.currentTarget.style.backgroundColor="transparent",onClick:()=>o(c.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:f.textColor},children:c.title||y("history.untitledChat")})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:f.mutedTextColor},children:mn(c.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:f.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:y("history.deleteChat"),onMouseEnter:h=>{h.currentTarget.style.color="#ef4444",h.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",h.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:h=>{h.currentTarget.style.color=f.mutedTextColor,h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.borderColor="transparent";},onClick:h=>{h.stopPropagation(),i(c.id);},children:jsx(Trash2,{size:"16",strokeWidth:"2"})})]})},c.id))})})]})]});return typeof document<"u"&&document.body?createPortal(b,document.body):b}var Ot={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};var le=t=>t.map(n=>({...n}));function Br(t){let[n,e]=useState(()=>{try{return t.loadChatPreferences()}catch(o){return console.warn("Failed to load chat preferences:",o),[]}});useEffect(()=>{if(n.length!==0)try{t.persistChatData(n);}catch(o){console.warn("Failed to persist chat data:",o);}},[n]);let r=useCallback(o=>{try{t.setCurrentChatId(o);let i=t.loadChat(o);return e(i?.messages||[]),!0}catch(i){return console.warn("Failed to load selected chat:",i),false}},[t]),a=useCallback(o=>{try{t.deleteChat(o,i=>{i&&e([]);});}catch(i){console.warn("Failed to delete chat:",i);}},[t]),s=useCallback(()=>{e([]),t.setCurrentChatId(null);},[t]);return {messages:n,setMessages:e,selectChat:r,deleteChat:a,resetChat:s}}function Lr(t){let{agentId:n,theme:e="dark",primaryColor:r,backgroundColor:a,borderColor:s,textColor:o,accentColor:i,width:f=420,height:y="100vh",expandable:l=true,alwaysOpen:b=false,defaultOpen:c=false,dir:M="ltr",language:h,floatingButtonPosition:k=M==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},placeholder:x,title:d,chatContainerClassName:v="",defaultReasoningOpen:m=false,hideReasoningContent:C=false}=t,u=h||(M==="rtl"?"ar":"en"),{t:g}=sn(u),T=x??g("input.placeholder"),R=d??g("general.agent"),{baseUrl:L,actions:$,components:H,setStreamingState:j,setChatOpenState:B}=Q(),I=useRef(`chat-${n}-${Date.now()}`).current,[Mt,et]=useState(""),[q,p]=useState(()=>{if(b)return true;try{let A=localStorage.getItem(`hsafaChat_${n}.showChat`);return A!==null?A==="true":c}catch{return c}}),[ce,it]=useState(false),[Y,J]=useState(""),[Tt,Kt]=useState(false),[S,vt]=useState(0),[yn,jt]=useState(null),[xn,de]=useState(""),[pe,At]=useState([]),ue=useRef(null),[ge,me]=useState(true),qt=useRef(false),bn=useRef(null),Cn=useRef(null),kn=useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),nt=Ge(n),{messages:rt,setMessages:wt,selectChat:fe,deleteChat:he,resetChat:Mn}=Br(nt),_=Qe(),St=nn(L||""),Jt=rn(),{assistantMsgIdRef:Tn,actionStatuses:vn,processActions:ye,resetActionTracking:An}=cn({actions:$,currentChatId:nt.currentChatId});useEffect(()=>{j(I,_.streaming);},[_.streaming,I,j]),useEffect(()=>(B(I,q),()=>{B(I,false),j(I,false);}),[q,I,B,j]),useEffect(()=>{if(!b)try{localStorage.setItem(`hsafaChat_${n}.showChat`,String(q));}catch(A){console.warn("Failed to save chat state:",A);}},[q,n,b]);let{attachments:Vt,uploading:xe,fileInputRef:be,formatBytes:wn,handleRemoveAttachment:Sn,handleFileSelection:Rn,clearAttachments:Ce}=St,ke=useCallback((A,F)=>{wt(P=>P.map(w=>{if(w.id===A&&w.role==="assistant"){let E=F.main_agent.find(O=>O.type==="response"),N=E?.type==="response"?E.items:[];return {...w,items:N,mainAgentActions:F.main_agent,firstAgentMessage:F.first_agent.message,firstAgentContinue:F.first_agent.continue,reasoningOpen:w.reasoningOpen}}return w}));},[]),Xt=useCallback(async({prompt:A,baseMessages:F,userMessage:P,assistantMessageId:w,chatId:E})=>{if(n){_.setError(null),_.setStreaming(true);try{let N=Ie(F);N.push({role:"user",content:P.content}),Tn.current=w,An(),await Jt.startStreaming({agentId:n,baseUrl:L,body:{prompt:A,chatId:E??void 0,messages:N},onUpdate:Dt=>{ke(w,Dt);let En=Dt.main_agent.find(zn=>zn.type==="response")?.items||[];ye(En,"partial");}});let $t=Jt.streamData?.main_agent?.find(Dt=>Dt.type==="response")?.items||[];ye($t,"final");}catch(N){_.setError(N?.message||"Request failed");}finally{_.setStreaming(false);}}},[n,L,Jt,_,ke]),$n=useCallback(A=>{fe(A)&&(it(false),J(""));},[fe,it,J]),In=useCallback(A=>{he(A),vt(F=>F+1);},[he]),ot=Ot[e],ut={primaryColor:r||ot.primaryColor,backgroundColor:a??"transparent",borderColor:s||ot.borderColor,textColor:o||ot.textColor,accentColor:i||ot.accentColor,mutedTextColor:ot.mutedTextColor,inputBackground:ot.inputBackground,cardBackground:ot.cardBackground,hoverBackground:ot.hoverBackground},Fn=useCallback(async()=>{if(!n)return;let A=Mt.trim();if(!A)return;let F=nt.currentChatId;F||(F=nt.createNewChat(A));let P=le(Vt),w=$e(A,P),E=Qt(m),N=rt;wt([...N,w,E]),et(""),Ce(),me(true),await Xt({prompt:A,baseMessages:N,userMessage:w,assistantMessageId:E.id,chatId:F});},[n,Mt,rt,Vt,Ce,Xt,nt,wt,et]),Dn=useCallback(async A=>{if(!A||!L)return;let F=Array.from(A);_.setError(null);let P=[];try{for(let w of F){if(w.size>St.MAX_UPLOAD_SIZE){_.setError(`"${w.name}" exceeds the ${St.formatBytes(St.MAX_UPLOAD_SIZE)} limit.`);continue}try{let E=new FormData;E.append("file",w);let N=await fetch(`${L}/api/uploads`,{method:"POST",body:E});if(!N.ok){let $t=await N.text().catch(()=>"");throw new Error($t||`Failed to upload ${w.name}`)}let O=await N.json(),Rt={id:O.id,name:O.name||w.name,url:O.url,mimeType:O.mimeType||w.type||"application/octet-stream",size:typeof O.size=="number"?O.size:w.size};P.push(Rt);}catch(E){console.error("Failed to upload attachment:",E),_.setError(String(E?.message??`Failed to upload ${w.name}`));}}P.length&&At(w=>[...w,...P]);}catch(w){console.error("Error adding attachments during edit:",w);}},[L,St,_]);return useEffect(()=>{if(qt.current){qt.current=false;return}ge&&requestAnimationFrame(()=>{ue.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[rt,_.streaming,ge]),useEffect(()=>{let A=document.querySelector(".chat-scroll-container");if(!A)return;let F=()=>{let{scrollTop:P,scrollHeight:w,clientHeight:E}=A,O=w-P-E<40;me(O);};return A.addEventListener("scroll",F),F(),()=>A.removeEventListener("scroll",F)},[]),typeof document<"u"?createPortal(jsxs(Fragment,{children:[jsxs("div",{className:v,style:{width:q?Tt?"100%":typeof f=="number"?`${f}px`:f:"0",height:y,display:"flex",flexDirection:"column",backgroundColor:q?ut.backgroundColor:"transparent",opacity:q?1:0,padding:q?"24px 16px":"0",transition:"all 0.3s ease-out",position:"fixed",top:0,...M==="rtl"?{left:0}:{right:0},bottom:0,zIndex:Tt?9999:1e3,pointerEvents:q?"auto":"none"},children:[jsx(pn,{title:R,expandable:l,alwaysOpen:b,maximized:Tt,streaming:_.streaming,dir:M,resolvedColors:ut,onMaximize:()=>Kt(A=>!A),onNew:Mn,onToggleHistory:()=>it(A=>!A),onClose:()=>p(false),historyBtnRef:Cn,t:g}),jsx(qe,{messages:rt,streaming:_.streaming,editingMessageId:yn,editingMessageText:xn,editingAttachments:pe,error:_.error,actionStatuses:vn,components:H,theme:e,resolvedColors:ut,hideReasoningContent:C,onEditingTextChange:de,onRemoveAttachment:A=>{At(F=>F.filter(P=>P.id!==A));},onAddAttachments:Dn,uploading:xe,onStartEdit:(A,F)=>{let P=rt.find(w=>w.id===A);jt(A),de(F),P&&P.role==="user"&&At(le(gt(P)));},onCancelEdit:()=>{jt(null),At([]);},onSaveEdit:async(A,F)=>{let P=rt.findIndex($t=>$t.id===A);if(P===-1)return;let w=rt[P];if(w.role!=="user")return;let E=F.trim(),N=Fe(w,E,le(pe)),O=rt.slice(0,P),Rt=Qt(m);wt([...O,N,Rt]),jt(null),At([]),await Xt({prompt:E,baseMessages:O,userMessage:N,assistantMessageId:Rt.id,chatId:nt.currentChatId??null});},onToggleReasoning:A=>{let F=document.querySelector(".chat-scroll-container"),P=F?.scrollTop||0;qt.current=true,wt(w=>w.map(E=>E.id===A&&E.role==="assistant"?{...E,reasoningOpen:!E.reasoningOpen}:E)),requestAnimationFrame(()=>{F&&(F.scrollTop=P);});},scrollAnchorRef:ue,t:g}),jsx(gn,{value:Mt,onChange:et,onSend:Fn,onStop:_.handleStop,streaming:_.streaming,placeholder:T,attachments:Vt,uploading:xe,onRemoveAttachment:Sn,onFileInputClick:()=>be.current?.click(),resolvedColors:ut,formatBytes:wn,textareaRef:bn,fileInputRef:be,onFileSelection:A=>Rn(A,_.setError),t:g,dir:M})]}),jsx(Je,{show:!q&&!b,onClick:()=>p(true),resolvedColors:ut,floatingButtonPosition:k}),jsx(fn,{isOpen:ce,onClose:()=>it(false),searchQuery:Y,onSearchChange:J,chats:nt.loadChatsIndex(),currentChatId:nt.currentChatId,onChatSelect:$n,onChatDelete:In,resolvedColors:ut,t:g}),jsx("style",{children:`
17
- @keyframes ${kn.current}-border-flow {
18
- 0% { background-position: 0% 50%; }
19
- 50% { background-position: 100% 50%; }
20
- 100% { background-position: 0% 50%; }
21
- }
22
-
23
- @keyframes pulse {
24
- 0%, 100% { opacity: 1; }
25
- 50% { opacity: 0.5; }
3
+ `),o="",r=false,l="",u=[],c=false,v=false,S=false,a=t==="dark"?"#374151":"#D1D5DB",f=t==="dark"?"#111827":"#F3F4F6",b=t==="dark"?"#E5E7EB":"#374151",g=t==="dark"?"#374151":"#F3F4F6",k=t==="dark"?"#F9FAFB":"#111827",i=()=>{c&&(o+="</ul>",c=false),v&&(o+="</ol>",v=false);},m=y=>{for(let p=y;p<n.length;p++)if(n[p].trim().length>0)return p;return -1},h=y=>{let p=y.trim(),F=p.startsWith("|")?p.slice(1):p;return (F.endsWith("|")?F.slice(0,-1):F).split("|").map(q=>q.trim())},C=y=>{let p=y.trim();if(!p.startsWith("|"))return false;let F=h(p);return F.length>=2&&F.some(U=>U.length>0)},E=y=>{let p=h(y);return p.length===0?false:p.every(F=>/^:?-{3,}:?$/.test(F))},M=y=>{let p=y.startsWith(":"),F=y.endsWith(":");return p&&F?"center":!p&&F?"right":"left"},w=y=>{let p=y,F=m(p+1);if(F===-1)return {tableHtml:"",endIndex:y};let U=h(n[p]),q=h(n[F]),Z=Math.max(U.length,q.length),z=[];for(let $=0;$<Z;$++){let H=q[$]||"---";z.push(M(H));}let Q=[],V=F+1;for(;V<n.length;){let $=n[V].trim();if($.length===0){V++;continue}if(!$.startsWith("|"))break;let H=h(n[V]),N=[];for(let L=0;L<Z;L++)N.push(H[L]??"");Q.push(N),V++;}let ee=`<div style="overflow: auto; max-width: 100%; max-height: 60vh; border-radius: 10px; margin: 8px 0;">
4
+ <table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;ee+="<thead><tr>";for(let $=0;$<Z;$++){let H=He(le(U[$]??"")),N=z[$],L=$===0,ge=$===Z-1;ee+=`<th style="text-align: ${N}; padding: 10px 12px; border-bottom: 1px solid ${a}; background-color: ${g}; color: ${k}; position: sticky; top: 0; z-index: 1; ${`${L?"border-top-left-radius: 10px;":""}${ge?"border-top-right-radius: 10px;":""}`}">${H}</th>`;}ee+="</tr></thead>",ee+="<tbody>";for(let $ of Q){ee+="<tr>";for(let H=0;H<Z;H++){let N=He(le($[H]??"")),L=z[H],ge=H===0;ee+=`<td style="text-align: ${L}; padding: 10px 12px; border-bottom: 1px solid ${a}; ${ge?`border-left: 1px solid ${a};`:""} border-right: 1px solid ${a};">${N}</td>`;}ee+="</tr>";}return ee+="</tbody></table></div>",{tableHtml:ee,endIndex:V-1}};for(let y=0;y<n.length;y++){let p=n[y],F=p.match(/^```\s*(\w+)?\s*$/);if(F){if(!r)i(),r=true,l=F[1]?String(F[1]):"",u=[];else {if(l==="mermaid"){S=true;let z=u.join(`
5
+ `);o+=`<div class="mermaid-placeholder" data-mermaid="${le(z)}"></div>`;}else {let z=le(u.join(`
6
+ `)),Q=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${f}; color: ${b}; border: 1px solid ${a}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${Q}">${z}</code></pre>`;}r=false,l="",u=[];}continue}if(r){u.push(p);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(p)){i(),o+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let U=p.match(/^(#{1,6})\s+(.+)$/);if(U){i();let z=U[1].length,Q=He(le(U[2].trim())),V=z<=2?"18px":z===3?"16px":"14px";o+=`<h${z} style="font-size: ${V}; font-weight: 600; margin: 8px 0 4px 0;">${Q}</h${z}>`;continue}if(C(p)){let z=m(y+1);if(z!==-1&&E(n[z])){i();let{tableHtml:Q,endIndex:V}=w(y);if(Q){o+=Q,y=V;continue}}}let q=p.match(/^\s*[-*]\s+(.+)$/),Z=p.match(/^\s*\d+\.\s+(.+)$/);if(q){c||(i(),o+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',c=true);let z=He(le(q[1]));o+=`<li style="margin: 2px 0;">${z}</li>`;continue}if(Z){v||(i(),o+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',v=true);let z=He(le(Z[1]));o+=`<li style="margin: 2px 0;">${z}</li>`;continue}if(p.trim().length===0)i(),o+='<div style="height: 8px;"></div>';else {i();let z=He(le(p));o+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${z}</p>`;}}if(r)if(l==="mermaid"){S=true;let y=u.join(`
7
+ `);o+=`<div class="mermaid-placeholder" data-mermaid="${le(y)}"></div>`;}else {let y=le(u.join(`
8
+ `)),p=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${f}; color: ${b}; border: 1px solid ${a}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${p}">${y}</code></pre>`;}return c&&(o+="</ul>"),v&&(o+="</ol>"),{html:o,hasMermaid:S}}function it({content:e,theme:t}){let{html:n,hasMermaid:o}=useMemo(()=>xr(e,t),[e,t]);if(!o)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let r=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),l=[];return r.forEach((u,c)=>{if(u.includes("mermaid-placeholder")){let v=u.match(/data-mermaid="([^"]*)"/);if(v){let S=v[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");l.push(ot.createElement(ln,{key:`mermaid-${c}`,chart:S,theme:t}));}}else u.trim()&&l.push(ot.createElement("div",{key:`html-${c}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:u}}));}),ot.createElement(ot.Fragment,{},...l)}var Cr=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]};function cn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:o,resolvedColors:r}){let l=[],u=[],c,v,S=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){u.push(a.text),c||(c=a.startDate),v=a.endDate,a.state==="done"&&(S=true);continue}let T=a.type==="dynamic-tool",f=typeof a.type=="string"&&a.type.startsWith("tool-");if(T||f||a.type==="tool-call"){u.length&&(l.push({type:"reasoning",texts:u,startDate:c,endDate:v,isCompleted:S}),u=[],c=void 0,v=void 0,S=false);let b=String(T?a.toolName||"dynamic-tool":f?a.type?.slice(5)||"tool":a.toolName||"tool");b==="getFromUser"||b==="get_from_user"?l.push({type:"tool",toolName:b,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):l.push({type:"tool",toolName:b,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate});continue}}return u.length&&l.push({type:"reasoning",texts:u,startDate:c,endDate:v,isCompleted:S}),l.length?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[l.map((a,T)=>{let f=`${t}-${T}`,b=n.has(f);if(a.type==="reasoning"){let h=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",C=a.texts&&a.texts.length>0&&a.texts.some(M=>M.trim().length>0),E=()=>{C&&o(f);};return h&&!C?null:jsx("div",{onClick:E,style:{cursor:C?"pointer":"default",padding:"0"},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!h&&jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{color:r.textColor,fontWeight:600,opacity:.9,background:h?"none":`linear-gradient(90deg, ${r.textColor}, ${r.mutedTextColor}, ${r.mutedTextColor})`,backgroundSize:h?"auto":"200% 100%",backgroundClip:h?"unset":"text",WebkitBackgroundClip:h?"unset":"text",WebkitTextFillColor:h?r.mutedTextColor:"transparent",animation:h?void 0:"shimmer 2s ease-in-out infinite"},children:h?"Finish Thinking":"Thinking"})]}),C&&jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:b?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsx("div",{style:{display:"grid",gridTemplateRows:b||!h?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsx("div",{style:{fontSize:"13px",color:r.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!h&&b?a.texts:h?b?a.texts:[]:[a.texts[a.texts.length-1]]).map((M,w)=>jsx("div",{style:{marginBottom:"6px"},children:jsx(it,{content:M,theme:"dark"})},`rg-line-${T}-${w}`))}):jsxs("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},f)}let{color:g,text:k}=Cr(a.status),i=a.status==="input-streaming"||a.status==="input-available",m=a.toolName==="getFromUser"||a.toolName==="get_from_user";return jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsxs("div",{style:{flex:1,minWidth:0},children:[jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxs("span",{style:{fontWeight:600,color:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:i?"pulse 1.5s ease-in-out infinite":void 0}}),k]}),jsx("span",{style:{fontWeight:500,color:r.textColor},children:a.toolName||"tool"})]}),m?jsx("div",{style:{marginTop:"8px"},children:jsx("div",{"data-get-from-user-host":a.toolCallId||f,style:{width:"100%"}})}):null]})},f)}),jsx("style",{children:`
9
+ @keyframes shimmer {
10
+ 0% { background-position: -200% 0; }
11
+ 100% { background-position: 200% 0; }
26
12
  }
27
-
28
- @keyframes spin {
29
- from { transform: rotate(0deg); }
30
- to { transform: rotate(360deg); }
13
+ `})]}):null}function dn({items:e,resolvedColors:t,UIComponents:n={}}){return !Array.isArray(e)||e.length===0?null:jsx("div",{style:{},children:jsx("div",{style:{margin:0,color:t.textColor,display:"flex",flexDirection:"column",gap:"12px"},children:e.map((o,r)=>{if(typeof o=="object"&&o!==null&&o.type==="ui"){let{component:u,props:c}=o,v=n[u];return v?jsx("div",{style:{padding:"16px",borderRadius:"12px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`},children:jsx(v,{props:c,resolvedColors:t})},r):jsx("div",{})}let l=typeof o=="string"?o:JSON.stringify(o);return jsx("div",{style:{whiteSpace:"pre-wrap",lineHeight:1.6},children:jsx(it,{content:l,theme:"dark"})},r)})})})}function un(e){if(!e||Number.isNaN(e))return "0 B";let t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return `${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function pn({attachment:e,resolvedColors:t,mode:n,onRemove:o,maxWidth:r="200px"}){let l=e.mimeType?.startsWith("image/"),u=n==="editable"||n==="input",c=n==="viewable",v={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":r,position:"relative"},S=jsxs(Fragment,{children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",backgroundColor:l?"transparent":t.accentColor,flexShrink:0},children:[l?jsx("img",{src:e.url,alt:e.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:a=>{a.target.style.display="none";let T=a.target.nextElementSibling;T&&(T.style.display="block");}}):null,jsx(se,{IconComponent:File$1,size:n==="input"?14:10,strokeWidth:"2",style:{display:l?"none":"block",color:t.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:un(e.size)})]}),n==="input"&&l&&jsx("button",{onClick:a=>{a.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:a=>{a.currentTarget.style.backgroundColor=t.hoverBackground,a.currentTarget.style.color=t.textColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=t.mutedTextColor;},children:jsx(se,{IconComponent:Eye,size:"12",strokeWidth:"2"})}),u&&o&&jsx("button",{onClick:a=>{a.stopPropagation(),o(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:a=>{a.currentTarget.style.backgroundColor="#ef444420",a.currentTarget.style.color="#ef4444";},onMouseLeave:a=>{a.currentTarget.style.backgroundColor="transparent",a.currentTarget.style.color=t.mutedTextColor;},children:jsx(se,{IconComponent:X,size:"12",strokeWidth:"2"})}),c&&jsx(se,{IconComponent:Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...v,textDecoration:"none"},onMouseEnter:a=>{a.currentTarget.style.backgroundColor=t.hoverBackground,a.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:a=>{a.currentTarget.style.backgroundColor=t.inputBackground,a.currentTarget.style.borderColor=t.borderColor;},children:S}):jsx("div",{style:v,children:S})}function at({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let o=typeof n=="function"?"editable":"viewable";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(r=>jsx(pn,{attachment:r,resolvedColors:t,mode:o,onRemove:n},r.id))})}function gn({messageId:e,initialText:t,editingText:n,onEditingTextChange:o,onCancel:r,onSave:l,streaming:u,resolvedColors:c,attachments:v,onRemoveAttachment:S,onAddAttachments:a,uploading:T,t:f}){let b=ot.useRef(null),g=i=>{i.key==="Escape"?r():i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),u||l(e,n||t));},k=i=>{let m=i.target.files;m&&m.length>0&&a&&a(m),b.current&&(b.current.value="");};return jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${c.primaryColor}`,backgroundColor:c.accentColor,color:c.textColor,marginBottom:"16px",marginTop:"16px"},children:[jsx("textarea",{autoFocus:true,style:{width:"100%",resize:"none",backgroundColor:"transparent",padding:"8px",lineHeight:"1.6",outline:"none",border:"none",color:"inherit",fontFamily:"inherit",fontSize:"inherit"},rows:Math.max(2,Math.min(10,Math.ceil((n||t).length/60))),value:n,onChange:i=>o(i.target.value),onKeyDown:g}),v&&v.length>0&&jsx("div",{style:{padding:"8px"},children:jsx(at,{attachments:v,resolvedColors:c,onRemove:S})}),T&&jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:c.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:f("input.uploadingFiles")})]}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",padding:"8px 8px 8px 0"},children:[a&&jsxs("div",{children:[jsx("input",{ref:b,type:"file",multiple:true,onChange:k,style:{display:"none"}}),jsx("button",{onClick:()=>b.current?.click(),disabled:T||u,title:f(T?"input.uploadingFiles":"input.attachFiles"),style:{display:"flex",margin:"0 10px",alignItems:"center",justifyContent:"center",borderRadius:"50%",width:"28px",height:"28px",transition:"all 0.2s",border:`1px solid ${c.borderColor}`,color:c.mutedTextColor,backgroundColor:"transparent",cursor:T||u?"not-allowed":"pointer",opacity:T||u?.5:1},onMouseEnter:i=>{!T&&!u&&(i.currentTarget.style.backgroundColor=c.inputBackground,i.currentTarget.style.borderColor=c.primaryColor);},onMouseLeave:i=>{i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.borderColor=c.borderColor;},children:jsx(Plus,{size:16,strokeWidth:2})})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${c.borderColor}`,color:c.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:i=>i.currentTarget.style.backgroundColor=c.inputBackground,onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",onClick:r,children:f("editor.cancel")}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${c.borderColor}`,backgroundColor:c.cardBackground,color:c.textColor,cursor:"pointer"},onMouseEnter:i=>i.currentTarget.style.borderColor=c.primaryColor,onMouseLeave:i=>i.currentTarget.style.borderColor=c.borderColor,onClick:()=>{u||l(e,n||t);},children:f("editor.saveAndRegenerate")})]})]})]})}function fn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:o,resolvedColors:r,t:l,onUserMessageClick:u,editingMessageId:c,editingText:v,onEditingTextChange:S,onCancelEdit:a,onSaveEdit:T,editAttachments:f,onRemoveEditAttachment:b,onAddEditAttachments:g,editUploading:k,UIComponents:i={}}){return jsxs(Fragment,{children:[jsx("style",{children:`
14
+ @keyframes jumpingDots {
15
+ 0%, 80%, 100% {
16
+ transform: translateY(0);
17
+ }
18
+ 40% {
19
+ transform: translateY(-5px);
20
+ }
31
21
  }
32
- `})]}),document.body):null}function Ur({children:t,theme:n="dark",primaryColor:e,backgroundColor:r,borderColor:a,textColor:s,mutedTextColor:o,enableBorderAnimation:i=true,borderRadius:f=16,enableContentBorder:y=true,className:l="",enableMargin:b=true,chatWidth:c=450,dir:M="ltr"}){let{isAnyStreaming:h,isAnyChatOpen:k}=Q(),x=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[d,v]=useState(false);useEffect(()=>{let L=setTimeout(()=>v(true),50);return ()=>clearTimeout(L)},[]);let m=Ot[n],C={primaryColor:e||m.primaryColor,backgroundColor:r||m.backgroundColor,borderColor:a||m.borderColor,textColor:s||m.textColor,accentColor:m.accentColor,mutedTextColor:o||m.mutedTextColor,inputBackground:m.inputBackground,cardBackground:m.cardBackground,hoverBackground:m.hoverBackground},u=typeof f=="number"?`${f}px`:f,g=typeof c=="number"?`${c}px`:c,T=b&&k?M==="rtl"?{marginLeft:g}:{marginRight:g}:{},R=b&&k?`calc(100% - ${g})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:l,style:{width:R,height:"100%",transition:d?"all 0.3s ease-out":"none",padding:k&&y?"16px":"0",...T},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:d?"all 0.3s ease-out":"none",borderRadius:k?u:"0",border:k&&h&&i?"none":k?`1px solid ${C.borderColor}`:"none",padding:k&&h&&i?"1.5px":"0",background:k&&h&&i?`linear-gradient(120deg, ${C.primaryColor}dd 0%, ${C.primaryColor}88 25%, ${C.primaryColor}00 50%, ${C.primaryColor}88 75%, ${C.primaryColor}dd 100%)`:"transparent",backgroundSize:k&&h&&i?"300% 300%":"auto",animation:k&&h&&i?`${x.current}-border-flow 3s ease-in-out infinite`:"none",filter:k&&h&&i?`drop-shadow(0 0 10px ${C.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:k&&y?u:"0",backgroundColor:k&&y?C.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${C.mutedTextColor}40 transparent`},children:t})})}),jsx("style",{children:`
33
- @keyframes ${x.current}-border-flow {
22
+ `}),jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((m,h)=>{let C=Array.isArray(m.parts)?m.parts:[],E=C.filter(w=>w.type==="text").map(w=>w&&typeof w.text=="string"?w.text:"").join(`
23
+ `),M=C.filter(w=>w.type==="file"||w.type==="image").map(w=>{if(w.type==="image"){let y=typeof w.image=="string"?w.image:w.image?.toString?.()||"";return {id:y||`${m.id}-img-${Date.now()}`,name:w.name||"image",url:y,mimeType:w.mediaType||"image/jpeg",size:w.size||0}}else return {id:w.url||`${m.id}-file-${Date.now()}`,name:w.name||"file",url:w.url||"",mimeType:w.mediaType||"application/octet-stream",size:w.size||0}});return jsx("div",{style:{padding:"0 4px"},children:m.role==="user"?c===m.id?jsx(gn,{messageId:m.id,initialText:E,editingText:v,onEditingTextChange:S,onCancel:a,onSave:T,streaming:t,resolvedColors:r,attachments:f,onRemoveAttachment:b,onAddAttachments:g,uploading:k,t:l}):jsx("div",{children:jsxs("div",{title:l("editor.clickToEdit"),onClick:()=>u(m.id,E,M),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:r.accentColor,color:r.textColor,marginBottom:"16px",marginTop:"16px"},onMouseEnter:w=>w.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:w=>w.currentTarget.style.backgroundColor=r.accentColor,children:[E,M.length>0&&jsx(at,{attachments:M,resolvedColors:r})]})}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[jsx(cn,{parts:C,messageId:m.id,openReasoningIds:n,toggleReasoning:o,resolvedColors:r}),(()=>{let w=C.find(y=>y.type==="data-final-response"&&y.data&&Array.isArray(y.data.items));return w?jsx(dn,{items:w.data.items,resolvedColors:r,UIComponents:i}):null})()]})},m.id)}),t&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function yn({input:e,setInput:t,textareaRef:n,fileInputRef:o,isLoading:r,uploading:l,attachments:u,formatBytes:c,handleRemoveAttachment:v,onFileInputChange:S,onSend:a,onStop:T,status:f,t:b,resolvedColors:g}){let k=f==="streaming"||f==="submitted",i=u.length>0||e.trim().length>0;return jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsx("div",{style:{position:"relative",flex:1},children:jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${g.borderColor}`,backgroundColor:g.cardBackground},children:[u.length>0&&jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:u.map(m=>{let h=m.mimeType.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:g.inputBackground,borderRadius:"10px",border:`1px solid ${g.borderColor}`,fontSize:"12px",color:g.textColor,position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:h?"transparent":g.cardBackground},children:h?jsx("img",{src:m.url,alt:m.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsx("span",{title:m.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:m.name}),jsx("span",{style:{color:g.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(m.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[h&&jsx("a",{href:m.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:g.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:b("input.previewImage"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsx("button",{onClick:()=>v(m.id),style:{background:"none",border:"none",color:g.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:b("input.removeFile"),children:jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},m.id)})}),l&&jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:g.mutedTextColor},children:[jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsx("span",{children:b("input.uploadingFiles")})]}),jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:b("input.placeholder"),value:e,onChange:m=>t(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),a());},disabled:r||l,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:g.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsx("input",{ref:o,type:"file",multiple:true,onChange:S,style:{display:"none"},accept:"*/*"}),jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:g.mutedTextColor},children:jsx("button",{onClick:()=>o.current?.click(),disabled:r||l,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:r||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:r||l?.5:1},"aria-label":b("input.attachFiles"),children:jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:r?jsx("button",{onClick:T,disabled:!k,"aria-label":b("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:k?1:.4,cursor:k?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:m=>{k&&(m.currentTarget.style.backgroundColor="#ef444430",m.currentTarget.style.transform="scale(1.02)");},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.transform="scale(1)";},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsx("button",{onClick:a,disabled:!i||l,"aria-label":b("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${g.borderColor}`,backgroundColor:g.cardBackground,color:!i||l?g.mutedTextColor:g.primaryColor,cursor:!i||l?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!i||l?.5:1},onMouseEnter:m=>{i&&!l&&(m.currentTarget.style.borderColor=g.primaryColor,m.currentTarget.style.transform="scale(1.02)");},onMouseLeave:m=>{m.currentTarget.style.borderColor=g.borderColor,m.currentTarget.style.transform="scale(1)";},children:jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"m5 12 7-7 7 7"}),jsx("path",{d:"M12 19V5"})]})})})]})})})}function $t(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,o=C=>`${t}.chat.${C}`,r=`${t}.currentChatId`,l=`${t}.showChat`,u=()=>{try{let C=localStorage.getItem(n);return C?JSON.parse(C):[]}catch{return []}},c=C=>{try{localStorage.setItem(n,JSON.stringify(C));}catch{}},v=C=>{try{let E=localStorage.getItem(o(C));return E?JSON.parse(E):null}catch{return null}},S=C=>{try{localStorage.setItem(o(C.id),JSON.stringify(C));}catch{}},a=C=>{let E=u(),M=E.findIndex(w=>w.id===C.id);M>=0?E[M]=C:E.unshift(C),c(E);},T=C=>{let M=u().filter(w=>w.id!==C);c(M);},f=C=>{try{localStorage.removeItem(o(C));}catch{}};return {loadChatsIndex:u,saveChatsIndex:c,loadChat:v,saveChat:S,upsertChatMeta:a,deleteChatMeta:T,deleteChatData:f,deleteChat:C=>{f(C),T(C);},loadShowChatPreference:C=>{try{let E=localStorage.getItem(l);return E!==null?E==="true":C}catch{return C}},saveShowChatPreference:C=>{try{localStorage.setItem(l,String(C));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(r)}catch{return null}},saveCurrentChatId:C=>{try{localStorage.setItem(r,C);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(r);}catch{}}}}function hn(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let o=Math.floor(n/60);if(o<60)return `${o}m`;let r=Math.floor(o/60);if(r<24)return `${r}h`;let l=Math.floor(r/24);if(l<7)return `${l}d`;let u=Math.floor(l/7);if(u<4)return `${u}w`;let c=Math.floor(l/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function xn({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:o,resolvedColors:r,onClose:l,onSearchChange:u,onChatSelect:c,onChatDelete:v,loadChatsIndex:S,historyPopupRef:a}){if(!e)return null;let T=jsxs(Fragment,{children:[jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:l}),jsxs("div",{ref:a,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${r.borderColor}`,backgroundColor:`${r.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${r.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:t,onChange:f=>u(f.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:r.inputBackground,padding:"8px 12px",fontSize:"14px",color:r.textColor,border:`1px solid ${r.borderColor}`,outline:"none"},onFocus:f=>f.currentTarget.style.borderColor=r.primaryColor,onBlur:f=>f.currentTarget.style.borderColor=r.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let f=t.toLowerCase().trim(),b=S();return f&&(b=b.filter(g=>(g.title||"").toLowerCase().includes(f))),!b||b.length===0?jsx("div",{style:{padding:"24px",color:r.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:b.map((g,k)=>jsx("div",{style:{borderTop:k>0?`1px solid ${r.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:g.id===n?r.cardBackground:"transparent"},children:[jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:r.textColor},onMouseEnter:i=>i.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",onClick:()=>c(g.id),children:jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsx("div",{style:{minWidth:"0",flex:"1"},children:jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:r.textColor},children:g.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:r.mutedTextColor},children:hn(g.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:r.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:i=>{i.currentTarget.style.color="#ef4444",i.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",i.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:i=>{i.currentTarget.style.color=r.mutedTextColor,i.currentTarget.style.backgroundColor="transparent",i.currentTarget.style.borderColor="transparent";},onClick:i=>{i.stopPropagation(),v(g.id);},children:jsx(se,{IconComponent:Trash2,size:"16",strokeWidth:"2"})})]})},g.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(T,document.body):T}function $r(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function Lr(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),o=n.querySelector("input, select, textarea");return o&&o.remove(),n.textContent?.trim()}}function Lt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function Ht(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function Hr(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let o=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let l=n.className.split(" ").filter(u=>u.trim()).slice(0,2);l.length>0&&(o+="."+l.join("."));}let r=n.parentElement;if(r){let l=Array.from(r.children).filter(u=>u.tagName===n.tagName);if(l.length>1){let u=l.indexOf(n)+1;o+=`:nth-child(${u})`;}}t.unshift(o),n=r;}return t.slice(-3).join(" > ")}async function je(e={}){try{let{includeHidden:t=!1,selector:n,what:o="content",limit:r}=e,l=document.querySelector(".hsafa-content-container");if(!l)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let u=n&&l.querySelector(n)||l,c=[],v=[];o==="inputs"?v=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:v=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],u.querySelectorAll(v.join(", ")).forEach(i=>{let m=$r(i);if(!m&&!t)return;let h={id:i.id||null,tag:i.tagName.toLowerCase(),className:i.className&&typeof i.className=="string"?i.className:void 0,isVisible:m,isInteractive:!0,selector:Hr(i)};i instanceof HTMLInputElement?(h.type=i.type,h.name=i.name||void 0,h.placeholder=i.placeholder||void 0,h.value=Ht(i),h.checked=i.type==="checkbox"||i.type==="radio"?i.checked:void 0,h.disabled=i.disabled,h.required=i.required):i instanceof HTMLTextAreaElement?(h.name=i.name||void 0,h.placeholder=i.placeholder||void 0,h.value=Ht(i),h.disabled=i.disabled,h.required=i.required):i instanceof HTMLSelectElement?(h.name=i.name||void 0,h.value=Ht(i),h.disabled=i.disabled,h.required=i.required,h.options=Array.from(i.options).map(C=>({value:C.value,label:C.text,selected:C.selected,disabled:C.disabled}))):i instanceof HTMLButtonElement?(h.type=i.type,h.disabled=i.disabled,h.text=Lt(i)):i instanceof HTMLAnchorElement?(h.href=i.href,h.text=Lt(i)):i instanceof HTMLImageElement?(h.text=i.alt||void 0,h.label=i.alt||h.label):h.text=Lt(i),h.label=Lr(i),h.role=i.getAttribute("role")||void 0,h.ariaLabel=i.getAttribute("aria-label")||void 0,c.push(h);});let a=i=>i.isVisible?o==="inputs"?i.tag==="input"||i.tag==="textarea"||i.tag==="select"||i.role==="textbox"?3:i.tag==="button"||i.tag==="a"?2:1:["header","nav","main","footer"].includes(i.tag)?5:["section","article","aside"].includes(i.tag)||["h1","h2","h3"].includes(i.tag)?4:["h4","h5","h6"].includes(i.tag)?3:i.tag==="form"?4:i.tag==="label"?3:i.tag==="input"||i.tag==="textarea"||i.tag==="select"?4:i.tag==="p"||i.tag==="img"||i.tag==="button"||i.tag==="a"?3:1:0;c.sort((i,m)=>a(m)-a(i));let T=c.length,b=Math.max(1,Math.min(200,typeof r=="number"?Math.floor(r):o==="inputs"?100:150)),g=T>b,k=g?c.slice(0,b):c;return {ok:!0,components:k,count:k.length,total:T,truncated:g,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=je);async function Ee(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(o){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:o?.message||String(o)}]}}}typeof window<"u"&&(window.guideCursor=Ee);function bn(e){return !!e&&e.nodeType===1}function ue(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Cn(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ue(e,"input");}function Br(e,t){e.checked!==t&&e.click();}function Dr(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(o=>o.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);ue(e,"input"),ue(e,"change");}function Pr(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(o=>{o.selected=n.has(o.value)||n.has(o.text);}),ue(e,"input"),ue(e,"change");}function zr(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function Wr(e,t){let n=Array.isArray(t)?t:[t],o=new DataTransfer;for(let r of n)o.items.add(r);Object.defineProperty(e,"files",{value:o.files,configurable:true}),ue(e,"input"),ue(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&bn(n)){let o=n.closest('[contenteditable="true"], [contenteditable=""]');o&&(n=o);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let o=n.tagName.toLowerCase();if(o==="input"){let r=n,l=(r.type||"text").toLowerCase();if(l==="checkbox")Br(r,!!e);else if(l==="radio"){let u=r.name;if(u&&e!=null&&String(r.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(u)}"][value="${CSS.escape(String(e))}"]`);c?c.click():r.click();}else r.click();}else if(l==="file")if(e instanceof File||Array.isArray(e)&&e.every(u=>u instanceof File))Wr(r,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let u=l==="date"?zr(e):String(e??"");Cn(r,u),ue(r,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="textarea"){let r=n,l=String(e??"");return Cn(r,l),ue(r,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="select"){let r=n;return r.multiple?Pr(r,Array.isArray(e)?e:[e]):Dr(r,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(bn(n)&&n.isContentEditable){let r=n;return r.focus(),r.textContent=String(e??""),ue(r,"input"),ue(r,"change"),r.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${o}`}],errors:[`Unsupported active element: ${o}`]}}catch(o){return {ok:false,filled:[{key:"active",status:"error",message:o?.message??String(o)}],errors:[o?.message??String(o)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var qe=null,lt={},vn=false,Be=null,dt=false;function Bt(e){e.classList.add("visible");}function An(){dt=true,Be!=null&&(clearTimeout(Be),Be=null);}function Nr(e,t=1500){dt||(Be!=null&&clearTimeout(Be),Be=window.setTimeout(()=>{dt||e.classList.remove("visible");},t));}function Gr(e,t=1200){dt=false,Nr(e,t);}function _r(e){let t=[],n=e?.parentElement;for(;n;){let o=getComputedStyle(n),r=o.overflow+o.overflowY+o.overflowX;/(auto|scroll)/.test(r)&&t.push(n),n=n.parentElement;}return t}async function jr(e,t=1500,n=160){let o=performance.now(),r=e?_r(e):[],l=()=>{let a=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return r.forEach(T=>{a.push(T.scrollLeft,T.scrollTop);}),a},u=()=>{if(!e)return {x:0,y:0};let a=e.getBoundingClientRect();return {x:a.left,y:a.top}},c=l(),v=u(),S=performance.now();return new Promise(a=>{function T(f){let b=l(),g=u(),k=false;for(let i=0;i<b.length;i++)if(b[i]!==c[i]){k=true;break}if(!k&&e&&(g.x!==v.x||g.y!==v.y)&&(k=true),k&&(c=b,v=g,S=f),f-S>=n||f-o>=t){a();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var Ur='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',qr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function Vr(){if(!lt.arrow)try{lt.arrow=Ur,lt.pointer=qr;}catch(e){console.warn("Failed to set cursor SVGs",e);}return lt}function wn({arrowSvg:e,pointerSvg:t}){return jsxs(Fragment,{children:[e&&jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function Kr(){let e="demo-fake-cursor",t=document.getElementById(e),n=await Vr();if(!vn){let o="cursor-controller-styles";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
24
+ .fake-cursor { pointer-events: none; opacity: 0; transition: opacity 0.2s ease; z-index: 2147483647; }
25
+ .fake-cursor.visible { opacity: 1; }
26
+ .fake-cursor .arrow { display: none; }
27
+ .fake-cursor .pointer { display: none; }
28
+ .fake-cursor.as-arrow .arrow { display: block; }
29
+ .fake-cursor.as-arrow .pointer { display: none; }
30
+ .fake-cursor.as-pointer .arrow { display: none; }
31
+ .fake-cursor.as-pointer .pointer { display: block; }
32
+ .fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
33
+ `,document.head.appendChild(r);}vn=true;}return t?(t.classList.add("as-arrow"),qe||(qe=createRoot(t),qe.render(jsx(wn,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),qe=createRoot(t),qe.render(jsx(wn,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function De(e,t,n){return Math.max(t,Math.min(n,e))}function Xr(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function In(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let o=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!o)return null;let r=o[1].split(/\s*,\s*/).map(Number),[l,u,c,v=1]=r;return {r:l,g:u,b:c,a:v}}function Yr({r:e,g:t,b:n}){let o=[e,t,n].map(r=>r/255).map(r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]}function Jr(e){let t=e?In(e):null;return !t||t.a===0?false:Yr(t)<.5}function Zr(e,t){let n=document.elementFromPoint(e,t),o=new Set;for(;n&&!o.has(n);){o.add(n);let u=getComputedStyle(n).backgroundColor,c=In(u);if(c&&c.a>0)return u;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Dt(e,t,n){let o=Zr(t,n),r=Jr(o),l=r?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=l,c.style.strokeWidth="1";}),e.style.filter=r?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function ct(e,t,n,o,r="ease-in-out",l="curve",u=.25,c="auto",v){An(),Bt(e);let S=performance.now(),a=r==="linear"?b=>b:Xr,T=l!=="straight",f={x:0,y:0};if(T){let b=n.x-t.x,g=n.y-t.y,k=Math.hypot(b,g)||1,i=(t.x+n.x)/2,m=(t.y+n.y)/2,h=-g/k,C=b/k,E=1;c==="left"?E=-1:c==="right"?E=1:E=Math.random()<.5?-1:1;let M=De(u,0,1)*k;f={x:i+E*h*M,y:m+E*C*M};}return new Promise(b=>{function g(k){let i=De((k-S)/o,0,1),m=a(i),h,C;if(T){let p=1-m;h=p*p*t.x+2*p*m*f.x+m*m*n.x,C=p*p*t.y+2*p*m*f.y+m*m*n.y;}else h=t.x+(n.x-t.x)*m,C=t.y+(n.y-t.y)*m;let M=.35*(1-m),w=Math.sin(k*.02)*M,y=Math.cos(k*.018)*M;e.style.left=`${h+w}px`,e.style.top=`${C+y}px`,Dt(e,h+w,C+y),v&&v({x:h+w,y:C+y,t:i,now:k}),i<1?requestAnimationFrame(g):b();}requestAnimationFrame(g);})}function Tn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function he(e,t,n,o){let r={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...o};try{let l=t==="pointerdown"||t==="mousedown",u=t==="pointerup"||t==="mouseup",c={button:0,buttons:l?1:0,isPrimary:!0,...r};if("PointerEvent"in window){let v=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(v);}else {let v=new MouseEvent(t,c);e.dispatchEvent(v);}}catch{let l=new MouseEvent(t,r);e.dispatchEvent(l);}}function Rn(e){return e&&typeof e=="object"&&e.nodeType===1}function Qr(e){if(!e)return document;if(Rn(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function Mn(e){if(Rn(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Qr(e.within??null).querySelectorAll(e.selector),o=Math.max(0,Math.min(n.length-1,e.nth??0)),r=n[o]??null;return {kind:r?"element":"position",element:r}}return {kind:"position",point:{x:0,y:0}}}function Sn(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let o=De(t.x,0,1),r=De(t.y,0,1);return {x:n.left+n.width*o,y:n.top+n.height*r}}function En(e){return {x:De(e.x,0,window.innerWidth),y:De(e.y,0,window.innerHeight)}}function eo(){return useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],o=[],r=await Kr();r.classList.add("visible","as-arrow"),r.classList.remove("as-pointer","pressing"),Bt(r),An();let l=parseFloat(r.style.left||"20")||20,u=parseFloat(r.style.top||"20")||20;Dt(r,l,u);for(let c of n){let{durationMs:v=800,easing:S="ease-in-out",offset:a,highlight:T=true,path:f="curve",curveStrength:b=.25,curveDirection:g="auto",anchor:k,cursorHotspot:i,dragTo:m}=c.options??{},h=c.action??c.options?.action??"none",C=performance.now(),E=Mn(c.target),M=null,w=null;if(E.kind==="element"&&E.element?(w=E.element,r.classList.remove("visible"),w.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await jr(w,1500,180),Bt(r),M=Sn(w,k)):E.kind==="position"&&E.point&&(M=E.point),!M){o.push({ok:false,action:h,targetKind:E.kind,durationMs:Math.round(performance.now()-C),error:"Target not found"});continue}let y={x:parseFloat(r.style.left||"20")||20,y:parseFloat(r.style.top||"20")||20},p=En(Tn(M,a));await ct(r,y,p,v,S,f,b,g);let F=p.x-y.x,U=p.y-y.y,q=Math.hypot(F,U)||1,Z=F/q,z=U/q,Q=Math.min(6,Math.max(3,q*.02)),V={x:p.x+Z*Q,y:p.y+z*Q};await ct(r,p,V,Math.max(70,v*.1),"ease-out","straight",0,"right"),await ct(r,V,p,120,"ease-out","straight",0,"left"),T&&(r.classList?.add("click"),setTimeout(()=>r.classList?.remove("click"),180));let ee=null;try{if(h==="click"){r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing");let $={x:i?.x??0,y:i?.y??0},H={x:p.x+$.x,y:p.y+$.y};r.style.left=`${H.x}px`,r.style.top=`${H.y}px`,Dt(r,H.x,H.y);let N=w??document.elementFromPoint(H.x,H.y)??document.body;he(N,"pointerdown",H),he(N,"mousedown",H),await new Promise(L=>setTimeout(L,90)),r.classList.remove("pressing"),he(N,"mouseup",H),he(N,"click",H),setTimeout(()=>{r.classList.remove("as-pointer"),r.classList.add("as-arrow");},140),N instanceof HTMLElement&&N.focus?.(),ee=N?.id??null;}else if(h==="drag"){if(!m)throw new Error("dragTo is required for action 'drag'");let $=Mn(m),H=null;if($.kind==="element"&&$.element&&(H=Sn($.element,k)),$.kind==="position"&&$.point&&(H=$.point),!H)throw new Error("dragTo target not found");let N=En(Tn(H,a)),L={x:p.x,y:p.y},ge=w??document.elementFromPoint(L.x,L.y)??document.body;r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing"),he(ge,"pointerdown",L),he(ge,"mousedown",L),await ct(r,L,N,Math.max(200,v),S,f,b,g,({x:Ve,y:Ke})=>{let ze=document.elementFromPoint(Ve,Ke)??document.body,ke={x:Ve,y:Ke};he(ze,"pointermove",ke),he(ze,"mousemove",ke);});let Ae=document.elementFromPoint(N.x,N.y)??document.body;r.classList.remove("pressing"),he(Ae,"pointerup",N),he(Ae,"mouseup",N);}o.push({ok:!0,action:h,targetKind:E.kind,durationMs:Math.round(performance.now()-C),clickedElementId:ee});}catch($){o.push({ok:false,action:h,targetKind:E.kind,durationMs:Math.round(performance.now()-C),error:$?.message??String($)});}}return Gr(r,2e3),{ok:o.every(c=>c.ok),steps:o}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var Fn=eo;function lo({agentId:e,theme:t,primaryColor:n,primaryColorDark:o,primaryColorLight:r,backgroundColor:l,borderColor:u,textColor:c,accentColor:v,baseUrl:S="",initialMessages:a=[],onMessagesChange:T,defaultOpen:f=true,floatingButtonPosition:b={bottom:24,right:24},UIComponents:g={},HsafaTools:k={}}){let{dir:i,theme:m,baseUrl:h}=Le(),C=t||m||"dark",E=S&&S.length>0?S:h||"",y={primaryColor:C==="dark"?o||n||"#ffffff":r||n||"#000000",backgroundColor:l||(C==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:u||(C==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(C==="dark"?"#EDEEF0":"#111827"),accentColor:v||(C==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:C==="dark"?"#9AA0A6":"#6B7280",inputBackground:C==="dark"?"#17181C":"#F3F4F6",cardBackground:C==="dark"?"#121318":"#FFFFFF",hoverBackground:C==="dark"?"#1c1e25":"#F3F4F6"},p=s=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[s]||s,{attachments:F,uploading:U,fileInputRef:q,formatBytes:Z,handleRemoveAttachment:z,handleFileSelection:Q,clearAttachments:V}=tn(E),[ee,$]=useState(null),[H,N]=useState(""),[L,ge]=useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),Ae=useMemo(()=>new DefaultChatTransport({api:`${E}/api/run/${e}`,fetch:async(s,d)=>{let R={...d?.body?JSON.parse(d.body):{},chatId:L};return fetch(s,{...d,body:JSON.stringify(R)})}}),[h,S,e,L]),Ve=useCallback(s=>{console.log("Message finished:",s);},[]),Ke=useCallback(s=>{console.error("Chat error:",s);},[]),ze=useMemo(()=>({getDomComponents:{tool:async({includeHidden:s,selector:d})=>await je({includeHidden:s,selector:d}),executeEachToken:false},controlCursor:{tool:async({target:s,action:d,anchor:x,durationMs:R,dragTo:B})=>{let O=await Ee(s,{action:d,anchor:x,durationMs:R,dragTo:B});if(O&&O.ok){let te=Array.isArray(O.steps)&&O.steps.length?O.steps[O.steps.length-1]:void 0,we=te?.clickedElementId?` (clicked element id: ${te.clickedElementId})`:"",ne=d||te?.action||"none";return {success:true,message:ne==="click"?`Cursor moved and clicked successfully${we}`:ne==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:O}}return {success:false,message:"Cursor action failed",details:O}},executeEachToken:false},fillActiveInput:{tool:async({value:s})=>{let d=await Ue(s);return {success:!!d?.ok,message:d?.ok?"Active input filled successfully":d?.errors?.[0]||"Failed to fill active input",details:d}},executeEachToken:true},getFromUser:{tool:async s=>({ok:true}),executeEachToken:true}}),[]),ke=useMemo(()=>({...ze,...k}),[ze,k]),ve=useRef(new Map),Ie=useRef(new Map),gt=useCallback(()=>{try{ve.current.forEach(s=>{try{s.remove();}catch{}}),ve.current.clear(),Ie.current.clear();}catch{}},[]),Xe=useCallback((s,d)=>{let x=ve.current.get(d);if(x){let A=x.parentElement,P=document.querySelector(`[data-get-from-user-host="${d}"]`);if(P&&A!==P){try{A?.removeChild(x);}catch{}P.innerHTML="",P.appendChild(x);}}else {x=document.createElement("div"),x.className="hsafa-inline-form";let A=document.querySelector(`[data-get-from-user-host="${d}"]`);A?(A.innerHTML="",A.appendChild(x)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(x),ve.current.set(d,x);}let R=s?.title||"Provide input",B=s?.description||"",O=s?.submitLabel||"Submit",te=s?.skipLabel||"Skip",we=Array.isArray(s?.fields)?s.fields:s?.label||s?.placeholder?[{id:"value",label:s?.label||"Value",type:"text",placeholder:s?.placeholder||""}]:[],ne=Ie.current.get(d)||{submitted:false,skipped:false,values:void 0};x.innerHTML="";let X=document.createElement("form");X.style.margin="12px 0",X.style.padding="14px",X.style.border="1px solid var(--hsafa-border, #2A2C33)",X.style.borderRadius="12px",X.style.background="var(--hsafa-card, #121318)",X.style.color="var(--hsafa-text, #EDEEF0)",X.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let Qe=document.createElement("div");if(Qe.style.fontWeight="600",Qe.style.marginBottom="6px",Qe.textContent=R,X.appendChild(Qe),B){let A=document.createElement("div");A.style.fontSize="12px",A.style.opacity="0.8",A.style.marginBottom="10px",A.textContent=B,X.appendChild(A);}we.forEach(A=>{let P=document.createElement("div");if(P.style.margin="10px 0",A.label){let I=document.createElement("label");I.style.display="block",I.style.fontSize="12px",I.style.marginBottom="6px",I.style.opacity="0.9",I.textContent=A.label,P.appendChild(I);}let j,Te=(A.type||"text").toLowerCase();if(Te==="textarea"){let I=document.createElement("textarea");I.placeholder=A.placeholder||"",I.value=A.value??"",I.style.width="100%",I.style.minHeight="72px",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",j=I;}else if(Te==="select"&&Array.isArray(A.options)){let I=document.createElement("select");I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",A.options.forEach(Mt=>{let St=document.createElement("option");St.value=String(Mt.value),St.text=String(Mt.label??Mt.value),I.appendChild(St);}),I.value=A.value??"",j=I;}else if(Te==="checkbox"){let I=document.createElement("input");I.type="checkbox",I.checked=!!A.value,I.style.transform="scale(1.1)",j=I;}else {let I=document.createElement("input");I.type=Te,I.placeholder=A.placeholder||"",I.value=A.value??"",I.style.width="100%",I.style.padding="10px 12px",I.style.border="1px solid var(--hsafa-border, #2A2C33)",I.style.borderRadius="10px",I.style.background="var(--hsafa-input-bg, #17181C)",I.style.color="inherit",j=I;}let wt=A.id||"value";j.dataset.fieldId=wt;let Tt=ne.values&&Object.prototype.hasOwnProperty.call(ne.values,wt)?ne.values[wt]:void 0;typeof Tt<"u"&&(j.type==="checkbox"?j.checked=!!Tt:j.value=String(Tt)),(ne.submitted||ne.skipped)&&(j.setAttribute("disabled","true"),j.style.opacity="0.7"),P.appendChild(j),X.appendChild(P);});let et=String(O).trim(),tt=String(te).trim(),nr=!!(et||tt),Y=null,_=null;if(nr){let A=document.createElement("div");A.style.display="flex",A.style.gap="8px",A.style.marginTop="10px",Y=document.createElement("button"),Y.type="submit",Y.textContent=et||"Submit",Y.style.padding="6px 10px",Y.style.borderRadius="8px",Y.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",Y.style.color="#000000",_=document.createElement("button"),_.type="button",_.textContent=tt||"Skip",_.style.padding="6px 10px",_.style.borderRadius="8px",_.style.background="transparent",_.style.border="1px solid var(--hsafa-border, #2A2C33)",_.style.color="inherit",ne.submitted&&(Y.textContent=`${et||"Submit"} \u2713`,Y.style.opacity="0.8",Y.disabled=true),ne.skipped&&(_.textContent=`${tt||"Skip"} \u2713`,_.style.opacity="0.8",_.disabled=true),A.appendChild(Y),A.appendChild(_),X.appendChild(A);}if(X.onsubmit=A=>{A.preventDefault();let P={};X.querySelectorAll("[data-field-id]").forEach(j=>{let Te=j.dataset.fieldId||"value";j.type==="checkbox"?P[Te]=j.checked:P[Te]=j.value??"";}),Ie.current.set(d,{submitted:true,skipped:false,values:P}),ft.current.addToolResult({tool:"getFromUser",toolCallId:d,output:{success:true,submitted:true,values:P}}),X.querySelectorAll("[data-field-id]").forEach(j=>{j.disabled=true,j.style.opacity="0.7";}),Y&&(Y.textContent=`${et||"Submit"} \u2713`,Y.style.opacity="0.8",Y.disabled=true),_&&(_.disabled=true);},_&&(_.onclick=()=>{Ie.current.set(d,{submitted:false,skipped:true,values:void 0}),ft.current.addToolResult({tool:"getFromUser",toolCallId:d,output:{success:true,submitted:false,skipped:true}}),X.querySelectorAll("[data-field-id]").forEach(A=>{A.disabled=true,A.style.opacity="0.7";}),_&&(_.textContent=`${tt||"Skip"} \u2713`,_.style.opacity="0.8",_.disabled=true),Y&&(Y.disabled=true);}),ne.submitted||ne.skipped){let A=document.createElement("div");A.style.marginTop="10px",A.style.fontSize="12px",A.style.display="flex",A.style.alignItems="center",A.style.gap="8px";let P=document.createElement("span");P.style.display="inline-flex",P.style.alignItems="center",P.style.padding="2px 8px",P.style.borderRadius="999px",P.style.fontWeight="600",P.style.fontSize="11px",ne.submitted?(P.style.background="rgba(16,185,129,0.15)",P.style.color="#10b981",P.textContent="Submitted"):(P.style.background="rgba(234,179,8,0.15)",P.style.color="#eab308",P.textContent="Skipped"),A.appendChild(P),X.appendChild(A);}x.appendChild(X);},[]),ft=useRef(null),Ln=useCallback(s=>{let d=ke[s];return d?typeof d=="object"&&"tool"in d?d.tool:typeof d=="function"?d:null:null},[ke]),fe=useChat({transport:Ae,onFinish:Ve,onError:Ke,experimental_throttle:10,sendAutomaticallyWhen:lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:s}){let d=Ln(s.toolName);if(s.toolName==="getFromUser"||s.toolName==="get_from_user"){try{Xe(s.input,s.toolCallId);}catch(x){console.error("get_from_user render error",x);}return}if(d)try{let x=await d(s.input);fe.addToolResult({tool:s.toolName,toolCallId:s.toolCallId,output:x});}catch(x){fe.addToolResult({tool:s.toolName,toolCallId:s.toolCallId,state:"output-error",errorText:x?.message||String(x)});}}}),{messages:W,sendMessage:Ye,status:yt,stop:Hn,error:zt}=fe;ft.current=fe;let Wt=useRef(new Map);useEffect(()=>{W.forEach(s=>{s.role==="assistant"&&s.parts?.forEach(d=>{if(!d.toolCallId)return;let x=d.toolName;if(!x&&d.type?.startsWith("tool-")&&(x=d.type.replace(/^tool-/,"")),!x)return;let R=ke[x];if(R&&typeof R=="object"&&R.executeEachToken&&R.tool){let B=d.input||d.args||{},O=JSON.stringify(B),te=Wt.current.get(d.toolCallId);if(O!==te&&O!=="{}"){Wt.current.set(d.toolCallId,O);try{x==="getFromUser"||x==="get_from_user"?Xe(B,d.toolCallId):R.tool(B);}catch(we){console.error(`Error executing streaming tool ${x}:`,we);}}}});});},[W,ke]),useEffect(()=>{try{let s=new Set,d=[];if(W.forEach(x=>{x.role==="assistant"&&(x.parts||[]).forEach(R=>{let B=R?.toolName||(typeof R?.type=="string"&&R.type.startsWith("tool-")?String(R.type.replace(/^tool-/,"")):void 0);if(B!=="getFromUser"&&B!=="get_from_user")return;let O=R?.toolCallId||"";if(!O)return;s.add(O);let te=R?.output;if(te&&(te.submitted||te.skipped||te.values)){let ne={submitted:!!te.submitted,skipped:!!te.skipped,values:te.values||void 0};Ie.current.set(O,ne);}let we=R?.input||R?.args||{};d.push({input:we,toolCallId:O});});}),ve.current.forEach((x,R)=>{if(!s.has(R)){let B=ve.current.get(R);try{B?.remove();}catch{}ve.current.delete(R),Ie.current.delete(R);}}),d.length>0){let x=requestAnimationFrame(()=>{d.forEach(({input:R,toolCallId:B})=>{try{Xe(R,B);}catch{}});});return ()=>cancelAnimationFrame(x)}}catch{}},[W,Xe]),useEffect(()=>{a&&a.length>0&&W.length===0&&console.log("Initial messages:",a);},[a,W.length]);let ht=useRef(T);useEffect(()=>{ht.current=T;},[T]);let We=useRef([]);useEffect(()=>{(W.length!==We.current.length||W.length>0&&We.current.length>0&&W[W.length-1]?.id!==We.current[We.current.length-1]?.id)&&ht.current&&(We.current=W,ht.current(W));},[W]);let J=yt==="submitted"||yt==="streaming",{setStreamingState:xt,setChatOpenState:bt}=Le(),[Je,Ot]=useState(()=>{try{return $t(e).loadShowChatPreference(!!f)}catch{return !!f}}),[Bn,Ct]=useState(false),[Dn,Pn]=useState(""),[zn,Wn]=useState(0),On=useRef(null),Nn=useRef(null),[Gn,Nt]=useState(new Set),[_n,Ze]=useState(null),[Gt,Oe]=useState(""),[kt,Re]=useState([]),[jn,_t]=useState(false),jt=useRef(null),Un=useRef(null),qn=Zt(J),G=useMemo(()=>$t(e),[e]),Ne=useRef(false),Ut=useRef(false);useEffect(()=>{if(!Ut.current){try{let s=G.loadCurrentChatId();if(s){Ne.current=!0,ge(s);let d=G.loadChat(s),x=d&&Array.isArray(d.messages)?d.messages:[];try{fe?.setMessages?.(x);}catch{}}}catch{}Ut.current=true;}},[G]),useEffect(()=>{if(W.length!==0)if(Ne.current){if(!J){let s=Date.now();G.saveChat({id:L,messages:W,agentId:e});let x=G.loadChatsIndex().find(R=>R.id===L);x&&G.upsertChatMeta({...x,updatedAt:s});}}else {let s=W.find(d=>d.role==="user");if(s){let d="";if(Array.isArray(s.parts)){let B=s.parts.find(O=>O&&O.type==="text");d=B&&typeof B.text=="string"?B.text:"";}let x=(d||"New chat").slice(0,80),R=Date.now();G.upsertChatMeta({id:L,title:x,createdAt:R,updatedAt:R}),G.saveChat({id:L,messages:W,agentId:e}),G.saveCurrentChatId(L),Ne.current=true;}}},[W,e,L,G,J]);let vt=useRef(false);useEffect(()=>{if(J){vt.current=true;return}if(vt.current){vt.current=false;try{let s=Date.now();G.saveChat({id:L,messages:W,agentId:e});let x=G.loadChatsIndex().find(R=>R.id===L);x&&G.upsertChatMeta({...x,updatedAt:s});}catch{}}},[J,W,L,e,G]),useEffect(()=>{try{xt(L,J);}catch{}return ()=>{try{xt(L,!1);}catch{}}},[L,J,xt]),useEffect(()=>{try{bt(L,Je);}catch{}return ()=>{try{bt(L,!1);}catch{}}},[L,Je,bt]);let Vn=useCallback(async()=>{let s=H.trim();if(!(!s&&F.length===0)&&!J)try{await Ye({text:s,files:F.map(d=>({type:"file",url:d.url,mediaType:d.mimeType||"application/octet-stream",...d.name?{name:d.name}:{},...d.size?{size:d.size}:{}}))}),N(""),V(),$(null);}catch(d){console.error("Failed to send message:",d),$("Failed to send message. Please try again.");}},[H,F,J,Ye,V]),qt=useCallback(()=>{if(J)return;gt(),N(""),V(),$(null),Ze(null),Oe(""),Re([]);try{fe?.setMessages?.([]);}catch{}Ne.current=false;let s=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;ge(s);try{G.saveCurrentChatId(s);}catch{}},[J,V,G,fe,gt]),Kn=useCallback(()=>{Ct(s=>!s);},[]),Xn=useCallback(()=>{Ot(false);try{G.saveShowChatPreference(!1);}catch{}},[G]),Yn=useCallback(async s=>{let d=s.target.files;d&&await Q(d,$),q.current&&(q.current.value="");},[Q,q]);useEffect(()=>{let s=jt.current;if(!s)return;s.style.height="24px",s.offsetHeight,s.style.height="auto";let d=Math.min(s.scrollHeight,200);s.style.height=`${d}px`;},[H]),ot.useEffect(()=>{let s=Un.current;if(!s)return;s.style.height="auto",s.offsetHeight;let d=Math.min(Math.max(s.scrollHeight,48),300);s.style.height=`${d}px`;},[Gt]);let Jn=useCallback(async s=>{_t(true);try{let d=await Promise.all(Array.from(s).map(async x=>{let R=new FormData;R.append("file",x);let B=await fetch(`${E}/api/upload`,{method:"POST",body:R});if(!B.ok)throw new Error(`Upload failed: ${B.statusText}`);let O=await B.json();return {id:O.url||`${Date.now()}-${Math.random()}`,name:x.name,url:O.url,mimeType:x.type,size:x.size}}));Re(x=>[...x,...d]);}catch(d){console.error("Failed to upload files:",d),$("Failed to upload files. Please try again.");}finally{_t(false);}},[E]),Zn=useCallback(s=>{Re(d=>d.filter(x=>x.id!==s));},[]),Qn=useCallback((s,d,x)=>{Ze(s),Oe(d),Re(x||[]);},[]),er=useCallback(()=>{Ze(null),Oe(""),Re([]);},[]),tr=useCallback(async(s,d)=>{if(!J)try{let x=W.findIndex(B=>B.id===s);if(x===-1)return;let R=W.slice(0,x);try{fe?.setMessages?.(R);}catch{}await Ye({text:d.trim(),files:kt.map(B=>({type:"file",url:B.url,mediaType:B.mimeType||"application/octet-stream",...B.name?{name:B.name}:{},...B.size?{size:B.size}:{}}))}),Ze(null),Oe(""),Re([]);}catch(x){console.error("Failed to save edit:",x),$("Failed to save message. Please try again.");}},[J,W,Ye,fe,kt]),Vt=jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:y.textColor,gap:"16px",zIndex:1e3,transform:Je?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsx(on,{title:p("general.agent"),alwaysOpen:false,streaming:J,dir:i||"ltr",resolvedColors:y,onNew:qt,onToggleHistory:Kn,onClose:Xn,historyBtnRef:On,t:p}),jsx("div",{ref:qn,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":y.primaryColor,"--hsafa-border":y.borderColor,"--hsafa-card":y.cardBackground,"--hsafa-text":y.textColor,"--hsafa-muted":y.mutedTextColor,"--hsafa-bg":y.backgroundColor,"--hsafa-hover":y.hoverBackground,"--hsafa-input-bg":y.inputBackground,"--hsafa-accent":y.accentColor},children:W.length===0?jsx("div",{style:{padding:"32px",textAlign:"center",color:y.mutedTextColor,fontSize:"14px"},children:p("messages.empty")}):jsx(fn,{chatMessages:W,isLoading:J,openReasoningIds:Gn,toggleReasoning:s=>Nt(d=>{let x=new Set(d);return x.has(s)?x.delete(s):x.add(s),x}),resolvedColors:y,t:p,onUserMessageClick:Qn,editingMessageId:_n,editingText:Gt,onEditingTextChange:Oe,onCancelEdit:er,onSaveEdit:tr,editAttachments:kt,onRemoveEditAttachment:Zn,onAddEditAttachments:Jn,editUploading:jn,UIComponents:g})}),jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[ee&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("span",{children:ee}),jsx("button",{onClick:()=>$(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),zt&&jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxs("span",{children:["An error occurred: ",zt.message||"Please try again."]}),jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsx(yn,{input:H,setInput:N,textareaRef:jt,fileInputRef:q,isLoading:J,uploading:U,attachments:F,formatBytes:Z,handleRemoveAttachment:z,onFileInputChange:Yn,onSend:Vn,onStop:()=>Hn(),status:yt,t:p,resolvedColors:y})]}),jsx(xn,{historyOpen:Bn,historySearch:Dn,currentChatId:L,refreshKey:zn,resolvedColors:y,onClose:()=>Ct(false),onSearchChange:Pn,onChatSelect:s=>{if(Ct(false),s&&s!==L){Ne.current=true,gt(),ge(s);try{G.saveCurrentChatId(s);}catch{}try{let d=G.loadChat(s),x=d&&Array.isArray(d.messages)?d.messages:[];try{fe?.setMessages?.(x);}catch{}}catch{}}},onChatDelete:s=>{try{G.deleteChat(s),Wn(d=>d+1),s===L&&qt();}catch{}},loadChatsIndex:()=>G.loadChatsIndex(),historyPopupRef:Nn}),jsx("style",{children:`
34
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
35
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
36
+ `})]});return typeof document<"u"&&document.body?jsxs(Fragment,{children:[createPortal(Vt,document.body),jsx(Xt,{show:!Je,onClick:()=>{Ot(true);try{G.saveShowChatPreference(!0);}catch{}},resolvedColors:y,floatingButtonPosition:b})]}):Vt}var $n={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function go({children:e,theme:t="dark",primaryColor:n,backgroundColor:o,borderColor:r,textColor:l,mutedTextColor:u,enableBorderAnimation:c=true,borderRadius:v=16,enableContentBorder:S=true,className:a="",enableMargin:T=true,chatWidth:f=420,dir:b="ltr"}){let{isAnyStreaming:g,isAnyChatOpen:k,dir:i,theme:m}=Le(),h=(b??i)||"ltr",C=(t??m)||"dark",E=useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[M,w]=useState(false);useEffect(()=>{let z=setTimeout(()=>w(true),50);return ()=>clearTimeout(z)},[]);let y=$n[C],p={primaryColor:n||y.primaryColor,backgroundColor:o||y.backgroundColor,borderColor:r||y.borderColor,textColor:l||y.textColor,accentColor:y.accentColor,mutedTextColor:u||y.mutedTextColor,inputBackground:y.inputBackground,cardBackground:y.cardBackground,hoverBackground:y.hoverBackground},F=typeof v=="number"?`${v}px`:v,U=typeof f=="number"?`${f}px`:f,q=T&&k?h==="rtl"?{marginLeft:U}:{marginRight:U}:{},Z=T&&k?`calc(100% - ${U})`:"100%";return jsxs(Fragment,{children:[jsx("div",{className:a,style:{width:Z,height:"100%",transition:M?"all 0.2s ease-out":"none",padding:k&&S?"16px":"0",...q},children:jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:M?"all 0.2s ease-out":"none",borderRadius:k?F:"0",border:k&&g&&c?"none":k?`1px solid ${p.borderColor}`:"none",padding:k&&g&&c?"1.5px":"0",background:k&&g&&c?`linear-gradient(120deg, ${p.primaryColor}dd 0%, ${p.primaryColor}88 25%, ${p.primaryColor}00 50%, ${p.primaryColor}88 75%, ${p.primaryColor}dd 100%)`:"transparent",backgroundSize:k&&g&&c?"300% 300%":"auto",animation:k&&g&&c?`${E.current}-border-flow 3s ease-in-out infinite`:"none",filter:k&&g&&c?`drop-shadow(0 0 10px ${p.primaryColor}40)`:"none"},children:jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:k&&S?F:"0",backgroundColor:k&&S?p.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${p.mutedTextColor}40 transparent`},children:e})})}),jsx("style",{children:`
37
+ @keyframes ${E.current}-border-flow {
34
38
  0% { background-position: 0% 50%; }
35
39
  50% { background-position: 100% 50%; }
36
40
  100% { background-position: 0% 50%; }
37
41
  }
38
- `})," "]})}export{Yr as Button,Ur as ContentContainer,Je as FloatingChatButton,Lr as HsafaChat,ir as HsafaProvider,qe as MessageList,rn as useAgentStreaming,aa as useAutoScroll,Ge as useChatStorage,nn as useFileUpload,Q as useHsafa,ga as useHsafaAction,ya as useHsafaComponent,Qe as useStreaming,na as useToggle};//# sourceMappingURL=index.js.map
42
+ `})," "]})}var Pt=class{constructor(){this.components=new Map;}register(t,n){this.components.set(t,n);}unregister(t){this.components.delete(t);}get(t){return this.components.get(t)}has(t){return this.components.has(t)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},ho=new Pt;export{wo as Button,go as ContentContainer,Fn as CursorController,Ue as FillActiveInput,Xt as FloatingChatButton,lo as HsafaChat,lr as HsafaProvider,ho as componentRegistry,Ee as controlCursor,je as getDomComponents,Ee as guideCursor,Zt as useAutoScroll,tn as useFileUpload,Le as useHsafa};//# sourceMappingURL=index.js.map
39
43
  //# sourceMappingURL=index.js.map