@hsafa/ui-sdk 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,20 @@
1
- import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState,useCallback,useRef,useEffect,useMemo,useContext}from'react';import {createPortal}from'react-dom';import {IconArrowsMaximize,IconPlus,IconHistory,IconTrash,IconChevronRight,IconPaperclip,IconLink,IconPlayerStop,IconArrowUp,IconMessage}from'@tabler/icons-react';var te={};var tr=({variant:s="primary",size:p="md",loading:g=false,disabled:b,children:z,className:$,...O})=>{let U=[te.button,te[s],te[p],g&&te.loading,$].filter(Boolean).join(" ");return jsxs("button",{className:U,disabled:b||g,...O,children:[g&&jsx("span",{className:te.spinner}),jsx("span",{className:g?te.hiddenText:void 0,children:z})]})};function ar(s=false){let[p,g]=useState(s),b=useCallback(()=>g(O=>!O),[]),z=useCallback(()=>g(true),[]),$=useCallback(()=>g(false),[]);return {on:p,toggle:b,setOn:g,setTrue:z,setFalse:$}}function lr(){let s=useRef(null);return useEffect(()=>{let p=s.current;if(!p)return;let g=new MutationObserver(()=>{p.scrollTop=p.scrollHeight;});return g.observe(p,{childList:true,subtree:true}),p.scrollTop=p.scrollHeight,()=>g.disconnect()},[]),s}var Ye=createContext(void 0);function zt({baseUrl:s,children:p}){let[g,b]=useState(new Map),[z,$]=useState(new Map),O=useCallback((I,w)=>(b(F=>{let f=new Map(F);return f.set(String(I),w),f}),()=>{b(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});}),[]),U=useCallback((I,w)=>{b(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});},[]),G=useCallback((I,w)=>($(F=>{let f=new Map(F);return f.set(String(I),w),f}),()=>{$(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});}),[]),oe=useCallback((I,w)=>{$(F=>{let f=new Map(F),m=f.get(String(I));return (!w||m===w)&&f.delete(String(I)),f});},[]),ge=useMemo(()=>({baseUrl:s,actions:g,components:z,registerAction:O,unregisterAction:U,registerComponent:G,unregisterComponent:oe}),[s,g,z,O,U,G,oe]);return jsx(Ye.Provider,{value:ge,children:p})}function re(){let s=useContext(Ye);return s||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{}}}function yr(s,p){let{registerAction:g}=re(),b=useRef(p);useEffect(()=>{b.current=p;},[p]),useEffect(()=>!s||typeof b.current!="function"?void 0:g(s,($,O)=>b.current($,O)),[s,g]);}function Cr(s,p){let{registerComponent:g}=re(),b=useRef(p);useEffect(()=>{b.current=p;},[p]),useEffect(()=>!s||typeof b.current!="function"?void 0:g(s,b.current),[s,g]);}function Xt(s){let p=Date.now()-s,g=Math.max(1,Math.floor(p/1e3));if(g<60)return `${g}s`;let b=Math.floor(g/60);if(b<60)return `${b}m`;let z=Math.floor(b/60);if(z<24)return `${z}h`;let $=Math.floor(z/24);if($<7)return `${$}d`;let O=Math.floor($/7);if(O<4)return `${O}w`;let U=Math.floor($/30);return U<12?`${U}mo`:`${Math.floor(U/12)}y`}function et(s,p){if(!s)return p;let g=s.endsWith("/")?s.slice(0,-1):s,b=p.startsWith("/")?p:`/${p}`;return `${g}${b}`}var Vt={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 Yt({agentId:s,children:p,theme:g="dark",primaryColor:b,backgroundColor:z,borderColor:$,textColor:O,accentColor:U,width:G=420,maxWidth:oe=420,height:ge="100vh",expandable:I=true,alwaysOpen:w=false,defaultOpen:F=true,dir:f="ltr",floatingButtonPosition:m=f==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},enableBorderAnimation:ne=true,enableContentPadding:tt=true,borderRadius:ke=16,enableContentBorder:Ae=true,placeholder:rt="Ask your question...",title:He="Agent",className:ot="",chatContainerClassName:nt=""}){let{baseUrl:Ee,actions:ze,components:at}=re(),fe=`hsafaChat_${s}`,Fe=`${fe}.chats`,ve=e=>`${fe}.chat.${e}`,J=`${fe}.currentChatId`,Be=`${fe}.showChat`,[ie,Ne]=useState(""),[V,xe]=useState(()=>{if(w)return true;try{let e=localStorage.getItem(Be);return e!==null?e==="true":F}catch{return F}});async function Le(e,n){if(!s)return;let r=n.trim();if(!r)return;_(null),ae(true);let a=A.findIndex(c=>c.id===e);if(a===-1||A[a].role!=="user"){ae(false);return}let i=A.slice(0,a),d={id:e,role:"user",text:r},B=ue(),k=[...i,d,{id:B,role:"assistant",items:[],reasoning:"",reasoningOpen:false}];M(k),ye(null);try{let c=[...i.map(N=>N.role==="user"?{role:"user",content:N.text}:{role:"assistant",items:Array.isArray(N.items)?N.items:[]}),{role:"user",content:r}],R={prompt:r,chatId:S??void 0,messages:c};M(N=>N.map(K=>K.id===B||K.id===e?{...K,requestParams:R}:K));let v=await fetch(et(Ee,`/api/run/${s}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(R)});if(!v.ok||!v.body){let N=await v.text().catch(()=>"");throw new Error(N||`Request failed with ${v.status}`)}let T=v.body.getReader(),ee=new TextDecoder,P="";for(;;){let{done:N,value:K}=await T.read();if(N)break;P+=ee.decode(K,{stream:!0});let x;for(;(x=P.indexOf(`
2
- `))!==-1;){let L=P.slice(0,x).trim();if(P=P.slice(x+1),!!L)try{let u=JSON.parse(L);if(u?.type==="meta"){if(u.actionExecuteMap&&typeof u.actionExecuteMap=="object"&&(Me.current=u.actionExecuteMap),u.assistantMessageId&&(se.current=String(u.assistantMessageId),me.current.clear(),he.current.clear(),W.current.clear(),Q(new Map)),u.chatId&&!S){Y(u.chatId),j.current=!0;let l=r,X=(Z.current||l||"New chat").slice(0,80),h=Date.now();de({id:u.chatId,title:X,createdAt:h,updatedAt:h}),ce({id:u.chatId,messages:k,agentId:s});try{localStorage.setItem(J,u.chatId);}catch{}}continue}if(u?.type==="reasoning"){let l=String(u.text??"");M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,reasoning:(h.reasoning??"")+l}:h));continue}if(u?.type==="partial"||u?.type==="final"){let l=u.value;l&&Array.isArray(l.items)&&(M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,items:l.items}:h)),Je(l.items,u.type==="partial"?"partial":"final")),u?.type==="final"&&M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,reasoningOpen:!1}:h));continue}if(u?.type==="usage"){let l=u?.value?.reasoningTokens;typeof l=="number"&&M(X=>X.map(h=>h.id===B&&h.role==="assistant"?{...h,reasoningTokens:l}:h));continue}if(u?.type==="error"){_(String(u.error??"Unknown error"));continue}}catch{}}}}catch(c){_(String(c?.message??c));}finally{if(ae(false),!S&&!j.current){let c=`local-${ue()}`;Y(c),j.current=true;let R=(Z.current||"New chat").slice(0,80),v=Date.now();de({id:c,title:R,createdAt:v,updatedAt:v}),ce({id:c,messages:A,agentId:s});try{localStorage.setItem(J,c);}catch{}}}}let[A,M]=useState([]),[y,ae]=useState(false),[De,_]=useState(null),le=useRef(null),[S,Y]=useState(null),[st,we]=useState(false),[Oe,it]=useState(""),[Gt,lt]=useState(0),[Pe,ct]=useState(false),[dt,ye]=useState(null),[be,je]=useState(""),ut=useRef(null),We=useRef(null),pt=useRef(null),[Te,gt]=useState(true),Se=useRef(false),j=useRef(false),Z=useRef(null),ft=useRef(null),xt=useRef(null),Me=useRef({}),se=useRef(void 0),me=useRef(new Set),he=useRef(new Map),W=useRef(new Map),[yt,Q]=useState(new Map),Ue=useCallback((e,n)=>{let r=he.current.get(e)||[],a=JSON.stringify(n);if(r.push(a),r.length>5&&r.shift(),he.current.set(e,r),r.length>=3){let i=r.slice(-3);return i.every(d=>d===i[0])}return false},[]),Je=useCallback((e,n)=>{!Array.isArray(e)||e.length===0||e.forEach((r,a)=>{if(!(!r||typeof r!="object")&&r.type==="action"){let i=String(r.name??"").trim();if(!i)return;let d=ze.get(i);if(!d){console.warn(`Action handler not found for: ${i}`);return}let B=!!Me.current[i],k=`${se.current||"assist"}:${i}:${a}`,c=`${i}:${a}`;try{if(n==="partial"&&B){Q(v=>new Map(v).set(c,"executing"));let R=setTimeout(()=>{Promise.resolve(d(r.params,{name:i,trigger:n,index:a,assistantMessageId:se.current,chatId:S||void 0})).catch(v=>{console.error(`Error executing streaming action ${i}:`,v),Q(T=>new Map(T).set(c,"executed"));});},50);W.current.set(`${c}_timeout`,R);}else if(n==="partial"&&!B){let R=Ue(c,r.params),v=W.current.get(c);R&&v!=="executed"?(W.current.set(c,"executed"),Q(T=>new Map(T).set(c,"executed")),Promise.resolve(d(r.params,{name:i,trigger:"params_complete",index:a,assistantMessageId:se.current,chatId:S||void 0})).catch(T=>{console.error(`Error executing stabilized action ${i}:`,T);})):v||(W.current.set(c,"executing"),Q(T=>new Map(T).set(c,"executing")));}else if(n==="final"&&W.current.get(c)!=="executed"&&!me.current.has(k)){me.current.add(k);let v=W.current.get(`${c}_timeout`);v&&(clearTimeout(v),W.current.delete(`${c}_timeout`)),W.current.set(c,"executed"),Q(T=>new Map(T).set(c,"executed")),Promise.resolve(d(r.params,{name:i,trigger:B?"final":"params_complete",index:a,assistantMessageId:se.current,chatId:S||void 0})).catch(T=>{console.error(`Error executing final action ${i}:`,T);});}}catch(R){console.error(`Error processing action ${i}:`,R);}}});},[ze,S,Ue]),$e=()=>{try{let e=localStorage.getItem(Fe);return e?JSON.parse(e):[]}catch{return []}},_e=e=>{try{localStorage.setItem(Fe,JSON.stringify(e));}catch{}},qe=e=>{try{let n=localStorage.getItem(ve(e));return n?JSON.parse(n):null}catch{return null}},ce=e=>{try{localStorage.setItem(ve(e.id),JSON.stringify(e));}catch{}},de=e=>{let n=$e(),r=n.findIndex(a=>a.id===e.id);r>=0?n[r]=e:n.unshift(e),_e(n);},bt=e=>{let r=$e().filter(a=>a.id!==e);_e(r);},mt=e=>{try{localStorage.removeItem(ve(e));}catch{}},ht=e=>{if(mt(e),bt(e),S===e){M([]),_(null),Y(null),j.current=false,Z.current=null;try{localStorage.removeItem(J);}catch{}}};useEffect(()=>{if(Se.current){Se.current=false;return}Te&&We.current?.scrollIntoView({behavior:"smooth",block:"end"});},[A,y,Te]),useEffect(()=>{try{let e=localStorage.getItem(J);if(e){let n=qe(e);n&&(Y(n.id),j.current=!0,M(n.messages||[]));}}catch{}},[]),useEffect(()=>{try{localStorage.setItem(Be,String(V));}catch{}},[V]),useEffect(()=>()=>{W.current.forEach((e,n)=>{n.endsWith("_timeout")&&clearTimeout(e);});},[]),useEffect(()=>{if(!S||!j.current)return;ce({id:S,messages:A,agentId:s});let n=A.find(i=>i.role==="user"),r=(Z.current||(n?.text??"New chat")).slice(0,80),a={id:S,title:r,createdAt:Date.now(),updatedAt:Date.now()};de(a);try{localStorage.setItem(J,S);}catch{}},[A,S,s]);let ue=()=>`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;function Ct(){le.current&&(le.current.abort(),le.current=null),ae(false),_("Request stopped by user");}async function Ke(){if(!s)return;let e=ie.trim();if(!e)return;_(null),ae(true),!S&&A.length===0&&(Z.current=e);let n=ue(),r=ue(),a={id:n,role:"user",text:e},i={id:r,role:"assistant",items:[],reasoning:"",reasoningOpen:false},d=[...A,a,i],B=[...A.map(k=>k.role==="user"?{role:"user",content:k.text}:{role:"assistant",items:Array.isArray(k.items)?k.items:[]}),{role:"user",content:e}];M(d),Ne("");try{le.current=new AbortController;let k={prompt:e,chatId:S??void 0,messages:B};M(ee=>ee.map(P=>P.id===r||P.id===n?{...P,requestParams:k}:P));let c=await fetch(et(Ee,`/api/run/${s}`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k),signal:le.current.signal});if(!c.ok||!c.body){let ee=await c.text().catch(()=>"");throw new Error(ee||`Request failed with ${c.status}`)}let R=c.body.getReader(),v=new TextDecoder,T="";for(;;){let{done:ee,value:P}=await R.read();if(ee)break;T+=v.decode(P,{stream:!0});let N;for(;(N=T.indexOf(`
3
- `))!==-1;){let K=T.slice(0,N).trim();if(T=T.slice(N+1),!!K)try{let x=JSON.parse(K);if(x?.type==="meta"){if(x.actionExecuteMap&&typeof x.actionExecuteMap=="object"&&(Me.current=x.actionExecuteMap),x.assistantMessageId&&(se.current=String(x.assistantMessageId),me.current.clear(),he.current.clear(),W.current.clear(),Q(new Map)),x.chatId&&!S){Y(x.chatId),j.current=!0;let L=e,u=(Z.current||L||"New chat").slice(0,80),l=Date.now();de({id:x.chatId,title:u,createdAt:l,updatedAt:l}),ce({id:x.chatId,messages:d,agentId:s});try{localStorage.setItem(J,x.chatId);}catch{}}continue}if(x?.type==="reasoning"){let L=String(x.text??"");M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoning:(l.reasoning??"")+L}:l));continue}if(x?.type==="partial"||x?.type==="final"){let L=x.value;L&&Array.isArray(L.items)&&(M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,items:L.items}:l)),Je(L.items,x.type==="partial"?"partial":"final")),x?.type==="final"&&M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoningOpen:!1}:l));continue}if(x?.type==="usage"){let L=x?.value?.reasoningTokens;typeof L=="number"&&M(u=>u.map(l=>l.id===r&&l.role==="assistant"?{...l,reasoningTokens:L}:l));continue}if(x?.type==="error"){_(String(x.error??"Unknown error"));continue}}catch{}}}}catch(k){_(String(k?.message??k));}finally{if(ae(false),!S&&!j.current){let k=`local-${ue()}`;Y(k),j.current=true;let c=(Z.current||"New chat").slice(0,80),R=Date.now();de({id:k,title:c,createdAt:R,updatedAt:R}),ce({id:k,messages:A,agentId:s});try{localStorage.setItem(J,k);}catch{}}}}function kt(e){return !Array.isArray(e)||e.length===0?null:jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:e.map((n,r)=>{let a=`it-${r}`;if(typeof n=="string")return jsx("div",{style:{borderRadius:"12px",padding:"16px",fontSize:"14px",whiteSpace:"pre-wrap",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`,color:t.textColor},children:n},a);if(n&&typeof n=="object"){if(n.type==="action"){let i=`${String(n.name??"action")}:${r}`,d=yt.get(i);return jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsx("div",{style:{padding:"8px",fontSize:"12px",color:t.mutedTextColor},children:d==="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(n.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(n.name??"action")," has executed"]})})},a)}if(n.type==="ui-component"||n.type==="ui"){let i=String(n.name??n.component??"").trim(),d=i?at.get(i):void 0;return d?jsx("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:jsx(d,{...n.props||{}})},a):jsxs("div",{style:{borderRadius:"12px",padding:"16px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:[jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:t.mutedTextColor},children:[jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:t.accentColor,border:`1px solid ${t.borderColor}`},children:"UI"}),jsx("span",{children:i||"component"}),jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(n.props??{},null,2)})]},a)}return jsx("div",{style:{borderRadius:"12px",padding:"16px",fontSize:"14px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`},children:jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(n,null,2)})},a)}return null})})}let q=Vt[g],t={primaryColor:b||q.primaryColor,backgroundColor:z||q.backgroundColor,borderColor:$||q.borderColor,textColor:O||q.textColor,accentColor:U||q.accentColor,mutedTextColor:q.mutedTextColor,inputBackground:q.inputBackground,cardBackground:q.cardBackground,hoverBackground:q.hoverBackground},vt={backgroundColor:t.backgroundColor,color:t.textColor,height:ge,display:"flex",width:"100%",fontFamily:'Rubik, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif'},wt={width:typeof G=="number"?`${G}px`:G,maxWidth:typeof oe=="number"?`${oe}px`:oe,display:"flex",flexDirection:"column",transition:"all 0.3s ease-out",overflow:"hidden"},Tt={position:"fixed",bottom:typeof m.bottom=="number"?`${m.bottom}px`:m.bottom,right:m.right?typeof m.right=="number"?`${m.right}px`:m.right:void 0,top:m.top?typeof m.top=="number"?`${m.top}px`:m.top:void 0,left:m.left?typeof m.left=="number"?`${m.left}px`:m.left:void 0,zIndex:1e3},Ie=typeof ke=="number"?`${ke}px`:ke,H=useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return jsxs("div",{className:ot,style:vt,dir:f,"data-hsafa-chat":H.current,children:[jsx("div",{style:{display:"flex",alignItems:"stretch",justifyContent:"stretch",width:"100%",height:"100%",transition:"all 0.3s ease-out",padding:V&&tt?"16px":"0"},children:jsx("div",{style:{position:"relative",display:"flex",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:V&&Ae?Ie:"0"},children:V&&Ae?jsx("div",{style:{width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Ie,border:y&&ne?"none":`1px solid ${t.borderColor}`,padding:y&&ne?"1.5px":"0",background:y&&ne?`linear-gradient(120deg, ${t.primaryColor}dd 0%, ${t.primaryColor}88 25%, ${t.primaryColor}00 50%, ${t.primaryColor}88 75%, ${t.primaryColor}dd 100%)`:"transparent",backgroundSize:y&&ne?"300% 300%":"auto",animation:y&&ne?`${H.current}-border-flow 3s ease-in-out infinite`:"none",filter:y&&ne?`drop-shadow(0 0 10px ${t.primaryColor}40)`:"none"},children:jsx("div",{className:"content-container",style:{width:"100%",height:"100%",borderRadius:Ie,backgroundColor:t.backgroundColor,overflowY:"auto",overflowX:"hidden",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:p})}):jsx("div",{className:"content-container",style:{width:"100%",height:"100%",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",overflowY:"auto",overflowX:"hidden",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:p})})}),jsxs("div",{className:nt,style:{...wt,height:ge,backgroundColor:V||w?t.backgroundColor:"transparent",...V||w?Pe&&I?{position:"fixed",inset:"0",zIndex:1050,width:"100%",maxWidth:"100%",padding:"24px"}:{padding:"24px 16px",opacity:1,transform:"translateX(0)",pointerEvents:"auto"}:{width:"0",maxWidth:"0",padding:"24px 0",opacity:0,transform:f==="rtl"?"translateX(8px)":"translateX(-8px)",pointerEvents:"none"}},children:[jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:He,style:{color:t.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:He})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:t.mutedTextColor},children:[I&&jsx("button",{"aria-label":Pe?"Minimize":"Maximize",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{xe(true),ct(e=>!e);},children:jsx(IconArrowsMaximize,{size:20,stroke:2})}),jsx("button",{"aria-label":"New",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>{if(!y){M([]),_(null),Y(null),j.current=false,Z.current=null;try{localStorage.removeItem(J);}catch{}}},children:jsx(IconPlus,{size:20,stroke:2})}),jsx("button",{"aria-label":"History",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>we(e=>!e),ref:ft,children:jsx(IconHistory,{size:20,stroke:2})}),st&&(()=>{let e=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:()=>we(false)}),jsxs("div",{ref:xt,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:`${t.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 ${t.borderColor}`,padding:"12px 16px"},children:jsx("div",{style:{flex:"1"},children:jsx("input",{autoFocus:true,value:Oe,onChange:n=>it(n.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:t.inputBackground,padding:"8px 12px",fontSize:"14px",color:t.textColor,border:`1px solid ${t.borderColor}`,outline:"none"},onFocus:n=>n.currentTarget.style.borderColor=t.primaryColor,onBlur:n=>n.currentTarget.style.borderColor=t.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let n=Oe.toLowerCase().trim(),r=$e();return n&&(r=r.filter(a=>(a.title||"").toLowerCase().includes(n))),!r||r.length===0?jsx("div",{style:{padding:"24px",color:t.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:r.map((a,i)=>jsx("div",{style:{borderTop:i>0?`1px solid ${t.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===S?t.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:t.textColor},onMouseEnter:d=>d.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor="transparent",onClick:()=>{let d=qe(a.id);if(d){Y(a.id),j.current=true,M(d.messages||[]);try{localStorage.setItem(J,a.id);}catch{}we(false),xe(true);}},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:t.textColor},children:a.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:t.mutedTextColor},children:Xt(a.updatedAt)})]})}),jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:t.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:d=>{d.currentTarget.style.color="#ef4444",d.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",d.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:d=>{d.currentTarget.style.color=t.mutedTextColor,d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.borderColor="transparent";},onClick:d=>{d.stopPropagation(),ht(a.id),lt(B=>B+1);},children:jsx(IconTrash,{size:16,stroke:2})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(e,document.body):e})(),!w&&jsx("button",{"aria-label":"Close chat",style:{backgroundColor:"transparent",color:t.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},onClick:()=>xe(false),children:jsx(IconChevronRight,{size:20,stroke:2,style:{transform:f==="rtl"?"rotate(180deg)":"none"}})})]})]}),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"},ref:pt,onScroll:e=>{let n=e.currentTarget,i=n.scrollHeight-(n.scrollTop+n.clientHeight)<=64;i!==Te&&gt(i);},children:[De&&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:De}),A.length===0&&!y&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.accentColor,color:t.mutedTextColor},children:"Start by sending a message to the agent."}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:A.map((e,n)=>jsx("div",{style:{padding:"0 4px"},children:e.role==="user"?dt===e.id?jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${t.primaryColor}`,backgroundColor:t.accentColor,color:t.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((be||e.text).length/60))),value:be,onChange:r=>je(r.target.value),onKeyDown:r=>{r.key==="Escape"?ye(null):r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),y||Le(e.id,be||e.text));}}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:"8px",padding:"8px 8px 8px 0"},children:[jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"background-color 0.2s",border:`1px solid ${t.borderColor}`,color:t.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:r=>r.currentTarget.style.backgroundColor=t.inputBackground,onMouseLeave:r=>r.currentTarget.style.backgroundColor="transparent",onClick:()=>ye(null),children:"Cancel"}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${t.borderColor}`,backgroundColor:t.cardBackground,color:t.textColor,cursor:"pointer"},onMouseEnter:r=>r.currentTarget.style.borderColor=t.primaryColor,onMouseLeave:r=>r.currentTarget.style.borderColor=t.borderColor,onClick:()=>{y||Le(e.id,be||e.text);},children:"Save"})]})]}):jsx("div",{title:"Click to edit",onClick:()=>{y||(ye(e.id),je(e.text));},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:t.accentColor,color:t.textColor},onMouseEnter:r=>r.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:r=>r.currentTarget.style.backgroundColor=t.accentColor,children:e.text}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.reasoning&&jsxs("div",{style:{borderRadius:"12px",padding:"12px",cursor:"pointer",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},onClick:()=>{Se.current=true,M(r=>r.map(a=>a.id===e.id&&a.role==="assistant"?{...a,reasoningOpen:!a.reasoningOpen}:a));},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[jsx("div",{style:{fontSize:"12px",color:t.mutedTextColor},children:"Reasoning"}),jsx("button",{type:"button",style:{fontSize:"12px",transition:"color 0.2s",color:t.mutedTextColor,background:"none",border:"none",cursor:"pointer"},onMouseEnter:r=>r.currentTarget.style.color=t.textColor,onMouseLeave:r=>r.currentTarget.style.color=t.mutedTextColor,children:e.reasoningOpen?"Hide":"Show full"})]}),e.reasoningOpen?jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:e.reasoning}):(()=>{let r=(e.reasoning||"").trim().split(`
4
- `).filter(i=>i.trim()),a=r.length>0?r[r.length-1]:"";return jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:t.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:a||"\u2026"})})()]}),kt(e.items),y&&n===A.length-1&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:t.mutedTextColor},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:t.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsx("span",{children:"Working\u2026"})]})]})},e.id))}),jsx("div",{ref:We})]}),jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:t.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 ${t.borderColor}`,backgroundColor:t.accentColor},children:[jsx("div",{style:{padding:"0 16px"},children:jsx("textarea",{"aria-label":"Prompt",rows:2,style:{height:"auto",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:t.textColor,fontFamily:"inherit"},placeholder:rt,value:ie,onChange:e=>Ne(e.target.value),onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),y||Ke());},ref:ut})}),jsxs("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:t.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:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Attach files",children:jsx(IconPaperclip,{size:18,stroke: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:e=>{e.currentTarget.style.backgroundColor=`${t.backgroundColor}99`,e.currentTarget.style.color=t.textColor;},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent",e.currentTarget.style.color=t.mutedTextColor;},"aria-label":"Insert link",children:jsx(IconLink,{size:18,stroke:2})})]}),jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:jsx("button",{"aria-label":y?"Stop":"Send",disabled:!y&&!ie.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${y?"#ef4444":t.borderColor}`,backgroundColor:y?"#ef444420":t.cardBackground,color:y?"#ef4444":t.mutedTextColor,opacity:!y&&!ie.trim()?.4:1,cursor:!y&&!ie.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:e=>{e.currentTarget.disabled||(y?(e.currentTarget.style.borderColor="#dc2626",e.currentTarget.style.backgroundColor="#dc262630",e.currentTarget.style.color="#dc2626"):(e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=t.hoverBackground,e.currentTarget.style.color=t.textColor));},onMouseLeave:e=>{e.currentTarget.disabled||(y?(e.currentTarget.style.borderColor="#ef4444",e.currentTarget.style.backgroundColor="#ef444420",e.currentTarget.style.color="#ef4444"):(e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.cardBackground,e.currentTarget.style.color=t.mutedTextColor));},onClick:()=>{y?Ct():Ke();},children:y?jsx(IconPlayerStop,{size:18,stroke:2}):jsx(IconArrowUp,{size:18,stroke:2})})})]})})})]}),!V&&!w&&jsx("button",{"aria-label":"Open chat",onClick:()=>xe(true),style:{...Tt,borderColor:t.borderColor,backgroundColor:t.accentColor,color:t.textColor,borderRadius:"50%",border:`1px solid ${t.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:e=>{e.currentTarget.style.borderColor=t.primaryColor,e.currentTarget.style.backgroundColor=`${t.accentColor}dd`;},onMouseLeave:e=>{e.currentTarget.style.borderColor=t.borderColor,e.currentTarget.style.backgroundColor=t.accentColor;},children:jsx(IconMessage,{size:20,stroke:2})}),jsx("style",{children:`
5
- /* Import Rubik font from Google Fonts */
6
- @import url('https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300..900;1,300..900&display=swap');
7
-
8
- @keyframes ${H.current}-border-flow {
1
+ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {Maximize2,Plus,History,ChevronRight,File,Eye,X,Loader2,Paperclip,Link,Square,ArrowUp,Trash2,Download,CheckCircle}from'lucide-react';import Bt,{createContext,useState,useCallback,useRef,useEffect,useMemo,useContext}from'react';import {createPortal}from'react-dom';var lt={};var Pr=({variant:t="primary",size:e="md",loading:n=false,disabled:o,children:a,className:l,...r})=>{let s=[lt.button,lt[t],lt[e],n&&lt.loading,l].filter(Boolean).join(" ");return jsxs("button",{className:s,disabled:o||n,...r,children:[n&&jsx("span",{className:lt.spinner}),jsx("span",{className:n?lt.hiddenText:void 0,children:a})]})};function Zt(t){if(!t||Number.isNaN(t))return "0 B";let e=["B","KB","MB","GB","TB"],n=Math.min(e.length-1,Math.floor(Math.log(t)/Math.log(1024)));return `${(t/Math.pow(1024,n)).toFixed(n===0?0:1)} ${e[n]}`}function Dt({attachments:t,resolvedColors:e,onRemove:n}){if(!Array.isArray(t)||t.length===0)return null;let o=typeof n=="function";return jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:t.map(a=>{let l=a.mimeType?.startsWith("image/");return o?jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 10px",backgroundColor:e.inputBackground,borderRadius:"8px",border:`1px solid ${e.borderColor}`,fontSize:"11px",color:e.textColor,maxWidth:"200px",position:"relative"},children:[jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",borderRadius:"3px",backgroundColor:l?"transparent":e.accentColor,flexShrink:0},children:l?jsx("img",{src:a.url,alt:a.name,style:{width:"16px",height:"16px",borderRadius:"3px",objectFit:"cover"}}):jsx(File,{size:"10",strokeWidth:"2",style:{color:e.mutedTextColor}})}),jsxs("div",{style:{minWidth:"0",flex:"1"},children:[jsx("div",{title:a.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:a.name}),jsx("div",{style:{fontSize:"9px",color:e.mutedTextColor,marginTop:"1px"},children:Zt(a.size)})]}),jsx("button",{onClick:()=>n(a.id),style:{display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:e.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:r=>{r.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",r.currentTarget.style.color="#ef4444";},onMouseLeave:r=>{r.currentTarget.style.backgroundColor="transparent",r.currentTarget.style.color=e.mutedTextColor;},children:jsx(X,{size:"12",strokeWidth:"2"})})]},a.id):jsxs("a",{href:a.url,target:"_blank",rel:"noreferrer",style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 10px",backgroundColor:e.inputBackground,borderRadius:"8px",border:`1px solid ${e.borderColor}`,fontSize:"11px",color:e.textColor,textDecoration:"none",transition:"all 0.2s",cursor:"pointer",maxWidth:"200px"},onMouseEnter:r=>{r.currentTarget.style.backgroundColor=e.hoverBackground,r.currentTarget.style.borderColor=e.primaryColor;},onMouseLeave:r=>{r.currentTarget.style.backgroundColor=e.inputBackground,r.currentTarget.style.borderColor=e.borderColor;},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",borderRadius:"3px",backgroundColor:l?"transparent":e.accentColor,flexShrink:0},children:[l?jsx("img",{src:a.url,alt:a.name,style:{width:"16px",height:"16px",borderRadius:"3px",objectFit:"cover"},onError:r=>{r.target.style.display="none";let s=r.target.nextElementSibling;s&&(s.style.display="block");}}):null,jsx(File,{size:"10",strokeWidth:"2",style:{display:l?"none":"block",color:e.mutedTextColor}})]}),jsxs("div",{style:{minWidth:"0",flex:"1"},children:[jsx("div",{title:a.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:a.name}),jsx("div",{style:{fontSize:"9px",color:e.mutedTextColor,marginTop:"1px"},children:Zt(a.size)})]}),jsx(Download,{size:"10",strokeWidth:"2",style:{color:e.mutedTextColor,flexShrink:0}})]},a.id)})})}function Me({messageId:t,initialText:e,editingText:n,onEditingTextChange:o,onCancel:a,onSave:l,streaming:r,resolvedColors:s,attachments:f,onRemoveAttachment:x,onAddAttachments:m,uploading:h,t:i}){let g=Bt.useRef(null),d=y=>{y.key==="Escape"?a():y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),r||l(t,n||e));},b=y=>{let p=y.target.files;p&&p.length>0&&m&&m(p),g.current&&(g.current.value="");};return jsxs("div",{style:{maxWidth:"720px",borderRadius:"16px",padding:"8px",fontSize:"15px",border:`2px solid ${s.primaryColor}`,backgroundColor:s.accentColor,color:s.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((n||e).length/60))),value:n,onChange:y=>o(y.target.value),onKeyDown:d}),f&&f.length>0&&jsx("div",{style:{padding:"8px"},children:jsx(Dt,{attachments:f,resolvedColors:s,onRemove:x})}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",padding:"8px 8px 8px 0"},children:[m&&jsxs("div",{children:[jsx("input",{ref:g,type:"file",multiple:true,onChange:b,style:{display:"none"}}),jsx("button",{onClick:()=>g.current?.click(),disabled:h||r,title:i(h?"input.uploadingFiles":"input.attachFiles"),style:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"50%",width:"28px",height:"28px",transition:"all 0.2s",border:`1px solid ${s.borderColor}`,color:s.mutedTextColor,backgroundColor:"transparent",cursor:h||r?"not-allowed":"pointer",opacity:h||r?.5:1},onMouseEnter:y=>{!h&&!r&&(y.currentTarget.style.backgroundColor=s.inputBackground,y.currentTarget.style.borderColor=s.primaryColor);},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="transparent",y.currentTarget.style.borderColor=s.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 ${s.borderColor}`,color:s.mutedTextColor,backgroundColor:"transparent",cursor:"pointer"},onMouseEnter:y=>y.currentTarget.style.backgroundColor=s.inputBackground,onMouseLeave:y=>y.currentTarget.style.backgroundColor="transparent",onClick:a,children:i("editor.cancel")}),jsx("button",{style:{borderRadius:"8px",padding:"4px 12px",fontSize:"14px",transition:"border-color 0.2s",border:`1px solid ${s.borderColor}`,backgroundColor:s.cardBackground,color:s.textColor,cursor:"pointer"},onMouseEnter:y=>y.currentTarget.style.borderColor=s.primaryColor,onMouseLeave:y=>y.currentTarget.style.borderColor=s.borderColor,onClick:()=>{r||l(t,n||e);},children:i("editor.saveAndRegenerate")})]})]})]})}function Bn(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,e){let n=(t||"").trim();if(!e||e.length===0)return n;let o=[];n&&o.push({type:"text",text:n});for(let a of e)o.push(Bn(a));return o}function ve(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>n.type==="text").map(n=>n.text).join(`
2
+ `):""}function Ae(t){if(typeof t=="string"||!Array.isArray(t))return [];let e=[];for(let n of t)if(n.type==="image"){let o=typeof n.image=="string"?n.image:n.image.toString();e.push({id:`img_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:"image",url:o,mimeType:n.mediaType||"image/jpeg",size:0});}else if(n.type==="file"){let o=typeof n.data=="string"?n.data:n.data.toString();e.push({id:`file_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:n.name||"file",url:o,mimeType:n.mediaType,size:0});}return e}function Gt(t){return t.role==="user"?t.text?t.text:ve(t.content):""}function ft(t){return t.role==="user"?t.attachments?t.attachments:Ae(t.content):[]}function we(t,e=[]){let n=Yt(t,e),o=Date.now();return {id:`user_${o}_${Math.random().toString(36).slice(2)}`,role:"user",content:n,createdAt:o,text:t,attachments:e.length>0?e:void 0}}function Qt(t=false){let e=Date.now();return {id:`assistant_${e}_${Math.random().toString(36).slice(2)}`,role:"assistant",items:[],reasoning:"",reasoningOpen:t,mainAgentActions:[],createdAt:e}}function Se(t){let e=[];for(let n of t)if(n.role==="user")e.push({role:n.role,content:n.content});else if(n.role==="assistant"){let o=[];if(n.firstAgentMessage&&o.push({type:"text",text:n.firstAgentMessage}),n.mainAgentActions&&n.mainAgentActions.length>0){for(let a of n.mainAgentActions)if(a.type==="reasoning"&&a.reasoning)o.push({type:"reasoning",text:a.reasoning});else if(a.type==="tool-call"&&a.toolName){let l=a.toolCallId||(typeof a.startDate=="number"&&a.toolName?`${a.toolName}_${a.startDate}`:`call_${a.toolName||"tool"}_${Math.abs(a.durationMs||0)}`);o.push({type:"tool-call",toolCallId:l,toolName:a.toolName,input:a.input||{}}),a.output!==void 0&&e.push({role:"tool",content:[{type:"tool-result",toolCallId:l,toolName:a.toolName,output:a.output,isError:a.status==="error"}]});}}if(n.items&&n.items.length>0){let a=JSON.stringify(n.items,null,2);o.push({type:"text",text:a});}o.length>0&&e.push({role:n.role,content:o});}return e}function Re(t,e,n){let o=n??ft(t),a=Yt(e,o);return {...t,content:a,text:e,attachments:o.length>0?o:void 0}}function $e(t){if(t.role==="user"){let e=Gt(t),n=ft(t);return n.length>0?`${e} [${n.length} attachment${n.length>1?"s":""}]`:e}else if(t.role==="assistant"){let n=(t.items||[]).filter(o=>o.type==="text");return n.length>0?n.map(o=>o.text||"").join(" ").slice(0,100):"Assistant response"}return ""}function Fe({message:t,isEditing:e,editingText:n,editingAttachments:o,onEditingTextChange:a,onStartEdit:l,onCancelEdit:r,onSaveEdit:s,onRemoveAttachment:f,onAddAttachments:x,uploading:m,streaming:h,resolvedColors:i,t:g}){let d=Gt(t),b=ft(t);return e?jsx(Me,{messageId:t.id,initialText:d,editingText:n,onEditingTextChange:a,onCancel:r,onSave:s,streaming:h,resolvedColors:i,attachments:o||b,onRemoveAttachment:f,onAddAttachments:x,uploading:m,t:g}):jsxs("div",{title:g("editor.clickToEdit"),onClick:()=>{h||l(t.id,d);},style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:i.accentColor,color:i.textColor},onMouseEnter:y=>y.currentTarget.style.backgroundColor=i.hoverBackground,onMouseLeave:y=>y.currentTarget.style.backgroundColor=i.accentColor,children:[d,jsx(Dt,{attachments:b,resolvedColors:i})]})}function Ee({reasoning:t,reasoningOpen:e,onToggleReasoning:n,resolvedColors:o}){return t?jsxs("div",{style:{borderRadius:"12px",padding:"12px",cursor:"pointer",backgroundColor:o.inputBackground,border:`1px solid ${o.borderColor}`},onClick:n,children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[jsx("div",{style:{fontSize:"12px",color:o.mutedTextColor},children:"Reasoning"}),jsx("button",{type:"button",style:{fontSize:"12px",transition:"color 0.2s",color:o.mutedTextColor,background:"none",border:"none",cursor:"pointer"},onMouseEnter:a=>a.currentTarget.style.color=o.textColor,onMouseLeave:a=>a.currentTarget.style.color=o.mutedTextColor,children:e?"Hide":"Show full"})]}),e?jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:t}):(()=>{let a=(t||"").trim().split(`
3
+ `).filter(r=>r.trim()),l=a.length>0?a[a.length-1]:"";return jsx("pre",{style:{fontSize:"12px",whiteSpace:"pre-wrap",wordBreak:"break-word",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:l||"\u2026"})})()]}):null}function Be({chart:t,theme:e}){let n=useRef(null),[o,a]=useState(null),[l,r]=useState(true);useEffect(()=>{let i=true;return (async()=>{try{r(!0),a(null);let d;try{d=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!i)return;if(d.default?.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:{darkMode:e==="dark",primaryColor:e==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:e==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:e==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&i){let b=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:y}=await d.default.render(b,t);if(n.current&&i){n.current.innerHTML=y;let p=n.current.querySelector("svg");p&&(p.style.maxWidth="100%",p.style.height="auto",p.style.display="block");}}}catch(d){i&&a(d instanceof Error?d.message:"Failed to render diagram");}finally{i&&r(false);}})(),()=>{i=false;}},[t,e]);let s=e==="dark"?"#374151":"#D1D5DB",f=e==="dark"?"#1F2937":"#F9FAFB",x=e==="dark"?"#7F1D1D":"#FEF2F2",m=e==="dark"?"#FCA5A5":"#DC2626",h=e==="dark"?"#9CA3AF":"#6B7280";return o?jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${s}`,backgroundColor:x,padding:"16px",margin:"8px 0"},children:[jsx("div",{style:{fontSize:"14px",color:m,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsx("div",{style:{fontSize:"12px",color:m,opacity:.8},children:o})]}):jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${s}`,backgroundColor:f,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[l&&jsx("div",{style:{fontSize:"14px",color:h,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsx("div",{ref:n,style:{display:l?"none":"block",textAlign:"center",minHeight:l?"0":"50px"}})]})}function et(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Pt(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 _n(t,e="dark"){let n=(t||"").replace(/\r\n/g,`
4
+ `).split(`
5
+ `),o="",a=false,l="",r=[],s=false,f=false,x=false,m=e==="dark"?"#374151":"#D1D5DB",i=e==="dark"?"#111827":"#F3F4F6",g=e==="dark"?"#E5E7EB":"#374151",d=()=>{s&&(o+="</ul>",s=false),f&&(o+="</ol>",f=false);};for(let b=0;b<n.length;b++){let y=n[b],p=y.match(/^```\s*(\w+)?\s*$/);if(p){if(!a)d(),a=true,l=p[1]?String(p[1]):"",r=[];else {if(l==="mermaid"){x=true;let u=r.join(`
6
+ `);o+=`<div class="mermaid-placeholder" data-mermaid="${et(u)}"></div>`;}else {let u=et(r.join(`
7
+ `)),C=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${i}; color: ${g}; border: 1px solid ${m}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${C}">${u}</code></pre>`;}a=false,l="",r=[];}continue}if(a){r.push(y);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(y)){d(),o+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let I=y.match(/^(#{1,6})\s+(.+)$/);if(I){d();let u=I[1].length,C=Pt(et(I[2].trim())),T=u<=2?"18px":u===3?"16px":"14px";o+=`<h${u} style="font-size: ${T}; font-weight: 600; margin: 8px 0 4px 0;">${C}</h${u}>`;continue}let M=y.match(/^\s*[-*]\s+(.+)$/),k=y.match(/^\s*\d+\.\s+(.+)$/);if(M){s||(d(),o+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',s=true);let u=Pt(et(M[1]));o+=`<li style="margin: 2px 0;">${u}</li>`;continue}if(k){f||(d(),o+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',f=true);let u=Pt(et(k[1]));o+=`<li style="margin: 2px 0;">${u}</li>`;continue}if(y.trim().length===0)d(),o+='<div style="height: 8px;"></div>';else {d();let u=Pt(et(y));o+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${u}</p>`;}}if(a)if(l==="mermaid"){x=true;let b=r.join(`
8
+ `);o+=`<div class="mermaid-placeholder" data-mermaid="${et(b)}"></div>`;}else {let b=et(r.join(`
9
+ `)),y=l?`language-${l}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${i}; color: ${g}; border: 1px solid ${m}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${y}">${b}</code></pre>`;}return s&&(o+="</ul>"),f&&(o+="</ol>"),{html:o,hasMermaid:x}}function ht({content:t,theme:e}){let{html:n,hasMermaid:o}=useMemo(()=>_n(t,e),[t,e]);if(!o)return jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let a=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),l=[];return a.forEach((r,s)=>{if(r.includes("mermaid-placeholder")){let f=r.match(/data-mermaid="([^"]*)"/);if(f){let x=f[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");l.push(Bt.createElement(Be,{key:`mermaid-${s}`,chart:x,theme:e}));}}else r.trim()&&l.push(Bt.createElement("div",{key:`html-${s}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:r}}));}),Bt.createElement(Bt.Fragment,{},...l)}function Pe({mainAgentActions:t,reasoningOpen:e,onToggleReasoning:n,resolvedColors:o,streaming:a=false,theme:l="dark",hideReasoningContent:r=false}){if(!t||t.length===0)return null;let s=t.filter(h=>h.type==="reasoning"||h.type==="tool-call");if(s.length===0)return null;let f=[...s].reverse().find(h=>h.type==="reasoning"),x=t.some(h=>h.type==="response"),m=jn(s);return jsxs("div",{style:{cursor:"pointer",padding:"0",maxWidth:"100%"},onClick:n,children:[e?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0",maxWidth:"100%",position:"relative"},children:[s.map((h,i)=>jsx(Kn,{action:h,resolvedColors:o,theme:l,isFirst:i===0,isLast:i===s.length-1,hideReasoningContent:r},i)),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:x?jsx("div",{style:{width:"8px",height:"8px",marginTop:"6px",zIndex:1},children:jsx(CheckCircle,{size:10,color:o.borderColor})}):jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:o.borderColor,marginTop:"6px",zIndex:1}})}),jsx("div",{style:{flex:1,minWidth:0},children:x&&jsx("div",{style:{fontSize:"11px",color:o.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&&!x?jsxs("div",{style:{fontSize:"13px",color:o.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:o.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:o.mutedTextColor,fontFamily:"monospace",fontSize:"12px",opacity:.5,letterSpacing:"0.1px"},children:["for ",Le(m)]})]}),!r&&f?.type==="reasoning"&&!x&&jsx("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:jsx(ht,{content:f.reasoning,theme:l})})]}),jsx("style",{children:`
10
+ @keyframes thinking-pulse {
11
+ 0%, 60%, 100% { opacity: 0.3; }
12
+ 30% { opacity: 1; }
13
+ }
14
+ `})]})}function jn(t){let e=0;for(let n of t)"startDate"in n&&"endDate"in n&&n.startDate&&n.endDate&&(e+=n.endDate-n.startDate);return e}function Le(t){if(t<1e3)return `${Math.round(t)}ms`;if(t<6e4)return `${(t/1e3).toFixed(1)}s`;{let e=Math.floor(t/6e4),n=Math.round(t%6e4/1e3);return `${e}m ${n}s`}}function Kn({action:t,resolvedColors:e,theme:n,isFirst:o,isLast:a,hideReasoningContent:l=false}){let r=null;if("startDate"in t&&"endDate"in t&&t.startDate&&t.endDate&&(r=Le(t.endDate-t.startDate)),t.type==="reasoning"){let s=t.status==="streaming";return jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[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:e.borderColor,marginTop:"6px",zIndex:1}}),jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:e.borderColor}})]}),jsxs("div",{style:{flex:1,minWidth:0},children:[jsxs("div",{style:{fontSize:"11px",color:e.mutedTextColor,marginBottom:"4px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{children:"Reasoning"}),r&&jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",color:e.mutedTextColor},children:r})]}),!l&&jsx("div",{style:{fontSize:"13px",color:e.mutedTextColor,lineHeight:"1.6",maxWidth:"100%",opacity:s?.8:1},children:jsx(ht,{content:t.reasoning,theme:n})})]})]})}if(t.type==="tool-call"){let s=t.status==="input_streaming",f=t.status==="running";t.status==="finished";let m=t.status==="error",h=n==="dark"?"#10b981":"#059669";s&&(h=n==="dark"?"#eab308":"#d97706"),f&&(h=n==="dark"?"#3b82f6":"#2563eb"),m&&(h=n==="dark"?"#ef4444":"#dc2626");let i="Called";return s&&(i="Inputting"),f&&(i="Running"),m&&(i="Error"),jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[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:h,marginTop:"6px",zIndex:1}}),jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:n==="dark"?e.borderColor:e.mutedTextColor}})]}),jsx("div",{style:{flex:1,minWidth:0},children:jsxs("div",{style:{fontSize:"12px",color:e.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsx("span",{style:{fontWeight:500,opacity:n==="dark"?.7:.6},children:i}),jsx("span",{style:{color:e.mutedTextColor,fontWeight:500},children:t.toolName||"tool"}),r&&jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",color:e.mutedTextColor,opacity:n==="dark"?.5:.6},children:r})]})})]})}return null}function Ne({mcpToolCalls:t,resolvedColors:e}){if(!t||t.length===0)return null;let n=new Map;t.forEach(l=>{let r=n.get(l.toolName);!r||r.status==="running"&&l.status==="completed"?n.set(l.toolName,{status:l.status||"pending",count:(r?.count||0)+1}):r&&r.count++;});let o=Array.from(n.values()).some(l=>l.status==="running"),a=Array.from(n.values()).filter(l=>l.status==="completed").length;return jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:e.cardBackground,border:`1px solid ${e.borderColor}`,fontSize:"12px",color:e.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:o?"#3b82f6":"#10b981"}}),jsx("span",{children:o?"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(n.entries()).map(([l,r])=>jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:e.inputBackground,border:`1px solid ${e.borderColor}`},children:[r.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:r.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:l}),r.count>1&&jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",r.count]})]},l))})]})}function We({items:t,mcpToolCalls:e,mcpToolResults:n,actionStatuses:o,components:a,theme:l,resolvedColors:r}){return !Array.isArray(t)||t.length===0?null:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.map((s,f)=>{let x=`it-${f}`;if(typeof s=="string")return jsx("div",{style:{padding:"0",color:r.textColor},children:jsx(ht,{content:s,theme:l})},x);if(s&&typeof s=="object"){if(s.type==="action"){let h=`${String(s.name??"action")}:${f}`,i=o.get(h);return jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsx("div",{style:{padding:"8px",fontSize:"12px",color:r.mutedTextColor},children:i==="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(s.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(s.name??"action")," has executed"]})})},x)}if(s.type==="ui"){let h=String(s.component??"").trim(),i=h?a.get(h):void 0;return i?jsx("div",{style:{padding:"0"},children:jsx(i,{...s.props||{}})},x):jsxs("div",{style:{padding:"0"},children:[jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:r.mutedTextColor},children:[jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:r.accentColor,border:`1px solid ${r.borderColor}`},children:"UI"}),jsx("span",{children:h||"component"}),jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(s.props??{},null,2)})]},x)}let m=s.text||s.content||s.message;return typeof m=="string"?jsx("div",{style:{padding:"0",color:r.textColor},children:jsx(ht,{content:m,theme:l})},x):jsx("div",{style:{padding:"0",fontSize:"14px"},children:jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:r.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(s,null,2)})},x)}return null}),jsx(Ne,{mcpToolCalls:e,resolvedColors:r})]})}function Oe({message:t,streaming:e,isLastMessage:n,actionStatuses:o,components:a,theme:l,resolvedColors:r,onToggleReasoning:s,hideReasoningContent:f=false}){let x=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:r.textColor,lineHeight:"1.5"},children:t.firstAgentMessage})}),x?jsx(Pe,{mainAgentActions:t.mainAgentActions,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>s(t.id),resolvedColors:r,streaming:e&&n,theme:l,hideReasoningContent:f}):jsx(Ee,{reasoning:t.reasoning,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>s(t.id),resolvedColors:r}),jsx(We,{items:t.items,mcpToolCalls:t.mcpToolCalls,mcpToolResults:t.mcpToolResults,actionStatuses:o,components:a,theme:l,resolvedColors:r}),e&&n&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:r.mutedTextColor},children:[jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsx("span",{children:"Working\u2026"})]})]})}function Ue({messages:t,streaming:e,editingMessageId:n,editingMessageText:o,editingAttachments:a,error:l,actionStatuses:r,components:s,theme:f,resolvedColors:x,onEditingTextChange:m,onRemoveAttachment:h,onAddAttachments:i,uploading:g,onStartEdit:d,onCancelEdit:b,onSaveEdit:y,onToggleReasoning:p,scrollAnchorRef:I,hideReasoningContent:M=false,t:k}){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:[l&&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:l}),t.length===0&&!e&&jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${x.borderColor}`,backgroundColor:x.accentColor,color:x.mutedTextColor},children:k("messages.empty")}),jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:t.map((u,C)=>jsx("div",{style:{padding:"0 4px"},children:u.role==="user"?jsx(Fe,{message:u,isEditing:n===u.id,editingText:o,editingAttachments:a,onEditingTextChange:m,onStartEdit:d,onCancelEdit:b,onSaveEdit:y,onRemoveAttachment:h,onAddAttachments:i,uploading:g,streaming:e,resolvedColors:x,t:k}):jsx(Oe,{message:u,streaming:e,isLastMessage:C===t.length-1,actionStatuses:r,components:s,theme:f,resolvedColors:x,onToggleReasoning:p,hideReasoningContent:M})},u.id))}),jsx("div",{ref:I})]})}function je({show:t,onClick:e,resolvedColors:n,floatingButtonPosition:o}){if(!t)return null;let a={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:e,style:{...a,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 No(t=false){let[e,n]=useState(t),o=useCallback(()=>n(r=>!r),[]),a=useCallback(()=>n(true),[]),l=useCallback(()=>n(false),[]);return {on:e,toggle:o,setOn:n,setTrue:a,setFalse:l}}function Oo(){let t=useRef(null);return useEffect(()=>{let e=t.current;if(!e)return;let n=new MutationObserver(()=>{e.scrollTop=e.scrollHeight;});return n.observe(e,{childList:true,subtree:true}),e.scrollTop=e.scrollHeight,()=>n.disconnect()},[]),t}var qe=createContext(void 0);function Qn({baseUrl:t,children:e}){let[n,o]=useState(new Map),[a,l]=useState(new Map),r=useCallback((h,i)=>(o(g=>{let d=new Map(g);return d.set(String(h),i),d}),()=>{o(g=>{let d=new Map(g),b=d.get(String(h));return (!i||b===i)&&d.delete(String(h)),d});}),[]),s=useCallback((h,i)=>{o(g=>{let d=new Map(g),b=d.get(String(h));return (!i||b===i)&&d.delete(String(h)),d});},[]),f=useCallback((h,i)=>(l(g=>{let d=new Map(g);return d.set(String(h),i),d}),()=>{l(g=>{let d=new Map(g),b=d.get(String(h));return (!i||b===i)&&d.delete(String(h)),d});}),[]),x=useCallback((h,i)=>{l(g=>{let d=new Map(g),b=d.get(String(h));return (!i||b===i)&&d.delete(String(h)),d});},[]),m=useMemo(()=>({baseUrl:t,actions:n,components:a,registerAction:r,unregisterAction:s,registerComponent:f,unregisterComponent:x}),[t,n,a,r,s,f,x]);return jsx(qe.Provider,{value:m,children:e})}function ut(){let t=useContext(qe);return t||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{}}}function Zo(t,e){let{registerAction:n}=ut(),o=useRef(e);useEffect(()=>{o.current=e;});let a=useCallback((l,r)=>o.current(l,r),[]);useEffect(()=>{if(!t||typeof e!="function"){console.warn(`[useHsafaAction] Invalid action registration: name="${t}", handler type="${typeof e}"`);return}return n(t,a)},[t,n,a]);}function ta(t,e){let{registerComponent:n}=ut(),o=useRef(e);useEffect(()=>{o.current=e;});let a=useMemo(()=>{let l=r=>{let s=o.current;return Bt.createElement(s,r)};return l.displayName=`HsafaStable(${t})`,l},[]);useEffect(()=>{if(!t||typeof e!="function"){console.warn(`[useHsafaComponent] Invalid component registration: name="${t}", component type="${typeof e}"`);return}return n(t,a)},[t,n,a]);}function Ze(t){let e=`hsafaChat_${t}`,n=`${e}.chats`,o=u=>`${e}.chat.${u}`,a=`${e}.currentChatId`,l=`${e}.showChat`,[r,s]=useState(null),f=useRef(false),x=useRef(null),m=()=>{try{let u=localStorage.getItem(n);return u?JSON.parse(u):[]}catch{return []}},h=u=>{try{localStorage.setItem(n,JSON.stringify(u));}catch{}},i=u=>{try{let C=localStorage.getItem(o(u));return C?JSON.parse(C):null}catch{return null}},g=u=>{try{localStorage.setItem(o(u.id),JSON.stringify(u));}catch{}},d=u=>{let C=m(),T=C.findIndex(F=>F.id===u.id);T>=0?C[T]=u:C.unshift(u),h(C);},b=u=>{let T=m().filter(F=>F.id!==u);h(T);},y=u=>{try{localStorage.removeItem(o(u));}catch{}};return {currentChatId:r,setCurrentChatId:s,hasChatRecordRef:f,pendingFirstTitleRef:x,loadChatsIndex:m,loadChat:i,saveChat:g,deleteChat:(u,C)=>{y(u),b(u);let T=r===u;if(T){s(null),f.current=false,x.current=null;try{localStorage.removeItem(a);}catch{}}C?.(T);},loadChatPreferences:()=>{try{let u=localStorage.getItem(a);if(u){let C=i(u);if(C)return s(C.id),f.current=!0,C.messages||[]}}catch{}return []},persistChatData:u=>{if(!r||!f.current)return;g({id:r,messages:u,agentId:t});let T=u.find(P=>P.role==="user"),F=T?$e(T):"New chat",q=(x.current||F).slice(0,80),S={id:r,title:q,createdAt:Date.now(),updatedAt:Date.now()};d(S);try{localStorage.setItem(a,r);}catch{}},createNewChat:u=>{let C=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;s(C),f.current=true;let T=(u||"New chat").slice(0,80),F=Date.now();d({id:C,title:T,createdAt:F,updatedAt:F});try{localStorage.setItem(a,C);}catch{}return C},upsertChatMeta:d,showChatKey:l}}function Ye(){let[t,e]=useState(false),[n,o]=useState(null),a=useRef(null),l=useRef({}),r=useRef(void 0),s=useRef(new Set),f=useRef(new Map),x=useRef(new Map),[m,h]=useState(new Map),i=useCallback((p,I)=>{let M=f.current.get(p)||[],k=JSON.stringify(I);if(M.push(k),M.length>5&&M.shift(),f.current.set(p,M),M.length>=3){let u=M.slice(-3);return u.every(C=>C===u[0])}return false},[]),g=useCallback((p,I,M,k)=>{!Array.isArray(p)||p.length===0||p.forEach((u,C)=>{if(!(!u||typeof u!="object")&&u.type==="action"){let T=String(u.name??"").trim();if(!T)return;let F=M.get(T);if(!F){console.warn(`Action handler not found for: ${T}`);return}let q=!!l.current[T],S=`${r.current||"assist"}:${T}:${C}`,P=`${T}:${C}`;try{if(I==="partial"&&q){h(L=>new Map(L).set(P,"executing"));let O=setTimeout(()=>{Promise.resolve(F(u.params,{name:T,trigger:I,index:C,assistantMessageId:r.current,chatId:k||void 0})).catch(L=>{console.error(`Error executing streaming action ${T}:`,L),h(z=>new Map(z).set(P,"executed"));});},50);x.current.set(`${P}_timeout`,O);}else if(I==="partial"&&!q){let O=i(P,u.params),L=x.current.get(P);O&&L!=="executed"?(x.current.set(P,"executed"),h(z=>new Map(z).set(P,"executed")),Promise.resolve(F(u.params,{name:T,trigger:"params_complete",index:C,assistantMessageId:r.current,chatId:k||void 0})).catch(z=>{console.error(`Error executing stabilized action ${T}:`,z);})):L||(x.current.set(P,"executing"),h(z=>new Map(z).set(P,"executing")));}else if(I==="final"&&x.current.get(P)!=="executed"&&!s.current.has(S)){s.current.add(S);let L=x.current.get(`${P}_timeout`);L&&(clearTimeout(L),x.current.delete(`${P}_timeout`)),x.current.set(P,"executed"),h(z=>new Map(z).set(P,"executed")),Promise.resolve(F(u.params,{name:T,trigger:q?"final":"params_complete",index:C,assistantMessageId:r.current,chatId:k||void 0})).catch(z=>{console.error(`Error executing final action ${T}:`,z);});}}catch(O){console.error(`Error processing action ${T}:`,O);}}});},[i]),d=useCallback(()=>{a.current&&(a.current.abort(),a.current=null),e(false),o("Request stopped by user");},[]),b=useCallback(()=>{s.current.clear(),f.current.clear(),x.current.clear(),h(new Map);},[]),y=useCallback(()=>{x.current.forEach((p,I)=>{I.endsWith("_timeout")&&clearTimeout(p);});},[]);return {streaming:t,setStreaming:e,error:n,setError:o,actionStatuses:m,setActionStatuses:h,abortControllerRef:a,actionExecMapRef:l,assistantMsgIdRef:r,calledFinalActionsRef:s,actionParamsHistoryRef:f,actionExecutionStatusRef:x,processActions:g,handleStop:d,resetActionTracking:b,cleanupTimeouts:y,hasActionParamsStabilized:i}}function Ge(t,e){if(!t)return e;let n=t.endsWith("/")?t.slice(0,-1):t,o=e.startsWith("/")?e:`/${e}`;return `${n}${o}`}var re=25*1024*1024;function tn(t){let[e,n]=useState([]),[o,a]=useState(false),l=useRef(null),r=useCallback(i=>{if(!i||Number.isNaN(i))return "0 B";let g=["B","KB","MB","GB","TB"],d=Math.min(g.length-1,Math.floor(Math.log(i)/Math.log(1024)));return `${(i/Math.pow(1024,d)).toFixed(d===0?0:1)} ${g[d]}`},[]),s=useCallback(async i=>{let g=new FormData;g.append("file",i);let d=await fetch(Ge(t,"/api/uploads"),{method:"POST",body:g});if(!d.ok){let y=await d.text().catch(()=>"");throw new Error(y||`Failed to upload ${i.name}`)}let b=await d.json();return {id:b.id,name:b.name||i.name,url:b.url,mimeType:b.mimeType||i.type||"application/octet-stream",size:typeof b.size=="number"?b.size:i.size}},[t]),f=useCallback(i=>{n(g=>g.filter(d=>d.id!==i));},[]),x=useCallback(async(i,g)=>{if(!i)return;let d=Array.isArray(i)?i:Array.from(i);g(null),a(true);let b=[];try{for(let y of d){if(y.size>re){g(`"${y.name}" exceeds the ${r(re)} limit.`);continue}try{let p=await s(y);b.push(p);}catch(p){console.error("Failed to upload attachment:",p),g(String(p?.message??`Failed to upload ${y.name}`));}}b.length&&n(y=>[...y,...b]);}finally{a(false);}},[s,r]),m=useCallback((i,g)=>{let d=[],b=(i||"").trim();b&&d.push({type:"text",text:b});for(let y of g||[]){let p=y.mimeType||"application/octet-stream";p.startsWith("image/")?d.push({type:"image",image:new URL(y.url),mediaType:p}):d.push({type:"file",data:y.url,mediaType:p,name:y.name});}return d},[]),h=useCallback(()=>{n([]);},[]);return {attachments:e,uploading:o,fileInputRef:l,formatBytes:r,handleRemoveAttachment:f,handleFileSelection:x,buildUserContent:m,clearAttachments:h,MAX_UPLOAD_SIZE:re}}function cr(t){return JSON.parse(JSON.stringify(t))}function en(){let[t,e]=useState(false),[n,o]=useState(null),[a,l]=useState(null),r=useRef(null),s=useCallback(async({agentId:m,body:h,baseUrl:i,onUpdate:g,signal:d})=>{try{let S=function(){let z=cr(k);l(z),g?.(z);};var b=S;e(!0),o(null);let y;if(d)r.current=null,y=d;else {let z=new AbortController;r.current=z,y=z.signal;}let I=`${i?i.replace(/\/$/,""):""}/api/run/${encodeURIComponent(m)}`,M=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(h??{}),signal:y});if(!M.ok||!M.body){let z=await M.text().catch(()=>"");throw new Error(`Request failed: ${M.status} ${M.statusText} - ${z}`)}let k={first_agent:{message:"",continue:!1},main_agent:[]},u=null,C=null,T=null,F=null,q=!1,P=M.body.getReader(),O=new TextDecoder("utf-8"),L="";for(S();;){let{value:z,done:rt}=await P.read();if(rt)break;L+=O.decode(z,{stream:!0});let mt=L.indexOf(`
15
+ `);for(;mt!==-1;){let it=L.slice(0,mt).trim();if(L=L.slice(mt+1),it.length>0)try{let c=JSON.parse(it);switch(c?.type){case "start":break;case "first-agent-start":k.first_agent.startDate=c?.startDate,k.first_agent.durationMs=c?.durationMs,S();break;case "first-agent-partial":typeof c?.message=="string"&&(k.first_agent.message=c.message),typeof c?.continue=="boolean"&&(k.first_agent.continue=c.continue),typeof c?.durationMs=="number"&&(k.first_agent.durationMs=c.durationMs),S();break;case "first-agent-end":typeof c?.message=="string"&&(k.first_agent.message=c.message),typeof c?.continue=="boolean"&&(k.first_agent.continue=c.continue),k.first_agent.endDate=c?.endDate,k.first_agent.durationMs=c?.durationMs,S();break;case "main-agent-start":q=!1;break;case "main-agent-step-finish":{let w={type:"step",stepNumber:void 0,finishReason:c?.finishReason,usage:c?.usage,endDate:c?.endDate,durationMs:c?.durationMs};k.main_agent.push(w),S();break}case "main-agent-skipped":q=!0;break;case "main-agent-reasoning-start":u={type:"reasoning",reasoning:"",status:"streaming",startDate:c?.startDate,durationMs:c?.durationMs},k.main_agent.push(u),S();break;case "main-agent-reasoning-delta":u&&typeof c?.text=="string"&&(u.reasoning+=c.text,u.durationMs=c?.durationMs,S());break;case "main-agent-reasoning-end":if(u){if(typeof c?.text=="string"&&c.text.length>0&&(u.reasoning+=c.text),u.status="finished",u.endDate=c?.endDate,u.durationMs=c?.durationMs,!u.reasoning||u.reasoning.trim().length===0){let w=k.main_agent.indexOf(u);w>-1&&k.main_agent.splice(w,1);}u=null,S();}else if(typeof c?.text=="string"&&c.text.length>0){let w={type:"reasoning",reasoning:c.text,status:"finished",endDate:c?.endDate,durationMs:c?.durationMs};k.main_agent.push(w),S();}break;case "main-agent-tool-call-start":C={type:"tool-call",toolCallId:c?.toolCallId,toolName:c?.toolName,inputText:"",input:void 0,output:void 0,status:"input_streaming",startDate:c?.startDate,durationMs:c?.durationMs},k.main_agent.push(C),S();break;case "main-agent-tool-input-delta":let $t=c?.delta||c?.argsTextDelta;C&&typeof $t=="string"&&(C.inputText=(C.inputText||"")+$t,C.durationMs=c?.durationMs,S());break;case "tool-call":case "main-agent-tool-call":if(C)C.input=c?.input,C.status="running",C.durationMs=c?.durationMs;else {let w=k.main_agent.find(kt=>kt.type==="tool-call"&&(kt.toolCallId===c?.toolCallId||kt.toolName===c?.toolName));w?(w.input=c?.input,w.status="running",w.durationMs=c?.durationMs,C=w):(C={type:"tool-call",toolCallId:c?.toolCallId,toolName:c?.toolName,input:c?.input,inputText:"",output:void 0,status:"running",durationMs:c?.durationMs},k.main_agent.push(C));}S();break;case "tool-result":case "main-agent-tool-result":let Q=C;if(Q||(Q=k.main_agent.find(w=>w.type==="tool-call"&&(w.toolCallId===c?.toolCallId||w.toolName===c?.toolName))||null),Q)Q.output=c?.output,Q.status="finished",Q.endDate=c?.endDate,Q.durationMs=c?.durationMs,C=null;else {let w={type:"tool-call",toolCallId:c?.toolCallId,toolName:c?.toolName,input:void 0,inputText:"",output:c?.output,status:"finished",endDate:c?.endDate,durationMs:c?.durationMs};k.main_agent.push(w);}S();break;case "tool-error":case "main-agent-tool-error":let Y=C;if(Y||(Y=k.main_agent.find(w=>w.type==="tool-call"&&(w.toolCallId===c?.toolCallId||w.toolName===c?.toolName))||null),Y)Y.error=c?.error,Y.status="error",Y.endDate=c?.endDate,Y.durationMs=c?.durationMs,C=null;else {let w={type:"tool-call",toolCallId:c?.toolCallId,toolName:c?.toolName,input:void 0,inputText:"",output:void 0,error:c?.error,status:"error",endDate:c?.endDate,durationMs:c?.durationMs};k.main_agent.push(w);}S();break;case "main-agent-response-partial":if(q)break;if(T||(T={type:"response",items:[],startDate:c?.startDate,durationMs:c?.durationMs},k.main_agent.push(T)),c?.value&&typeof c.value=="object"){let w=Array.isArray(c.value.items)?c.value.items:T.items;Object.assign(T,c.value),T.items=w,T.durationMs=c?.durationMs;}S();break;case "text-delta":case "main-agent-text-delta":typeof c?.text=="string"&&c.text&&(F||(F={type:"text",text:"",status:"streaming",startDate:c?.startDate,durationMs:c?.durationMs},k.main_agent.push(F)),F.text+=c.text,F.durationMs=c?.durationMs,S());break;case "text-end":F&&(F.status="finished",F.endDate=c?.endDate,F.durationMs=c?.durationMs,F=null,S());break;case "source":case "main-agent-source":let Ct={type:"source",source:c?.source,durationMs:c?.durationMs};k.main_agent.push(Ct),S();break;case "file":case "main-agent-file":let X={type:"file",file:c?.file,durationMs:c?.durationMs};k.main_agent.push(X),S();break;case "final":if(q)break;if(c?.value&&typeof c.value=="object"){T||(T={type:"response",items:[],endDate:c?.endDate,durationMs:c?.durationMs},k.main_agent.push(T));let w=Array.isArray(c.value.items)?c.value.items:T.items;Object.assign(T,c.value),T.items=w,T.endDate=c?.endDate,T.durationMs=c?.durationMs;}S();break;case "error":case "main-agent-error":throw new Error(c?.error||"Unknown agent error");default:break}}catch(c){console.warn("Failed to parse streaming line:",c);}mt=L.indexOf(`
16
+ `);}}try{P.releaseLock();}catch{}return e(!1),k}catch(y){return y.name==="AbortError"?o("Request was cancelled"):o(y?.message||"Request failed"),e(false),null}},[]),f=useCallback(()=>{r.current&&(r.current.abort(),r.current=null),e(false);},[]),x=useCallback(()=>{l(null),o(null),e(false);},[]);return {streaming:t,error:n,streamData:a,startStreaming:s,stopStreaming:f,reset:x}}var nn={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 rn(t,e){return nn[t]?.[e]||nn.en[e]||e}function on(t="en"){return {t:useCallback(n=>rn(t,n),[t]),language:t}}function sn({title:t,expandable:e,alwaysOpen:n,maximized:o,streaming:a,dir:l,resolvedColors:r,onMaximize:s,onNew:f,onToggleHistory:x,onClose:m,historyBtnRef:h,t:i}){return jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:l==="rtl"?"rtl":"ltr"},children:[jsx("div",{style:{minWidth:"0"},children:jsx("h1",{title:t,style:{color:r.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:r.mutedTextColor},children:[e&&jsx("button",{"aria-label":i(o?"header.minimize":"header.maximize"),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:g=>{g.currentTarget.style.backgroundColor=r.hoverBackground,g.currentTarget.style.color=r.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=r.mutedTextColor;},onClick:s,children:jsx(Maximize2,{size:"20",strokeWidth:"2"})}),jsx("button",{"aria-label":i("header.new"),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:g=>{g.currentTarget.style.backgroundColor=r.hoverBackground,g.currentTarget.style.color=r.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=r.mutedTextColor;},onClick:()=>{a||f();},children:jsx(Plus,{size:"20",strokeWidth:"2"})}),jsx("button",{"aria-label":i("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:g=>{g.currentTarget.style.backgroundColor=r.hoverBackground,g.currentTarget.style.color=r.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=r.mutedTextColor;},onClick:x,ref:h,children:jsx(History,{size:"20",strokeWidth:"2"})}),!n&&jsx("button",{"aria-label":i("header.close"),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:g=>{g.currentTarget.style.backgroundColor=r.hoverBackground,g.currentTarget.style.color=r.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=r.mutedTextColor;},onClick:m,children:jsx(ChevronRight,{size:"20",strokeWidth:"2",style:{transform:l==="rtl"?"rotate(180deg)":"none"}})})]})]})}function ln({value:t,onChange:e,onSend:n,onStop:o,streaming:a,placeholder:l,attachments:r,uploading:s,onRemoveAttachment:f,onFileInputClick:x,resolvedColors:m,formatBytes:h,textareaRef:i,fileInputRef:g,onFileSelection:d,t:b,dir:y="ltr"}){return Bt.useEffect(()=>{let p=i.current;if(p){p.style.height="auto";let I=Math.min(p.scrollHeight,200);p.style.height=`${I}px`;}},[t,i]),jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:m.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 ${m.borderColor}`,backgroundColor:m.accentColor},children:[r.length>0&&jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:r.map(p=>{let I=p.mimeType?.startsWith("image/");return jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:m.inputBackground,borderRadius:"10px",border:`1px solid ${m.borderColor}`,fontSize:"12px",color:m.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:I?"transparent":m.accentColor},children:[I?jsx("img",{src:p.url,alt:p.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:M=>{M.target.style.display="none";let k=M.target.nextElementSibling;k&&(k.style.display="block");}}):null,jsx(File,{size:"14",strokeWidth:"2",style:{display:I?"none":"block",color:m.mutedTextColor}})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsx("span",{title:p.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:p.name}),jsx("span",{style:{color:m.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:h(p.size)})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[I&&jsx("button",{onClick:M=>{M.stopPropagation(),window.open(p.url,"_blank");},style:{background:"none",border:"none",color:m.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:b("input.previewImage"),onMouseEnter:M=>{M.currentTarget.style.backgroundColor=m.hoverBackground,M.currentTarget.style.color=m.textColor;},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="transparent",M.currentTarget.style.color=m.mutedTextColor;},children:jsx(Eye,{size:"12",strokeWidth:"2"})}),jsx("button",{onClick:M=>{M.stopPropagation(),f(p.id);},style:{background:"none",border:"none",color:m.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:b("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=m.mutedTextColor;},children:jsx(X,{size:"12",strokeWidth:"2"})})]})]},p.id)})}),s&&jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:m.mutedTextColor},children:[jsx(Loader2,{size:"14",strokeWidth:"2",style:{animation:"spin 1s linear infinite"}}),jsx("span",{children:b("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:m.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:l,value:t,onChange:p=>e(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),a||n());},ref:i})}),jsxs("div",{style:{position:"absolute",bottom:"8px",...y==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:m.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:p=>{p.currentTarget.style.backgroundColor=`${m.backgroundColor}99`,p.currentTarget.style.color=m.textColor;},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=m.mutedTextColor;},"aria-label":b("input.attachFiles"),onClick:x,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:p=>{p.currentTarget.style.backgroundColor=`${m.backgroundColor}99`,p.currentTarget.style.color=m.textColor;},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=m.mutedTextColor;},"aria-label":b("input.insertLink"),children:jsx(Link,{size:"18",strokeWidth:"2"})})]}),jsx("input",{type:"file",ref:g,multiple:true,accept:"*/*",style:{display:"none"},onChange:p=>d(p.target.files)}),jsx("div",{style:{position:"absolute",bottom:"8px",...y==="rtl"?{left:"8px"}:{right:"8px"}},children:jsx("button",{"aria-label":b(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":m.borderColor}`,backgroundColor:a?"#ef444420":m.cardBackground,color:a?"#ef4444":m.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{p.currentTarget.disabled||(a?(p.currentTarget.style.borderColor="#dc2626",p.currentTarget.style.backgroundColor="#dc262630",p.currentTarget.style.color="#dc2626"):(p.currentTarget.style.borderColor=m.primaryColor,p.currentTarget.style.backgroundColor=m.hoverBackground,p.currentTarget.style.color=m.textColor));},onMouseLeave:p=>{p.currentTarget.disabled||(a?(p.currentTarget.style.borderColor="#ef4444",p.currentTarget.style.backgroundColor="#ef444420",p.currentTarget.style.color="#ef4444"):(p.currentTarget.style.borderColor=m.borderColor,p.currentTarget.style.backgroundColor=m.cardBackground,p.currentTarget.style.color=m.mutedTextColor));},onClick:()=>{a?o():n();},children:a?jsx(Square,{size:"18",strokeWidth:"2"}):jsx(ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function cn(t){let e=Date.now()-t,n=Math.max(1,Math.floor(e/1e3));if(n<60)return `${n}s`;let o=Math.floor(n/60);if(o<60)return `${o}m`;let a=Math.floor(o/60);if(a<24)return `${a}h`;let l=Math.floor(a/24);if(l<7)return `${l}d`;let r=Math.floor(l/7);if(r<4)return `${r}w`;let s=Math.floor(l/30);return s<12?`${s}mo`:`${Math.floor(s/12)}y`}function dn({isOpen:t,onClose:e,searchQuery:n,onSearchChange:o,chats:a,currentChatId:l,onChatSelect:r,onChatDelete:s,resolvedColors:f,t:x}){if(!t)return null;let m=n.trim()?a.filter(i=>(i.title||"").toLowerCase().includes(n.toLowerCase().trim())):a,h=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:e}),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:n,onChange:i=>o(i.target.value),placeholder:x("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:i=>i.currentTarget.style.borderColor=f.primaryColor,onBlur:i=>i.currentTarget.style.borderColor=f.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:m.length===0?jsx("div",{style:{padding:"24px",color:f.mutedTextColor,textAlign:"center"},children:x("history.noChatsFound")}):jsx("div",{children:m.map((i,g)=>jsx("div",{style:{borderTop:g>0?`1px solid ${f.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:i.id===l?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:d=>d.currentTarget.style.backgroundColor=f.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor="transparent",onClick:()=>r(i.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:i.title||x("history.untitledChat")})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:f.mutedTextColor},children:cn(i.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:x("history.deleteChat"),onMouseEnter:d=>{d.currentTarget.style.color="#ef4444",d.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",d.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:d=>{d.currentTarget.style.color=f.mutedTextColor,d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.borderColor="transparent";},onClick:d=>{d.stopPropagation(),s(i.id);},children:jsx(Trash2,{size:"16",strokeWidth:"2"})})]})},i.id))})})]})]});return typeof document<"u"&&document.body?createPortal(h,document.body):h}var pn={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 un=createContext(null),ie=t=>t.map(e=>({...e}));function Ir(t,e){let n=Se(t);return n.push({role:"user",content:e.content}),n}function Fr(t){let[e,n]=useState(()=>{try{return t.loadChatPreferences()}catch(r){return console.warn("Failed to load chat preferences:",r),[]}});useEffect(()=>{if(e.length!==0)try{t.persistChatData(e);}catch(r){console.warn("Failed to persist chat data:",r);}},[e]);let o=useCallback(r=>{try{t.setCurrentChatId(r);let s=t.loadChat(r);return n(s?.messages||[]),!0}catch(s){return console.warn("Failed to load selected chat:",s),false}},[t]),a=useCallback(r=>{try{t.deleteChat(r,s=>{s&&n([]);});}catch(s){console.warn("Failed to delete chat:",s);}},[t]),l=useCallback(()=>{n([]),t.setCurrentChatId(null);},[t]);return {messages:e,setMessages:n,selectChat:o,deleteChat:a,resetChat:l}}function Dr(t){let{agentId:e,children:n,theme:o="dark",primaryColor:a,backgroundColor:l,borderColor:r,textColor:s,accentColor:f,width:x=420,height:m="100vh",expandable:h=true,alwaysOpen:i=false,defaultOpen:g=true,dir:d="ltr",language:b,floatingButtonPosition:y=d==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},enableBorderAnimation:p=true,enableContentPadding:I=true,borderRadius:M=16,enableContentBorder:k=true,placeholder:u,title:C,className:T="",chatContainerClassName:F="",defaultReasoningOpen:q=false,hideReasoningContent:S=false}=t,P=b||(d==="rtl"?"ar":"en"),{t:O}=on(P),L=u??O("input.placeholder"),z=C??O("general.agent"),{baseUrl:rt,components:mt}=ut(),it=useContext(un),[c,_t]=useState(false);useEffect(()=>{if(it)return it.registerNestedChat(),()=>it.unregisterNestedChat()},[it]);let $t={registerNestedChat:()=>_t(true),unregisterNestedChat:()=>_t(false)},Q=!c,[Y,Ct]=useState(""),[X,w]=useState(()=>{if(i)return true;try{let v=localStorage.getItem(`hsafaChat_${e}.showChat`);return v!==null?v==="true":g}catch{return g}}),[kt,It]=useState(false),[gn,Ot]=useState(""),[Ut,mn]=useState(false),[zr,fn]=useState(0),[hn,jt]=useState(null),[yn,le]=useState(""),[ce,Tt]=useState([]),de=useRef(null),[pe,ue]=useState(true),Kt=useRef(false),xn=useRef(null),bn=useRef(null),ge=useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),st=Ze(e),{messages:ot,setMessages:Mt,selectChat:me,deleteChat:fe,resetChat:Cn}=Fr(st),H=Ye(),vt=tn(rt||""),he=en(),{attachments:qt,uploading:ye,fileInputRef:xe,formatBytes:kn,handleRemoveAttachment:Tn,handleFileSelection:Mn,clearAttachments:be}=vt,Ce=useCallback((v,R)=>{Mt(B=>B.map(A=>{if(A.id===v&&A.role==="assistant"){let D=R.main_agent.find(U=>U.type==="response"),_=D?.type==="response"?D.items:[];return {...A,items:_,mainAgentActions:R.main_agent,firstAgentMessage:R.first_agent.message,firstAgentContinue:R.first_agent.continue,reasoningOpen:A.reasoningOpen}}return A}));},[]),Vt=useCallback(async({prompt:v,baseMessages:R,userMessage:B,assistantMessageId:A,chatId:D})=>{if(e){H.setError(null),H.setStreaming(true);try{let _=Ir(R,B);await he.startStreaming({agentId:e,baseUrl:rt,body:{prompt:v,chatId:D??void 0,messages:_},onUpdate:U=>Ce(A,U)});}catch(_){H.setError(_?.message||"Request failed");}finally{H.setStreaming(false);}}},[e,rt,he,H,Ce]),vn=useCallback(v=>{me(v)&&(It(false),Ot(""));},[me,It,Ot]),An=useCallback(v=>{fe(v),fn(R=>R+1);},[fe]),tt=pn[o],N={primaryColor:a||tt.primaryColor,backgroundColor:l||tt.backgroundColor,borderColor:r||tt.borderColor,textColor:s||tt.textColor,accentColor:f||tt.accentColor,mutedTextColor:tt.mutedTextColor,inputBackground:tt.inputBackground,cardBackground:tt.cardBackground,hoverBackground:tt.hoverBackground},Xt=typeof M=="number"?`${M}px`:M,wn=useCallback(async()=>{if(!e)return;let v=Y.trim();if(!v)return;let R=st.currentChatId;R||(R=st.createNewChat(v));let B=ie(qt),A=we(v,B),D=Qt(q),_=ot;Mt([..._,A,D]),Ct(""),be(),ue(true),await Vt({prompt:v,baseMessages:_,userMessage:A,assistantMessageId:D.id,chatId:R});},[e,Y,ot,qt,be,Vt,st,Mt,Ct]),Sn=useCallback(async v=>{if(!v||!rt)return;let R=Array.from(v);H.setError(null);let B=[];try{for(let A of R){if(A.size>vt.MAX_UPLOAD_SIZE){H.setError(`"${A.name}" exceeds the ${vt.formatBytes(vt.MAX_UPLOAD_SIZE)} limit.`);continue}try{let D=new FormData;D.append("file",A);let _=await fetch(`${rt}/api/uploads`,{method:"POST",body:D});if(!_.ok){let Jt=await _.text().catch(()=>"");throw new Error(Jt||`Failed to upload ${A.name}`)}let U=await _.json(),Ft={id:U.id,name:U.name||A.name,url:U.url,mimeType:U.mimeType||A.type||"application/octet-stream",size:typeof U.size=="number"?U.size:A.size};B.push(Ft);}catch(D){console.error("Failed to upload attachment:",D),H.setError(String(D?.message??`Failed to upload ${A.name}`));}}B.length&&Tt(A=>[...A,...B]);}catch(A){console.error("Error adding attachments during edit:",A);}},[rt,vt,H]);useEffect(()=>{if(Kt.current){Kt.current=false;return}pe&&requestAnimationFrame(()=>{de.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[ot,H.streaming,pe]),useEffect(()=>{let v=document.querySelector(".chat-scroll-container");if(!v)return;let R=()=>{let{scrollTop:B,scrollHeight:A,clientHeight:D}=v,U=A-B-D<40;ue(U);};return v.addEventListener("scroll",R),R(),()=>v.removeEventListener("scroll",R)},[]);let Rn={backgroundColor:N.backgroundColor,color:N.textColor,height:m,display:"flex",width:"100%",fontFamily:"Rubik, ui-sans-serif, system-ui, sans-serif"},$n=Q&&typeof document<"u"?createPortal(jsxs(Fragment,{children:[jsxs("div",{className:F,style:{width:X?Ut?"100%":typeof x=="number"?`${x}px`:x:"0",height:m,display:"flex",flexDirection:"column",backgroundColor:X?N.backgroundColor:"transparent",opacity:X?1:0,padding:X?"24px 16px":"0",transition:"all 0.3s ease-out",position:"fixed",top:0,...d==="rtl"?{left:0}:{right:0},bottom:0,zIndex:Ut?9999:1e3,pointerEvents:X?"auto":"none"},children:[jsx(sn,{title:z,expandable:h,alwaysOpen:i,maximized:Ut,streaming:H.streaming,dir:d,resolvedColors:N,onMaximize:()=>mn(v=>!v),onNew:Cn,onToggleHistory:()=>It(v=>!v),onClose:()=>w(false),historyBtnRef:bn,t:O}),jsx(Ue,{messages:ot,streaming:H.streaming,editingMessageId:hn,editingMessageText:yn,editingAttachments:ce,error:H.error,actionStatuses:H.actionStatuses,components:mt,theme:o,resolvedColors:N,hideReasoningContent:S,onEditingTextChange:le,onRemoveAttachment:v=>{Tt(R=>R.filter(B=>B.id!==v));},onAddAttachments:Sn,uploading:ye,onStartEdit:(v,R)=>{let B=ot.find(A=>A.id===v);jt(v),le(R),B&&B.role==="user"&&Tt(ie(ft(B)));},onCancelEdit:()=>{jt(null),Tt([]);},onSaveEdit:async(v,R)=>{let B=ot.findIndex(Jt=>Jt.id===v);if(B===-1)return;let A=ot[B];if(A.role!=="user")return;let D=R.trim(),_=Re(A,D,ie(ce)),U=ot.slice(0,B),Ft=Qt(q);Mt([...U,_,Ft]),jt(null),Tt([]),await Vt({prompt:D,baseMessages:U,userMessage:_,assistantMessageId:Ft.id,chatId:st.currentChatId??null});},onToggleReasoning:v=>{let R=document.querySelector(".chat-scroll-container"),B=R?.scrollTop||0;Kt.current=true,Mt(A=>A.map(D=>D.id===v&&D.role==="assistant"?{...D,reasoningOpen:!D.reasoningOpen}:D)),requestAnimationFrame(()=>{R&&(R.scrollTop=B);});},scrollAnchorRef:de,t:O}),jsx(ln,{value:Y,onChange:Ct,onSend:wn,onStop:H.handleStop,streaming:H.streaming,placeholder:L,attachments:qt,uploading:ye,onRemoveAttachment:Tn,onFileInputClick:()=>xe.current?.click(),resolvedColors:N,formatBytes:kn,textareaRef:xn,fileInputRef:xe,onFileSelection:v=>Mn(v,H.setError),t:O,dir:d})]}),jsx(je,{show:!X&&!i,onClick:()=>w(true),resolvedColors:N,floatingButtonPosition:y}),jsx(dn,{isOpen:kt,onClose:()=>It(false),searchQuery:gn,onSearchChange:Ot,chats:st.loadChatsIndex(),currentChatId:st.currentChatId,onChatSelect:vn,onChatDelete:An,resolvedColors:N,t:O}),jsx("style",{children:`
17
+ @keyframes ${ge.current}-border-flow {
9
18
  0% { background-position: 0% 50%; }
10
19
  50% { background-position: 100% 50%; }
11
20
  100% { background-position: 0% 50%; }
@@ -20,68 +29,5 @@ import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createContext,useState
20
29
  from { transform: rotate(0deg); }
21
30
  to { transform: rotate(360deg); }
22
31
  }
23
-
24
- /* Scoped placeholder styles */
25
- [data-hsafa-chat="${H.current}"] textarea::placeholder {
26
- color: ${t.mutedTextColor};
27
- }
28
-
29
- /* Ensure textarea styles work in all environments */
30
- [data-hsafa-chat="${H.current}"] textarea {
31
- background: transparent !important;
32
- border: none !important;
33
- outline: none !important;
34
- resize: none !important;
35
- font-family: inherit !important;
36
- }
37
-
38
- /* Custom scrollbar styles for content container */
39
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar {
40
- width: 6px;
41
- }
42
-
43
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar-track {
44
- background: transparent;
45
- border-radius: 3px;
46
- }
47
-
48
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar-thumb {
49
- background: ${t.mutedTextColor}40;
50
- border-radius: 3px;
51
- border: 1px solid transparent;
52
- }
53
-
54
- [data-hsafa-chat="${H.current}"] .content-container::-webkit-scrollbar-thumb:hover {
55
- background: ${t.mutedTextColor}60;
56
- }
57
-
58
- /* Chat scrollbar styles */
59
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar {
60
- width: 4px;
61
- }
62
-
63
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar-track {
64
- background: transparent;
65
- }
66
-
67
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar-thumb {
68
- background: ${t.borderColor};
69
- border-radius: 2px;
70
- }
71
-
72
- [data-hsafa-chat="${H.current}"] .chat-scroll-container::-webkit-scrollbar-thumb:hover {
73
- background: ${t.mutedTextColor};
74
- }
75
-
76
- /* Ensure all fixed positioned elements stay within content box */
77
- [data-hsafa-chat="${H.current}"] * {
78
- /* Prevent any child from breaking out of the content container */
79
- }
80
-
81
- /* Force fixed elements to be contained within the content box */
82
- [data-hsafa-chat="${H.current}"] .content-container * {
83
- /* Any fixed, absolute, or sticky elements will be contained */
84
- max-width: 100% !important;
85
- }
86
- `})]})}export{tr as Button,Yt as HsafaChat,zt as HsafaProvider,lr as useAutoScroll,re as useHsafa,yr as useHsafaAction,Cr as useHsafaComponent,ar as useToggle};//# sourceMappingURL=index.js.map
32
+ `})]}),document.body):null;return jsxs(un.Provider,{value:$t,children:[jsx("div",{className:T,style:Rn,dir:d,children:jsx("div",{style:{display:"flex",width:X?`calc(100% - ${typeof x=="number"?x:420}px)`:"100%",height:"100%",transition:"all 0.3s ease-out",padding:X&&I?"16px":"0"},children:jsx("div",{style:{position:"relative",display:"flex",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:X&&k?Xt:"0"},children:X&&k?jsx("div",{style:{width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Xt,border:H.streaming&&p?"none":`1px solid ${N.borderColor}`,padding:H.streaming&&p?"1.5px":"0",background:H.streaming&&p?`linear-gradient(120deg, ${N.primaryColor}dd 0%, ${N.primaryColor}88 25%, ${N.primaryColor}00 50%, ${N.primaryColor}88 75%, ${N.primaryColor}dd 100%)`:"transparent",backgroundSize:H.streaming&&p?"300% 300%":"auto",animation:H.streaming&&p?`${ge.current}-border-flow 3s ease-in-out infinite`:"none",filter:H.streaming&&p?`drop-shadow(0 0 10px ${N.primaryColor}40)`:"none"},children:jsx("div",{className:"content-container",style:{width:"100%",height:"100%",borderRadius:Xt,backgroundColor:N.backgroundColor,overflowX:"hidden",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${N.mutedTextColor}40 transparent`},children:n})}):jsx("div",{className:"content-container",style:{width:"100%",height:"100%",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",overflowX:"hidden",scrollbarWidth:"thin",scrollbarColor:`${N.mutedTextColor}40 transparent`},children:n})})})}),$n]})}export{Pr as Button,je as FloatingChatButton,Dr as HsafaChat,Qn as HsafaProvider,Ue as MessageList,en as useAgentStreaming,Oo as useAutoScroll,Ze as useChatStorage,tn as useFileUpload,ut as useHsafa,Zo as useHsafaAction,ta as useHsafaComponent,Ye as useStreaming,No as useToggle};//# sourceMappingURL=index.js.map
87
33
  //# sourceMappingURL=index.js.map