@hsafa/ui-sdk 0.2.4 → 0.2.5

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.cjs CHANGED
@@ -13,7 +13,7 @@
13
13
  }
14
14
  `})]})}function Gn(t){return t.reduce((n,e)=>"startDate"in e&&"endDate"in e&&e.startDate&&e.endDate?n+(e.endDate-e.startDate):n,0)}function Ne(t){if(t<1e3)return `${Math.round(t)}ms`;if(t<6e4)return `${(t/1e3).toFixed(1)}s`;let n=Math.floor(t/6e4),e=Math.round(t%6e4/1e3);return `${n}m ${e}s`}function Qn({action:t,resolvedColors:n,theme:e,isFirst:r,isLast:a,hideReasoningContent:s=false}){let o="startDate"in t&&"endDate"in t&&t.startDate&&t.endDate?Ne(t.endDate-t.startDate):null,i=y=>{let l={input_streaming:{color:e==="dark"?"#eab308":"#d97706",text:"Inputting"},running:{color:e==="dark"?"#3b82f6":"#2563eb",text:"Running"},error:{color:e==="dark"?"#ef4444":"#dc2626",text:"Error"},finished:{color:e==="dark"?"#10b981":"#059669",text:"Called"}};return l[y.status]||l.finished},f=y=>jsxRuntime.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",width:"24px",flexShrink:0},children:[jsxRuntime.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:y,marginTop:"6px",zIndex:1}}),jsxRuntime.jsx("div",{style:{position:"absolute",top:"20px",left:"50%",transform:"translateX(-50%)",width:"2px",height:"calc(100% + 4px)",backgroundColor:e==="dark"?n.borderColor:n.mutedTextColor}})]});if(t.type==="reasoning")return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[f(n.borderColor),jsxRuntime.jsxs("div",{style:{flex:1,minWidth:0},children:[jsxRuntime.jsxs("div",{style:{fontSize:"11px",color:n.mutedTextColor,marginBottom:"4px",fontWeight:500,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{children:"Reasoning"}),o&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px"},children:o})]}),!s&&jsxRuntime.jsx("div",{style:{fontSize:"13px",color:n.mutedTextColor,lineHeight:"1.6",maxWidth:"100%",opacity:t.status==="streaming"?.8:1},children:jsxRuntime.jsx(mt,{content:t.reasoning,theme:e})})]})]});if(t.type==="tool-call"){let{color:y,text:l}=i(t);return jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",paddingBottom:a?"0":"16px",position:"relative",marginBottom:"6px"},children:[f(y),jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:n.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsx("span",{style:{fontWeight:500,opacity:e==="dark"?.7:.6},children:l}),jsxRuntime.jsx("span",{style:{fontWeight:500},children:t.toolName||"tool"}),o&&jsxRuntime.jsx("span",{style:{fontFamily:"monospace",fontSize:"10px",opacity:e==="dark"?.5:.6},children:o})]})})]})}return null}function Oe({mcpToolCalls:t,resolvedColors:n}){if(!t||t.length===0)return null;let e=new Map;t.forEach(s=>{let o=e.get(s.toolName);!o||o.status==="running"&&s.status==="completed"?e.set(s.toolName,{status:s.status||"pending",count:(o?.count||0)+1}):o&&o.count++;});let r=Array.from(e.values()).some(s=>s.status==="running"),a=Array.from(e.values()).filter(s=>s.status==="completed").length;return jsxRuntime.jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:n.cardBackground,border:`1px solid ${n.borderColor}`,fontSize:"12px",color:n.mutedTextColor},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:r?"#3b82f6":"#10b981"}}),jsxRuntime.jsx("span",{children:r?"Agent is using tools":a>0?`Agent used ${a} tool${a>1?"s":""}`:"Agent used tools"})]}),jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Array.from(e.entries()).map(([s,o])=>jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:n.inputBackground,border:`1px solid ${n.borderColor}`},children:[o.status==="running"?jsxRuntime.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:[jsxRuntime.jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.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"})]}):jsxRuntime.jsx("span",{style:{display:"inline-block",height:"4px",width:"4px",borderRadius:"50%",backgroundColor:o.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsxRuntime.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:s}),o.count>1&&jsxRuntime.jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",o.count]})]},s))})]})}function Ue({items:t,mcpToolCalls:n,mcpToolResults:e,actionStatuses:r,components:a,theme:s,resolvedColors:o}){return !Array.isArray(t)||t.length===0?null:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.map((i,f)=>{let y=`it-${f}`;if(typeof i=="string")return jsxRuntime.jsx("div",{style:{padding:"0",color:o.textColor},children:jsxRuntime.jsx(mt,{content:i,theme:s})},y);if(i&&typeof i=="object"){if(i.type==="action"){let b=`${String(i.name??"action")}:${f}`,c=r.get(b);return jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:jsxRuntime.jsx("div",{style:{padding:"8px",fontSize:"12px",color:o.mutedTextColor},children:c==="executing"?jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{style:{opacity:.25},cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.jsx("path",{style:{opacity:.75},fill:"currentColor",d:"m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),String(i.name??"action")," is executing"]}):jsxRuntime.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:"#10b981"}}),String(i.name??"action")," has executed"]})})},y)}if(i.type==="ui"){let b=String(i.component??"").trim(),c=b?a.get(b):void 0;return c?jsxRuntime.jsx("div",{style:{padding:"0"},children:jsxRuntime.jsx(c,{...i.props||{}})},y):jsxRuntime.jsxs("div",{style:{padding:"0"},children:[jsxRuntime.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px",fontSize:"12px",marginBottom:"8px",color:o.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",backgroundColor:o.accentColor,border:`1px solid ${o.borderColor}`},children:"UI"}),jsxRuntime.jsx("span",{children:b||"component"}),jsxRuntime.jsx("span",{style:{marginLeft:"8px",opacity:.7},children:"(unregistered)"})]}),jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i.props??{},null,2)})]},y)}let l=i.text||i.content||i.message;return typeof l=="string"?jsxRuntime.jsx("div",{style:{padding:"0",color:o.textColor},children:jsxRuntime.jsx(mt,{content:l,theme:s})},y):jsxRuntime.jsx("div",{style:{padding:"0",fontSize:"14px"},children:jsxRuntime.jsx("pre",{style:{fontSize:"12px",overflow:"auto",color:o.mutedTextColor,margin:"0",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'},children:JSON.stringify(i,null,2)})},y)}return null}),jsxRuntime.jsx(Oe,{mcpToolCalls:n,resolvedColors:o})]})}function je({message:t,streaming:n,isLastMessage:e,actionStatuses:r,components:a,theme:s,resolvedColors:o,onToggleReasoning:i,hideReasoningContent:f=false}){let y=t.mainAgentActions&&t.mainAgentActions.length>0;return jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[t.firstAgentMessage&&jsxRuntime.jsx("div",{style:{padding:"12px 0"},children:jsxRuntime.jsx("div",{style:{fontSize:"13px",color:o.textColor,lineHeight:"1.5"},children:t.firstAgentMessage})}),y?jsxRuntime.jsx(We,{mainAgentActions:t.mainAgentActions,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o,streaming:n&&e,theme:s,hideReasoningContent:f}):jsxRuntime.jsx(He,{reasoning:t.reasoning,reasoningOpen:t.reasoningOpen,onToggleReasoning:()=>i(t.id),resolvedColors:o}),jsxRuntime.jsx(Ue,{items:t.items,mcpToolCalls:t.mcpToolCalls,mcpToolResults:t.mcpToolResults,actionStatuses:r,components:a,theme:s,resolvedColors:o}),n&&e&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:o.mutedTextColor},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"}}),jsxRuntime.jsx("span",{children:"Working\u2026"})]})]})}function qe({messages:t,streaming:n,editingMessageId:e,editingMessageText:r,editingAttachments:a,error:s,actionStatuses:o,components:i,theme:f,resolvedColors:y,onEditingTextChange:l,onRemoveAttachment:b,onAddAttachments:c,uploading:M,onStartEdit:h,onCancelEdit:k,onSaveEdit:x,onToggleReasoning:d,scrollAnchorRef:v,hideReasoningContent:m=false,t:C}){return jsxRuntime.jsxs("div",{className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth"},children:[s&&jsxRuntime.jsx("div",{style:{margin:"0 8px",borderRadius:"12px",backgroundColor:"rgba(239, 68, 68, 0.1)",color:"#fca5a5",border:"1px solid rgba(239, 68, 68, 0.3)",padding:"12px",fontSize:"14px"},children:s}),t.length===0&&!n&&jsxRuntime.jsx("div",{style:{margin:"0 8px",borderRadius:"12px",padding:"16px",border:`1px solid ${y.borderColor}`,backgroundColor:y.accentColor,color:y.mutedTextColor},children:C("messages.empty")}),jsxRuntime.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"16px"},children:t.map((u,g)=>jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:u.role==="user"?jsxRuntime.jsx(ze,{message:u,isEditing:e===u.id,editingText:r,editingAttachments:a,onEditingTextChange:l,onStartEdit:h,onCancelEdit:k,onSaveEdit:x,onRemoveAttachment:b,onAddAttachments:c,uploading:M,streaming:n,resolvedColors:y,t:C}):jsxRuntime.jsx(je,{message:u,streaming:n,isLastMessage:g===t.length-1,actionStatuses:o,components:i,theme:f,resolvedColors:y,onToggleReasoning:d,hideReasoningContent:m})},u.id))}),jsxRuntime.jsx("div",{ref:v})]})}function Je({show:t,onClick:n,resolvedColors:e,floatingButtonPosition:r}){if(!t)return null;let a={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:n,style:{...a,borderColor:e.borderColor,backgroundColor:e.accentColor,color:e.textColor,borderRadius:"50%",border:`1px solid ${e.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:s=>{s.currentTarget.style.borderColor=e.primaryColor,s.currentTarget.style.backgroundColor=`${e.accentColor}dd`;},onMouseLeave:s=>{s.currentTarget.style.borderColor=e.borderColor,s.currentTarget.style.backgroundColor=e.accentColor;},children:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function na(t=false){let[n,e]=Bt.useState(t),r=Bt.useCallback(()=>e(o=>!o),[]),a=Bt.useCallback(()=>e(true),[]),s=Bt.useCallback(()=>e(false),[]);return {on:n,toggle:r,setOn:e,setTrue:a,setFalse:s}}function aa(){let t=Bt.useRef(null);return Bt.useEffect(()=>{let n=t.current;if(!n)return;let e=new MutationObserver(()=>{n.scrollTop=n.scrollHeight;});return e.observe(n,{childList:true,subtree:true}),n.scrollTop=n.scrollHeight,()=>e.disconnect()},[]),t}var Ve=Bt.createContext(void 0);function ir({baseUrl:t,children:n}){let[e,r]=Bt.useState(new Map),[a,s]=Bt.useState(new Map),[o,i]=Bt.useState(new Map),[f,y]=Bt.useState(new Map),l=Bt.useCallback((m,C)=>(r(u=>{let g=new Map(u);return g.set(String(m),C),g}),()=>{r(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});}),[]),b=Bt.useCallback((m,C)=>{r(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});},[]),c=Bt.useCallback((m,C)=>(s(u=>{let g=new Map(u);return g.set(String(m),C),g}),()=>{s(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});}),[]),M=Bt.useCallback((m,C)=>{s(u=>{let g=new Map(u),T=g.get(String(m));return (!C||T===C)&&g.delete(String(m)),g});},[]),h=Bt.useCallback((m,C)=>{i(u=>{let g=new Map(u);return C?g.set(m,true):g.delete(m),g});},[]),k=Bt.useCallback((m,C)=>{y(u=>{let g=new Map(u);return C?g.set(m,true):g.delete(m),g});},[]),x=Bt.useMemo(()=>Array.from(o.values()).some(m=>m),[o]),d=Bt.useMemo(()=>Array.from(f.values()).some(m=>m),[f]),v=Bt.useMemo(()=>({baseUrl:t,actions:e,components:a,registerAction:l,unregisterAction:b,registerComponent:c,unregisterComponent:M,isAnyStreaming:x,setStreamingState:h,isAnyChatOpen:d,setChatOpenState:k}),[t,e,a,l,b,c,M,x,h,d,k]);return jsxRuntime.jsx(Ve.Provider,{value:v,children:n})}function Q(){let t=Bt.useContext(Ve);return t||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{}}}function ga(t,n){let{registerAction:e}=Q(),r=Bt.useRef(n);Bt.useEffect(()=>{r.current=n;});let a=Bt.useCallback((s,o)=>r.current(s,o),[]);Bt.useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaAction] Invalid action registration: name="${t}", handler type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function ya(t,n){let{registerComponent:e}=Q(),r=Bt.useRef(n);Bt.useEffect(()=>{r.current=n;});let a=Bt.useMemo(()=>{let s=o=>{let i=r.current;return Bt__default.default.createElement(i,o)};return s.displayName=`HsafaStable(${t})`,s},[]);Bt.useEffect(()=>{if(!t||typeof n!="function"){console.warn(`[useHsafaComponent] Invalid component registration: name="${t}", component type="${typeof n}"`);return}return e(t,a)},[t,e,a]);}function Ge(t){let n=`hsafaChat_${t}`,e=`${n}.chats`,r=u=>`${n}.chat.${u}`,a=`${n}.currentChatId`,s=`${n}.showChat`,[o,i]=Bt.useState(null),f=Bt.useRef(false),y=Bt.useRef(null),l=()=>{try{let u=localStorage.getItem(e);return u?JSON.parse(u):[]}catch{return []}},b=u=>{try{localStorage.setItem(e,JSON.stringify(u));}catch{}},c=u=>{try{let g=localStorage.getItem(r(u));return g?JSON.parse(g):null}catch{return null}},M=u=>{try{localStorage.setItem(r(u.id),JSON.stringify(u));}catch{}},h=u=>{let g=l(),T=g.findIndex(R=>R.id===u.id);T>=0?g[T]=u:g.unshift(u),b(g);},k=u=>{let T=l().filter(R=>R.id!==u);b(T);},x=u=>{try{localStorage.removeItem(r(u));}catch{}};return {currentChatId:o,setCurrentChatId:i,hasChatRecordRef:f,pendingFirstTitleRef:y,loadChatsIndex:l,loadChat:c,saveChat:M,deleteChat:(u,g)=>{x(u),k(u);let T=o===u;if(T){i(null),f.current=false,y.current=null;try{localStorage.removeItem(a);}catch{}}g?.(T);},loadChatPreferences:()=>{try{let u=localStorage.getItem(a);if(u){let g=c(u);if(g)return i(g.id),f.current=!0,g.messages||[]}}catch{}return []},persistChatData:u=>{if(!o||!f.current)return;M({id:o,messages:u,agentId:t});let T=u.find(H=>H.role==="user"),R=T?De(T):"New chat",L=(y.current||R).slice(0,80),$={id:o,title:L,createdAt:Date.now(),updatedAt:Date.now()};h($);try{localStorage.setItem(a,o);}catch{}},createNewChat:u=>{let g=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;i(g),f.current=true;let T=(u||"New chat").slice(0,80),R=Date.now();h({id:g,title:T,createdAt:R,updatedAt:R});try{localStorage.setItem(a,g);}catch{}return g},upsertChatMeta:h,showChatKey:s}}function Qe(){let[t,n]=Bt.useState(false),[e,r]=Bt.useState(null),a=Bt.useRef(null),s=Bt.useRef({}),o=Bt.useRef(void 0),i=Bt.useRef(new Set),f=Bt.useRef(new Map),y=Bt.useRef(new Map),[l,b]=Bt.useState(new Map),c=Bt.useCallback((d,v)=>{let m=f.current.get(d)||[],C=JSON.stringify(v);if(m.push(C),m.length>5&&m.shift(),f.current.set(d,m),m.length>=3){let u=m.slice(-3);return u.every(g=>g===u[0])}return false},[]),M=Bt.useCallback((d,v,m,C)=>{!Array.isArray(d)||d.length===0||d.forEach((u,g)=>{if(!(!u||typeof u!="object")&&u.type==="action"){let T=String(u.name??"").trim();if(!T)return;let R=m.get(T);if(!R){console.warn(`Action handler not found for: ${T}`);return}let L=!!s.current[T],$=`${o.current||"assist"}:${T}:${g}`,H=`${T}:${g}`;try{if(v==="partial"&&L){b(B=>new Map(B).set(H,"executing"));let j=setTimeout(()=>{Promise.resolve(R(u.params,{name:T,trigger:v,index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(B=>{console.error(`Error executing streaming action ${T}:`,B),b(I=>new Map(I).set(H,"executed"));});},50);y.current.set(`${H}_timeout`,j);}else if(v==="partial"&&!L){let j=c(H,u.params),B=y.current.get(H);j&&B!=="executed"?(y.current.set(H,"executed"),b(I=>new Map(I).set(H,"executed")),Promise.resolve(R(u.params,{name:T,trigger:"params_complete",index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(I=>{console.error(`Error executing stabilized action ${T}:`,I);})):B||(y.current.set(H,"executing"),b(I=>new Map(I).set(H,"executing")));}else if(v==="final"&&y.current.get(H)!=="executed"&&!i.current.has($)){i.current.add($);let B=y.current.get(`${H}_timeout`);B&&(clearTimeout(B),y.current.delete(`${H}_timeout`)),y.current.set(H,"executed"),b(I=>new Map(I).set(H,"executed")),Promise.resolve(R(u.params,{name:T,trigger:L?"final":"params_complete",index:g,assistantMessageId:o.current,chatId:C||void 0})).catch(I=>{console.error(`Error executing final action ${T}:`,I);});}}catch(j){console.error(`Error processing action ${T}:`,j);}}});},[c]),h=Bt.useCallback(()=>{a.current&&(a.current.abort(),a.current=null),n(false),r("Request stopped by user");},[]),k=Bt.useCallback(()=>{i.current.clear(),f.current.clear(),y.current.clear(),b(new Map);},[]),x=Bt.useCallback(()=>{y.current.forEach((d,v)=>{v.endsWith("_timeout")&&clearTimeout(d);});},[]);return {streaming:t,setStreaming:n,error:e,setError:r,actionStatuses:l,setActionStatuses:b,abortControllerRef:a,actionExecMapRef:s,assistantMsgIdRef:o,calledFinalActionsRef:i,actionParamsHistoryRef:f,actionExecutionStatusRef:y,processActions:M,handleStop:h,resetActionTracking:k,cleanupTimeouts:x,hasActionParamsStabilized:c}}function tn(t,n){if(!t)return n;let e=t.endsWith("/")?t.slice(0,-1):t,r=n.startsWith("/")?n:`/${n}`;return `${e}${r}`}var oe=25*1024*1024;function nn(t){let[n,e]=Bt.useState([]),[r,a]=Bt.useState(false),s=Bt.useRef(null),o=Bt.useCallback(c=>{if(!c||Number.isNaN(c))return "0 B";let M=["B","KB","MB","GB","TB"],h=Math.min(M.length-1,Math.floor(Math.log(c)/Math.log(1024)));return `${(c/Math.pow(1024,h)).toFixed(h===0?0:1)} ${M[h]}`},[]),i=Bt.useCallback(async c=>{let M=new FormData;M.append("file",c);let h=await fetch(tn(t,"/api/uploads"),{method:"POST",body:M});if(!h.ok){let x=await h.text().catch(()=>"");throw new Error(x||`Failed to upload ${c.name}`)}let k=await h.json();return {id:k.id,name:k.name||c.name,url:k.url,mimeType:k.mimeType||c.type||"application/octet-stream",size:typeof k.size=="number"?k.size:c.size}},[t]),f=Bt.useCallback(c=>{e(M=>M.filter(h=>h.id!==c));},[]),y=Bt.useCallback(async(c,M)=>{if(!c)return;let h=Array.isArray(c)?c:Array.from(c);M(null),a(true);let k=[];try{for(let x of h){if(x.size>oe){M(`"${x.name}" exceeds the ${o(oe)} limit.`);continue}try{let d=await i(x);k.push(d);}catch(d){console.error("Failed to upload attachment:",d),M(String(d?.message??`Failed to upload ${x.name}`));}}k.length&&e(x=>[...x,...k]);}finally{a(false);}},[i,o]),l=Bt.useCallback((c,M)=>{let h=[],k=(c||"").trim();k&&h.push({type:"text",text:k});for(let x of M||[]){let d=x.mimeType||"application/octet-stream";d.startsWith("image/")?h.push({type:"image",image:new URL(x.url),mediaType:d}):h.push({type:"file",data:x.url,mediaType:d,name:x.name});}return h},[]),b=Bt.useCallback(()=>{e([]);},[]);return {attachments:n,uploading:r,fileInputRef:s,formatBytes:o,handleRemoveAttachment:f,handleFileSelection:y,buildUserContent:l,clearAttachments:b,MAX_UPLOAD_SIZE:oe}}function hr(t){return JSON.parse(JSON.stringify(t))}function rn(){let[t,n]=Bt.useState(false),[e,r]=Bt.useState(null),[a,s]=Bt.useState(null),o=Bt.useRef(null),i=Bt.useCallback(async({agentId:l,body:b,baseUrl:c,onUpdate:M,signal:h})=>{try{let $=function(){let I=hr(C);s(I),M?.(I);};var k=$;n(!0),r(null);let x;if(h)o.current=null,x=h;else {let I=new AbortController;o.current=I,x=I.signal;}let v=`${c?c.replace(/\/$/,""):""}/api/run/${encodeURIComponent(l)}`,m=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/x-ndjson"},body:JSON.stringify(b??{}),signal:x});if(!m.ok||!m.body){let I=await m.text().catch(()=>"");throw new Error(`Request failed: ${m.status} ${m.statusText} - ${I}`)}let C={first_agent:{message:"",continue:!1},main_agent:[]},u=null,g=null,T=null,R=null,L=!1,H=m.body.getReader(),j=new TextDecoder("utf-8"),B="";for($();;){let{value:I,done:Mt}=await H.read();if(Mt)break;B+=j.decode(I,{stream:!0});let et=B.indexOf(`
15
15
  `);for(;et!==-1;){let q=B.slice(0,et).trim();if(B=B.slice(et+1),q.length>0)try{let p=JSON.parse(q);switch(p?.type){case "start":break;case "first-agent-start":C.first_agent.startDate=p?.startDate,C.first_agent.durationMs=p?.durationMs,$();break;case "first-agent-partial":typeof p?.message=="string"&&(C.first_agent.message=p.message),typeof p?.continue=="boolean"&&(C.first_agent.continue=p.continue),typeof p?.durationMs=="number"&&(C.first_agent.durationMs=p.durationMs),$();break;case "first-agent-end":typeof p?.message=="string"&&(C.first_agent.message=p.message),typeof p?.continue=="boolean"&&(C.first_agent.continue=p.continue),C.first_agent.endDate=p?.endDate,C.first_agent.durationMs=p?.durationMs,$();break;case "main-agent-start":L=!1;break;case "main-agent-step-finish":{let S={type:"step",stepNumber:void 0,finishReason:p?.finishReason,usage:p?.usage,endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S),$();break}case "main-agent-skipped":L=!0;break;case "main-agent-reasoning-start":u={type:"reasoning",reasoning:"",status:"streaming",startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(u),$();break;case "main-agent-reasoning-delta":u&&typeof p?.text=="string"&&(u.reasoning+=p.text,u.durationMs=p?.durationMs,$());break;case "main-agent-reasoning-end":if(u){if(typeof p?.text=="string"&&p.text.length>0&&(u.reasoning+=p.text),u.status="finished",u.endDate=p?.endDate,u.durationMs=p?.durationMs,!u.reasoning||u.reasoning.trim().length===0){let S=C.main_agent.indexOf(u);S>-1&&C.main_agent.splice(S,1);}u=null,$();}else if(typeof p?.text=="string"&&p.text.length>0){let S={type:"reasoning",reasoning:p.text,status:"finished",endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S),$();}break;case "main-agent-tool-call-start":g={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,inputText:"",input:void 0,output:void 0,status:"input_streaming",startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(g),$();break;case "main-agent-tool-input-delta":let it=p?.delta||p?.argsTextDelta;g&&typeof it=="string"&&(g.inputText=(g.inputText||"")+it,g.durationMs=p?.durationMs,$());break;case "tool-call":case "main-agent-tool-call":if(g)g.input=p?.input,g.status="running",g.durationMs=p?.durationMs;else {let S=C.main_agent.find(vt=>vt.type==="tool-call"&&(vt.toolCallId===p?.toolCallId||vt.toolName===p?.toolName));S?(S.input=p?.input,S.status="running",S.durationMs=p?.durationMs,g=S):(g={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,input:p?.input,inputText:"",output:void 0,status:"running",durationMs:p?.durationMs},C.main_agent.push(g));}$();break;case "tool-result":case "main-agent-tool-result":let Y=g;if(Y||(Y=C.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===p?.toolCallId||S.toolName===p?.toolName))||null),Y)Y.output=p?.output,Y.status="finished",Y.endDate=p?.endDate,Y.durationMs=p?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,input:void 0,inputText:"",output:p?.output,status:"finished",endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S);}$();break;case "tool-error":case "main-agent-tool-error":let J=g;if(J||(J=C.main_agent.find(S=>S.type==="tool-call"&&(S.toolCallId===p?.toolCallId||S.toolName===p?.toolName))||null),J)J.error=p?.error,J.status="error",J.endDate=p?.endDate,J.durationMs=p?.durationMs,g=null;else {let S={type:"tool-call",toolCallId:p?.toolCallId,toolName:p?.toolName,input:void 0,inputText:"",output:void 0,error:p?.error,status:"error",endDate:p?.endDate,durationMs:p?.durationMs};C.main_agent.push(S);}$();break;case "main-agent-response-partial":if(L)break;if(T||(T={type:"response",items:[],startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(T)),p?.value&&typeof p.value=="object"){let S=Array.isArray(p.value.items)?p.value.items:T.items;Object.assign(T,p.value),T.items=S,T.durationMs=p?.durationMs;}$();break;case "text-delta":case "main-agent-text-delta":typeof p?.text=="string"&&p.text&&(R||(R={type:"text",text:"",status:"streaming",startDate:p?.startDate,durationMs:p?.durationMs},C.main_agent.push(R)),R.text+=p.text,R.durationMs=p?.durationMs,$());break;case "text-end":R&&(R.status="finished",R.endDate=p?.endDate,R.durationMs=p?.durationMs,R=null,$());break;case "source":case "main-agent-source":let Tt={type:"source",source:p?.source,durationMs:p?.durationMs};C.main_agent.push(Tt),$();break;case "file":case "main-agent-file":let Kt={type:"file",file:p?.file,durationMs:p?.durationMs};C.main_agent.push(Kt),$();break;case "final":if(L)break;if(p?.value&&typeof p.value=="object"){T||(T={type:"response",items:[],endDate:p?.endDate,durationMs:p?.durationMs},C.main_agent.push(T));let S=Array.isArray(p.value.items)?p.value.items:T.items;Object.assign(T,p.value),T.items=S,T.endDate=p?.endDate,T.durationMs=p?.durationMs;}$();break;case "error":case "main-agent-error":throw new Error(p?.error||"Unknown agent error");default:break}}catch(p){console.warn("Failed to parse streaming line:",p);}et=B.indexOf(`
16
- `);}}try{H.releaseLock();}catch{}return n(!1),C}catch(x){return x.name==="AbortError"?r("Request was cancelled"):r(x?.message||"Request failed"),n(false),null}},[]),f=Bt.useCallback(()=>{o.current&&(o.current.abort(),o.current=null),n(false);},[]),y=Bt.useCallback(()=>{s(null),r(null),n(false);},[]);return {streaming:t,error:e,streamData:a,startStreaming:i,stopStreaming:f,reset:y}}var on={en:{"header.maximize":"Maximize","header.minimize":"Minimize","header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit","messages.empty":"Start by sending a message to the agent.","messages.error":"An error occurred","history.search":"Search","history.noChatsFound":"No chats found.","history.untitledChat":"Untitled chat","history.deleteChat":"Delete chat","general.agent":"Agent"},ar:{"header.maximize":"\u062A\u0643\u0628\u064A\u0631","header.minimize":"\u062A\u0635\u063A\u064A\u0631","header.new":"\u062C\u062F\u064A\u062F","header.history":"\u0627\u0644\u0633\u062C\u0644","header.close":"\u0625\u063A\u0644\u0627\u0642 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","input.placeholder":"\u0627\u0637\u0631\u062D \u0633\u0624\u0627\u0644\u0643...","input.attachFiles":"\u0625\u0631\u0641\u0627\u0642 \u0645\u0644\u0641\u0627\u062A","input.insertLink":"\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637","input.send":"\u0625\u0631\u0633\u0627\u0644","input.stop":"\u0625\u064A\u0642\u0627\u0641","input.uploadingFiles":"\u062C\u0627\u0631\u064A \u0631\u0641\u0639 \u0627\u0644\u0645\u0644\u0641\u0627\u062A...","input.previewImage":"\u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0635\u0648\u0631\u0629","input.removeFile":"\u062D\u0630\u0641 \u0627\u0644\u0645\u0644\u0641","editor.cancel":"\u0625\u0644\u063A\u0627\u0621","editor.saveAndRegenerate":"\u062D\u0641\u0638 \u0648\u0625\u0639\u0627\u062F\u0629 \u062A\u0648\u0644\u064A\u062F","editor.clickToEdit":"\u0627\u0646\u0642\u0631 \u0644\u0644\u062A\u0639\u062F\u064A\u0644","messages.empty":"\u0627\u0628\u062F\u0623 \u0628\u0625\u0631\u0633\u0627\u0644 \u0631\u0633\u0627\u0644\u0629 \u0625\u0644\u0649 \u0627\u0644\u0648\u0643\u064A\u0644.","messages.error":"\u062D\u062F\u062B \u062E\u0637\u0623","history.search":"\u0628\u062D\u062B","history.noChatsFound":"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u0645\u062D\u0627\u062F\u062B\u0627\u062A.","history.untitledChat":"\u0645\u062D\u0627\u062F\u062B\u0629 \u0628\u062F\u0648\u0646 \u0639\u0646\u0648\u0627\u0646","history.deleteChat":"\u062D\u0630\u0641 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","general.agent":"\u0627\u0644\u0648\u0643\u064A\u0644"}};function an(t,n){return on[t]?.[n]||on.en[n]||n}function sn(t="en"){return {t:Bt.useCallback(e=>an(t,e),[t]),language:t}}function cn({actions:t,currentChatId:n}){let e=Bt.useRef({}),r=Bt.useRef(void 0),a=Bt.useRef(new Set),[s,o]=Bt.useState(new Map);Bt.useEffect(()=>()=>{},[]);let i=Bt.useCallback((y,l)=>{if(!Array.isArray(y)||y.length===0){l==="final"&&o(b=>{let c=new Map(b);return c.forEach((M,h)=>c.set(h,"executed")),c});return}y.forEach((b,c)=>{if(!(!b||typeof b!="object")&&b.type==="action"){let M=String(b.name??"").trim();if(!M)return;let h=t.get(M);if(!h)return;let k=typeof b.executeOnStream=="boolean"?b.executeOnStream:!!e.current[M],x=`${r.current||"assist"}:${M}:${c}`,d=`${M}:${c}`;try{l==="partial"&&k?(o(v=>new Map(v).set(d,"executing")),Promise.resolve(h(b.params,{name:M,trigger:l,index:c,assistantMessageId:r.current,chatId:n||void 0})).catch(v=>{o(m=>new Map(m).set(d,"executed"));})):l==="partial"&&!k?o(v=>{if(v.get(d)==="executing")return v;let m=new Map(v);return m.set(d,"executing"),m}):l==="final"&&(a.current.has(x)?o(v=>new Map(v).set(d,"executed")):(a.current.add(x),o(v=>new Map(v).set(d,"executed")),Promise.resolve(h(b.params,{name:M,trigger:k?"final":"params_complete",index:c,assistantMessageId:r.current,chatId:n||void 0})).catch(v=>{console.error(`[useActions] Error executing final action "${M}":`,v);})));}catch(v){console.error(`[useActions] Error processing action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));}}});},[t,n]),f=Bt.useCallback(()=>{a.current.clear(),o(new Map);},[]);return {actionExecMapRef:e,assistantMsgIdRef:r,actionStatuses:s,processActions:i,resetActionTracking:f}}function Wt({icon:t,onClick:n,ariaLabel:e,resolvedColors:r,disabled:a=false,title:s}){return jsxRuntime.jsx("button",{"aria-label":e,title:s,disabled:a,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:o=>{a||(o.currentTarget.style.backgroundColor=r.hoverBackground,o.currentTarget.style.color=r.textColor);},onMouseLeave:o=>{o.currentTarget.style.backgroundColor="transparent",o.currentTarget.style.color=r.mutedTextColor;},onClick:n,children:t})}function pn({title:t,expandable:n,alwaysOpen:e,maximized:r,streaming:a,dir:s,resolvedColors:o,onMaximize:i,onNew:f,onToggleHistory:y,onClose:l,historyBtnRef:b,t:c}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:s==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:t,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:t})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[n&&jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.Maximize2,{size:"20",strokeWidth:"2"}),onClick:i,ariaLabel:c(r?"header.minimize":"header.maximize"),resolvedColors:o}),jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.Plus,{size:"20",strokeWidth:"2"}),onClick:()=>{a||f();},ariaLabel:c("header.new"),resolvedColors:o,disabled:a}),jsxRuntime.jsx("button",{ref:b,"aria-label":c("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:M=>{M.currentTarget.style.backgroundColor=o.hoverBackground,M.currentTarget.style.color=o.textColor;},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="transparent",M.currentTarget.style.color=o.mutedTextColor;},onClick:y,children:jsxRuntime.jsx(lucideReact.History,{size:"20",strokeWidth:"2"})}),!e&&jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.ChevronRight,{size:"20",strokeWidth:"2",style:{transform:s==="rtl"?"rotate(180deg)":"none"}}),onClick:l,ariaLabel:c("header.close"),resolvedColors:o})]})]})}function gn({value:t,onChange:n,onSend:e,onStop:r,streaming:a,placeholder:s,attachments:o,uploading:i,onRemoveAttachment:f,onFileInputClick:y,resolvedColors:l,formatBytes:b,textareaRef:c,fileInputRef:M,onFileSelection:h,t:k,dir:x="ltr"}){return Bt__default.default.useEffect(()=>{let d=c.current;if(d){d.style.height="24px",d.offsetHeight,d.style.height="auto";let v=Math.min(d.scrollHeight,200);d.style.height=`${v}px`;}},[t,c]),Bt__default.default.useEffect(()=>{let d=c.current;d&&!t&&(d.style.height="24px");},[c,t]),jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:l.backgroundColor},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:"1"},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${l.borderColor}`,backgroundColor:l.accentColor},children:[o.length>0&&jsxRuntime.jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:o.map(d=>{let v=d.mimeType?.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:l.inputBackground,borderRadius:"10px",border:`1px solid ${l.borderColor}`,fontSize:"12px",color:l.textColor,transition:"all 0.2s ease-out",cursor:"pointer",position:"relative"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:v?"transparent":l.accentColor},children:[v?jsxRuntime.jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:m=>{m.target.style.display="none";let C=m.target.nextElementSibling;C&&(C.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:"14",strokeWidth:"2",style:{display:v?"none":"block",color:l.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsxRuntime.jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:d.name}),jsxRuntime.jsx("span",{style:{color:l.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:b(d.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[v&&jsxRuntime.jsx("button",{onClick:m=>{m.stopPropagation(),window.open(d.url,"_blank");},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:k("input.previewImage"),onMouseEnter:m=>{m.currentTarget.style.backgroundColor=l.hoverBackground,m.currentTarget.style.color=l.textColor;},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=l.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),jsxRuntime.jsx("button",{onClick:m=>{m.stopPropagation(),f(d.id);},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:k("input.removeFile"),onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.color="#ef4444";},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=l.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})})]})]},d.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:l.mutedTextColor},children:[jsxRuntime.jsx(lucideReact.Loader2,{size:"14",strokeWidth:"2",style:{animation:"spin 1s linear infinite"}}),jsxRuntime.jsx("span",{children:k("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{"aria-label":"Prompt",rows:1,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:l.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:s,value:t,onChange:d=>n(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),a||e());},ref:c})}),jsxRuntime.jsxs("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:l.mutedTextColor},children:[jsxRuntime.jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,d.currentTarget.style.color=l.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=l.mutedTextColor;},"aria-label":k("input.attachFiles"),onClick:y,children:jsxRuntime.jsx(lucideReact.Paperclip,{size:"18",strokeWidth:"2"})}),jsxRuntime.jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,d.currentTarget.style.color=l.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=l.mutedTextColor;},"aria-label":k("input.insertLink"),children:jsxRuntime.jsx(lucideReact.Link,{size:"18",strokeWidth:"2"})})]}),jsxRuntime.jsx("input",{type:"file",ref:M,multiple:true,accept:"*/*",style:{display:"none"},onChange:d=>h(d.target.files)}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{left:"8px"}:{right:"8px"}},children:jsxRuntime.jsx("button",{"aria-label":k(a?"input.stop":"input.send"),disabled:!a&&!t.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a?"#ef4444":l.borderColor}`,backgroundColor:a?"#ef444420":l.cardBackground,color:a?"#ef4444":l.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#dc2626",d.currentTarget.style.backgroundColor="#dc262630",d.currentTarget.style.color="#dc2626"):(d.currentTarget.style.borderColor=l.primaryColor,d.currentTarget.style.backgroundColor=l.hoverBackground,d.currentTarget.style.color=l.textColor));},onMouseLeave:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#ef4444",d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.color="#ef4444"):(d.currentTarget.style.borderColor=l.borderColor,d.currentTarget.style.backgroundColor=l.cardBackground,d.currentTarget.style.color=l.mutedTextColor));},onClick:()=>{a?r():e();},children:a?jsxRuntime.jsx(lucideReact.Square,{size:"18",strokeWidth:"2"}):jsxRuntime.jsx(lucideReact.ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function mn(t){let n=Date.now()-t,e=Math.max(1,Math.floor(n/1e3));if(e<60)return `${e}s`;let r=Math.floor(e/60);if(r<60)return `${r}m`;let a=Math.floor(r/60);if(a<24)return `${a}h`;let s=Math.floor(a/24);if(s<7)return `${s}d`;let o=Math.floor(s/7);if(o<4)return `${o}w`;let i=Math.floor(s/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function fn({isOpen:t,onClose:n,searchQuery:e,onSearchChange:r,chats:a,currentChatId:s,onChatSelect:o,onChatDelete:i,resolvedColors:f,t:y}){if(!t)return null;let l=e.trim()?a.filter(c=>(c.title||"").toLowerCase().includes(e.toLowerCase().trim())):a,b=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:n}),jsxRuntime.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:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${f.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:e,onChange:c=>r(c.target.value),placeholder:y("history.search"),style:{width:"100%",borderRadius:"8px",backgroundColor:f.inputBackground,padding:"8px 12px",fontSize:"14px",color:f.textColor,border:`1px solid ${f.borderColor}`,outline:"none"},onFocus:c=>c.currentTarget.style.borderColor=f.primaryColor,onBlur:c=>c.currentTarget.style.borderColor=f.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:l.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:f.mutedTextColor,textAlign:"center"},children:y("history.noChatsFound")}):jsxRuntime.jsx("div",{children:l.map((c,M)=>jsxRuntime.jsx("div",{style:{borderTop:M>0?`1px solid ${f.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:c.id===s?f.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:f.textColor},onMouseEnter:h=>h.currentTarget.style.backgroundColor=f.hoverBackground,onMouseLeave:h=>h.currentTarget.style.backgroundColor="transparent",onClick:()=>o(c.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:f.textColor},children:c.title||y("history.untitledChat")})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:f.mutedTextColor},children:mn(c.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:f.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:y("history.deleteChat"),onMouseEnter:h=>{h.currentTarget.style.color="#ef4444",h.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",h.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:h=>{h.currentTarget.style.color=f.mutedTextColor,h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.borderColor="transparent";},onClick:h=>{h.stopPropagation(),i(c.id);},children:jsxRuntime.jsx(lucideReact.Trash2,{size:"16",strokeWidth:"2"})})]})},c.id))})})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(b,document.body):b}var Ot={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};var le=t=>t.map(n=>({...n}));function Br(t){let[n,e]=Bt.useState(()=>{try{return t.loadChatPreferences()}catch(o){return console.warn("Failed to load chat preferences:",o),[]}});Bt.useEffect(()=>{if(n.length!==0)try{t.persistChatData(n);}catch(o){console.warn("Failed to persist chat data:",o);}},[n]);let r=Bt.useCallback(o=>{try{t.setCurrentChatId(o);let i=t.loadChat(o);return e(i?.messages||[]),!0}catch(i){return console.warn("Failed to load selected chat:",i),false}},[t]),a=Bt.useCallback(o=>{try{t.deleteChat(o,i=>{i&&e([]);});}catch(i){console.warn("Failed to delete chat:",i);}},[t]),s=Bt.useCallback(()=>{e([]),t.setCurrentChatId(null);},[t]);return {messages:n,setMessages:e,selectChat:r,deleteChat:a,resetChat:s}}function Lr(t){let{agentId:n,theme:e="dark",primaryColor:r,backgroundColor:a,borderColor:s,textColor:o,accentColor:i,width:f=420,height:y="100vh",expandable:l=true,alwaysOpen:b=false,defaultOpen:c=false,dir:M="ltr",language:h,floatingButtonPosition:k=M==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},placeholder:x,title:d,chatContainerClassName:v="",defaultReasoningOpen:m=false,hideReasoningContent:C=false}=t,u=h||(M==="rtl"?"ar":"en"),{t:g}=sn(u),T=x??g("input.placeholder"),R=d??g("general.agent"),{baseUrl:L,actions:$,components:H,setStreamingState:j,setChatOpenState:B}=Q(),I=Bt.useRef(`chat-${n}-${Date.now()}`).current,[Mt,et]=Bt.useState(""),[q,p]=Bt.useState(()=>{if(b)return true;try{let A=localStorage.getItem(`hsafaChat_${n}.showChat`);return A!==null?A==="true":c}catch{return c}}),[ce,it]=Bt.useState(false),[Y,J]=Bt.useState(""),[Tt,Kt]=Bt.useState(false),[S,vt]=Bt.useState(0),[yn,jt]=Bt.useState(null),[xn,de]=Bt.useState(""),[pe,At]=Bt.useState([]),ue=Bt.useRef(null),[ge,me]=Bt.useState(true),qt=Bt.useRef(false),bn=Bt.useRef(null),Cn=Bt.useRef(null),kn=Bt.useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),nt=Ge(n),{messages:rt,setMessages:wt,selectChat:fe,deleteChat:he,resetChat:Mn}=Br(nt),_=Qe(),St=nn(L||""),Jt=rn(),{assistantMsgIdRef:Tn,actionStatuses:vn,processActions:ye,resetActionTracking:An}=cn({actions:$,currentChatId:nt.currentChatId});Bt.useEffect(()=>{j(I,_.streaming);},[_.streaming,I,j]),Bt.useEffect(()=>(B(I,q),()=>{B(I,false),j(I,false);}),[q,I,B,j]),Bt.useEffect(()=>{if(!b)try{localStorage.setItem(`hsafaChat_${n}.showChat`,String(q));}catch(A){console.warn("Failed to save chat state:",A);}},[q,n,b]);let{attachments:Vt,uploading:xe,fileInputRef:be,formatBytes:wn,handleRemoveAttachment:Sn,handleFileSelection:Rn,clearAttachments:Ce}=St,ke=Bt.useCallback((A,F)=>{wt(P=>P.map(w=>{if(w.id===A&&w.role==="assistant"){let E=F.main_agent.find(O=>O.type==="response"),N=E?.type==="response"?E.items:[];return {...w,items:N,mainAgentActions:F.main_agent,firstAgentMessage:F.first_agent.message,firstAgentContinue:F.first_agent.continue,reasoningOpen:w.reasoningOpen}}return w}));},[]),Xt=Bt.useCallback(async({prompt:A,baseMessages:F,userMessage:P,assistantMessageId:w,chatId:E})=>{if(n){_.setError(null),_.setStreaming(true);try{let N=Ie(F);N.push({role:"user",content:P.content}),Tn.current=w,An(),await Jt.startStreaming({agentId:n,baseUrl:L,body:{prompt:A,chatId:E??void 0,messages:N},onUpdate:Dt=>{ke(w,Dt);let En=Dt.main_agent.find(zn=>zn.type==="response")?.items||[];ye(En,"partial");}});let $t=Jt.streamData?.main_agent?.find(Dt=>Dt.type==="response")?.items||[];ye($t,"final");}catch(N){_.setError(N?.message||"Request failed");}finally{_.setStreaming(false);}}},[n,L,Jt,_,ke]),$n=Bt.useCallback(A=>{fe(A)&&(it(false),J(""));},[fe,it,J]),In=Bt.useCallback(A=>{he(A),vt(F=>F+1);},[he]),ot=Ot[e],ut={primaryColor:r||ot.primaryColor,backgroundColor:a??"transparent",borderColor:s||ot.borderColor,textColor:o||ot.textColor,accentColor:i||ot.accentColor,mutedTextColor:ot.mutedTextColor,inputBackground:ot.inputBackground,cardBackground:ot.cardBackground,hoverBackground:ot.hoverBackground},Fn=Bt.useCallback(async()=>{if(!n)return;let A=Mt.trim();if(!A)return;let F=nt.currentChatId;F||(F=nt.createNewChat(A));let P=le(Vt),w=$e(A,P),E=Qt(m),N=rt;wt([...N,w,E]),et(""),Ce(),me(true),await Xt({prompt:A,baseMessages:N,userMessage:w,assistantMessageId:E.id,chatId:F});},[n,Mt,rt,Vt,Ce,Xt,nt,wt,et]),Dn=Bt.useCallback(async A=>{if(!A||!L)return;let F=Array.from(A);_.setError(null);let P=[];try{for(let w of F){if(w.size>St.MAX_UPLOAD_SIZE){_.setError(`"${w.name}" exceeds the ${St.formatBytes(St.MAX_UPLOAD_SIZE)} limit.`);continue}try{let E=new FormData;E.append("file",w);let N=await fetch(`${L}/api/uploads`,{method:"POST",body:E});if(!N.ok){let $t=await N.text().catch(()=>"");throw new Error($t||`Failed to upload ${w.name}`)}let O=await N.json(),Rt={id:O.id,name:O.name||w.name,url:O.url,mimeType:O.mimeType||w.type||"application/octet-stream",size:typeof O.size=="number"?O.size:w.size};P.push(Rt);}catch(E){console.error("Failed to upload attachment:",E),_.setError(String(E?.message??`Failed to upload ${w.name}`));}}P.length&&At(w=>[...w,...P]);}catch(w){console.error("Error adding attachments during edit:",w);}},[L,St,_]);return Bt.useEffect(()=>{if(qt.current){qt.current=false;return}ge&&requestAnimationFrame(()=>{ue.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[rt,_.streaming,ge]),Bt.useEffect(()=>{let A=document.querySelector(".chat-scroll-container");if(!A)return;let F=()=>{let{scrollTop:P,scrollHeight:w,clientHeight:E}=A,O=w-P-E<40;me(O);};return A.addEventListener("scroll",F),F(),()=>A.removeEventListener("scroll",F)},[]),typeof document<"u"?reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:v,style:{width:q?Tt?"100%":typeof f=="number"?`${f}px`:f:"0",height:y,display:"flex",flexDirection:"column",backgroundColor:q?ut.backgroundColor:"transparent",opacity:q?1:0,padding:q?"24px 16px":"0",transition:"all 0.3s ease-out",position:"fixed",top:0,...M==="rtl"?{left:0}:{right:0},bottom:0,zIndex:Tt?9999:1e3,pointerEvents:q?"auto":"none"},children:[jsxRuntime.jsx(pn,{title:R,expandable:l,alwaysOpen:b,maximized:Tt,streaming:_.streaming,dir:M,resolvedColors:ut,onMaximize:()=>Kt(A=>!A),onNew:Mn,onToggleHistory:()=>it(A=>!A),onClose:()=>p(false),historyBtnRef:Cn,t:g}),jsxRuntime.jsx(qe,{messages:rt,streaming:_.streaming,editingMessageId:yn,editingMessageText:xn,editingAttachments:pe,error:_.error,actionStatuses:vn,components:H,theme:e,resolvedColors:ut,hideReasoningContent:C,onEditingTextChange:de,onRemoveAttachment:A=>{At(F=>F.filter(P=>P.id!==A));},onAddAttachments:Dn,uploading:xe,onStartEdit:(A,F)=>{let P=rt.find(w=>w.id===A);jt(A),de(F),P&&P.role==="user"&&At(le(gt(P)));},onCancelEdit:()=>{jt(null),At([]);},onSaveEdit:async(A,F)=>{let P=rt.findIndex($t=>$t.id===A);if(P===-1)return;let w=rt[P];if(w.role!=="user")return;let E=F.trim(),N=Fe(w,E,le(pe)),O=rt.slice(0,P),Rt=Qt(m);wt([...O,N,Rt]),jt(null),At([]),await Xt({prompt:E,baseMessages:O,userMessage:N,assistantMessageId:Rt.id,chatId:nt.currentChatId??null});},onToggleReasoning:A=>{let F=document.querySelector(".chat-scroll-container"),P=F?.scrollTop||0;qt.current=true,wt(w=>w.map(E=>E.id===A&&E.role==="assistant"?{...E,reasoningOpen:!E.reasoningOpen}:E)),requestAnimationFrame(()=>{F&&(F.scrollTop=P);});},scrollAnchorRef:ue,t:g}),jsxRuntime.jsx(gn,{value:Mt,onChange:et,onSend:Fn,onStop:_.handleStop,streaming:_.streaming,placeholder:T,attachments:Vt,uploading:xe,onRemoveAttachment:Sn,onFileInputClick:()=>be.current?.click(),resolvedColors:ut,formatBytes:wn,textareaRef:bn,fileInputRef:be,onFileSelection:A=>Rn(A,_.setError),t:g,dir:M})]}),jsxRuntime.jsx(Je,{show:!q&&!b,onClick:()=>p(true),resolvedColors:ut,floatingButtonPosition:k}),jsxRuntime.jsx(fn,{isOpen:ce,onClose:()=>it(false),searchQuery:Y,onSearchChange:J,chats:nt.loadChatsIndex(),currentChatId:nt.currentChatId,onChatSelect:$n,onChatDelete:In,resolvedColors:ut,t:g}),jsxRuntime.jsx("style",{children:`
16
+ `);}}try{H.releaseLock();}catch{}return n(!1),C}catch(x){return x.name==="AbortError"?r("Request was cancelled"):r(x?.message||"Request failed"),n(false),null}},[]),f=Bt.useCallback(()=>{o.current&&(o.current.abort(),o.current=null),n(false);},[]),y=Bt.useCallback(()=>{s(null),r(null),n(false);},[]);return {streaming:t,error:e,streamData:a,startStreaming:i,stopStreaming:f,reset:y}}var on={en:{"header.maximize":"Maximize","header.minimize":"Minimize","header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit","messages.empty":"Start by sending a message to the agent.","messages.error":"An error occurred","history.search":"Search","history.noChatsFound":"No chats found.","history.untitledChat":"Untitled chat","history.deleteChat":"Delete chat","general.agent":"Agent"},ar:{"header.maximize":"\u062A\u0643\u0628\u064A\u0631","header.minimize":"\u062A\u0635\u063A\u064A\u0631","header.new":"\u062C\u062F\u064A\u062F","header.history":"\u0627\u0644\u0633\u062C\u0644","header.close":"\u0625\u063A\u0644\u0627\u0642 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","input.placeholder":"\u0627\u0637\u0631\u062D \u0633\u0624\u0627\u0644\u0643...","input.attachFiles":"\u0625\u0631\u0641\u0627\u0642 \u0645\u0644\u0641\u0627\u062A","input.insertLink":"\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637","input.send":"\u0625\u0631\u0633\u0627\u0644","input.stop":"\u0625\u064A\u0642\u0627\u0641","input.uploadingFiles":"\u062C\u0627\u0631\u064A \u0631\u0641\u0639 \u0627\u0644\u0645\u0644\u0641\u0627\u062A...","input.previewImage":"\u0645\u0639\u0627\u064A\u0646\u0629 \u0627\u0644\u0635\u0648\u0631\u0629","input.removeFile":"\u062D\u0630\u0641 \u0627\u0644\u0645\u0644\u0641","editor.cancel":"\u0625\u0644\u063A\u0627\u0621","editor.saveAndRegenerate":"\u062D\u0641\u0638 \u0648\u0625\u0639\u0627\u062F\u0629 \u062A\u0648\u0644\u064A\u062F","editor.clickToEdit":"\u0627\u0646\u0642\u0631 \u0644\u0644\u062A\u0639\u062F\u064A\u0644","messages.empty":"\u0627\u0628\u062F\u0623 \u0628\u0625\u0631\u0633\u0627\u0644 \u0631\u0633\u0627\u0644\u0629 \u0625\u0644\u0649 \u0627\u0644\u0648\u0643\u064A\u0644.","messages.error":"\u062D\u062F\u062B \u062E\u0637\u0623","history.search":"\u0628\u062D\u062B","history.noChatsFound":"\u0644\u0645 \u064A\u062A\u0645 \u0627\u0644\u0639\u062B\u0648\u0631 \u0639\u0644\u0649 \u0645\u062D\u0627\u062F\u062B\u0627\u062A.","history.untitledChat":"\u0645\u062D\u0627\u062F\u062B\u0629 \u0628\u062F\u0648\u0646 \u0639\u0646\u0648\u0627\u0646","history.deleteChat":"\u062D\u0630\u0641 \u0627\u0644\u0645\u062D\u0627\u062F\u062B\u0629","general.agent":"\u0627\u0644\u0648\u0643\u064A\u0644"}};function an(t,n){return on[t]?.[n]||on.en[n]||n}function sn(t="en"){return {t:Bt.useCallback(e=>an(t,e),[t]),language:t}}function cn({actions:t,currentChatId:n}){let e=Bt.useRef({}),r=Bt.useRef(void 0),a=Bt.useRef(new Set),[s,o]=Bt.useState(new Map);Bt.useEffect(()=>()=>{},[]);let i=Bt.useCallback((y,l)=>{if(!Array.isArray(y)||y.length===0){l==="final"&&o(b=>{let c=new Map(b);return c.forEach((M,h)=>c.set(h,"executed")),c});return}y.forEach((b,c)=>{if(!(!b||typeof b!="object")&&b.type==="action"){let M=String(b.name??"").trim();if(!M)return;let h=t.get(M);if(!h)return;let k=typeof b.executeOnStream=="boolean"?b.executeOnStream:!!e.current[M],x=`${r.current||"assist"}:${M}:${c}`,d=`${M}:${c}`;try{l==="partial"&&k?(o(v=>new Map(v).set(d,"executing")),Promise.resolve(h(b.params,{name:M,trigger:l,index:c,assistantMessageId:r.current,chatId:n||void 0})).then(()=>{o(v=>new Map(v).set(d,"executed"));}).catch(v=>{console.error(`[useActions] Error executing streaming action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));})):l==="partial"&&!k?o(v=>{if(v.get(d)==="executing")return v;let m=new Map(v);return m.set(d,"executing"),m}):l==="final"&&(!k&&!a.current.has(x)?(a.current.add(x),Promise.resolve(h(b.params,{name:M,trigger:"params_complete",index:c,assistantMessageId:r.current,chatId:n||void 0})).then(()=>{o(v=>new Map(v).set(d,"executed"));}).catch(v=>{console.error(`[useActions] Error executing final action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));})):k||o(v=>new Map(v).set(d,"executed")));}catch(v){console.error(`[useActions] Error processing action "${M}":`,v),o(m=>new Map(m).set(d,"executed"));}}});},[t,n]),f=Bt.useCallback(()=>{a.current.clear(),o(new Map);},[]);return {actionExecMapRef:e,assistantMsgIdRef:r,actionStatuses:s,processActions:i,resetActionTracking:f}}function Wt({icon:t,onClick:n,ariaLabel:e,resolvedColors:r,disabled:a=false,title:s}){return jsxRuntime.jsx("button",{"aria-label":e,title:s,disabled:a,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:o=>{a||(o.currentTarget.style.backgroundColor=r.hoverBackground,o.currentTarget.style.color=r.textColor);},onMouseLeave:o=>{o.currentTarget.style.backgroundColor="transparent",o.currentTarget.style.color=r.mutedTextColor;},onClick:n,children:t})}function pn({title:t,expandable:n,alwaysOpen:e,maximized:r,streaming:a,dir:s,resolvedColors:o,onMaximize:i,onNew:f,onToggleHistory:y,onClose:l,historyBtnRef:b,t:c}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:s==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:t,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:t})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[n&&jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.Maximize2,{size:"20",strokeWidth:"2"}),onClick:i,ariaLabel:c(r?"header.minimize":"header.maximize"),resolvedColors:o}),jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.Plus,{size:"20",strokeWidth:"2"}),onClick:()=>{a||f();},ariaLabel:c("header.new"),resolvedColors:o,disabled:a}),jsxRuntime.jsx("button",{ref:b,"aria-label":c("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:M=>{M.currentTarget.style.backgroundColor=o.hoverBackground,M.currentTarget.style.color=o.textColor;},onMouseLeave:M=>{M.currentTarget.style.backgroundColor="transparent",M.currentTarget.style.color=o.mutedTextColor;},onClick:y,children:jsxRuntime.jsx(lucideReact.History,{size:"20",strokeWidth:"2"})}),!e&&jsxRuntime.jsx(Wt,{icon:jsxRuntime.jsx(lucideReact.ChevronRight,{size:"20",strokeWidth:"2",style:{transform:s==="rtl"?"rotate(180deg)":"none"}}),onClick:l,ariaLabel:c("header.close"),resolvedColors:o})]})]})}function gn({value:t,onChange:n,onSend:e,onStop:r,streaming:a,placeholder:s,attachments:o,uploading:i,onRemoveAttachment:f,onFileInputClick:y,resolvedColors:l,formatBytes:b,textareaRef:c,fileInputRef:M,onFileSelection:h,t:k,dir:x="ltr"}){return Bt__default.default.useEffect(()=>{let d=c.current;if(d){d.style.height="24px",d.offsetHeight,d.style.height="auto";let v=Math.min(d.scrollHeight,200);d.style.height=`${v}px`;}},[t,c]),Bt__default.default.useEffect(()=>{let d=c.current;d&&!t&&(d.style.height="24px");},[c,t]),jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px",backgroundColor:l.backgroundColor},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:"1"},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${l.borderColor}`,backgroundColor:l.accentColor},children:[o.length>0&&jsxRuntime.jsx("div",{style:{padding:"12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:o.map(d=>{let v=d.mimeType?.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:l.inputBackground,borderRadius:"10px",border:`1px solid ${l.borderColor}`,fontSize:"12px",color:l.textColor,transition:"all 0.2s ease-out",cursor:"pointer",position:"relative"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:v?"transparent":l.accentColor},children:[v?jsxRuntime.jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"},onError:m=>{m.target.style.display="none";let C=m.target.nextElementSibling;C&&(C.style.display="block");}}):null,jsxRuntime.jsx(lucideReact.File,{size:"14",strokeWidth:"2",style:{display:v?"none":"block",color:l.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:"0",flex:"1"},children:[jsxRuntime.jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:d.name}),jsxRuntime.jsx("span",{style:{color:l.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:b(d.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[v&&jsxRuntime.jsx("button",{onClick:m=>{m.stopPropagation(),window.open(d.url,"_blank");},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:k("input.previewImage"),onMouseEnter:m=>{m.currentTarget.style.backgroundColor=l.hoverBackground,m.currentTarget.style.color=l.textColor;},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=l.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.Eye,{size:"12",strokeWidth:"2"})}),jsxRuntime.jsx("button",{onClick:m=>{m.stopPropagation(),f(d.id);},style:{background:"none",border:"none",color:l.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:k("input.removeFile"),onMouseEnter:m=>{m.currentTarget.style.backgroundColor="#ef444420",m.currentTarget.style.color="#ef4444";},onMouseLeave:m=>{m.currentTarget.style.backgroundColor="transparent",m.currentTarget.style.color=l.mutedTextColor;},children:jsxRuntime.jsx(lucideReact.X,{size:"12",strokeWidth:"2"})})]})]},d.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:l.mutedTextColor},children:[jsxRuntime.jsx(lucideReact.Loader2,{size:"14",strokeWidth:"2",style:{animation:"spin 1s linear infinite"}}),jsxRuntime.jsx("span",{children:k("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{"aria-label":"Prompt",rows:1,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:l.textColor,fontFamily:"inherit",overflow:"auto"},placeholder:s,value:t,onChange:d=>n(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),a||e());},ref:c})}),jsxRuntime.jsxs("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{right:"8px"}:{left:"8px"},display:"flex",alignItems:"center",gap:"4px",color:l.mutedTextColor},children:[jsxRuntime.jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,d.currentTarget.style.color=l.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=l.mutedTextColor;},"aria-label":k("input.attachFiles"),onClick:y,children:jsxRuntime.jsx(lucideReact.Paperclip,{size:"18",strokeWidth:"2"})}),jsxRuntime.jsx("button",{style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit"},onMouseEnter:d=>{d.currentTarget.style.backgroundColor=`${l.backgroundColor}99`,d.currentTarget.style.color=l.textColor;},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="transparent",d.currentTarget.style.color=l.mutedTextColor;},"aria-label":k("input.insertLink"),children:jsxRuntime.jsx(lucideReact.Link,{size:"18",strokeWidth:"2"})})]}),jsxRuntime.jsx("input",{type:"file",ref:M,multiple:true,accept:"*/*",style:{display:"none"},onChange:d=>h(d.target.files)}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",...x==="rtl"?{left:"8px"}:{right:"8px"}},children:jsxRuntime.jsx("button",{"aria-label":k(a?"input.stop":"input.send"),disabled:!a&&!t.trim(),style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a?"#ef4444":l.borderColor}`,backgroundColor:a?"#ef444420":l.cardBackground,color:a?"#ef4444":l.mutedTextColor,opacity:!a&&!t.trim()?.4:1,cursor:!a&&!t.trim()?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#dc2626",d.currentTarget.style.backgroundColor="#dc262630",d.currentTarget.style.color="#dc2626"):(d.currentTarget.style.borderColor=l.primaryColor,d.currentTarget.style.backgroundColor=l.hoverBackground,d.currentTarget.style.color=l.textColor));},onMouseLeave:d=>{d.currentTarget.disabled||(a?(d.currentTarget.style.borderColor="#ef4444",d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.color="#ef4444"):(d.currentTarget.style.borderColor=l.borderColor,d.currentTarget.style.backgroundColor=l.cardBackground,d.currentTarget.style.color=l.mutedTextColor));},onClick:()=>{a?r():e();},children:a?jsxRuntime.jsx(lucideReact.Square,{size:"18",strokeWidth:"2"}):jsxRuntime.jsx(lucideReact.ArrowUp,{size:"18",strokeWidth:"2"})})})]})})})}function mn(t){let n=Date.now()-t,e=Math.max(1,Math.floor(n/1e3));if(e<60)return `${e}s`;let r=Math.floor(e/60);if(r<60)return `${r}m`;let a=Math.floor(r/60);if(a<24)return `${a}h`;let s=Math.floor(a/24);if(s<7)return `${s}d`;let o=Math.floor(s/7);if(o<4)return `${o}w`;let i=Math.floor(s/30);return i<12?`${i}mo`:`${Math.floor(i/12)}y`}function fn({isOpen:t,onClose:n,searchQuery:e,onSearchChange:r,chats:a,currentChatId:s,onChatSelect:o,onChatDelete:i,resolvedColors:f,t:y}){if(!t)return null;let l=e.trim()?a.filter(c=>(c.title||"").toLowerCase().includes(e.toLowerCase().trim())):a,b=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:n}),jsxRuntime.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:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${f.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:e,onChange:c=>r(c.target.value),placeholder:y("history.search"),style:{width:"100%",borderRadius:"8px",backgroundColor:f.inputBackground,padding:"8px 12px",fontSize:"14px",color:f.textColor,border:`1px solid ${f.borderColor}`,outline:"none"},onFocus:c=>c.currentTarget.style.borderColor=f.primaryColor,onBlur:c=>c.currentTarget.style.borderColor=f.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:l.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:f.mutedTextColor,textAlign:"center"},children:y("history.noChatsFound")}):jsxRuntime.jsx("div",{children:l.map((c,M)=>jsxRuntime.jsx("div",{style:{borderTop:M>0?`1px solid ${f.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:c.id===s?f.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:f.textColor},onMouseEnter:h=>h.currentTarget.style.backgroundColor=f.hoverBackground,onMouseLeave:h=>h.currentTarget.style.backgroundColor="transparent",onClick:()=>o(c.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:f.textColor},children:c.title||y("history.untitledChat")})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:f.mutedTextColor},children:mn(c.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:f.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:y("history.deleteChat"),onMouseEnter:h=>{h.currentTarget.style.color="#ef4444",h.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",h.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:h=>{h.currentTarget.style.color=f.mutedTextColor,h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.borderColor="transparent";},onClick:h=>{h.stopPropagation(),i(c.id);},children:jsxRuntime.jsx(lucideReact.Trash2,{size:"16",strokeWidth:"2"})})]})},c.id))})})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(b,document.body):b}var Ot={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};var le=t=>t.map(n=>({...n}));function Br(t){let[n,e]=Bt.useState(()=>{try{return t.loadChatPreferences()}catch(o){return console.warn("Failed to load chat preferences:",o),[]}});Bt.useEffect(()=>{if(n.length!==0)try{t.persistChatData(n);}catch(o){console.warn("Failed to persist chat data:",o);}},[n]);let r=Bt.useCallback(o=>{try{t.setCurrentChatId(o);let i=t.loadChat(o);return e(i?.messages||[]),!0}catch(i){return console.warn("Failed to load selected chat:",i),false}},[t]),a=Bt.useCallback(o=>{try{t.deleteChat(o,i=>{i&&e([]);});}catch(i){console.warn("Failed to delete chat:",i);}},[t]),s=Bt.useCallback(()=>{e([]),t.setCurrentChatId(null);},[t]);return {messages:n,setMessages:e,selectChat:r,deleteChat:a,resetChat:s}}function Lr(t){let{agentId:n,theme:e="dark",primaryColor:r,backgroundColor:a,borderColor:s,textColor:o,accentColor:i,width:f=420,height:y="100vh",expandable:l=true,alwaysOpen:b=false,defaultOpen:c=false,dir:M="ltr",language:h,floatingButtonPosition:k=M==="rtl"?{bottom:16,left:16}:{bottom:16,right:16},placeholder:x,title:d,chatContainerClassName:v="",defaultReasoningOpen:m=false,hideReasoningContent:C=false}=t,u=h||(M==="rtl"?"ar":"en"),{t:g}=sn(u),T=x??g("input.placeholder"),R=d??g("general.agent"),{baseUrl:L,actions:$,components:H,setStreamingState:j,setChatOpenState:B}=Q(),I=Bt.useRef(`chat-${n}-${Date.now()}`).current,[Mt,et]=Bt.useState(""),[q,p]=Bt.useState(()=>{if(b)return true;try{let A=localStorage.getItem(`hsafaChat_${n}.showChat`);return A!==null?A==="true":c}catch{return c}}),[ce,it]=Bt.useState(false),[Y,J]=Bt.useState(""),[Tt,Kt]=Bt.useState(false),[S,vt]=Bt.useState(0),[yn,jt]=Bt.useState(null),[xn,de]=Bt.useState(""),[pe,At]=Bt.useState([]),ue=Bt.useRef(null),[ge,me]=Bt.useState(true),qt=Bt.useRef(false),bn=Bt.useRef(null),Cn=Bt.useRef(null),kn=Bt.useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),nt=Ge(n),{messages:rt,setMessages:wt,selectChat:fe,deleteChat:he,resetChat:Mn}=Br(nt),_=Qe(),St=nn(L||""),Jt=rn(),{assistantMsgIdRef:Tn,actionStatuses:vn,processActions:ye,resetActionTracking:An}=cn({actions:$,currentChatId:nt.currentChatId});Bt.useEffect(()=>{j(I,_.streaming);},[_.streaming,I,j]),Bt.useEffect(()=>(B(I,q),()=>{B(I,false),j(I,false);}),[q,I,B,j]),Bt.useEffect(()=>{if(!b)try{localStorage.setItem(`hsafaChat_${n}.showChat`,String(q));}catch(A){console.warn("Failed to save chat state:",A);}},[q,n,b]);let{attachments:Vt,uploading:xe,fileInputRef:be,formatBytes:wn,handleRemoveAttachment:Sn,handleFileSelection:Rn,clearAttachments:Ce}=St,ke=Bt.useCallback((A,F)=>{wt(P=>P.map(w=>{if(w.id===A&&w.role==="assistant"){let E=F.main_agent.find(O=>O.type==="response"),N=E?.type==="response"?E.items:[];return {...w,items:N,mainAgentActions:F.main_agent,firstAgentMessage:F.first_agent.message,firstAgentContinue:F.first_agent.continue,reasoningOpen:w.reasoningOpen}}return w}));},[]),Xt=Bt.useCallback(async({prompt:A,baseMessages:F,userMessage:P,assistantMessageId:w,chatId:E})=>{if(n){_.setError(null),_.setStreaming(true);try{let N=Ie(F);N.push({role:"user",content:P.content}),Tn.current=w,An(),await Jt.startStreaming({agentId:n,baseUrl:L,body:{prompt:A,chatId:E??void 0,messages:N},onUpdate:Dt=>{ke(w,Dt);let En=Dt.main_agent.find(zn=>zn.type==="response")?.items||[];ye(En,"partial");}});let $t=Jt.streamData?.main_agent?.find(Dt=>Dt.type==="response")?.items||[];ye($t,"final");}catch(N){_.setError(N?.message||"Request failed");}finally{_.setStreaming(false);}}},[n,L,Jt,_,ke]),$n=Bt.useCallback(A=>{fe(A)&&(it(false),J(""));},[fe,it,J]),In=Bt.useCallback(A=>{he(A),vt(F=>F+1);},[he]),ot=Ot[e],ut={primaryColor:r||ot.primaryColor,backgroundColor:a??"transparent",borderColor:s||ot.borderColor,textColor:o||ot.textColor,accentColor:i||ot.accentColor,mutedTextColor:ot.mutedTextColor,inputBackground:ot.inputBackground,cardBackground:ot.cardBackground,hoverBackground:ot.hoverBackground},Fn=Bt.useCallback(async()=>{if(!n)return;let A=Mt.trim();if(!A)return;let F=nt.currentChatId;F||(F=nt.createNewChat(A));let P=le(Vt),w=$e(A,P),E=Qt(m),N=rt;wt([...N,w,E]),et(""),Ce(),me(true),await Xt({prompt:A,baseMessages:N,userMessage:w,assistantMessageId:E.id,chatId:F});},[n,Mt,rt,Vt,Ce,Xt,nt,wt,et]),Dn=Bt.useCallback(async A=>{if(!A||!L)return;let F=Array.from(A);_.setError(null);let P=[];try{for(let w of F){if(w.size>St.MAX_UPLOAD_SIZE){_.setError(`"${w.name}" exceeds the ${St.formatBytes(St.MAX_UPLOAD_SIZE)} limit.`);continue}try{let E=new FormData;E.append("file",w);let N=await fetch(`${L}/api/uploads`,{method:"POST",body:E});if(!N.ok){let $t=await N.text().catch(()=>"");throw new Error($t||`Failed to upload ${w.name}`)}let O=await N.json(),Rt={id:O.id,name:O.name||w.name,url:O.url,mimeType:O.mimeType||w.type||"application/octet-stream",size:typeof O.size=="number"?O.size:w.size};P.push(Rt);}catch(E){console.error("Failed to upload attachment:",E),_.setError(String(E?.message??`Failed to upload ${w.name}`));}}P.length&&At(w=>[...w,...P]);}catch(w){console.error("Error adding attachments during edit:",w);}},[L,St,_]);return Bt.useEffect(()=>{if(qt.current){qt.current=false;return}ge&&requestAnimationFrame(()=>{ue.current?.scrollIntoView({behavior:"smooth",block:"end"});});},[rt,_.streaming,ge]),Bt.useEffect(()=>{let A=document.querySelector(".chat-scroll-container");if(!A)return;let F=()=>{let{scrollTop:P,scrollHeight:w,clientHeight:E}=A,O=w-P-E<40;me(O);};return A.addEventListener("scroll",F),F(),()=>A.removeEventListener("scroll",F)},[]),typeof document<"u"?reactDom.createPortal(jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:v,style:{width:q?Tt?"100%":typeof f=="number"?`${f}px`:f:"0",height:y,display:"flex",flexDirection:"column",backgroundColor:q?ut.backgroundColor:"transparent",opacity:q?1:0,padding:q?"24px 16px":"0",transition:"all 0.3s ease-out",position:"fixed",top:0,...M==="rtl"?{left:0}:{right:0},bottom:0,zIndex:Tt?9999:1e3,pointerEvents:q?"auto":"none"},children:[jsxRuntime.jsx(pn,{title:R,expandable:l,alwaysOpen:b,maximized:Tt,streaming:_.streaming,dir:M,resolvedColors:ut,onMaximize:()=>Kt(A=>!A),onNew:Mn,onToggleHistory:()=>it(A=>!A),onClose:()=>p(false),historyBtnRef:Cn,t:g}),jsxRuntime.jsx(qe,{messages:rt,streaming:_.streaming,editingMessageId:yn,editingMessageText:xn,editingAttachments:pe,error:_.error,actionStatuses:vn,components:H,theme:e,resolvedColors:ut,hideReasoningContent:C,onEditingTextChange:de,onRemoveAttachment:A=>{At(F=>F.filter(P=>P.id!==A));},onAddAttachments:Dn,uploading:xe,onStartEdit:(A,F)=>{let P=rt.find(w=>w.id===A);jt(A),de(F),P&&P.role==="user"&&At(le(gt(P)));},onCancelEdit:()=>{jt(null),At([]);},onSaveEdit:async(A,F)=>{let P=rt.findIndex($t=>$t.id===A);if(P===-1)return;let w=rt[P];if(w.role!=="user")return;let E=F.trim(),N=Fe(w,E,le(pe)),O=rt.slice(0,P),Rt=Qt(m);wt([...O,N,Rt]),jt(null),At([]),await Xt({prompt:E,baseMessages:O,userMessage:N,assistantMessageId:Rt.id,chatId:nt.currentChatId??null});},onToggleReasoning:A=>{let F=document.querySelector(".chat-scroll-container"),P=F?.scrollTop||0;qt.current=true,wt(w=>w.map(E=>E.id===A&&E.role==="assistant"?{...E,reasoningOpen:!E.reasoningOpen}:E)),requestAnimationFrame(()=>{F&&(F.scrollTop=P);});},scrollAnchorRef:ue,t:g}),jsxRuntime.jsx(gn,{value:Mt,onChange:et,onSend:Fn,onStop:_.handleStop,streaming:_.streaming,placeholder:T,attachments:Vt,uploading:xe,onRemoveAttachment:Sn,onFileInputClick:()=>be.current?.click(),resolvedColors:ut,formatBytes:wn,textareaRef:bn,fileInputRef:be,onFileSelection:A=>Rn(A,_.setError),t:g,dir:M})]}),jsxRuntime.jsx(Je,{show:!q&&!b,onClick:()=>p(true),resolvedColors:ut,floatingButtonPosition:k}),jsxRuntime.jsx(fn,{isOpen:ce,onClose:()=>it(false),searchQuery:Y,onSearchChange:J,chats:nt.loadChatsIndex(),currentChatId:nt.currentChatId,onChatSelect:$n,onChatDelete:In,resolvedColors:ut,t:g}),jsxRuntime.jsx("style",{children:`
17
17
  @keyframes ${kn.current}-border-flow {
18
18
  0% { background-position: 0% 50%; }
19
19
  50% { background-position: 100% 50%; }