@hsafa/ui-sdk 0.1.3 → 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.cjs +18 -72
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +438 -43
- package/dist/index.d.ts +438 -43
- package/dist/index.js +18 -72
- package/dist/index.js.map +1 -1
- package/examples/nested-chat-example.tsx +61 -0
- package/package.json +5 -1
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';
|
|
2
|
-
`)
|
|
3
|
-
`))!==-1;){let X=R.slice(0,L).trim();if(R=R.slice(L+1),!!X)try{let f=JSON.parse(X);if(f?.type==="meta"){if(f.actionExecuteMap&&typeof f.actionExecuteMap=="object"&&(Re.current=f.actionExecuteMap),f.assistantMessageId&&(ie.current=String(f.assistantMessageId),he.current.clear(),Ce.current.clear(),J.current.clear(),ee(new Map)),f.chatId&&!I){Z(f.chatId),U.current=!0;let $=e,i=(G.current||$||"New chat").slice(0,80),s=Date.now();ue({id:f.chatId,title:i,createdAt:s,updatedAt:s}),de({id:f.chatId,messages:c,agentId:l});try{localStorage.setItem(_,f.chatId);}catch{}}continue}if(f?.type==="reasoning"){let $=String(f.text??"");T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,reasoning:(s.reasoning??"")+$}:s));continue}if(f?.type==="tool-call"){let $=f.toolName,i=f.args;T(s=>s.map(C=>C.id===o&&C.role==="assistant"?{...C,mcpToolCalls:[...C.mcpToolCalls||[],{toolName:$,args:i,timestamp:Date.now(),status:"running"}]}:C));continue}if(f?.type==="tool-result"){let $=f.toolName,i=f.result;T(s=>s.map(C=>C.id===o&&C.role==="assistant"?{...C,mcpToolCalls:(C.mcpToolCalls||[]).map(y=>y.toolName===$?{...y,status:"completed"}:y),mcpToolResults:{...C.mcpToolResults||{},[$]:i}}:C));continue}if(f?.type==="partial"||f?.type==="final"){let $=f.value;$&&Array.isArray($.items)&&(T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,items:$.items}:s)),_e($.items,f.type==="partial"?"partial":"final")),f?.type==="final"&&T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,reasoningOpen:!1}:s));continue}if(f?.type==="usage"){let $=f?.value?.reasoningTokens;typeof $=="number"&&T(i=>i.map(s=>s.id===o&&s.role==="assistant"?{...s,reasoningTokens:$}:s));continue}if(f?.type==="error"){K(String(f.error??"Unknown error"));continue}}catch{}}}}catch(d){K(String(d?.message??d));}finally{if(se(false),!I&&!U.current){let d=`local-${pe()}`;Z(d),U.current=true;let g=(G.current||"New chat").slice(0,80),z=Date.now();ue({id:d,title:g,createdAt:z,updatedAt:z}),de({id:d,messages:E,agentId:l});try{localStorage.setItem(_,d);}catch{}}}}function wt(e,a,o){return !Array.isArray(e)||e.length===0?null:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.map((n,u)=>{let c=`it-${u}`;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},c);if(n&&typeof n=="object"){if(n.type==="action"){let p=`${String(n.name??"action")}:${u}`,d=bt.get(p);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"]})})},c)}if(n.type==="ui-component"||n.type==="ui"){let p=String(n.name??n.component??"").trim(),d=p?it.get(p):void 0;return d?jsx("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:jsx(d,{...n.props||{}})},c):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:p||"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)})]},c)}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)})},c)}return null}),a&&a.length>0&&(()=>{let n=new Map;a.forEach(p=>{let d=n.get(p.toolName);!d||d.status==="running"&&p.status==="completed"?n.set(p.toolName,{status:p.status||"pending",count:(d?.count||0)+1}):d&&d.count++;});let u=Array.from(n.values()).some(p=>p.status==="running"),c=Array.from(n.values()).filter(p=>p.status==="completed").length;return jsxs("div",{style:{borderRadius:"12px",padding:"12px",backgroundColor:t.cardBackground,border:`1px solid ${t.borderColor}`,fontSize:"12px",color:t.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:u?"#3b82f6":"#10b981"}}),jsx("span",{children:u?"Agent is using tools":c>0?`Agent used ${c} tool${c>1?"s":""}`:"Agent used tools"})]}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Array.from(n.entries()).map(([p,d])=>jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"11px",padding:"4px 8px",borderRadius:"6px",backgroundColor:t.inputBackground,border:`1px solid ${t.borderColor}`},children:[d.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:d.status==="completed"?"#10b981":"#ef4444",flexShrink:0}}),jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"120px"},children:p}),d.count>1&&jsxs("span",{style:{opacity:.6,flexShrink:0,fontSize:"10px"},children:["\xD7",d.count]})]},p))})]})})()]})}let V=Zt[m],t={primaryColor:v||V.primaryColor,backgroundColor:N||V.backgroundColor,borderColor:A||V.borderColor,textColor:P||V.textColor,accentColor:q||V.accentColor,mutedTextColor:V.mutedTextColor,inputBackground:V.inputBackground,cardBackground:V.cardBackground,hoverBackground:V.hoverBackground},Tt={backgroundColor:t.backgroundColor,color:t.textColor,height:fe,display:"flex",width:"100%",fontFamily:'Rubik, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif'},St={width:typeof Q=="number"?`${Q}px`:Q,maxWidth:typeof ne=="number"?`${ne}px`:ne,display:"flex",flexDirection:"column",transition:"all 0.3s ease-out",overflow:"hidden"},Mt={position:"fixed",bottom:typeof w.bottom=="number"?`${w.bottom}px`:w.bottom,right:w.right?typeof w.right=="number"?`${w.right}px`:w.right:void 0,top:w.top?typeof w.top=="number"?`${w.top}px`:w.top:void 0,left:w.left?typeof w.left=="number"?`${w.left}px`:w.left:void 0,zIndex:1e3},Ie=typeof ve=="number"?`${ve}px`:ve,B=useRef(`hsafa-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return jsxs("div",{className:at,style:Tt,dir:h,"data-hsafa-chat":B.current,children:[jsx("div",{style:{display:"flex",alignItems:"stretch",justifyContent:"stretch",width:"100%",height:"100%",transition:"all 0.3s ease-out",padding:Y&&ot?"16px":"0"},children:jsx("div",{style:{position:"relative",display:"flex",width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Y&&ze?Ie:"0"},children:Y&&ze?jsx("div",{style:{width:"100%",height:"100%",transition:"all 0.3s ease-out",borderRadius:Ie,border:k&&ae?"none":`1px solid ${t.borderColor}`,padding:k&&ae?"1.5px":"0",background:k&&ae?`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:k&&ae?"300% 300%":"auto",animation:k&&ae?`${B.current}-border-flow 3s ease-in-out infinite`:"none",filter:k&&ae?`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,overflowX:"hidden",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${t.mutedTextColor}40 transparent`},children:x})}):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:`${t.mutedTextColor}40 transparent`},children:x})})}),jsxs("div",{className:st,style:{...St,height:fe,backgroundColor:Y||M?t.backgroundColor:"transparent",...Y||M?We&&H?{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:h==="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:Ee,style:{color:t.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:Ee})}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:t.mutedTextColor},children:[H&&jsx("button",{"aria-label":We?"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),ut(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(!k){T([]),K(null),Z(null),U.current=false,G.current=null;try{localStorage.removeItem(_);}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:()=>Te(e=>!e),ref:xt,children:jsx(IconHistory,{size:20,stroke:2})}),lt&&(()=>{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:()=>Te(false)}),jsxs("div",{ref:mt,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:je,onChange:a=>ct(a.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:a=>a.currentTarget.style.borderColor=t.primaryColor,onBlur:a=>a.currentTarget.style.borderColor=t.borderColor})})}),jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let a=je.toLowerCase().trim(),o=$e();return a&&(o=o.filter(n=>(n.title||"").toLowerCase().includes(a))),!o||o.length===0?jsx("div",{style:{padding:"24px",color:t.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsx("div",{children:o.map((n,u)=>jsx("div",{style:{borderTop:u>0?`1px solid ${t.borderColor}`:"none"},children:jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:n.id===I?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:c=>c.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:c=>c.currentTarget.style.backgroundColor="transparent",onClick:()=>{let c=Ve(n.id);if(c){Z(n.id),U.current=true,T(c.messages||[]);try{localStorage.setItem(_,n.id);}catch{}Te(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:n.title||"Untitled chat"})}),jsx("div",{style:{flexShrink:0,fontSize:"12px",color:t.mutedTextColor},children:Yt(n.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:c=>{c.currentTarget.style.color="#ef4444",c.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",c.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:c=>{c.currentTarget.style.color=t.mutedTextColor,c.currentTarget.style.backgroundColor="transparent",c.currentTarget.style.borderColor="transparent";},onClick:c=>{c.stopPropagation(),kt(n.id),dt(p=>p+1);},children:jsx(IconTrash,{size:16,stroke:2})})]})},n.id))})})()})]})]});return typeof document<"u"&&document.body?createPortal(e,document.body):e})(),!M&&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:h==="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:ft,onScroll:e=>{let a=e.currentTarget,u=a.scrollHeight-(a.scrollTop+a.clientHeight)<=64;u!==Se&&yt(u);},children:[Pe&&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:Pe}),E.length===0&&!k&&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:E.map((e,a)=>jsx("div",{style:{padding:"0 4px"},children:e.role==="user"?pt===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:o=>Ue(o.target.value),onKeyDown:o=>{o.key==="Escape"?me(null):o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),k||Oe(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:o=>o.currentTarget.style.backgroundColor=t.inputBackground,onMouseLeave:o=>o.currentTarget.style.backgroundColor="transparent",onClick:()=>me(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:o=>o.currentTarget.style.borderColor=t.primaryColor,onMouseLeave:o=>o.currentTarget.style.borderColor=t.borderColor,onClick:()=>{k||Oe(e.id,be||e.text);},children:"Save"})]})]}):jsx("div",{title:"Click to edit",onClick:()=>{k||(me(e.id),Ue(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:o=>o.currentTarget.style.backgroundColor=t.hoverBackground,onMouseLeave:o=>o.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:()=>{Me.current=true,T(o=>o.map(n=>n.id===e.id&&n.role==="assistant"?{...n,reasoningOpen:!n.reasoningOpen}:n));},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:o=>o.currentTarget.style.color=t.textColor,onMouseLeave:o=>o.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 o=(e.reasoning||"").trim().split(`
|
|
4
|
-
`).
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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&<.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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/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="${B.current}"] textarea::placeholder {
|
|
26
|
-
color: ${t.mutedTextColor};
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/* Ensure textarea styles work in all environments */
|
|
30
|
-
[data-hsafa-chat="${B.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="${B.current}"] .content-container::-webkit-scrollbar {
|
|
40
|
-
width: 6px;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
[data-hsafa-chat="${B.current}"] .content-container::-webkit-scrollbar-track {
|
|
44
|
-
background: transparent;
|
|
45
|
-
border-radius: 3px;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
[data-hsafa-chat="${B.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="${B.current}"] .content-container::-webkit-scrollbar-thumb:hover {
|
|
55
|
-
background: ${t.mutedTextColor}60;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/* Chat scrollbar styles */
|
|
59
|
-
[data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar {
|
|
60
|
-
width: 4px;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
[data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar-track {
|
|
64
|
-
background: transparent;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
[data-hsafa-chat="${B.current}"] .chat-scroll-container::-webkit-scrollbar-thumb {
|
|
68
|
-
background: ${t.borderColor};
|
|
69
|
-
border-radius: 2px;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
[data-hsafa-chat="${B.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="${B.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="${B.current}"] .content-container * {
|
|
83
|
-
/* Any fixed, absolute, or sticky elements will be contained */
|
|
84
|
-
max-width: 100% !important;
|
|
85
|
-
}
|
|
86
|
-
`})]})}export{or as Button,Gt as HsafaChat,Ft as HsafaProvider,dr as useAutoScroll,oe as useHsafa,br as useHsafaAction,vr as useHsafaComponent,ir 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
|