import{a$ as Oe,w as et,Q as Ee,N as Ge,u as We,x as Ft,r as l,y as wa,H as At,e,D as at,f as ht,g as nt,dy as ia,A as te,a4 as Et,S as Ue,B as G,ar as uo,as as us,at as po,aO as ho,av as ns,aw as je,bR as ka,a9 as vt,au as fo,i as ft,l as Nt,al as Ca,G as we,b3 as go,a7 as xe,ef as mo,eg as xo,eh as yo,ax as ps,ay as hs,L as Me,T as de,az as fs,J as gt,K as mt,P as p,n as bo,af as dt,W as jo,$ as $e,a0 as Xe,aW as wo,a2 as la,b0 as Sa,ei as va,a1 as ko,a3 as Co,ej as So,ek as vo,el as Zt,em as Io,d as Do,cL as gs,ac as es,cN as os,en as To,O as qe,h as Mo,a5 as ce,a6 as Ao,cX as Eo,eo as ms,_ as Ro,ep as Fo,Z as ut,q as No,b_ as Ia,dZ as Da,d_ as Ta,M as Ma,ai as Pe,aj as Po,dq as Uo,dr as Oo,aJ as pt,cO as Lo,ak as zo,aN as Ae,bo as Bo,dN as ca,cU as Ho,eq as xs,k as Aa,aq as Ze,aZ as da,dC as Ea,aB as rs,er as $o,es as Wo,et as qo,eu as Go,ev as _o,ew as Vo,ex as Jo,ey as Qo,aH as tt,ez as Ko,eA as Yo,eB as Xo,eC as Zo,eD as er,eE as tr,eF as sr,aR as ar,eG as nr,eH as or,a8 as Ra,eI as rr,eJ as ir,eK as lr,bV as ys,eL as cr,eM as lt,eN as Tt,cV as ct,e0 as dr,dB as ur,dE as ua,dD as pa,dF as pr,dG as hr,c4 as fr,eO as gr,dI as ts,dJ as mr,cW as xr,U as yr,eP as br,eQ as jr}from"./index-_6SmYgWK.js";import{S as wr,A as kr,V as Cr,a as Sr,C as vr,L as Ir,I as Dr,e as is,u as Tr,f as Mr,g as Mt,m as Ar,h as Er,l as Rr,t as ha,i as Fr}from"./index-BupL1YuJ.js";import{d as bs}from"./ExpandMore-DfVpxsz-.js";import{T as Nr}from"./Table-DcZ35doG.js";import{v as ls,H as Pr}from"./vectorstore-khdhkL5P.js";import{I as Ur}from"./NodeInfoDialog-BSQc04od.js";import{I as Or}from"./IconDeviceFloppy-WiT0BtR9.js";import{D as Lr,N as zr,a as cs}from"./DocStoreInputHandler-CaPW_OoW.js";import{L as Br}from"./llamaindex-B_JSDULd.js";import{v as Hr}from"./v4-CtRu48qb.js";/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var fa=Oe("outline","circle-dot","IconCircleDot",[["path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",key:"svg-0"}],["path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0",key:"svg-1"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var $r=Oe("outline","microphone","IconMicrophone",[["path",{d:"M9 2m0 3a3 3 0 0 1 3 -3h0a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3h0a3 3 0 0 1 -3 -3z",key:"svg-0"}],["path",{d:"M5 10a7 7 0 0 0 14 0",key:"svg-1"}],["path",{d:"M8 21l8 0",key:"svg-2"}],["path",{d:"M12 17l0 4",key:"svg-3"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var Wr=Oe("outline","minus","IconMinus",[["path",{d:"M5 12l14 0",key:"svg-0"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var ga=Oe("outline","photo-plus","IconPhotoPlus",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M12.5 21h-6.5a3 3 0 0 1 -3 -3v-12a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6.5",key:"svg-1"}],["path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l4 4",key:"svg-2"}],["path",{d:"M14 14l1 -1c.67 -.644 1.45 -.824 2.182 -.54",key:"svg-3"}],["path",{d:"M16 19h6",key:"svg-4"}],["path",{d:"M19 16v6",key:"svg-5"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var Hi=Oe("outline","refresh-alert","IconRefreshAlert",[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}],["path",{d:"M12 9l0 3",key:"svg-2"}],["path",{d:"M12 15l.01 0",key:"svg-3"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var ss=Oe("outline","send","IconSend",[["path",{d:"M10 14l11 -11",key:"svg-0"}],["path",{d:"M21 3l-6.5 18a.55 .55 0 0 1 -1 0l-3.5 -7l-7 -3.5a.55 .55 0 0 1 0 -1l18 -6.5",key:"svg-1"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var qr=Oe("outline","thumb-down","IconThumbDown",[["path",{d:"M7 13v-8a1 1 0 0 0 -1 -1h-2a1 1 0 0 0 -1 1v7a1 1 0 0 0 1 1h3a4 4 0 0 1 4 4v1a2 2 0 0 0 4 0v-5h3a2 2 0 0 0 2 -2l-1 -5a2 3 0 0 0 -2 -2h-7a3 3 0 0 0 -3 3",key:"svg-0"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var Gr=Oe("outline","thumb-up","IconThumbUp",[["path",{d:"M7 11v8a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1v-7a1 1 0 0 1 1 -1h3a4 4 0 0 0 4 -4v-1a2 2 0 0 1 4 0v5h3a2 2 0 0 1 2 2l-1 5a2 3 0 0 1 -2 2h-7a3 3 0 0 1 -3 -3",key:"svg-0"}]]);/**
 * @license @tabler/icons-react v3.31.0 - MIT
 *
 * This source code is licensed under the MIT license.
 * See the LICENSE file in the root directory of this source tree.
 */var _r=Oe("filled","square-filled","IconSquareFilled",[["path",{d:"M19 2h-14a3 3 0 0 0 -3 3v14a3 3 0 0 0 3 3h14a3 3 0 0 0 3 -3v-14a3 3 0 0 0 -3 -3z",key:"svg-0"}]]);const ds=l.forwardRef(function({value:o,onClick:c},g){return e.jsx(Ca,{style:{borderRadius:15,border:"1px solid #e0e0e0"},onClick:c,ref:g,children:o})});ds.propTypes={value:p.string,onClick:p.func};function Fa(a){var m,R,D,z;const[o,c]=l.useState(!1),[g,f]=l.useState({}),j=U=>(H,F)=>{const B={...g};B[U]=F,f(B)},u=a.selected.indexOf(a.upsertHistory.id)!==-1;return e.jsxs(e.Fragment,{children:[e.jsxs(ns,{sx:{"&:last-child td, &:last-child th":{border:0}},children:[e.jsx(je,{padding:"checkbox",children:e.jsx(ka,{color:"primary",checked:u,onChange:U=>a.handleSelect(U,a.upsertHistory.id),inputProps:{"aria-labelledby":a.upsertHistory.id}})}),e.jsx(je,{children:go(a.upsertHistory.date).format("MMMM Do YYYY, h:mm:ss a")}),e.jsx(je,{children:((m=a.upsertHistory.result)==null?void 0:m.numAdded)??"0"}),e.jsx(je,{children:((R=a.upsertHistory.result)==null?void 0:R.numUpdated)??"0"}),e.jsx(je,{children:((D=a.upsertHistory.result)==null?void 0:D.numSkipped)??"0"}),e.jsx(je,{children:((z=a.upsertHistory.result)==null?void 0:z.numDeleted)??"0"}),e.jsx(je,{children:e.jsx(xe,{"aria-label":"expand row",size:"small",color:"inherit",onClick:()=>c(!o),children:o?e.jsx(mo,{}):e.jsx(xo,{})})})]}),o&&e.jsx(ns,{sx:{"& td":{border:0}},children:e.jsx(je,{sx:{pb:0,pt:0},colSpan:6,children:e.jsx(yo,{in:o,timeout:"auto",unmountOnExit:!0,children:e.jsx(G,{sx:{mt:1,mb:2},children:(a.upsertHistory.flowData??[]).map((U,H)=>e.jsxs(ps,{expanded:g[U.id]||!1,onChange:j(U.id),disableGutters:!0,children:[e.jsx(hs,{expandIcon:e.jsx(bs,{}),"aria-controls":`nodes-accordian-${U.name}`,id:`nodes-accordian-header-${U.name}`,children:e.jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e.jsx("div",{style:{width:40,height:40,marginRight:10,borderRadius:"50%",backgroundColor:"white"},children:e.jsx("img",{style:{width:"100%",height:"100%",padding:7,borderRadius:"50%",objectFit:"contain"},alt:U.name,src:`${Me}/api/v1/node-icon/${U.name}`})}),e.jsx(de,{variant:"h5",children:U.label}),e.jsx("div",{style:{display:"flex",flexDirection:"row",width:"max-content",borderRadius:15,background:"rgb(254,252,191)",padding:5,paddingLeft:10,paddingRight:10,marginLeft:10},children:e.jsx("span",{style:{color:"rgb(116,66,16)",fontSize:"0.825rem"},children:U.id})})]})}),e.jsx(fs,{children:U.paramValues[0]&&e.jsx(Nr,{sx:{minWidth:150},rows:U.paramValues,columns:Object.keys(U.paramValues[0])})})]},H))})})})})]})}Fa.propTypes={upsertHistory:p.object,theme:p.any,isDarkMode:p.bool,selected:p.array,handleSelect:p.func};const Na=({show:a,dialogProps:o,onCancel:c})=>{const g=document.getElementById("portal"),f=et(),j=Ee(h=>h.customization),u=Ge(),m=We(ls.getUpsertHistory);Ft();const R=(...h)=>f(gt(...h)),D=(...h)=>f(mt(...h)),[z,U]=l.useState([]),[H,F]=l.useState(new Date(new Date().setMonth(new Date().getMonth()-1))),[B,_]=l.useState(new Date),[b,x]=l.useState([]),A=h=>{if(h.target.checked){const S=z.map(N=>N.id);x(S);return}x([])},I=h=>{const S=new Date(h);S.setHours(0,0,0,0),F(S),m.request(o.chatflow.id,{startDate:S,endDate:B})},X=h=>{const S=new Date(h);S.setHours(23,59,59,999),_(S),m.request(o.chatflow.id,{endDate:S,startDate:H})},q=(h,S)=>{const N=b.indexOf(S);let P=[];N===-1?P=P.concat(b,S):N===0?P=P.concat(b.slice(1)):N===b.length-1?P=P.concat(b.slice(0,-1)):N>0&&(P=P.concat(b.slice(0,N),b.slice(N+1))),x(P)},ne=async()=>{try{await ls.deleteUpsertHistory(b),R({message:"Succesfully deleted upsert history",options:{key:new Date().getTime()+Math.random(),variant:"success",action:h=>e.jsx(te,{style:{color:"white"},onClick:()=>D(h),children:e.jsx(we,{})})}}),U(z.filter(h=>!b.includes(h.id))),x([])}catch(h){R({message:`Failed to delete Upsert History: ${typeof h.response.data=="object"?h.response.data.message:h.response.data}`,options:{key:new Date().getTime()+Math.random(),variant:"error",persist:!0,action:S=>e.jsx(te,{style:{color:"white"},onClick:()=>D(S),children:e.jsx(we,{})})}}),x([])}};l.useEffect(()=>{m.data&&U(m.data)},[m.data]),l.useEffect(()=>(o.chatflow&&m.request(o.chatflow.id),()=>{U([]),F(new Date(new Date().setMonth(new Date().getMonth()-1))),_(new Date)}),[o]),l.useEffect(()=>(f(a?{type:wa}:{type:At}),()=>f({type:At})),[a,f]);const y=a?e.jsxs(at,{onClose:c,open:a,fullWidth:!0,maxWidth:"lg","aria-labelledby":"upsert-history-dialog-title","aria-describedby":"upsert-history-dialog-description",children:[e.jsx(ht,{sx:{fontSize:"1rem"},id:"upsert-history-dialog-title",children:o.title}),e.jsx(nt,{children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",width:"100%",marginBottom:10},children:[e.jsxs("div",{style:{marginRight:10},children:[e.jsx("b",{style:{marginRight:10},children:"From Date"}),e.jsx(ia,{selected:H,onChange:h=>I(h),selectsStart:!0,startDate:H,endDate:B,customInput:e.jsx(ds,{})})]}),e.jsxs("div",{style:{marginRight:10},children:[e.jsx("b",{style:{marginRight:10},children:"To Date"}),e.jsx(ia,{selected:B,onChange:h=>X(h),selectsEnd:!0,startDate:H,endDate:B,minDate:H,maxDate:new Date,customInput:e.jsx(ds,{})})]})]}),b.length>0&&e.jsxs(te,{sx:{mt:1,mb:2},variant:"outlined",onClick:ne,color:"error",startIcon:e.jsx(Et,{}),children:["Delete ",b.length," ",b.length===1?"row":"rows"]}),z.length<=0&&e.jsxs(Ue,{sx:{alignItems:"center",justifyContent:"center"},flexDirection:"column",children:[e.jsx(G,{sx:{p:7,height:"auto"},children:e.jsx("img",{style:{objectFit:"cover",height:"20vh",width:"auto"},src:Pr,alt:"HistoryEmptySVG"})}),e.jsx("div",{children:"No Upsert History Yet"})]}),z.length>0&&e.jsx(uo,{component:us,children:e.jsxs(po,{sx:{minWidth:650},"aria-label":"simple table",children:[e.jsx(ho,{children:e.jsxs(ns,{children:[e.jsx(je,{padding:"checkbox",children:e.jsx(ka,{color:"primary",checked:b.length===z.length,onChange:A,inputProps:{"aria-label":"select all"}})}),e.jsx(je,{children:"Date"}),e.jsxs(je,{children:["Added"," ",e.jsx(vt,{style:{marginBottom:2,marginLeft:10},title:"Number of vector embeddings added to Vector Store"})]}),e.jsxs(je,{children:["Updated"," ",e.jsx(vt,{style:{marginBottom:2,marginLeft:10},title:"Updated existing vector embeddings. Only works when a Record Manager is connected to the Vector Store"})]}),e.jsxs(je,{children:["Skipped"," ",e.jsx(vt,{style:{marginBottom:2,marginLeft:10},title:"Number of same vector embeddings that exists, and were skipped re-upserting again. Only works when a Record Manager is connected to the Vector Store"})]}),e.jsxs(je,{children:["Deleted"," ",e.jsx(vt,{style:{marginBottom:2,marginLeft:10},title:"Deleted vector embeddings. Only works when a Record Manager with a Cleanup method is connected to the Vector Store"})]}),e.jsx(je,{children:"Details"})]})}),e.jsx(fo,{children:z.map((h,S)=>e.jsx(Fa,{upsertHistory:h,theme:u,isDarkMode:j.isDarkMode,selected:b,handleSelect:q},S))})]})})]})}),e.jsx(ft,{children:e.jsx(te,{onClick:c,children:"Close"})})]}):null;return Nt.createPortal(y,g)};Na.propTypes={show:p.bool,dialogProps:p.object,onCancel:p.func};const Vr=({chatflow:a,isAgentCanvas:o,isAgentflowV2:c,handleSaveFlow:g,handleDeleteFlow:f,handleLoadFlow:j})=>{const u=Ge(),m=et(),R=bo(),D=l.useRef(),z=l.useRef(),[U,H]=l.useState(null),[F,B]=l.useState(""),[_,b]=l.useState(!1),[x,A]=l.useState(!1),[I,X]=l.useState(!1),[q,ne]=l.useState({}),[y,h]=l.useState(!1),[S,N]=l.useState({}),[P,O]=l.useState(!1),[V,oe]=l.useState({}),[ee,w]=l.useState(!1),[L,re]=l.useState({}),[se,Q]=l.useState(!1),[ie,ve]=l.useState({}),[ke,Te]=l.useState(!1),[Re,Le]=l.useState({}),me=(...$)=>m(gt(...$)),C=(...$)=>m(mt(...$)),[T,M]=l.useState(o?"agentflows:create":"chatflows:create"),v=o?"Agents":"Chatflow",W=We(dt.updateChatflow),Z=Ee($=>$.canvas),ae=$=>{if(b(!1),$==="deleteChatflow")f();else if($==="viewMessages")N({title:"View Messages",chatflow:a,isChatflow:!c}),h(!0);else if($==="viewLeads")oe({title:"View Leads",chatflow:a}),O(!0);else if($==="saveAsTemplate"){if(Z.isDirty){me({message:"Please save the flow before exporting as template",options:{key:new Date().getTime()+Math.random(),variant:"error",persist:!0,action:le=>e.jsx(te,{style:{color:"white"},onClick:()=>C(le),children:e.jsx(we,{})})}});return}Le({title:"Export As Template",chatflow:a}),Te(!0)}else if($==="viewUpsertHistory")re({title:"View Upsert History",chatflow:a}),w(!0);else if($==="chatflowConfiguration")ve({title:`${v} Configuration`,chatflow:a}),Q(!0);else if($==="duplicateChatflow")try{let le=a.flowData;const Ie=JSON.parse(le);le=JSON.stringify(Ie),localStorage.setItem("duplicatedFlowData",le),c?window.open(`${Zt}/v2/agentcanvas`,"_blank"):o?window.open(`${Zt}/agentcanvas`,"_blank"):window.open(`${Zt}/canvas`,"_blank")}catch(le){console.error(le)}else if($==="exportChatflow")try{const le=JSON.parse(a.flowData);let Ie=JSON.stringify(Io(le),null,2);const Fe=new Blob([Ie],{type:"application/json"}),Ve=URL.createObjectURL(Fe);let Se=`${a.name} ${v}.json`,Je=document.createElement("a");Je.setAttribute("href",Ve),Je.setAttribute("download",Se),Je.click()}catch(le){console.error(le)}},K=$=>{b(!1),j($)},pe=()=>{if(a.id){const $={name:D.current.value};W.request(a.id,$)}},Ce=()=>{let $=!1;try{const Fe=JSON.parse(a.flowData).nodes;for(const Ve of Fe)if(Ve.data.inputParams.find(Se=>Se.type==="file")){$=!0;break}}catch(Ie){console.error(Ie)}let le=!1;try{const Fe=JSON.parse(a.flowData).nodes;for(const Ve of Fe)if(Ve.data.inputParams.find(Se=>Se.name==="sessionId")){le=!0;break}}catch(Ie){console.error(Ie)}ne({title:"Embed in website or use as API",chatflowid:a.id,chatflowApiKeyId:a.apikeyid,isFormDataRequired:$,isSessionMemory:le,isAgentCanvas:o,isAgentflowV2:c}),X(!0)},_e=()=>{a.id?g(F):A(!0)},ot=$=>{A(!1),M(o?"agentflows:update":"chatflows:update"),g($)};return l.useEffect(()=>{W.data&&(B(W.data.name),M(o?"agentflows:update":"chatflows:update"),m({type:jo,chatflow:W.data})),H(!1)},[W.data]),l.useEffect(()=>{a&&(B(a.name),se&&ve({title:`${v} Configuration`,chatflow:a}))},[a,v,se]),e.jsxs(e.Fragment,{children:[e.jsxs(Ue,{flexDirection:"row",justifyContent:"space-between",sx:{width:"100%"},children:[e.jsxs(Ue,{flexDirection:"row",sx:{width:"100%",maxWidth:"50%"},children:[e.jsx(G,{children:e.jsx($e,{title:"Back",sx:{borderRadius:"50%"},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",background:u.palette.secondary.light,color:u.palette.secondary.dark,"&:hover":{background:u.palette.secondary.dark,color:u.palette.secondary.light}},color:"inherit",onClick:()=>{window.history.state&&window.history.state.idx>0?R(-1):R("/",{replace:!0})},children:e.jsx(wo,{stroke:1.5,size:"1.3rem"})})})}),e.jsx(G,{sx:{width:"100%"},children:U?e.jsxs(Ue,{flexDirection:"row",sx:{width:"100%"},children:[e.jsx(Sa,{autoFocus:!0,size:"small",inputRef:D,sx:{width:"100%",ml:2},defaultValue:F,onKeyDown:$=>{$.key==="Enter"?pe():$.key==="Escape"&&H(!1)}}),e.jsx($e,{title:"Save Name",sx:{borderRadius:"50%"},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",background:u.palette.success.light,color:u.palette.success.dark,ml:1,"&:hover":{background:u.palette.success.dark,color:u.palette.success.light}},color:"inherit",onClick:pe,children:e.jsx(va,{stroke:1.5,size:"1.3rem"})})}),e.jsx($e,{title:"Cancel",sx:{borderRadius:"50%"},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",background:u.palette.error.light,color:u.palette.error.dark,ml:1,"&:hover":{background:u.palette.error.dark,color:u.palette.error.light}},color:"inherit",onClick:()=>H(!1),children:e.jsx(we,{stroke:1.5,size:"1.3rem"})})})]}):e.jsxs(Ue,{flexDirection:"row",children:[e.jsxs(de,{sx:{fontSize:"1.5rem",fontWeight:600,ml:2,textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap"},children:[Z.isDirty&&e.jsx("strong",{style:{color:u.palette.orange.main},children:"*"})," ",F]}),(a==null?void 0:a.id)&&e.jsx(la,{permission:T,children:e.jsx($e,{title:"Edit Name",sx:{borderRadius:"50%"},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",ml:1,background:u.palette.secondary.light,color:u.palette.secondary.dark,"&:hover":{background:u.palette.secondary.dark,color:u.palette.secondary.light}},color:"inherit",onClick:()=>H(!0),children:e.jsx(Ur,{stroke:1.5,size:"1.3rem"})})})})]})})]}),e.jsxs(G,{children:[(a==null?void 0:a.id)&&e.jsx($e,{title:"API Endpoint",sx:{borderRadius:"50%",mr:2},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",background:u.palette.canvasHeader.deployLight,color:u.palette.canvasHeader.deployDark,"&:hover":{background:u.palette.canvasHeader.deployDark,color:u.palette.canvasHeader.deployLight}},color:"inherit",onClick:Ce,children:e.jsx(ko,{stroke:1.5,size:"1.3rem"})})}),e.jsx(la,{permission:T,children:e.jsx($e,{title:`Save ${v}`,sx:{borderRadius:"50%",mr:2},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",background:u.palette.canvasHeader.saveLight,color:u.palette.canvasHeader.saveDark,"&:hover":{background:u.palette.canvasHeader.saveDark,color:u.palette.canvasHeader.saveLight}},color:"inherit",onClick:_e,children:e.jsx(Or,{stroke:1.5,size:"1.3rem"})})})}),e.jsx($e,{ref:z,title:"Settings",sx:{borderRadius:"50%"},children:e.jsx(Xe,{variant:"rounded",sx:{...u.typography.commonAvatar,...u.typography.mediumAvatar,transition:"all .2s ease-in-out",background:u.palette.canvasHeader.settingsLight,color:u.palette.canvasHeader.settingsDark,"&:hover":{background:u.palette.canvasHeader.settingsDark,color:u.palette.canvasHeader.settingsLight}},onClick:()=>b(!_),children:e.jsx(Co,{stroke:1.5,size:"1.3rem"})})})]})]}),e.jsx(wr,{chatflow:a,isSettingsOpen:_,anchorEl:z.current,onClose:()=>b(!1),onSettingsItemClick:ae,onUploadFile:K,isAgentCanvas:o}),e.jsx(So,{show:x,dialogProps:{title:`Save New ${v}`,confirmButtonName:"Save",cancelButtonName:"Cancel"},onCancel:()=>A(!1),onConfirm:ot}),I&&e.jsx(kr,{show:I,dialogProps:q,onCancel:()=>X(!1)}),e.jsx(Cr,{show:y,dialogProps:S,onCancel:()=>h(!1)}),e.jsx(Sr,{show:P,dialogProps:V,onCancel:()=>O(!1)}),ke&&e.jsx(vo,{show:ke,dialogProps:Re,onCancel:()=>Te(!1)}),e.jsx(Na,{show:ee,dialogProps:L,onCancel:()=>w(!1)}),e.jsx(vr,{show:se,dialogProps:ie,onCancel:()=>Q(!1),isAgentCanvas:o},"chatflowConfiguration")]})};Vr.propTypes={chatflow:p.object,handleSaveFlow:p.func,handleDeleteFlow:p.func,handleLoadFlow:p.func,isAgentCanvas:p.bool,isAgentflowV2:p.bool};const Jr="/assets/agentflow-generator-DGaU2pb2.gif",Qr=[{text:"An agent that can autonomously search the web and generate report"},{text:"Summarize a document"},{text:"Generate response to user queries and send it to Slack"},{text:"A team of agents that can handle all customer queries"}],Pa=({show:a,dialogProps:o,onCancel:c,onConfirm:g})=>{const f=document.getElementById("portal"),[j,u]=l.useState(""),[m,R]=l.useState(""),[D,z]=l.useState(!1),[U,H]=l.useState(0),[F,B]=l.useState([]),[_,b]=l.useState([]),[x,A]=l.useState({}),I=Ee(w=>w.customization),X=We(Do.getChatModels),{reactFlowInstance:q}=l.useContext(gs),ne=Ge(),y=et();Ft();const h=(...w)=>y(gt(...w)),S=(...w)=>y(mt(...w)),N=({inputParam:w,newValue:L})=>{A(re=>{const se={...re};return w.type==="credential"?(se.credential=L,se.inputs={...se.inputs,[os]:L}):se.inputs={...se.inputs,[w.name]:L},se.inputParams=es(se),se})},P=w=>w==null?!0:typeof w=="string"?w.trim()==="":Array.isArray(w)?w.length===0:!1,O=l.useCallback(()=>{var re,se;if(!x||Object.keys(x).length===0)return{isValid:!1,missingFields:[]};const w=es(x).filter(Q=>!Q.hidden&&Q.display!==!1),L=[];for(const Q of w)Q.optional||(Q.type==="credential"?x.credential||(re=x.inputs)!=null&&re[os]||L.push(Q.label||"Credential"):P((se=x.inputs)==null?void 0:se[Q.name])&&L.push(Q.label||Q.name));return{isValid:L.length===0,missingFields:L}},[x]),V=w=>{h({message:w||"Please fill in all mandatory fields.",options:{key:new Date().getTime()+Math.random(),variant:"warning",action:L=>e.jsx(te,{style:{color:"white"},onClick:()=>S(L),children:e.jsx(we,{})})}})};l.useEffect(()=>{if(X.data){B(X.data);const w=X.data.map(L=>({label:L.label,name:L.name,imageSrc:`${Me}/api/v1/node-icon/${L.name}`}));b(w)}},[X.data]),l.useEffect(()=>{let w;return D?(H(0),w=setInterval(()=>{H(L=>{if(L>=95)return clearInterval(w),95;const re=L<30?3:L<60?5:L<80?2:.5;return Math.min(L+re,95)})},500)):H(100),()=>{w&&clearInterval(w)}},[D]);const oe=async()=>{var re,se;if(!j.trim())return;const{isValid:w,missingFields:L}=O();if(!w){const Q=L.length>0?`Please fill in the following required fields: ${L.join(", ")}`:"Please fill in all mandatory fields for the selected model.";V(Q);return}try{z(!0);const Q=await dt.generateAgentflow({question:j.trim(),selectedChatModel:x});Q.data&&Q.data.nodes&&Q.data.edges?(q.setNodes(Q.data.nodes),q.setEdges(Q.data.edges),g()):h({message:Q.error||"Failed to generate agentflow",options:{key:new Date().getTime()+Math.random(),variant:"error",persist:!1,action:ie=>e.jsx(te,{style:{color:"white"},onClick:()=>S(ie),children:e.jsx(we,{})})}})}catch(Q){h({message:((se=(re=Q.response)==null?void 0:re.data)==null?void 0:se.message)||"Failed to generate agentflow",options:{key:new Date().getTime()+Math.random(),variant:"error",persist:!1,action:ie=>e.jsx(te,{style:{color:"white"},onClick:()=>S(ie),children:e.jsx(we,{})})}})}finally{z(!1)}};l.useEffect(()=>{a?X.request():(u(""),R(""),H(0))},[a]);const ee=a?e.jsx(e.Fragment,{children:e.jsxs(at,{fullWidth:!0,maxWidth:D?"sm":"md",open:a,onClose:D?null:c,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[e.jsx(ht,{sx:{fontSize:"1rem"},id:"alert-dialog-title",children:o.title}),e.jsx(nt,{children:D?e.jsxs("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",flexDirection:"column"},children:[e.jsx("img",{src:Jr,alt:"Generating Agentflow",style:{maxWidth:"100%",height:"auto"}}),e.jsx(de,{variant:"h5",sx:{mt:2},children:"Generating your Agentflow..."}),e.jsxs(G,{sx:{width:"100%",mt:2},children:[e.jsx(To,{variant:"determinate",value:U,sx:{height:10,borderRadius:5,"& .MuiLinearProgress-bar":{background:"linear-gradient(45deg, #FF6B6B 30%, #FF8E53 90%)",borderRadius:5}}}),e.jsx(de,{variant:"body2",color:"text.secondary",align:"center",sx:{mt:1},children:`${Math.round(U)}%`})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:o.description}),e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%",marginTop:"25px"},children:Qr.map((w,L)=>e.jsx(te,{size:"small",sx:{textTransform:"none",mr:1,mb:1,borderRadius:"16px",border:"none",backgroundColor:I.isDarkMode?"rgba(255,255,255,0.05)":"rgba(0,0,0,0.03)",boxShadow:"0 2px 4px rgba(0,0,0,0.1)","&:hover":{backgroundColor:I.isDarkMode?"rgba(255,255,255,0.1)":"rgba(0,0,0,0.06)",boxShadow:"0 4px 8px rgba(0,0,0,0.15)"}},variant:"contained",color:"inherit",onClick:()=>{u(w.text),R("")},children:w.text},L))}),!m&&e.jsx(qe,{sx:{mt:2,width:"100%"},type:"text",multiline:!0,rows:12,disabled:D,value:j,placeholder:"Describe your agent here",onChange:w=>u(w.target.value)}),m&&e.jsx(qe,{sx:{mt:2,width:"100%"},type:"text",multiline:!0,rows:12,value:m,onChange:w=>R(w.target.value)}),e.jsxs(G,{sx:{mt:2},children:[e.jsx("div",{style:{display:"flex",flexDirection:"row"},children:e.jsxs(de,{children:["Select model to generate agentflow",e.jsx("span",{style:{color:"red"},children:" *"})]})}),e.jsx(Mo,{name:"chatModel",options:_??[],onSelect:w=>{if(!w)A({});else{const L=F.find(re=>re.name===w);if(L){const re=`${L.name}_0`,se=ce.cloneDeep(L),Q=Ao(se,re);A(Q)}}},value:x?x==null?void 0:x.name:"choose an option"},JSON.stringify(x))]}),x&&Object.keys(x).length>0&&e.jsx(G,{sx:{p:0,mt:1,mb:1,border:1,borderColor:ne.palette.grey[900]+25,borderRadius:2},children:es(x).filter(w=>!w.hidden&&w.display!==!1).map((w,L)=>e.jsx(Lr,{inputParam:w,data:x,onNodeDataChange:N},L))})]})}),e.jsx(ft,{sx:{pb:3,pr:3},children:D?null:e.jsxs(e.Fragment,{children:[!m&&e.jsx(Eo,{loading:D,variant:"contained",onClick:()=>{oe()},sx:{background:"linear-gradient(45deg, #FF6B6B 30%, #FF8E53 90%)","&:hover":{background:"linear-gradient(45deg, #FF8E53 30%, #FF6B6B 90%)"}},startIcon:e.jsx(ms,{size:20}),disabled:D||!j.trim()||!x||!Object.keys(x).length||!O().isValid,children:"Generate"}),m&&e.jsx(te,{variant:"outlined",startIcon:e.jsx(Ro,{size:20}),onClick:()=>{R("")},children:"Back"})]})})]})}):null;return Nt.createPortal(ee,f)};Pa.propTypes={show:p.bool,dialogProps:p.object,onConfirm:p.func,onCancel:p.func};const Kr="/assets/utilNodes-9P4ffRXr.png";function Yr(a){return{id:`attachment-tab-${a}`,"aria-controls":`attachment-tabpanel-${a}`}}const ma=["Agents","Memory","Record Manager","Utilities"],Ua=["agentMemory","sqliteAgentMemory","postgresAgentMemory","mySQLAgentMemory"],It={Memory:Ua,Utilities:["getVariable","setVariable","stickyNote"]},Dt={Memory:Ua},Oa=({nodesData:a,node:o,isAgentCanvas:c,isAgentflowv2:g,onFlowGenerated:f})=>{const j=Ge(),u=Ee(C=>C.customization),m=et(),[R,D]=l.useState(""),[z,U]=l.useState({}),[H,F]=l.useState(!1),[B,_]=l.useState({}),[b,x]=l.useState(0),[A,I]=l.useState(!1),[X,q]=l.useState({}),ne=window.location.pathname.includes("/v2/agentcanvas"),y=l.useRef(null),h=l.useRef(H),S=l.useRef(),N=()=>{const C=S.current;C&&(C.scrollTop=0)},P=(C,T)=>{x(T),w(R,T)},O=C=>{let T=[];if(C){const M=It[C]||[];T=a.filter(v=>v.category===C&&M.includes(v.name))}else for(const M in It){const v=It[M];T.push(...a.filter(W=>W.category===M&&v.includes(W.name)))}return T},V=(C,T)=>{const M=((C??"")+"").trim().toLowerCase();if(!M)return 0;const v=((T??"")+"").toLowerCase();let W=0,Z=0,ae=-1,K=-1,pe=0;const Ce=v.indexOf(M);if(Ce!==-1)return W=1e3,Ce===0?W+=200:(v[Ce-1]===" "||v[Ce-1]==="-"||v[Ce-1]==="_")&&(W+=100),W-=Ce*2,W-=(v.length-M.length)*3,W;for(let $=0;$<v.length&&Z<M.length;$++)v[$]===M[Z]&&(W+=10,K===$-1?(pe++,W+=5+pe*2):pe=0,$===0&&(W+=20),$>0&&(v[$-1]===" "||v[$-1]==="-"||v[$-1]==="_")&&(W+=15),ae===-1&&(ae=$),K=$,Z++);if(Z<M.length)return 0;W-=Math.max(0,v.length-M.length)*2;const _e=K-ae+1,ot=Math.max(0,_e-M.length);return W-=ot*3,W},oe=(C,T)=>!T||T.trim()===""?C:C.map(v=>{const W=V(T,v.name),Z=V(T,v.label),ae=V(T,v.category)*.5,K=Math.max(W,Z,ae);return{node:v,score:K}}).filter(v=>v.score>0).sort((v,W)=>W.score-v.score).map(v=>v.node),ee=C=>{if(c){const M=a.filter(v=>!ma.includes(v.category));return M.push(...O()),oe(M,C)}let T=a.filter(M=>M.category!=="Multi Agents"&&M.category!=="Sequential Agents");for(const M in Dt){const v=Dt[M];T=T.filter(W=>!v.includes(W.name))}return oe(T,C)},w=(C,T)=>{D(C),setTimeout(()=>{if(C){const M=ee(C);re(M,T??b,!0),N()}else C===""&&(re(a,T??b),N())},500)},L=(C,T=0)=>{const M=C.filter(Z=>!Z.tags),v=C.filter(Z=>Z.tags&&Z.tags.includes("LlamaIndex")),W=C.filter(Z=>Z.tags&&Z.tags.includes("Utilities"));return T===0?M:T===1?v:W},re=(C,T,M)=>{if(c){const v={},W=C.reduce(function(ae,K){return ae[K.category]=ae[K.category]||[],ae[K.category].push(K),v[K.category]=!!M,ae},Object.create(null)),Z={};for(const ae in W){if(ne){if(ae!=="Agent Flows")continue}else if(ae==="Agent Flows")continue;if(!ma.includes(ae)){const K=W[ae].filter(pe=>!pe.tags||!pe.tags.includes("LlamaIndex"));if(!K.length)continue;Z[ae]=K}Object.keys(It).includes(ae)&&(Z[ae]=O(ae))}U(Z),v["Multi Agents"]=!0,v["Sequential Agents"]=!0,v.Memory=!0,v["Agent Flows"]=!0,_(v)}else{const v=L(C,T),W={},Z=v.reduce(function(K,pe){return K[pe.category]=K[pe.category]||[],K[pe.category].push(pe),W[pe.category]=!!M,K},Object.create(null)),ae={};for(const K in Z)if(!(K==="Agent Flows"||K==="Multi Agents"||K==="Sequential Agents")){if(Object.keys(Dt).includes(K)){const pe=Dt[K];Z[K]=Z[K].filter(Ce=>!pe.includes(Ce.name))}ae[K]=Z[K]}U(ae),_(W)}},se=C=>(T,M)=>{const v={...B};v[C]=M,_(v)},Q=C=>{y.current&&y.current.contains(C.target)||F(!1)},ie=()=>{F(C=>!C)},ve=(C,T)=>{C.dataTransfer.setData("application/reactflow",JSON.stringify(T)),C.dataTransfer.effectAllowed="move"},ke=C=>C===0?Ir:C===1?Br:Kr,Te=C=>{const T=xs.find(M=>M.name===C.name);return T?e.jsx(T.icon,{size:30,color:C.color}):null};l.useEffect(()=>{h.current===!0&&H===!1&&y.current.focus(),h.current=H},[H]),l.useEffect(()=>{o&&F(!1)},[o]),l.useEffect(()=>{a&&(re(a),m({type:Fo,componentNodes:a}))},[a,m]);const Re=()=>{I(!0),q({title:"What would you like to build?",description:"Enter your prompt to generate an agentflow. Performance may vary with different models. Only nodes and edges are generated, you will need to fill in the input fields for each node."})},Le=()=>{I(!1)},me=()=>{I(!1),f()};return e.jsxs(e.Fragment,{children:[e.jsx(ut,{sx:{left:20,top:20},ref:y,size:"small",color:"primary","aria-label":"add",title:"Add Node",onClick:ie,children:H?e.jsx(Wr,{}):e.jsx(No,{})}),g&&e.jsx(ut,{sx:{left:40,top:20,background:"linear-gradient(45deg, #FF6B6B 30%, #FF8E53 90%)","&:hover":{background:"linear-gradient(45deg, #FF8E53 30%, #FF6B6B 90%)"}},onClick:Re,size:"small",color:"primary","aria-label":"generate",title:"Generate Agentflow",children:e.jsx(ms,{})}),e.jsx(Pa,{show:A,dialogProps:X,onCancel:Le,onConfirm:me}),e.jsx(Ia,{placement:"bottom-end",open:H,anchorEl:y.current,role:void 0,transition:!0,disablePortal:!0,popperOptions:{modifiers:[{name:"offset",options:{offset:[-40,14]}}]},sx:{zIndex:1e3},children:({TransitionProps:C})=>e.jsx(Da,{in:H,...C,children:e.jsx(us,{children:e.jsx(Ta,{onClickAway:Q,children:e.jsxs(Ma,{border:!1,elevation:16,content:!1,boxShadow:!0,shadow:j.shadows[16],children:[e.jsxs(G,{sx:{p:2},children:[e.jsx(Ue,{children:e.jsx(de,{variant:"h4",children:"Add Nodes"})}),e.jsx(qe,{autoFocus:!0,sx:{width:"100%",pr:2,pl:2,my:2},id:"input-search-node",value:R,onChange:T=>w(T.target.value),placeholder:"Search nodes",startAdornment:e.jsx(Pe,{position:"start",children:e.jsx(Po,{stroke:1.5,size:"1rem",color:j.palette.grey[500]})}),endAdornment:e.jsx(Pe,{position:"end",sx:{cursor:"pointer",color:j.palette.grey[500],"&:hover":{color:j.palette.grey[900]}},title:"Clear Search",children:e.jsx(we,{stroke:1.5,size:"1rem",onClick:()=>w(""),style:{cursor:"pointer"}})}),"aria-describedby":"search-helper-text",inputProps:{"aria-label":"weight"}}),!c&&e.jsx(Uo,{sx:{position:"relative",minHeight:"50px",height:"50px"},variant:"fullWidth",value:b,onChange:P,"aria-label":"tabs",children:["LangChain","LlamaIndex","Utilities"].map((T,M)=>e.jsx(Oo,{icon:e.jsxs("div",{style:{borderRadius:"50%",position:"relative"},children:[e.jsx("img",{style:{width:"20px",height:"20px",borderRadius:"50%",objectFit:"contain"},src:ke(M),alt:T}),T==="LlamaIndex"&&e.jsx("span",{style:{position:"absolute",top:"-4px",right:"-6px",backgroundColor:"#ff9800",color:"white",borderRadius:"50%",width:"12px",height:"12px",fontSize:"10px",fontWeight:"bold",display:"flex",alignItems:"center",justifyContent:"center"},children:"!"})]}),iconPosition:"start",sx:{minHeight:"50px",height:"50px"},label:T,...Yr(M)},M))}),e.jsx(pt,{})]}),e.jsx(Lo,{containerRef:T=>{S.current=T},style:{height:"100%",maxHeight:`calc(100vh - ${c?"300":"380"}px)`,overflowX:"hidden"},children:e.jsx(G,{sx:{p:2,pt:0},children:e.jsx(zo,{sx:{width:"100%",maxWidth:370,py:0,borderRadius:"10px",[j.breakpoints.down("md")]:{maxWidth:370},"& .MuiListItemSecondaryAction-root":{top:22},"& .MuiDivider-root":{my:0},"& .list-container":{pl:7}},children:Object.keys(z).sort().map(T=>e.jsxs(ps,{expanded:B[T]||!1,onChange:se(T),disableGutters:!0,children:[e.jsx(hs,{expandIcon:e.jsx(bs,{}),"aria-controls":`nodes-accordian-${T}`,id:`nodes-accordian-header-${T}`,children:T.split(";").length>1?e.jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e.jsx(de,{variant:"h5",children:T.split(";")[0]})," ",e.jsx(Ae,{sx:{width:"max-content",fontWeight:700,fontSize:"0.65rem",background:T.split(";")[1]==="DEPRECATING"?j.palette.warning.main:j.palette.teal.main,color:T.split(";")[1]!=="DEPRECATING"?"white":"inherit"},size:"small",label:T.split(";")[1]})]}):e.jsx(de,{variant:"h5",children:T})}),e.jsx(fs,{children:z[T].map((M,v)=>e.jsxs("div",{onDragStart:W=>ve(W,M),draggable:!0,children:[e.jsx(Ca,{sx:{p:0,borderRadius:`${u.borderRadius}px`,cursor:"move"},children:e.jsxs(Bo,{alignItems:"center",children:[M.color&&!M.icon?e.jsx(ca,{children:e.jsx("div",{style:{width:50,height:"auto",display:"flex",alignItems:"center",justifyContent:"center"},children:Te(M)})}):e.jsx(ca,{children:e.jsx("div",{style:{width:50,height:50,borderRadius:"50%",backgroundColor:"white"},children:e.jsx("img",{style:{width:"100%",height:"100%",padding:10,objectFit:"contain"},alt:M.name,src:`${Me}/api/v1/node-icon/${M.name}`})})}),e.jsx(Ho,{sx:{ml:1},primary:e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e.jsx("span",{children:M.label})," ",M.badge&&e.jsx(Ae,{sx:{width:"max-content",fontWeight:700,fontSize:"0.65rem",background:M.badge==="DEPRECATING"?j.palette.warning.main:j.palette.teal.main,color:M.badge!=="DEPRECATING"?"white":"inherit"},size:"small",label:M.badge})]}),M.author&&e.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:700},children:["By ",M.author]})]}),secondary:M.description})]})}),v===z[T].length-1?null:e.jsx(pt,{})]},M.name))})]},T))})})})]})})})})})]})};Oa.propTypes={nodesData:p.array,node:p.object,onFlowGenerated:p.func,isAgentCanvas:p.bool,isAgentflowv2:p.bool};const $i=l.memo(Oa);async function Xr(a,o){const c=a.getReader();let g;for(;!(g=await c.read()).done;)o(g.value)}function Zr(a){let o,c,g,f=!1;return function(u){o===void 0?(o=u,c=0,g=-1):o=ti(o,u);const m=o.length;let R=0;for(;c<m;){f&&(o[c]===10&&(R=++c),f=!1);let D=-1;for(;c<m&&D===-1;++c)switch(o[c]){case 58:g===-1&&(g=c-R);break;case 13:f=!0;case 10:D=c;break}if(D===-1)break;a(o.subarray(R,D),g),R=c,g=-1}R===m?o=void 0:R!==0&&(o=o.subarray(R),c-=R)}}function ei(a,o,c){let g=xa();const f=new TextDecoder;return function(u,m){if(u.length===0)c==null||c(g),g=xa();else if(m>0){const R=f.decode(u.subarray(0,m)),D=m+(u[m+1]===32?2:1),z=f.decode(u.subarray(D));switch(R){case"data":g.data=g.data?g.data+`
`+z:z;break;case"event":g.event=z;break;case"id":a(g.id=z);break;case"retry":const U=parseInt(z,10);isNaN(U)||o(g.retry=U);break}}}}function ti(a,o){const c=new Uint8Array(a.length+o.length);return c.set(a),c.set(o,a.length),c}function xa(){return{data:"",event:"",id:"",retry:void 0}}var si=function(a,o){var c={};for(var g in a)Object.prototype.hasOwnProperty.call(a,g)&&o.indexOf(g)<0&&(c[g]=a[g]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function")for(var f=0,g=Object.getOwnPropertySymbols(a);f<g.length;f++)o.indexOf(g[f])<0&&Object.prototype.propertyIsEnumerable.call(a,g[f])&&(c[g[f]]=a[g[f]]);return c};const Rt="text/event-stream",ai=1e3,ya="last-event-id";function ni(a,o){var{signal:c,headers:g,onopen:f,onmessage:j,onclose:u,onerror:m,openWhenHidden:R,fetch:D}=o,z=si(o,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((U,H)=>{const F=Object.assign({},g);F.accept||(F.accept=Rt);let B;function _(){B.abort(),document.hidden||q()}R||document.addEventListener("visibilitychange",_);let b=ai,x=0;function A(){document.removeEventListener("visibilitychange",_),window.clearTimeout(x),B.abort()}c==null||c.addEventListener("abort",()=>{A(),U()});const I=D??window.fetch,X=f??oi;async function q(){var ne;B=new AbortController;try{const y=await I(a,Object.assign(Object.assign({},z),{headers:F,signal:B.signal}));await X(y),await Xr(y.body,Zr(ei(h=>{h?F[ya]=h:delete F[ya]},h=>{b=h},j))),u==null||u(),A(),U()}catch(y){if(!B.signal.aborted)try{const h=(ne=m==null?void 0:m(y))!==null&&ne!==void 0?ne:b;window.clearTimeout(x),x=window.setTimeout(q,h)}catch(h){A(),H(h)}}}q()})}function oi(a){const o=a.headers.get("content-type");if(!(o!=null&&o.startsWith(Rt)))throw new Error(`Expected content-type to be ${Rt}, Actual: ${o}`)}const ba="/assets/wave-sound-CdNNyn1h.jpg",ri=({show:a,onCancel:o,onConfirm:c})=>{const g=document.getElementById("portal"),f=et(),[j,u]=l.useState(""),m=l.useCallback(z=>u(z.target.value),[u]),R=()=>{c(j)};l.useEffect(()=>(f(a?{type:wa}:{type:At}),()=>{f({type:At}),u("")}),[a,f]);const D=a?e.jsxs(at,{onClose:o,open:a,fullWidth:!0,maxWidth:"sm","aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[e.jsx(ht,{sx:{fontSize:"1rem"},id:"alert-dialog-title",children:"Provide additional feedback"}),e.jsx(nt,{children:e.jsx(G,{sx:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between"},children:e.jsx(qe,{autoFocus:!0,id:"feedbackContentInput",multiline:!0,name:"feedbackContentInput",onChange:m,placeholder:"What do you think of the response?",rows:4,value:j,sx:{width:"100%"}})})}),e.jsxs(ft,{children:[e.jsx(te,{onClick:o,children:"Cancel"}),e.jsx(Aa,{variant:"contained",onClick:R,children:"Submit Feedback"})]})]}):null;return Nt.createPortal(D,g)},La=({isGrid:a,starterPrompts:o,sx:c,onPromptClick:g})=>e.jsx(G,{className:"button-container",sx:{width:"100%",maxWidth:a?"inherit":"400px",p:1.5,display:"flex",gap:1,...c},children:o.map((f,j)=>e.jsx(Ae,{label:f.prompt,className:"button",onClick:u=>g(f.prompt,u)},j))});La.propTypes={isGrid:p.bool,starterPrompts:p.array,sx:p.object,onPromptClick:p.func};const ii="/assets/next-agent--RPptFkm.gif",js=({agent:a,index:o,customization:c,chatflowid:g,isDialog:f,onSourceDialogClick:j,renderArtifacts:u,agentReasoningArtifacts:m,getAgentIcon:R,removeDuplicateURL:D,isValidURL:z,onURLClick:U,getLabel:H})=>a.nextAgent?e.jsx(Ze,{sx:{border:c.isDarkMode?"none":"1px solid #e0e0e0",borderRadius:`${c.borderRadius}px`,background:c.isDarkMode?"linear-gradient(to top, #303030, #212121)":"linear-gradient(to top, #f6f3fb, #f2f8fc)",mb:1},children:e.jsx(da,{children:e.jsxs(Ue,{sx:{alignItems:"center",justifyContent:"flex-start",width:"100%"},flexDirection:"row",children:[e.jsx(G,{sx:{height:"auto",pr:1},children:e.jsx("img",{style:{objectFit:"cover",height:"35px",width:"auto"},src:ii,alt:"agentPNG"})}),e.jsx("div",{children:a.nextAgent})]})})},o):e.jsx(Ze,{sx:{mb:1},children:e.jsxs(da,{children:[e.jsxs(Ue,{sx:{alignItems:"center",justifyContent:"flex-start",width:"100%"},flexDirection:"row",children:[e.jsx(G,{sx:{height:"auto",pr:1},children:e.jsx("img",{style:{objectFit:"cover",height:"25px",width:"auto"},src:R(a.nodeName,a.instructions),alt:"agentPNG"})}),e.jsx("div",{children:a.agentName})]}),a.usedTools&&a.usedTools.length>0&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%"},children:a.usedTools.map((F,B)=>F!==null?e.jsx(Ae,{size:"small",label:F.tool,component:"a",sx:{mr:1,mt:1},variant:"outlined",clickable:!0,icon:e.jsx(Ea,{size:15}),onClick:()=>j(F,"Used Tools")},B):null)}),a.state&&Object.keys(a.state).length>0&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%"},children:e.jsx(Ae,{size:"small",label:"State",component:"a",sx:{mr:1,mt:1},variant:"outlined",clickable:!0,icon:e.jsx(Dr,{size:15}),onClick:()=>j(a.state,"State")})}),a.artifacts&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",flexDirection:"row",width:"100%",gap:"8px"},children:m(a.artifacts).map((F,B)=>F!==null?e.jsx(e.Fragment,{children:u(F,B,!0)}):null)}),a.messages.length>0&&e.jsx(rs,{chatflowid:g,isFullWidth:f,children:a.messages.length>1?a.messages.join("\\n"):a.messages[0]}),a.instructions&&e.jsx("p",{children:a.instructions}),a.messages.length===0&&!a.instructions&&e.jsx("p",{children:"Finished"}),a.sourceDocuments&&a.sourceDocuments.length>0&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%"},children:D(a).map((F,B)=>{const _=F&&F.metadata&&F.metadata.source?z(F.metadata.source):void 0;return e.jsx(Ae,{size:"small",label:H(_,F)||"",component:"a",sx:{mr:1,mb:1},variant:"outlined",clickable:!0,onClick:()=>_?U(F.metadata.source):j(F)},B)})})]})},o);js.propTypes={agent:p.object.isRequired,index:p.number.isRequired,customization:p.object.isRequired,chatflowid:p.string,isDialog:p.bool,onSourceDialogClick:p.func.isRequired,renderArtifacts:p.func.isRequired,agentReasoningArtifacts:p.func.isRequired,getAgentIcon:p.func.isRequired,removeDuplicateURL:p.func.isRequired,isValidURL:p.func.isRequired,onURLClick:p.func.isRequired,getLabel:p.func.isRequired};js.displayName="AgentReasoningCard";const za=a=>{switch(a){case"FINISHED":return"success.dark";case"ERROR":case"TIMEOUT":return"error.main";case"TERMINATED":case"STOPPED":return"error.main";case"INPROGRESS":return"warning.dark"}},li=tt(tr)(({theme:a})=>({color:a.palette.grey[400]})),ci=tt(sr)(({theme:a})=>({flexDirection:"row-reverse",borderRadius:a.spacing(.7),marginBottom:a.spacing(.5),marginTop:a.spacing(.5),padding:a.spacing(.5),paddingRight:a.spacing(1),fontWeight:500,"&.Mui-expanded ":{"&:not(.Mui-focused, .Mui-selected, .Mui-selected.Mui-focused) .labelIcon":{color:a.palette.primary.dark,...a.applyStyles("light",{color:a.palette.primary.main})},"&::before":{content:'""',display:"block",position:"absolute",left:"16px",top:"44px",height:"calc(100% - 48px)",width:"1.5px",backgroundColor:a.palette.grey[700],...a.applyStyles("light",{backgroundColor:a.palette.grey[300]})}},"&:hover":{backgroundColor:ar(a.palette.primary.main,.1),color:"white",...a.applyStyles("light",{color:a.palette.primary.main})},"&.Mui-focused, &.Mui-selected, &.Mui-selected.Mui-focused":{backgroundColor:a.palette.primary.dark,color:a.palette.primary.contrastText,...a.applyStyles("light",{backgroundColor:a.palette.primary.main})}})),di=tt(de)(({theme:a})=>({color:a.palette.text.primary}));function ws({icon:a,itemStatus:o,children:c,name:g,label:f,data:j,metadata:u,...m}){const[R,D]=l.useState(!1),z=F=>{F.stopPropagation(),D(!0)},U=()=>D(!1),H=g==="iterationAgentflow";return e.jsxs(nr,{...m,sx:{display:"flex",alignItems:"center",flexDirection:"column"},children:[e.jsxs(G,{sx:{display:"flex",alignItems:"center",width:"100%"},children:[(()=>{if(H)return e.jsx(G,{sx:{mr:1,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(or,{size:20,color:"#9C89B8"})});const F=xs.find(B=>B.name===g);return F?e.jsx(G,{sx:{mr:1,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(F.icon,{size:20,color:F.color})}):null})(),e.jsx(di,{sx:{flex:1},children:c}),e.jsx(xe,{onClick:z,size:"small",title:"View Details",sx:{ml:2,zIndex:10},children:e.jsx(Ra,{size:15,color:"teal"})}),a&&e.jsx(G,{component:a,className:"labelIcon",color:za(o),sx:{ml:1,fontSize:"1.2rem"}})]}),e.jsxs(at,{open:R,onClose:U,maxWidth:"md",fullWidth:!0,disableBackdropClick:!0,children:[e.jsx(nt,{onClick:F=>F.stopPropagation(),children:j?e.jsx(rr,{data:j,label:f,metadata:u}):e.jsx(de,{color:"text.secondary",children:"No data available for this item"})}),e.jsx(ft,{children:e.jsx(te,{onClick:U,children:"Close"})})]})]})}ws.propTypes={icon:p.elementType,itemStatus:p.string,expandable:p.bool,children:p.node,name:p.string,label:p.string,status:p.object,data:p.object,metadata:p.object};ws.displayName="CustomLabel";const Ba=a=>Array.isArray(a)?a.length>0&&a.some(Ba):!!a,Ha=(a,o)=>{switch(a){case"FINISHED":return Vo;case"ERROR":case"TIMEOUT":return _o;case"TERMINATED":return c=>e.jsx(Go,{...c,color:o.palette.error.main});case"STOPPED":return qo;case"INPROGRESS":return c=>e.jsx(Wo,{...c,color:o.palette.warning.dark,className:`spin-animation ${c.className||""}`})}},ks=l.forwardRef(function(o,c){var h;const{id:g,itemId:f,label:j,disabled:u,children:m,agentflowId:R,sessionId:D,...z}=o,U=Ge(),{getRootProps:H,getContentProps:F,getIconContainerProps:B,getCheckboxProps:_,getLabelProps:b,getGroupTransitionProps:x,getDragAndDropOverlayProps:A,status:I,publicAPI:X}=Jo({id:g,itemId:f,children:m,label:j,disabled:u,rootRef:c}),q=X.getItem(f),ne=Ba(m);let y;return q.status&&(y=Ha(q.status,U)),e.jsx(Qo,{itemId:f,children:e.jsxs(li,{...H(z),children:[e.jsxs(ci,{...F(),children:[e.jsx(Ko,{...B(),children:e.jsx(Yo,{status:I})}),e.jsx(Xo,{..._()}),e.jsx(ws,{...b({icon:y,itemStatus:q.status,expandable:ne&&I.expanded,name:q.name||((h=q.id)==null?void 0:h.split("_")[0]),label:q.label,status:I,data:q.data,metadata:{agentflowId:R,sessionId:D}})}),e.jsx(Zo,{...A()})]}),m&&e.jsx(er,{...x(),style:{borderLeft:`${I.selected?"3px solid":"1px dashed"} ${(()=>{var P;const S=q.name||((P=q.id)==null?void 0:P.split("_")[0]),N=xs.find(O=>O.name===S);return N?N.color:U.palette.primary.main})()}`,marginLeft:"13px",paddingLeft:"8px"}})]})})});ks.propTypes={id:p.string,itemId:p.string,label:p.string,disabled:p.bool,children:p.node,agentflowId:p.string,sessionId:p.string,className:p.string};ks.displayName="CustomTreeItem";const $a=({status:a,execution:o,agentflowId:c,sessionId:g})=>{const[f,j]=l.useState([]),[u,m]=l.useState([]),[R,D]=l.useState(null),z=Ge(),U=b=>{let x=[];return b.forEach(A=>{x.push(A.id),A.children&&A.children.length>0&&(x=[...x,...U(A.children)])}),x},H=b=>{b.forEach(y=>{const h=S=>{for(const N in S)N===os&&delete S[N],typeof S[N]=="object"&&h(S[N])};h(y.data)});const x=new Map;b.forEach((y,h)=>{const S=`${y.nodeId}_${h}`;x.set(S,{...y,uniqueNodeId:S,children:[],executionIndex:h})});const A=new Map;b.forEach((y,h)=>{var S,N;if((S=y.data)!=null&&S.parentNodeId&&((N=y.data)==null?void 0:N.iterationIndex)!==void 0){const P=y.data.parentNodeId,O=y.data.iterationIndex;A.has(P)||A.set(P,new Map);const V=A.get(P);V.has(O)||V.set(O,[]),V.get(O).push(`${y.nodeId}_${h}`)}}),A.forEach((y,h)=>{y.forEach((S,N)=>{var Q;let P=null;for(let ie=0;ie<b.length;ie++)if(b[ie].nodeId===h){P=b[ie];break}if(!P)return;const O=S[0],V=x.get(O),oe=((Q=V==null?void 0:V.data)==null?void 0:Q.iterationContext)||{index:N},ee=`${h}_${N}`,w=`Iteration #${N}`,L=S.map(ie=>x.get(ie)),re=L.some(ie=>ie.status==="ERROR")?"ERROR":L.some(ie=>ie.status==="INPROGRESS")?"INPROGRESS":L.every(ie=>ie.status==="FINISHED")?"FINISHED":"UNKNOWN",se={nodeId:ee,nodeLabel:w,data:{name:"iterationAgentflow",iterationIndex:N,iterationContext:oe,isVirtualNode:!0,parentIterationId:h},previousNodeIds:[],status:re,uniqueNodeId:ee,children:[],executionIndex:-1};x.set(ee,se),S.forEach(ie=>{const ve=x.get(ie);ve&&(ve.virtualParentId=ee)})})});const I=[],X=new Set;b.forEach((y,h)=>{var P,O;const S=`${y.nodeId}_${h}`,N=x.get(S);if(!((P=y.data)!=null&&P.parentNodeId&&((O=y.data)==null?void 0:O.iterationIndex)!==void 0))if(y.previousNodeIds.length===0)I.push(N);else{let V=-1,oe=null;if(y.previousNodeIds.forEach(ee=>{for(let w=0;w<h;w++)b[w].nodeId===ee&&w>V&&(V=w,oe=ee)}),V!==-1){const ee=`${oe}_${V}`,w=x.get(ee);w&&(w.children.push(N),X.add(S))}}}),A.forEach((y,h)=>{const S=[];b.forEach((P,O)=>{P.nodeId===h&&S.push(`${P.nodeId}_${O}`)});let N=null;for(let P=S.length-1;P>=0;P--){const O=S[P],V=x.get(O);if(V){N=V;break}}N&&y.forEach((P,O)=>{const V=`${h}_${O}`,oe=x.get(V);oe&&N.children.push(oe)})}),x.forEach(y=>{if(y.virtualParentId){const h=x.get(y.virtualParentId);if(h)if(y.previousNodeIds.length===0)h.children.push(y);else{let S=!1;for(const N of y.previousNodeIds)x.forEach(P=>{var O,V,oe,ee;P.nodeId===N&&((O=P.data)==null?void 0:O.iterationIndex)===((V=y.data)==null?void 0:V.iterationIndex)&&((oe=P.data)==null?void 0:oe.parentNodeId)===((ee=y.data)==null?void 0:ee.parentNodeId)&&!S&&(P.children.push(y),S=!0)});S||h.children.push(y)}}});const q=y=>{y.children&&y.children.length>0&&(y.children.sort((h,S)=>{var O,V,oe,ee;const N=((O=h.data)==null?void 0:O.name)==="iterationAgentflow"||((V=h.data)==null?void 0:V.isVirtualNode),P=((oe=S.data)==null?void 0:oe.name)==="iterationAgentflow"||((ee=S.data)==null?void 0:ee.isVirtualNode);return N===P?h.executionIndex-S.executionIndex:N?-1:1}),y.children.forEach(q))};I.forEach(q);const ne=y=>{var h;return{id:y.uniqueNodeId,label:y.nodeLabel,name:(h=y.data)==null?void 0:h.name,status:y.status,data:y.data,children:y.children.map(ne)}};return I.map(ne)},F=(b,x)=>{m(x)};l.useEffect(()=>{if(o){const b=H(o);j(b),m(U(b)),b.length>0&&D(b[0])}},[o]);const B=(b,x)=>{const A=(X,q)=>{for(const ne of X){if(ne.id===q)return ne;if(ne.children){const y=A(ne.children,q);if(y)return y}}return null},I=A(f,x);D(I)},_=l.useCallback(b=>{const x=I=>{let X=[];return I.forEach(q=>{q.status&&X.push(q.status),q.children&&q.children.length>0&&(X=[...X,...x(q.children)])}),X},A=x(b);return A.includes("ERROR")?"ERROR":A.includes("INPROGRESS")?"INPROGRESS":A.includes("STOPPED")?"STOPPED":A.every(I=>I==="FINISHED")?"FINISHED":null},[]);return e.jsx(G,{sx:{display:"flex",height:"100%",width:"100%",mt:2},children:e.jsxs(ps,{sx:{width:"100%"},children:[e.jsxs(hs,{expandIcon:e.jsx(bs,{}),sx:{"& .MuiAccordionSummary-content":{alignItems:"center"}},children:[f.length>0&&(()=>{const b=a??_(f);return e.jsx(G,{sx:{mr:1,fontSize:"1.2rem"},children:e.jsx(G,{component:Ha(b,z),sx:{mr:1,fontSize:"1.2rem",color:za(b)}})})})(),e.jsx(de,{children:"Process Flow"})]}),e.jsx(pt,{}),e.jsx(fs,{children:e.jsx($o,{expandedItems:u,onExpandedItemsChange:F,selectedItems:R?[R.id]:[],onSelectedItemsChange:B,items:f,slots:{item:b=>e.jsx(ks,{...b,agentflowId:c,sessionId:g})},sx:{width:"100%"}})})]})})};$a.propTypes={status:p.string,execution:p.array,agentflowId:p.string,sessionId:p.string};const ui=l.memo($a),pi=tt($e)(({theme:a})=>({position:"relative",height:200,borderRadius:"10px",[a.breakpoints.down("sm")]:{width:"100% !important",height:100},"&:hover, &.Mui-focusVisible":{zIndex:1,"& .MuiImageBackdrop-root":{opacity:.4},"& .MuiImageMarked-root":{opacity:1},"& .MuiTypography-root":{border:"4px solid currentColor"}}})),hi=tt("span")({position:"absolute",borderRadius:"10px",left:0,right:0,top:0,bottom:0,backgroundSize:"cover",backgroundPosition:"center 40%"}),fi=tt("span")(({theme:a})=>({position:"absolute",borderRadius:"10px",left:0,right:0,top:0,bottom:0,backgroundColor:a.palette.common.black,opacity:.1,transition:a.transitions.create("opacity")})),gi=tt("span")(()=>({height:25,width:25,backgroundColor:"transparent",position:"absolute",top:"auto",left:"auto",opacity:0})),Wa=a=>{const o=Ee(c=>c.customization);return e.jsx(xe,{disabled:a.isDisabled||a.isLoading,onClick:a.onClick,size:"small",sx:{background:"transparent",border:"none"},title:"Copy to clipboard",children:e.jsx(ir,{style:{width:"20px",height:"20px"},color:a.isLoading?"#9e9e9e":o.isDarkMode?"white":"#1e88e5"})})};Wa.propTypes={isDisabled:p.bool,isLoading:p.bool,onClick:p.func};const qa=a=>{const o=Ee(c=>c.customization);return e.jsx(xe,{disabled:a.isDisabled||a.isLoading,onClick:a.onClick,size:"small",sx:{background:"transparent",border:"none"},title:"Thumbs Up",children:e.jsx(Gr,{style:{width:"20px",height:"20px"},color:a.rating==="THUMBS_UP"?"#9e9e9e":o.isDarkMode?"white":"#1e88e5"})})};qa.propTypes={isDisabled:p.bool,isLoading:p.bool,onClick:p.func,rating:p.string};const Ga=a=>{const o=Ee(c=>c.customization);return e.jsx(xe,{disabled:a.isDisabled||a.isLoading,onClick:a.onClick,size:"small",sx:{background:"transparent",border:"none"},title:"Thumbs Down",children:e.jsx(qr,{style:{width:"20px",height:"20px"},color:a.rating==="THUMBS_DOWN"?"#9e9e9e":o.isDarkMode?"white":"#1e88e5"})})};Ga.propTypes={isDisabled:p.bool,isLoading:p.bool,onClick:p.func,rating:p.string};let Cs,_a;function mi(){Cs=document.getElementsByClassName("start-recording-button")[0]}function xi(){Cs.style.display="none",wi()}function Va(){Cs.style.display="block",clearInterval(Qa)}let Ja,yi=1,Qa;function bi(a,o){mi(),ue.start().then(()=>{a&&a(!0),Ja=new Date,xi()}).catch(c=>{switch(c.message.includes("mediaDevices API or getUserMedia method is not supported in this browser.")&&o&&o(!0),c.name){case"AbortError":console.log("An AbortError has occurred.");break;case"NotAllowedError":console.log("A NotAllowedError has occurred. User might have denied permission.");break;case"NotFoundError":console.log("A NotFoundError has occurred.");break;case"NotReadableError":console.log("A NotReadableError has occurred.");break;case"SecurityError":console.log("A SecurityError has occurred.");break;case"TypeError":console.log("A TypeError has occurred.");break;case"InvalidStateError":console.log("An InvalidStateError has occurred.");break;case"UnknownError":console.log("An UnknownError has occurred.");break;default:console.log("An error occurred with the error name "+c.name)}})}function Ka(a){ue.stop().then(o=>{Va(),a&&a(o)}).catch(o=>{switch(o.name){case"InvalidStateError":console.log("An InvalidStateError has occurred.");break;default:console.log("An error occurred with the error name "+o.name)}})}function ji(){ue.cancel(),Va()}function wi(){_a=document.getElementById("elapsed-time"),ja("00:00"),Qa=setInterval(()=>{let a=Ci(Ja);ja(a)},1e3)}function ja(a){_a.innerHTML=a,ki(a)&&Ka()}function ki(a){let o=a.split(":"),c="0"+yi;return o.length===3&&o[0]===c}function Ci(a){let c=new Date-a;c=c/1e3;let g=Math.floor(c%60);g=g<10?"0"+g:g,c=Math.floor(c/60);let f=c%60;f=f<10?"0"+f:f,c=Math.floor(c/60);let j=c%24;c=Math.floor(c/24);let m=j+c*24;return m=m<10?"0"+m:m,m==="00"?f+":"+g:m+":"+f+":"+g}const ue={audioBlobs:[],mediaRecorder:null,streamBeingCaptured:null,start:function(){return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0}).then(a=>{ue.streamBeingCaptured=a,ue.mediaRecorder=new MediaRecorder(a),ue.audioBlobs=[],ue.mediaRecorder.addEventListener("dataavailable",o=>{ue.audioBlobs.push(o.data)}),lr?ue.mediaRecorder.start(1e3):ue.mediaRecorder.start()}):Promise.reject(new Error("mediaDevices API or getUserMedia method is not supported in this browser."))},stop:function(){return new Promise(a=>{let o=ue.mediaRecorder.mimeType;ue.mediaRecorder.addEventListener("stop",()=>{let c=new Blob(ue.audioBlobs,{type:o});a(c)}),ue.cancel()})},cancel:function(){ue.mediaRecorder.stop(),ue.stopStream(),ue.resetRecordingProperties()},stopStream:function(){ue.streamBeingCaptured.getTracks().forEach(a=>a.stop())},resetRecordingProperties:function(){ue.mediaRecorder=null,ue.streamBeingCaptured=null}},Si=(a,o,c)=>ys.post(`/attachments/${a}/${o}`,c,{headers:{"Content-Type":"multipart/form-data"}}),vi={createAttachment:Si},Ii=(a,o)=>ys.post(`/feedback/${a}`,o),Di=(a,o)=>ys.put(`/feedback/${a}`,o),as={addFeedback:Ii,updateFeedback:Di},Ya=({isGrid:a,followUpPrompts:o,sx:c,onPromptClick:g})=>{const f=Ee(j=>j.customization);return e.jsx(G,{className:"button-container",sx:{width:"100%",maxWidth:a?"inherit":"400px",p:1.5,display:"flex",gap:1,...c},children:Array.isArray(o)&&o.map((j,u)=>e.jsx(Ae,{label:j,className:"button",onClick:m=>g(j,m),sx:{backgroundColor:"transparent",border:"1px solid",boxShadow:"0px 2px 1px -1px rgba(0,0,0,0.2)",color:"#2196f3",transition:"all 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms","&:hover":{backgroundColor:f.isDarkMode?"rgba(0, 0, 0, 0.12)":"rgba(0, 0, 0, 0.05)",border:"1px solid"}}},u))})};Ya.propTypes={isGrid:p.bool,followUpPrompts:p.array,sx:p.object,onPromptClick:p.func};class Ti{constructor(o=10){this.history=[],this.currentIndex=-1,this.tempInput="",this.maxHistory=o,this.loadHistory()}addToHistory(o){o.trim()&&(this.history[0]!==o&&(this.history.unshift(o),this.history.length>this.maxHistory&&this.history.pop()),this.currentIndex=-1,this.saveHistory())}getPreviousInput(o){return this.currentIndex===-1&&(this.tempInput=o),this.currentIndex<this.history.length-1?(this.currentIndex++,this.history[this.currentIndex]):this.history[this.currentIndex]||this.tempInput}getNextInput(){return this.currentIndex>-1?(this.currentIndex--,this.currentIndex===-1?this.tempInput:this.history[this.currentIndex]):this.tempInput}saveHistory(){try{localStorage.setItem("chatInputHistory",JSON.stringify(this.history))}catch(o){console.warn("Failed to save chat history to localStorage:",o)}}loadHistory(){try{const o=localStorage.getItem("chatInputHistory");o&&(this.history=JSON.parse(o))}catch(o){console.warn("Failed to load chat history from localStorage:",o)}}}const Mi={width:"128px",height:"128px",objectFit:"cover"},Xa=({item:a,disabled:o,customization:c,onDelete:g})=>{const[f,j]=l.useState(!1),u=c.isDarkMode?"rgba(0, 0, 0, 0.3)":"transparent";return e.jsxs("div",{onMouseEnter:()=>j(!0),onMouseLeave:()=>j(!1),style:{position:"relative",display:"inline-block"},children:[e.jsxs(Ze,{sx:{display:"inline-flex",alignItems:"center",height:"48px",width:"max-content",p:2,mr:1,flex:"0 0 auto",transition:"opacity 0.3s",opacity:1,backgroundColor:f?"rgba(0, 0, 0, 0.3)":u},variant:"outlined",children:[e.jsx(Mt,{size:20,style:{transition:"filter 0.3s",filter:f?"blur(2px)":"none"}}),e.jsx("span",{style:{marginLeft:"5px",color:c.isDarkMode?"white":"inherit",transition:"filter 0.3s",filter:f?"blur(2px)":"none"},children:a.name})]}),f&&!o&&e.jsx(te,{disabled:o,onClick:()=>g(a),startIcon:e.jsx(Et,{color:"white",size:22}),title:"Remove attachment",sx:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"transparent","&:hover":{backgroundColor:"transparent"}}})]})};Xa.propTypes={item:p.object,customization:p.object,disabled:p.bool,onDelete:p.func};const Za=({open:a,chatflowid:o,isAgentCanvas:c,isDialog:g,previews:f,setPreviews:j})=>{var na,oa;const u=Ge(),m=Ee(t=>t.customization),R=l.useRef(),D=et(),{onAgentflowNodeStatusUpdate:z,clearAgentflowNodeStatus:U}=l.useContext(gs);Ft();const H=(...t)=>D(gt(...t)),F=(...t)=>D(mt(...t)),[B,_]=l.useState(""),[b,x]=l.useState(!1),[A,I]=l.useState([{message:"Hi there! How can I help?",type:"apiMessage"}]),[X,q]=l.useState(!1),[ne,y]=l.useState(!1),[h,S]=l.useState(!1),[N,P]=l.useState({}),[O,V]=l.useState(Hr()),[oe,ee]=l.useState(!1),[w,L]=l.useState([]),[re,se]=l.useState(""),[Q,ie]=l.useState(""),[ve]=l.useState(new Ti(10)),ke=l.useRef(null),Te=We(is.getInternalChatmessageFromChatflow),Re=We(cr.getAllExecutions),Le=We(dt.getIsChatflowStreaming),me=We(dt.getAllowChatflowUploads),C=We(dt.getSpecificChatflow),[T,M]=l.useState([]),[v,W]=l.useState(!1),[Z,ae]=l.useState("*"),[K,pe]=l.useState(!1),[Ce,_e]=l.useState(""),[ot,$]=l.useState(!1),[le,Ie]=l.useState(null),[Fe,Ve]=l.useState(""),[Se,Je]=l.useState(""),[Pt,an]=l.useState(""),[nn,Ss]=l.useState(!1),[on,vs]=l.useState(!1),[Ut,rn]=l.useState(!1),[Is,st]=l.useState([]),Ds=l.useRef(null),Ts=l.useRef(null),[Qe,ln]=l.useState(!1),[Ke,Ot]=l.useState(!1),[Lt,cn]=l.useState(!1),[Ms,zt]=l.useState(!1),[dn,rt]=l.useState(!1),[As,Bt]=l.useState(!1),[un,pn]=l.useState(!1),[hn,Ht]=l.useState(!1),[Es,$t]=l.useState(""),[Rs,Wt]=l.useState(null),[fn,Fs]=l.useState(""),[gn,mn]=l.useState(""),[xn,yn]=l.useState(""),[bn,jn]=l.useState(""),[Ns,Ps]=l.useState({}),[Us,wn]=l.useState([]),[kn,qt]=l.useState(!0),[xt,it]=l.useState({}),[yt,bt]=l.useState({}),[De,Os]=l.useState({}),[Cn,Gt]=l.useState(!1),[Ne,ze]=l.useState({mediaSource:null,sourceBuffer:null,audio:null,chunkQueue:[],isBuffering:!1,audioFormat:null,abortController:null}),_t=l.useRef(!1),Be=l.useRef(null),Ls=t=>{const n=me.data;let s=!1;if(!n)return console.warn("Upload constraints not loaded yet"),!1;if(n.isImageUploadAllowed){const r=t.type,i=t.size/1024/1024;n.imgUploadSizeAndTypes&&Array.isArray(n.imgUploadSizeAndTypes)&&n.imgUploadSizeAndTypes.forEach(d=>{d.fileTypes&&d.fileTypes.includes(r)&&i<=d.maxUploadSize&&(s=!0)})}if(v)return!0;if(n.isRAGFileUploadAllowed){const r=t.name.split(".").pop();r&&n.fileUploadSizeAndTypes&&Array.isArray(n.fileUploadSizeAndTypes)&&n.fileUploadSizeAndTypes.forEach(i=>{(i.fileTypes&&i.fileTypes.length===1&&i.fileTypes[0]==="*"||i.fileTypes&&i.fileTypes.includes(`.${r}`))&&(s=!0)})}return s||alert("Cannot upload file. Kindly check the allowed file types and maximum allowed size."),s},Sn=async t=>{if(!Qe&&!Ke)return;t.preventDefault(),zt(!1);let n=[],s=[];if(t.dataTransfer.files.length>0){for(const i of t.dataTransfer.files){if(Ls(i)===!1)return;const d=new FileReader,{name:k}=i;(!i.type||!re.includes(i.type))&&s.push({file:i,type:v?"file:full":"file:rag"}),n.push(new Promise(J=>{d.onload=E=>{var Y;if(!((Y=E==null?void 0:E.target)!=null&&Y.result))return;const{result:fe}=E.target;let be;i.type.startsWith("audio/")?be=ba:be=URL.createObjectURL(i),J({data:fe,preview:be,type:"file",name:k,mime:i.type})},d.readAsDataURL(i)}))}const r=await Promise.all(n);L(s),j(i=>[...i,...r])}if(t.dataTransfer.items)for(const r of t.dataTransfer.items)r.kind==="string"&&r.type.match("^text/uri-list")?r.getAsString(i=>{let d={data:i,preview:i,type:"url",name:i?i.substring(i.lastIndexOf("/")+1):""};j(k=>[...k,d])}):r.kind==="string"&&r.type.match("^text/html")&&r.getAsString(i=>{if(i.indexOf("href")===-1)return;let d=i?i.substring(i.indexOf("href")+6):"",k=d.substring(0,d.indexOf('"')),J={data:k,preview:k,type:"url",name:k?k.substring(k.lastIndexOf("/")+1):""};j(E=>[...E,J])})},zs=async t=>{if(!(t.target.files&&t.target.files[0]))return;let s=[],r=[];for(const d of t.target.files){if(Ls(d)===!1)return;(!d.type||!re.includes(d.type))&&r.push({file:d,type:v?"file:full":"file:rag"});const k=new FileReader,{name:J}=d;s.push(new Promise(E=>{k.onload=fe=>{var Y;if(!((Y=fe==null?void 0:fe.target)!=null&&Y.result))return;const{result:be}=fe.target;E({data:be,preview:URL.createObjectURL(d),type:"file",name:J,mime:d.type})},k.readAsDataURL(d)}))}const i=await Promise.all(s);L(r),j(d=>[...d,...i]),t.target.value=null},vn=t=>{let n="";const s=t.type.indexOf(";");s===-1?n=t.type:n=t.type?t.type.substring(0,s):"";const r=new FileReader;r.readAsDataURL(t),r.onloadend=()=>{const d={data:r.result,preview:ba,type:"audio",name:`audio_${Date.now()}.wav`,mime:n};j(k=>[...k,d])}},jt=t=>{(Qe||Ke)&&(t.preventDefault(),t.stopPropagation(),t.type==="dragenter"||t.type==="dragover"?zt(!0):t.type==="dragleave"&&zt(!1))},In=async()=>{ee(!0);try{await sa(),Yt(),await is.abortMessage(o,O),ee(!1)}catch(t){ee(!1),H({message:typeof t.response.data=="object"?t.response.data.message:t.response.data,options:{key:new Date().getTime()+Math.random(),variant:"error",persist:!0,action:n=>e.jsx(te,{style:{color:"white"},onClick:()=>F(n),children:e.jsx(we,{})})}})}},Vt=t=>{t.type==="file"&&URL.revokeObjectURL(t.preview),j(f.filter(n=>n!==t))},Bs=()=>{Ts.current.click()},Hs=()=>{Ds.current.click()},Dn=()=>{f.forEach(t=>URL.revokeObjectURL(t.preview)),j([])},Tn=()=>{rt(!0),bi(rt,Bt)},$s=()=>{As||ji(),rt(!1),Bt(!1)},Mn=async()=>{pn(!0),Ka(vn)},wt=(t,n)=>{P({data:t,title:n}),S(!0)},Ws=t=>{window.open(t,"_blank")},kt=()=>{R.current&&R.current.scrollTo({top:fr})},Jt=t=>{_t.current=t,Be.current&&(clearTimeout(Be.current),Be.current=null),Be.current=setTimeout(()=>{_t.current=!1,Be.current=null},300)},An=l.useCallback(t=>_(t.target.value),[_]),En=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].message+=t,s[s.length-1].feedback=null),s})},Rn=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s.push({message:t,type:"apiMessage"}),s})},Fn=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].sourceDocuments=t),s})},Nn=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].agentReasoning=t),s})},Pn=t=>{I(t==="INPROGRESS"?n=>[...n,{message:"",type:"apiMessage",agentFlowEventStatus:t}]:n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].agentFlowEventStatus=t),s})},Un=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].agentFlowExecutedData=t),s})},On=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].action=t),s})},Ln=t=>{t.forEach(n=>{(n.type==="png"||n.type==="jpeg")&&(n.data=`${Me}/api/v1/get-upload-file?chatflowId=${o}&chatId=${O}&fileName=${n.data.replace("FILE-STORAGE::","")}`)}),I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].artifacts=t),s})},zn=t=>{I(n=>{let s=[...ce.cloneDeep(n)];if(s[s.length-1].type==="userMessage")return s;const r=s[s.length-1].agentReasoning;return r&&r.length>0&&r.push({nextAgent:t}),s[s.length-1].agentReasoning=r,s})},Bn=t=>{z(t)},Hn=t=>{I(n=>{let s=[...ce.cloneDeep(n)];if(s[s.length-1].type==="userMessage")return s;const r=s[s.length-1];if(r.calledTools&&r.calledTools.length>0){const d=r.calledTools.map(k=>t.find(E=>E.tool===k.tool)||k).filter(k=>!t.some(J=>J.tool===k.tool));s[s.length-1].calledTools=d.length>0?d:void 0}return s[s.length-1].usedTools=t,s})},$n=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].calledTools=t),s})},Qt=()=>{I(t=>{let n=[...ce.cloneDeep(t)];if(n[n.length-1].type==="userMessage")return n;const s=n[n.length-1];return s&&s.calledTools&&s.calledTools.length>0&&(s.usedTools&&s.usedTools.length>0||(n[n.length-1].calledTools=void 0)),n})},Wn=t=>{I(n=>{let s=[...ce.cloneDeep(n)];return s[s.length-1].type==="userMessage"||(s[s.length-1].fileAnnotations=t),s})},qn=()=>{ee(!1),I(t=>{let n=[...ce.cloneDeep(t)];if(n[n.length-1].type==="userMessage")return n;const s=n[n.length-1].agentReasoning;return s&&s.length>0&&(n[n.length-1].agentReasoning=s.filter(r=>!r.nextAgent)),n[n.length-1].calledTools=void 0,n}),setTimeout(()=>{var t;(t=ke.current)==null||t.focus()},100),H({message:"Message stopped",options:{key:new Date().getTime()+Math.random(),variant:"success",action:t=>e.jsx(te,{style:{color:"white"},onClick:()=>F(t),children:e.jsx(we,{})})}})},qs=(t="Oops! There seems to be an error. Please try again.")=>{t=t.replace(`Unable to parse JSON response from chat agent.

`,""),I(n=>[...n,{message:t,type:"apiMessage"}]),x(!1),_(""),L([]),setTimeout(()=>{var n;(n=ke.current)==null||n.focus()},100)},Gs=async t=>{_(t),Ye(void 0,t)},Gn=async t=>{_(t),st([]),Ye(void 0,t)},_s=(t,n="",s="")=>{let r=fn;s&&(r=s);const i=n||r.charAt(0).toUpperCase()+r.slice(1);Ye(void 0,i,void 0,{type:r,startNodeId:t==null?void 0:t.nodeId,feedback:n})},Vs=()=>{Rs&&(_s(Rs,Es),Ht(!1),$t(""),Wt(null),Fs(""))},Kt=async(t,n)=>{if(_(t.label),I(s=>{let r=[...ce.cloneDeep(s)];return r[r.length-1].type==="userMessage"||(r[r.length-1].action=null),r}),t.type.includes("agentflowv2")){const s=t.type.includes("approve")?"proceed":"reject";Fs(s),n.data&&n.data.input&&n.data.input.humanInputEnableFeedback?(Wt(n.data),Ht(!0)):_s(n.data,"",s)}else Ye(void 0,t.label,n)},Js=(t,n)=>{if(t.chatMessageId&&I(s=>{let r=[...ce.cloneDeep(s)];return r[r.length-1].type==="apiMessage"&&(r[r.length-1].id=t.chatMessageId),r}),t.chatId&&V(t.chatId),n===""&&t.question&&I(s=>{let r=[...ce.cloneDeep(s)];return r[r.length-2].type==="apiMessage"||(r[r.length-2].message=t.question),r}),t.followUpPrompts){const s=JSON.parse(t.followUpPrompts);st(typeof s=="string"?JSON.parse(s):s)}},_n=async t=>{if(!w.length)return t;if(v){const n=w.filter(s=>s.type==="file:full");if(n.length>0){const s=new FormData;for(const d of n)s.append("files",d.file);s.append("chatId",O);const i=(await vi.createAttachment(o,O,s)).data;for(const d of i){const k=d.content,J=d.name,E=t.findIndex(fe=>fe.name===J);E!==-1&&(t[E]={...t[E],data:k,name:J,type:"file:full"})}}}else if(Lt){const n=w.filter(s=>s.type==="file:rag");if(n.length>0){const s=new FormData;for(const i of n)s.append("files",i.file);s.append("chatId",O),await ls.upsertVectorStoreWithFormData(o,s),await(i=>new Promise(d=>setTimeout(d,i)))(2500),t=t.map(i=>({...i,type:"file:rag"}))}}return t},Ye=async(t,n,s,r)=>{if(t&&t.preventDefault(),!n&&B.trim()===""){const k=f.filter(J=>!J.mime.startsWith("image")&&J.type!=="audio").length>0;if(!f.length||f.length&&k)return}let i=B;typeof n=="string"?(n!==void 0&&n.trim()!==""&&(i=n),i.trim()&&ve.addToHistory(i)):typeof n=="object"&&(i=Object.entries(n).map(([k,J])=>`${k}: ${J}`).join(`
`)),x(!0),U();let d=f.map(k=>({data:k.data,type:k.type,name:k.name,mime:k.mime}));try{d=await _n(d)}catch{qs("Unable to upload documents");return}Dn(),I(k=>[...k,{message:i,type:"userMessage",fileUploads:d}]);try{const k={question:i,chatId:O};if(typeof n=="object"&&(k.form=n,delete k.question),d&&d.length>0&&(k.uploads=d),Se&&(k.leadEmail=Se),s&&(k.action=s),r&&(k.humanInput=r),X)Vn(o,k);else{const J=await gr.sendMessageAndGetPrediction(o,k);if(J.data){const E=J.data;Js(E,i);let fe="";E.text?fe=E.text:E.json?fe="```json\n"+JSON.stringify(E.json,null,2):fe=JSON.stringify(E,null,2),I(be=>[...be,{message:fe,id:E==null?void 0:E.chatMessageId,sourceDocuments:E==null?void 0:E.sourceDocuments,usedTools:E==null?void 0:E.usedTools,calledTools:E==null?void 0:E.calledTools,fileAnnotations:E==null?void 0:E.fileAnnotations,agentReasoning:E==null?void 0:E.agentReasoning,agentFlowExecutedData:E==null?void 0:E.agentFlowExecutedData,action:E==null?void 0:E.action,artifacts:E==null?void 0:E.artifacts,type:"apiMessage",feedback:null}]),lt(o,E.chatId),x(!1),_(""),L([]),setTimeout(()=>{var be;(be=ke.current)==null||be.focus(),kt()},100)}}}catch(k){qs(k.response.data.message);return}},Vn=async(t,n)=>{const s=n.chatId,r=n.question;n.streaming=!0,await ni(`${Me}/api/v1/internal-prediction/${t}`,{openWhenHidden:!0,method:"POST",body:JSON.stringify(n),headers:{"Content-Type":"application/json","x-request-from":"internal"},async onopen(i){i.ok&&i.headers.get("content-type")},async onmessage(i){const d=JSON.parse(i.data);switch(d.event){case"start":I(k=>[...k,{message:"",type:"apiMessage"}]);break;case"token":En(d.data);break;case"sourceDocuments":Fn(d.data);break;case"usedTools":Hn(d.data);break;case"calledTools":$n(d.data);break;case"fileAnnotations":Wn(d.data);break;case"agentReasoning":Nn(d.data);break;case"agentFlowEvent":Pn(d.data);break;case"agentFlowExecutedData":Un(d.data);break;case"artifacts":Ln(d.data);break;case"action":On(d.data);break;case"nextAgent":zn(d.data);break;case"nextAgentFlow":Bn(d.data);break;case"metadata":Js(d.data,r);break;case"error":Rn(d.data);break;case"abort":qn(d.data),Ct();break;case"tts_start":Zs(d.data);break;case"tts_data":ea(d.data.audioChunk);break;case"tts_end":ta();break;case"tts_abort":ro(d.data);break;case"end":Qt(),lt(t,s),Ct();break}},async onclose(){Qt(),Ct()},async onerror(i){throw console.error("EventSource Error: ",i),Ct(),i}})},Ct=()=>{Qt(),x(!1),_(""),L([]),setTimeout(()=>{var t;(t=ke.current)==null||t.focus(),kt()},100)},Jn=t=>{const n=t.isComposing||t.keyCode===229;if(t.key==="ArrowUp"&&!n){t.preventDefault();const s=ve.getPreviousInput(B);_(s)}else if(t.key==="ArrowDown"&&!n){t.preventDefault();const s=ve.getNextInput();_(s)}else t.key==="Enter"&&B&&!n?!t.shiftKey&&B&&Ye(t):t.key==="Enter"&&t.preventDefault()},Qs=(t,n)=>{if(t&&typeof t=="object"){if(t.pathname&&typeof t.pathname=="string")return t.pathname.substring(0,15)==="/"?t.host||"":`${t.pathname.substring(0,15)}...`;if(t.host)return t.host}return n&&n.pageContent&&typeof n.pageContent=="string"?`${n.pageContent.substring(0,15)}...`:""},Qn=()=>v?Z===""?"*":Z:Q.includes("*")?"*":Q||"*",Kn=async t=>{try{const n=await xr.post(`${Me}/api/v1/openai-assistants-file/download`,{fileName:t.fileName,chatflowId:o,chatId:O},{responseType:"blob"}),s=new Blob([n.data],{type:n.headers["content-type"]}),r=window.URL.createObjectURL(s),i=document.createElement("a");i.href=r,i.download=t.fileName,document.body.appendChild(i),i.click(),i.remove()}catch(n){console.error("Download failed:",n)}},Yn=(t,n)=>t?`${Me}/api/v1/node-icon/${t}`:n?Ar:Er;l.useEffect(()=>{var t,n;if((t=Te.data)!=null&&t.length){const s=(n=Te.data[0])==null?void 0:n.chatId;V(s);const r=Te.data.map(i=>{const d={id:i.id,message:i.content,feedback:i.feedback,type:i.role};return i.sourceDocuments&&(d.sourceDocuments=i.sourceDocuments),i.usedTools&&(d.usedTools=i.usedTools),i.calledTools&&(d.calledTools=i.calledTools),i.fileAnnotations&&(d.fileAnnotations=i.fileAnnotations),i.agentReasoning&&(d.agentReasoning=i.agentReasoning),i.action&&(d.action=i.action),i.artifacts&&(d.artifacts=i.artifacts,d.artifacts.forEach(k=>{(k.type==="png"||k.type==="jpeg")&&(k.data=`${Me}/api/v1/get-upload-file?chatflowId=${o}&chatId=${s}&fileName=${k.data.replace("FILE-STORAGE::","")}`)})),i.fileUploads&&(d.fileUploads=i.fileUploads,d.fileUploads.forEach(k=>{k.type==="stored-file"&&(k.data=`${Me}/api/v1/get-upload-file?chatflowId=${o}&chatId=${s}&fileName=${k.name}`)})),i.followUpPrompts&&(d.followUpPrompts=JSON.parse(i.followUpPrompts)),i.role==="apiMessage"&&i.execution&&i.execution.executionData&&(d.agentFlowExecutedData=JSON.parse(i.execution.executionData)),d});I(i=>[...i,...r]),lt(o,s)}},[Te.data]),l.useEffect(()=>{var t,n;if((t=Re.data)!=null&&t.length){const s=(n=Re.data[0])==null?void 0:n.sessionId;V(s);const r=Re.data.map(i=>{const d=typeof i.executionData=="string"?JSON.parse(i.executionData):i.executionData;return{id:i.id,agentFlow:d}});I(i=>[...i,...r]),lt(o,s)}},[Re.data]),l.useEffect(()=>{var t;Le.data&&q(((t=Le.data)==null?void 0:t.isStreaming)??!1)},[Le.data]),l.useEffect(()=>{var t,n,s,r,i;me.data&&(ln(((t=me.data)==null?void 0:t.isImageUploadAllowed)??!1),cn(((n=me.data)==null?void 0:n.isRAGFileUploadAllowed)??!1),y(((s=me.data)==null?void 0:s.isSpeechToTextEnabled)??!1),se((r=me.data)==null?void 0:r.imgUploadSizeAndTypes.map(d=>d.fileTypes).join(",")),ie((i=me.data)==null?void 0:i.fileUploadSizeAndTypes.map(d=>d.fileTypes).join(",")))},[me.data]),l.useEffect(()=>{var t,n,s,r,i,d,k,J,E,fe,be;if(C.data){if(qt(!1),(t=C.data)!=null&&t.flowData){const ye=(JSON.parse((n=C.data)==null?void 0:n.flowData).nodes??[]).find(ge=>ge.data.name==="startAgentflow");if(ye){const ge=(s=ye.data.inputs)==null?void 0:s.startInputType;mn(ge);const He=(r=ye.data.inputs)==null?void 0:r.formInputTypes;if(ge==="formInput"&&He&&He.length>0){for(const Xt of He)Xt.type==="options"&&(Xt.options=Xt.addOptions.map(ra=>({label:ra.option,name:ra.option})));wn(He),Ps({id:"formInput",inputs:{},inputParams:He}),yn((i=ye.data.inputs)==null?void 0:i.formTitle),jn((d=ye.data.inputs)==null?void 0:d.formDescription)}Re.request({agentflowId:o})}}if((k=C.data)!=null&&k.chatbotConfig&&JSON.parse((J=C.data)==null?void 0:J.chatbotConfig)){let Y=JSON.parse((E=C.data)==null?void 0:E.chatbotConfig);if(Y.starterPrompts){let ye=[];Object.getOwnPropertyNames(Y.starterPrompts).forEach(ge=>{Y.starterPrompts[ge]&&ye.push(Y.starterPrompts[ge])}),M(ye.filter(ge=>ge.prompt!==""))}Y.chatFeedback&&pe(Y.chatFeedback.status),Y.leads&&(Ie(Y.leads),Y.leads.status&&!Tt(o).lead&&I(ye=>{const ge={message:"",type:"leadCaptureMessage"};return[...ye,ge]})),Y.followUpPrompts&&rn(Y.followUpPrompts.status),Y.fullFileUpload&&(W(Y.fullFileUpload.status),(fe=Y.fullFileUpload)!=null&&fe.allowedUploadFileTypes&&ae((be=Y.fullFileUpload)==null?void 0:be.allowedUploadFileTypes))}}if(C.data&&C.data.textToSpeech)try{const Y=typeof C.data.textToSpeech=="string"?JSON.parse(C.data.textToSpeech):C.data.textToSpeech;let ye=!1;Y&&Object.keys(Y).forEach(ge=>{var He;ge!=="none"&&((He=Y==null?void 0:Y[ge])!=null&&He.status)&&(ye=!0)}),Gt(ye)}catch{Gt(!1)}else Gt(!1)},[C.data]),l.useEffect(()=>{C.error&&qt(!1)},[C.error]),l.useEffect(()=>{Ot(v?!0:!!Lt)},[Lt,v]),l.useEffect(()=>{_t.current||kt()},[A]),l.useEffect(()=>{g&&ke&&setTimeout(()=>{var t;(t=ke.current)==null||t.focus()},100)},[g,ke]),l.useEffect(()=>{var t;if(a&&o){Te.request(o),Le.request(o),me.request(o),C.request(o),setTimeout(()=>{kt()},100),rt(!1),qt(!0);const n=(t=Tt(o))==null?void 0:t.lead;n&&(vs(!!n),Je(n.email))}return()=>{_(""),L([]),x(!1),I([{message:"Hi there! How can I help?",type:"apiMessage"}])}},[a,o]),l.useEffect(()=>{const t=f.filter(n=>n.type==="audio").length>0;f.length>=1&&t&&(rt(!1),Bt(!1),Gs(""))},[f]),l.useEffect(()=>{if(Ut&&A.length>0){const t=A[A.length-1];if(t.type==="apiMessage"&&t.followUpPrompts){if(Array.isArray(t.followUpPrompts)&&st(t.followUpPrompts),typeof t.followUpPrompts=="string"){const n=JSON.parse(t.followUpPrompts);st(n)}}else t.type==="userMessage"&&st([])}},[Ut,A]);const Xn=async t=>{try{await navigator.clipboard.writeText(t||"")}catch(n){console.error("Error copying to clipboard:",n)}},Zn=async t=>{const n={chatflowid:o,chatId:O,messageId:t,rating:"THUMBS_UP",content:""},s=await as.addFeedback(o,n);if(s.data){const r=s.data;let i="";r&&r.id&&(i=r.id),I(d=>[...ce.cloneDeep(d)].map(J=>(J.id===t&&(J.feedback={rating:"THUMBS_UP"}),J))),_e(i),$(!0)}},eo=async t=>{const n={chatflowid:o,chatId:O,messageId:t,rating:"THUMBS_DOWN",content:""},s=await as.addFeedback(o,n);if(s.data){const r=s.data;let i="";r&&r.id&&(i=r.id),I(d=>[...ce.cloneDeep(d)].map(J=>(J.id===t&&(J.feedback={rating:"THUMBS_DOWN"}),J))),_e(i),$(!0)}},to=async t=>{const n={content:t};(await as.updateFeedback(Ce,n)).data&&(_e(""),$(!1))},so=async t=>{t&&t.preventDefault(),Ss(!0);const n={chatflowid:o,chatId:O,name:Fe,email:Se,phone:Pt},s=await Rr.addLead(n);if(s.data){const r=s.data;V(r.chatId),lt(o,r.chatId,{lead:{name:Fe,email:Se,phone:Pt}}),vs(!0),Je(Se),I(i=>{let d=[...ce.cloneDeep(i)];return d[d.length-1].type!=="leadCaptureMessage"||(d[d.length-1].message=le.successMessage||"Thank you for submitting your contact information."),d})}Ss(!1)},Ks=t=>{De[t]&&(De[t].pause(),De[t].currentTime=0,Os(n=>{const s={...n};return delete s[t],s})),Ne.audio&&(Ne.audio.pause(),St()),bt(n=>{const s={...n};return delete s[t],s}),it(n=>{const s={...n};return delete s[t],s})},Ys=async t=>{Jt(!0),await ha.abortTTS({chatflowId:o,chatId:O,chatMessageId:t}),Ks(t),ee(!1)},Yt=()=>{Object.keys(De).forEach(t=>{De[t]&&(De[t].pause(),De[t].currentTime=0)}),Os({}),Ne.abortController&&Ne.abortController.abort(),Ne.audio&&(Ne.audio.pause(),St()),bt({}),it({})},ao=async(t,n)=>{if(!xt[t]){if(yt[t]||De[t]){Ys(t);return}Jt(!0),await sa(),Yt(),Zs({chatMessageId:t,format:"mp3"});try{const s=new AbortController;ze(E=>({...E,abortController:s}));const r=await fetch("/api/v1/text-to-speech/generate",{method:"POST",headers:{"Content-Type":"application/json","x-request-from":"internal"},credentials:"include",signal:s.signal,body:JSON.stringify({chatflowId:o,chatId:O,chatMessageId:t,text:n})});if(!r.ok)throw new Error(`TTS request failed: ${r.status}`);const i=r.body.getReader(),d=new TextDecoder;let k="",J=!1;for(;!J&&!s.signal.aborted;){const E=await i.read();if(J=E.done,J)break;const fe=E.value,be=d.decode(fe,{stream:!0});k+=be;const Y=k.split(`

`);k=Y.pop()||"";for(const ye of Y)if(ye.trim()){const ge=no(ye);if(ge)switch(ge.event){case"tts_start":break;case"tts_data":s.signal.aborted||ea(ge.data.audioChunk);break;case"tts_end":s.signal.aborted||ta();break}}}}catch(s){s.name==="AbortError"?console.error("TTS request was aborted"):(console.error("Error with TTS:",s),H({message:`TTS failed: ${s.message}`,options:{variant:"error"}}))}finally{it(s=>{const r={...s};return delete r[t],r})}}},no=t=>{const n=t.split(`
`),s={};for(const r of n)if(r.startsWith("event:"))s.event=r.substring(6).trim();else if(r.startsWith("data:")){const i=r.substring(5).trim();try{const d=JSON.parse(i);d.data&&(s.data=d.data)}catch(d){console.error("Error parsing SSE data:",d,"Raw data:",i)}}return s.event?s:null},oo=t=>{try{const n=new MediaSource,s=new Audio;s.src=URL.createObjectURL(n),n.addEventListener("sourceopen",()=>{try{const r=(t.format==="mp3","audio/mpeg"),i=n.addSourceBuffer(r);ze(d=>({...d,mediaSource:n,sourceBuffer:i,audio:s})),s.play().catch(d=>{console.error("Error starting audio playback:",d)})}catch(r){console.error("Error setting up source buffer:",r),console.error("MediaSource readyState:",n.readyState),console.error("Requested MIME type:",mimeType)}}),s.addEventListener("playing",()=>{it(r=>{const i={...r};return delete i[t.chatMessageId],i}),bt(r=>({...r,[t.chatMessageId]:!0}))}),s.addEventListener("ended",()=>{bt(r=>{const i={...r};return delete i[t.chatMessageId],i}),St()})}catch(n){console.error("Error initializing TTS streaming:",n)}},St=()=>{ze(t=>{if(t.abortController&&t.abortController.abort(),t.audio&&(t.audio.pause(),t.audio.removeAttribute("src"),t.audio.src&&URL.revokeObjectURL(t.audio.src)),t.mediaSource){if(t.mediaSource.readyState==="open")try{t.mediaSource.endOfStream()}catch{}t.mediaSource.removeEventListener("sourceopen",()=>{})}return{mediaSource:null,sourceBuffer:null,audio:null,chunkQueue:[],isBuffering:!1,audioFormat:null,abortController:null}})},Xs=()=>{ze(t=>{if(!t.sourceBuffer||t.sourceBuffer.updating||t.chunkQueue.length===0)return t;const n=t.chunkQueue.shift();try{return t.sourceBuffer.appendBuffer(n),{...t,chunkQueue:[...t.chunkQueue],isBuffering:!0}}catch(s){return console.error("Error appending chunk to buffer:",s),t}})},Zs=t=>{Jt(!0),Yt(),it(n=>({...n,[t.chatMessageId]:!0})),I(n=>{const s=[...ce.cloneDeep(n)],r=s[s.length-1];return r.type==="userMessage"||r.id||(s[s.length-1].id=t.chatMessageId),s}),ze({mediaSource:null,sourceBuffer:null,audio:null,chunkQueue:[],isBuffering:!1,audioFormat:t.format,abortController:null}),setTimeout(()=>oo(t),0)},ea=t=>{try{const n=Uint8Array.from(atob(t),s=>s.charCodeAt(0));ze(s=>{const r={...s,chunkQueue:[...s.chunkQueue,n]};return s.sourceBuffer&&!s.sourceBuffer.updating&&setTimeout(()=>Xs(),0),r})}catch(n){console.error("Error handling TTS data chunk:",n)}},ta=()=>{ze(t=>{if(t.mediaSource&&t.mediaSource.readyState==="open")try{if(t.sourceBuffer&&t.chunkQueue.length>0&&!t.sourceBuffer.updating){const n=[...t.chunkQueue];return n.forEach((s,r)=>{setTimeout(()=>{if(t.sourceBuffer&&!t.sourceBuffer.updating)try{t.sourceBuffer.appendBuffer(s),r===n.length-1&&setTimeout(()=>{t.mediaSource&&t.mediaSource.readyState==="open"&&t.mediaSource.endOfStream()},100)}catch(i){console.error("Error appending remaining chunk:",i)}},r*50)}),{...t,chunkQueue:[]}}t.sourceBuffer&&!t.sourceBuffer.updating?t.mediaSource.endOfStream():t.sourceBuffer&&t.sourceBuffer.addEventListener("updateend",()=>{t.mediaSource&&t.mediaSource.readyState==="open"&&t.mediaSource.endOfStream()},{once:!0})}catch(n){console.error("Error ending TTS stream:",n)}return t})},ro=t=>{const n=t.chatMessageId;Ks(n)},sa=async()=>{const t=Object.keys(xt).concat(Object.keys(yt));for(const n of t)await ha.abortTTS({chatflowId:o,chatId:O,chatMessageId:n})};l.useEffect(()=>{if(Ne.sourceBuffer){const t=Ne.sourceBuffer,n=()=>{ze(s=>({...s,isBuffering:!1})),setTimeout(()=>Xs(),0)};return t.addEventListener("updateend",n),()=>{t.removeEventListener("updateend",n)}}},[Ne.sourceBuffer]),l.useEffect(()=>()=>{St(),Be.current&&(clearTimeout(Be.current),Be.current=null)},[]);const he=()=>b||!o||(le==null?void 0:le.status)&&!on||A[A.length-1].action&&Object.keys(A[A.length-1].action).length>0,io=t=>{var n,s;return t.mime.startsWith("image/")?e.jsxs(pi,{focusRipple:!0,style:{width:"48px",height:"48px",marginRight:"10px",flex:"0 0 auto"},disabled:he(),onClick:()=>Vt(t),children:[e.jsx(hi,{style:{backgroundImage:`url(${t.data})`}}),e.jsx(fi,{className:"MuiImageBackdrop-root"}),e.jsx(gi,{className:"MuiImageMarked-root",children:e.jsx(Et,{size:20,color:"white"})})]}):t.mime.startsWith("audio/")?e.jsxs(Ze,{sx:{display:"inline-flex",alignItems:"center",height:"48px",width:g?((n=R==null?void 0:R.current)==null?void 0:n.offsetWidth)/4:((s=R==null?void 0:R.current)==null?void 0:s.offsetWidth)/2,p:.5,mr:1,backgroundColor:u.palette.grey[500],flex:"0 0 auto"},variant:"outlined",children:[e.jsx(ts,{component:"audio",sx:{color:"transparent"},controls:!0,src:t.data}),e.jsx(xe,{disabled:he(),onClick:()=>Vt(t),size:"small",children:e.jsx(Et,{size:20,color:"white"})})]}):e.jsx(Xa,{disabled:he(),item:t,customization:m,onDelete:()=>Vt(t)})},lo=(t,n)=>{var s,r;return(s=t==null?void 0:t.mime)!=null&&s.startsWith("image/")?e.jsx(Ze,{sx:{p:0,m:0,maxWidth:128,marginRight:"10px",flex:"0 0 auto"},children:e.jsx(ts,{component:"img",image:t.data,sx:{height:64},alt:"preview",style:Mi})},n):(r=t==null?void 0:t.mime)!=null&&r.startsWith("audio/")?e.jsxs("audio",{controls:"controls",children:["Your browser does not support the <audio> tag.",e.jsx("source",{src:t.data,type:t.mime})]}):e.jsxs(Ze,{sx:{display:"inline-flex",alignItems:"center",height:"48px",width:"max-content",p:2,mr:1,flex:"0 0 auto",backgroundColor:m.isDarkMode?"rgba(0, 0, 0, 0.3)":"transparent"},variant:"outlined",children:[e.jsx(Mt,{size:20}),e.jsx("span",{style:{marginLeft:"5px",color:m.isDarkMode?"white":"inherit"},children:t.name})]})},co=t=>{const n=ce.cloneDeep(t);for(let s=0;s<n.length;s++){const r=n[s];if(r&&(r.type==="png"||r.type==="jpeg")){const i=r.data;n[s].data=`${Me}/api/v1/get-upload-file?chatflowId=${o}&chatId=${O}&fileName=${i.replace("FILE-STORAGE::","")}`}}return n},aa=(t,n,s)=>t.type==="png"||t.type==="jpeg"?e.jsx(Ze,{sx:{p:0,m:0,mt:2,mb:2,flex:"0 0 auto"},children:e.jsx(ts,{component:"img",image:t.data,sx:{height:"auto"},alt:"artifact",style:{width:s?"200px":"100%",height:s?"200px":"auto",objectFit:"cover"}})},n):t.type==="html"?e.jsx("div",{style:{marginTop:"20px"},children:e.jsx(mr,{html:t.data})}):e.jsx(rs,{chatflowid:o,isFullWidth:g,children:t.data});return kn?e.jsx(G,{sx:{width:"100%",height:"100%",position:"relative",backgroundColor:u.palette.background.paper},children:e.jsx(G,{sx:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)"},children:e.jsx(ct,{})})}):gn==="formInput"&&A.length===1?e.jsx(G,{sx:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",p:2,backgroundColor:u.palette.background.paper},children:e.jsx(G,{sx:{width:"100%",height:"100%",position:"relative"},children:e.jsxs(G,{sx:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"100%",maxWidth:"600px",maxHeight:"90%",p:3,backgroundColor:m.isDarkMode?dr(u.palette.background.paper,.2):u.palette.background.paper,boxShadow:m.isDarkMode?"0px 0px 15px 0px rgba(255, 255, 255, 0.1)":u.shadows[3],borderRadius:2,overflowY:"auto"},children:[e.jsx(de,{variant:"h4",sx:{mb:1,textAlign:"center"},children:xn||"Please Fill Out The Form"}),e.jsx(de,{variant:"body1",sx:{mb:3,textAlign:"center",color:u.palette.text.secondary},children:bn||"Complete all fields below to continue"}),e.jsx(G,{sx:{mb:3},children:Us&&Us.map((t,n)=>e.jsx(G,{sx:{mb:2},children:e.jsx(zr,{inputParam:t,data:Ns,isAdditionalParams:!0,onCustomDataChange:({inputParam:s,newValue:r})=>{Ps(i=>({...i,inputs:{...i.inputs,[s.name]:r}}))}})},n))}),e.jsx(te,{variant:"contained",fullWidth:!0,disabled:b,onClick:()=>Ye(null,Ns.inputs),sx:{mb:2,borderRadius:20,background:"linear-gradient(45deg, #673ab7 30%, #1e88e5 90%)"},children:b?"Submitting...":"Submit"})]})})}):e.jsxs("div",{onDragEnter:jt,children:[Ms&&e.jsx("div",{className:"image-dropzone",onDragEnter:jt,onDragLeave:jt,onDragEnd:jt,onDrop:Sn}),Ms&&(((na=me.data)==null?void 0:na.isImageUploadAllowed)||((oa=me.data)==null?void 0:oa.isRAGFileUploadAllowed))&&e.jsxs(G,{className:"drop-overlay",children:[e.jsx(de,{variant:"h2",children:"Drop here to upload"}),[...me.data.imgUploadSizeAndTypes,...me.data.fileUploadSizeAndTypes].map(t=>{var n;return e.jsxs(e.Fragment,{children:[e.jsx(de,{variant:"subtitle1",children:(n=t.fileTypes)==null?void 0:n.join(", ")}),t.maxUploadSize&&e.jsxs(de,{variant:"subtitle1",children:["Max Allowed Size: ",t.maxUploadSize," MB"]})]})})]}),e.jsx("div",{ref:R,className:`${g?"cloud-dialog":"cloud"}`,children:e.jsx("div",{id:"messagelist",className:"messagelist",children:A&&A.map((t,n)=>{var s;return e.jsxs(G,{sx:{background:t.type==="apiMessage"||t.type==="leadCaptureMessage"?u.palette.asyncSelect.main:""},style:{display:"flex"},className:t.type==="userMessage"&&b&&n===A.length-1?m.isDarkMode?"usermessagewaiting-dark":"usermessagewaiting-light":t.type==="usermessagewaiting"?"apimessage":"usermessage",children:[t.type==="apiMessage"||t.type==="leadCaptureMessage"?e.jsx("img",{src:ur,alt:"AI",width:"30",height:"30",className:"boticon"}):e.jsx("img",{src:Tr,alt:"Me",width:"30",height:"30",className:"usericon"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100%"},children:[t.fileUploads&&t.fileUploads.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",flexDirection:"column",width:"100%",gap:"8px"},children:t.fileUploads.map((r,i)=>e.jsx(e.Fragment,{children:lo(r,i)}))}),t.agentReasoning&&t.agentReasoning.length>0&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%"},children:t.agentReasoning.map((r,i)=>e.jsx(js,{agent:r,index:i,customization:m,chatflowid:o,isDialog:g,onSourceDialogClick:wt,renderArtifacts:aa,agentReasoningArtifacts:co,getAgentIcon:Yn,removeDuplicateURL:pa,isValidURL:ua,onURLClick:Ws,getLabel:Qs},i))}),t.agentFlowExecutedData&&Array.isArray(t.agentFlowExecutedData)&&t.agentFlowExecutedData.length>0&&e.jsx(ui,{status:t.agentFlowEventStatus,execution:t.agentFlowExecutedData,agentflowId:o,sessionId:O}),t.calledTools&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%"},children:t.calledTools.map((r,i)=>r?e.jsx(Ae,{size:"small",label:r.tool,component:"a",sx:{mr:1,mt:1,borderColor:"primary.main",color:"primary.main",backgroundColor:"rgba(25, 118, 210, 0.1)",opacity:.9,"&:hover":{backgroundColor:"rgba(25, 118, 210, 0.2)",opacity:1}},variant:"outlined",clickable:!0,icon:e.jsx(ct,{size:15,color:"primary"}),onClick:()=>wt(r,"Called Tools")},`called-${i}`):null)}),t.usedTools&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%"},children:t.usedTools.map((r,i)=>r?e.jsx(Ae,{size:"small",label:r.tool,component:"a",sx:{mr:1,mt:1,borderColor:r.error?"error.main":void 0,color:r.error?"error.main":void 0},variant:"outlined",clickable:!0,icon:e.jsx(Ea,{size:15,color:r.error?u.palette.error.main:void 0}),onClick:()=>wt(r,"Used Tools")},`used-${i}`):null)}),t.artifacts&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",flexDirection:"column",width:"100%"},children:t.artifacts.map((r,i)=>r!==null?e.jsx(e.Fragment,{children:aa(r,i)}):null)}),e.jsx("div",{className:"markdownanswer",children:t.type==="leadCaptureMessage"&&!((s=Tt(o))!=null&&s.lead)&&le.status?e.jsxs(G,{sx:{display:"flex",flexDirection:"column",gap:2,marginTop:2},children:[e.jsx(de,{sx:{lineHeight:"1.5rem",whiteSpace:"pre-line"},children:le.title||"Let us know where we can reach you:"}),e.jsxs("form",{style:{display:"flex",flexDirection:"column",gap:"8px",width:g?"50%":"100%"},onSubmit:so,children:[le.name&&e.jsx(qe,{id:"leadName",type:"text",fullWidth:!0,placeholder:"Name",name:"leadName",value:Fe,autoFocus:!0,onChange:r=>Ve(r.target.value)}),le.email&&e.jsx(qe,{id:"leadEmail",type:"email",fullWidth:!0,placeholder:"Email Address",name:"leadEmail",value:Se,onChange:r=>Je(r.target.value)}),le.phone&&e.jsx(qe,{id:"leadPhone",type:"number",fullWidth:!0,placeholder:"Phone Number",name:"leadPhone",value:Pt,onChange:r=>an(r.target.value)}),e.jsx(G,{sx:{display:"flex",alignItems:"center"},children:e.jsx(te,{variant:"outlined",fullWidth:!0,type:"submit",sx:{borderRadius:"20px"},children:nn?"Saving...":"Save"})})]})]}):e.jsx(e.Fragment,{children:e.jsx(rs,{chatflowid:o,isFullWidth:g,children:t.message})})}),t.fileAnnotations&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%",marginBottom:"8px"},children:t.fileAnnotations.map((r,i)=>e.jsx(te,{sx:{fontSize:"0.85rem",textTransform:"none",mb:1},variant:"outlined",onClick:()=>Kn(r),endIcon:e.jsx(pr,{color:u.palette.primary.main}),children:r.fileName},i))}),t.sourceDocuments&&e.jsx("div",{style:{display:"block",flexDirection:"row",width:"100%",marginBottom:"8px"},children:pa(t).map((r,i)=>{const d=r.metadata&&r.metadata.source?ua(r.metadata.source):void 0;return e.jsx(Ae,{size:"small",label:Qs(d,r)||"",component:"a",sx:{mr:1,mb:1},variant:"outlined",clickable:!0,onClick:()=>d?Ws(r.metadata.source):wt(r)},i)})}),t.action&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",flexDirection:"row",width:"100%",gap:"8px",marginBottom:"8px"},children:(t.action.elements||[]).map((r,i)=>e.jsx(e.Fragment,{children:r.type==="approve-button"&&r.label==="Yes"||r.type==="agentflowv2-approve-button"?e.jsx(te,{sx:{width:"max-content",borderRadius:"20px",background:m.isDarkMode?"transparent":"white"},variant:"outlined",color:"success",startIcon:e.jsx(va,{}),onClick:()=>Kt(r,t.action),children:r.label},i):r.type==="reject-button"&&r.label==="No"||r.type==="agentflowv2-reject-button"?e.jsx(te,{sx:{width:"max-content",borderRadius:"20px",background:m.isDarkMode?"transparent":"white"},variant:"outlined",color:"error",startIcon:e.jsx(we,{}),onClick:()=>Kt(r,t.action),children:r.label},i):e.jsx(te,{sx:{width:"max-content",borderRadius:"20px",background:"white"},variant:"outlined",onClick:()=>Kt(r,t.action),children:r.label},i)}))}),t.type==="apiMessage"&&t.id?e.jsx(e.Fragment,{children:e.jsxs(G,{sx:{display:"flex",alignItems:"center",justifyContent:"start",gap:1},children:[Cn&&e.jsx(xe,{size:"small",onClick:()=>yt[t.id]?Ys(t.id):ao(t.id,t.message),disabled:xt[t.id],sx:{backgroundColor:De[t.id]?"primary.main":"transparent",color:De[t.id]?"white":"inherit","&:hover":{backgroundColor:De[t.id]?"primary.dark":"action.hover"}},children:xt[t.id]?e.jsx(ct,{size:16}):yt[t.id]?e.jsx(fa,{style:{width:"20px",height:"20px"},color:"red"}):e.jsx(Mr,{style:{width:"20px",height:"20px"},color:m.isDarkMode?"white":"#1e88e5"})}),K&&e.jsxs(e.Fragment,{children:[e.jsx(Wa,{onClick:()=>Xn(t.message)}),!t.feedback||t.feedback.rating===""||t.feedback.rating==="THUMBS_UP"?e.jsx(qa,{isDisabled:t.feedback&&t.feedback.rating==="THUMBS_UP",rating:t.feedback?t.feedback.rating:"",onClick:()=>Zn(t.id)}):null,!t.feedback||t.feedback.rating===""||t.feedback.rating==="THUMBS_DOWN"?e.jsx(Ga,{isDisabled:t.feedback&&t.feedback.rating==="THUMBS_DOWN",rating:t.feedback?t.feedback.rating:"",onClick:()=>eo(t.id)}):null]})]})}):null]})]},n)})})}),A&&A.length===1&&T.length>0&&e.jsx("div",{style:{position:"relative"},children:e.jsx(La,{sx:{bottom:f&&f.length>0?70:0},starterPrompts:T||[],onPromptClick:Gs,isGrid:g})}),A&&A.length>2&&Ut&&Is.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(pt,{sx:{width:"100%"}}),e.jsxs(G,{sx:{display:"flex",flexDirection:"column",position:"relative",pt:1.5},children:[e.jsxs(Ue,{sx:{flexDirection:"row",alignItems:"center",px:1.5,gap:.5},children:[e.jsx(ms,{size:12}),e.jsx(de,{sx:{fontSize:"0.75rem"},variant:"body2",children:"Try these prompts"})]}),e.jsx(Ya,{sx:{bottom:f&&f.length>0?70:0},followUpPrompts:Is||[],onPromptClick:Gn,isGrid:g})]})]}),e.jsx(pt,{sx:{width:"100%"}}),e.jsxs("div",{className:"center",children:[f&&f.length>0&&e.jsx(G,{sx:{width:"100%",mb:1.5,display:"flex",alignItems:"center"},children:f.map((t,n)=>e.jsx(l.Fragment,{children:io(t)},n))}),dn?e.jsx(e.Fragment,{children:As?e.jsx("div",{className:"overlay",children:e.jsxs("div",{className:"browser-not-supporting-audio-recording-box",children:[e.jsx(de,{variant:"body1",children:"To record audio, use modern browsers like Chrome or Firefox that support audio recording."}),e.jsx(te,{variant:"contained",color:"error",size:"small",type:"button",onClick:()=>$s(),children:"Okay"})]})}):e.jsxs(G,{sx:{width:"100%",height:"54px",px:2,border:"1px solid",borderRadius:3,backgroundColor:m.isDarkMode?"#32353b":"#fafafa",borderColor:"rgba(0, 0, 0, 0.23)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{className:"recording-elapsed-time",children:[e.jsx("span",{className:"red-recording-dot",children:e.jsx(fa,{})}),e.jsx(de,{id:"elapsed-time",children:"00:00"}),un&&e.jsx(de,{ml:1.5,children:"Sending..."})]}),e.jsxs("div",{className:"recording-control-buttons-container",children:[e.jsx(xe,{onClick:$s,size:"small",children:e.jsx(we,{color:b||!o?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})}),e.jsx(xe,{onClick:Mn,size:"small",children:e.jsx(ss,{color:b||!o?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})]})]})}):e.jsxs("form",{style:{width:"100%"},onSubmit:Ye,children:[e.jsx(qe,{inputRef:ke,autoFocus:!0,sx:{width:"100%"},disabled:he(),onKeyDown:Jn,id:"userInput",name:"userInput",placeholder:b?"Waiting for response...":"Type your question...",value:B,onChange:An,multiline:!0,maxRows:g?7:2,startAdornment:e.jsxs(e.Fragment,{children:[Qe&&!Ke&&e.jsx(Pe,{position:"start",sx:{ml:2},children:e.jsx(xe,{onClick:Hs,type:"button",disabled:he(),edge:"start",children:e.jsx(ga,{color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})}),!Qe&&Ke&&e.jsx(Pe,{position:"start",sx:{ml:2},children:e.jsx(xe,{onClick:Bs,type:"button",disabled:he(),edge:"start",children:e.jsx(Mt,{color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})}),Qe&&Ke&&e.jsxs(Pe,{position:"start",sx:{ml:2},children:[e.jsx(xe,{onClick:Hs,type:"button",disabled:he(),edge:"start",children:e.jsx(ga,{color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})}),e.jsx(xe,{sx:{ml:0},onClick:Bs,type:"button",disabled:he(),edge:"start",children:e.jsx(Mt,{color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})]}),!Qe&&!Ke&&e.jsx(G,{sx:{pl:1}})]}),endAdornment:e.jsxs(e.Fragment,{children:[ne&&e.jsx(Pe,{position:"end",children:e.jsx(xe,{onClick:()=>Tn(),type:"button",disabled:he(),edge:"end",children:e.jsx($r,{className:"start-recording-button",color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})}),!c&&e.jsx(Pe,{position:"end",sx:{paddingRight:"15px"},children:e.jsx(xe,{type:"submit",disabled:he(),edge:"end",children:b?e.jsx("div",{children:e.jsx(ct,{color:"inherit",size:20})}):e.jsx(ss,{color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})}),c&&e.jsxs(e.Fragment,{children:[!b&&e.jsx(Pe,{position:"end",sx:{paddingRight:"15px"},children:e.jsx(xe,{type:"submit",disabled:he(),edge:"end",children:e.jsx(ss,{color:he()?"#9e9e9e":m.isDarkMode?"white":"#1e88e5"})})}),b&&e.jsx(Pe,{position:"end",sx:{padding:"15px",mr:1},children:e.jsx(xe,{edge:"end",title:oe?"Stopping...":"Stop",style:{border:oe?"none":"2px solid red"},onClick:()=>In(),disabled:oe,children:oe?e.jsx("div",{children:e.jsx(ct,{color:"error",size:20})}):e.jsx(_r,{size:15,color:"red"})})})]})]})}),Qe&&e.jsx("input",{style:{display:"none"},multiple:!0,ref:Ds,type:"file",onChange:zs,accept:re||"*"}),Ke&&e.jsx("input",{style:{display:"none"},multiple:!0,ref:Ts,type:"file",onChange:zs,accept:Qn()})]})]}),e.jsx(hr,{show:h,dialogProps:N,onCancel:()=>S(!1)}),e.jsx(ri,{show:ot,onCancel:()=>$(!1),onConfirm:to}),e.jsxs(at,{maxWidth:"md",fullWidth:!0,open:hn,onClose:()=>{Ht(!1),Wt(null),$t("")},children:[e.jsx(ht,{variant:"h5",children:"Provide Feedback"}),e.jsx(nt,{children:e.jsx(Sa,{autoFocus:!0,margin:"dense",label:"Feedback",fullWidth:!0,multiline:!0,rows:4,value:Es,onChange:t=>$t(t.target.value)})}),e.jsxs(ft,{children:[e.jsx(te,{onClick:Vs,children:"Cancel"}),e.jsx(te,{onClick:Vs,variant:"contained",children:"Submit"})]})]})]})};Za.propTypes={open:p.bool,chatflowid:p.string,isAgentCanvas:p.bool,isDialog:p.bool,previews:p.array,setPreviews:p.func};const en=l.memo(Za),tn=({show:a,dialogProps:o,isAgentCanvas:c,onClear:g,onCancel:f,previews:j,setPreviews:u})=>{const m=document.getElementById("portal"),R=Ee(z=>z.customization),D=a?e.jsxs(at,{open:a,fullWidth:!0,maxWidth:"md",onClose:f,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",sx:{overflow:"visible"},children:[e.jsx(ht,{sx:{fontSize:"1rem",p:1.5},id:"alert-dialog-title",children:e.jsxs("div",{style:{display:"flex",flexDirection:"row"},children:[o.title,e.jsx("div",{style:{flex:1}}),R.isDarkMode&&e.jsx(Aa,{variant:"outlined",color:"error",title:"Clear Conversation",onClick:g,startIcon:e.jsx(cs,{}),children:"Clear Chat"}),!R.isDarkMode&&e.jsx(te,{variant:"outlined",color:"error",title:"Clear Conversation",onClick:g,startIcon:e.jsx(cs,{}),children:"Clear Chat"})]})}),e.jsx(nt,{className:"cloud-dialog-wrapper",sx:{display:"flex",justifyContent:"flex-end",flexDirection:"column",p:0},children:e.jsx(en,{isDialog:!0,open:o.open,isAgentCanvas:c,chatflowid:o.chatflowid,previews:j,setPreviews:u})})]}):null;return Nt.createPortal(D,m)};tn.propTypes={show:p.bool,dialogProps:p.object,isAgentCanvas:p.bool,onClear:p.func,onCancel:p.func,previews:p.array,setPreviews:p.func};const sn=({chatflowid:a,isAgentCanvas:o,onOpenChange:c})=>{const g=Ge(),{confirm:f}=yr(),j=et(),{clearAgentflowNodeStatus:u}=l.useContext(gs);Ft();const m=(...h)=>j(gt(...h)),R=(...h)=>j(mt(...h)),[D,z]=l.useState(!1),[U,H]=l.useState(!1),[F,B]=l.useState({}),[_,b]=l.useState([]),x=l.useRef(null),A=l.useRef(D),I=h=>{x.current&&x.current.contains(h.target)||(z(!1),c&&c(!1))},X=()=>{const h=!D;z(h),c&&c(h)},q=()=>{B({open:!0,chatflowid:a}),H(!0)},ne=()=>{const h={...F,open:!1};B(h),u(),setTimeout(()=>{const S={...F,open:!0};B(S)},500)},y=async()=>{if(await f({title:"Clear Chat History",description:"Are you sure you want to clear all chat history?",confirmButtonName:"Clear",cancelButtonName:"Cancel"}))try{const N=Tt(a);if(!N.chatId)return;await is.deleteChatmessage(a,{chatId:N.chatId,chatType:"INTERNAL"}),br(a),ne(),m({message:"Succesfully cleared all chat history",options:{key:new Date().getTime()+Math.random(),variant:"success",action:P=>e.jsx(te,{style:{color:"white"},onClick:()=>R(P),children:e.jsx(we,{})})}})}catch(N){m({message:typeof N.response.data=="object"?N.response.data.message:N.response.data,options:{key:new Date().getTime()+Math.random(),variant:"error",persist:!0,action:P=>e.jsx(te,{style:{color:"white"},onClick:()=>R(P),children:e.jsx(we,{})})}})}};return l.useEffect(()=>{A.current===!0&&D===!1&&(x.current.focus(),c&&c(!1)),A.current=D},[D,a]),e.jsxs(e.Fragment,{children:[e.jsx(ut,{sx:{position:"absolute",right:20,top:20},ref:x,size:"small",color:"secondary","aria-label":"chat",title:"Chat",onClick:X,children:D?e.jsx(we,{}):e.jsx(Fr,{})}),D&&e.jsx(ut,{sx:{position:"absolute",right:80,top:20},onClick:y,size:"small",color:"error","aria-label":"clear",title:"Clear Chat History",children:e.jsx(cs,{})}),D&&e.jsx(ut,{sx:{position:"absolute",right:140,top:20},onClick:q,size:"small",color:"primary","aria-label":"expand",title:"Expand Chat",children:e.jsx(Ra,{})}),e.jsx(Ia,{placement:"bottom-end",open:D,anchorEl:x.current,role:void 0,transition:!0,disablePortal:!0,popperOptions:{modifiers:[{name:"offset",options:{offset:[40,14]}}]},sx:{zIndex:1e3},children:({TransitionProps:h})=>e.jsx(Da,{in:D,...h,children:e.jsx(us,{children:e.jsx(Ta,{onClickAway:I,children:e.jsx(Ma,{border:!1,className:"cloud-wrapper",elevation:16,content:!1,boxShadow:!0,shadow:g.shadows[16],children:e.jsx(en,{isAgentCanvas:o,chatflowid:a,open:D,previews:_,setPreviews:b})})})})})}),e.jsx(tn,{show:U,dialogProps:F,isAgentCanvas:o,onClear:y,onCancel:()=>H(!1),previews:_,setPreviews:b})]})};sn.propTypes={chatflowid:p.string,isAgentCanvas:p.bool,onOpenChange:p.func};const Wi=l.memo(sn);function Ai(a,o=!0){const{navigator:c}=l.useContext(jr);l.useEffect(()=>{if(!o)return;const g=c.block(f=>{const j={...f,retry(){g(),f.retry()}};a(j)});return g},[c,a,o])}function qi(a,o=!0){const c=l.useCallback(g=>{window.confirm(a)&&g.retry()},[a]);Ai(c,o)}export{$i as A,Vr as C,Hi as I,Wi as a,qi as u};
