@chatsystem/client 1.1.79 → 1.1.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -135,7 +135,7 @@ For more details see https://formatjs.io/docs/getting-started/message-distributi
135
135
  transition-colors
136
136
  enabled:hover:scale-[1.02] active:scale-[0.98]
137
137
  chatsystem-mic-button
138
- ${n??""}`,"data-testid":"mic-button",onClick:e,disabled:t,type:"button","aria-label":"Start voice input",children:C.jsx("span",{"data-state":"closed",children:C.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"24",height:"24","aria-hidden":"true",className:"text-white dark:text-black",children:[C.jsx("path",{d:"M12 14.5c1.66 0 3-1.34 3-3V6.5c0-1.66-1.34-3-3-3s-3 1.34-3 3v5c0 1.66 1.34 3 3 3Z",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinejoin:"round"}),C.jsx("path",{d:"M12 14.5V18",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),C.jsx("path",{d:"M8.5 18h7",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),C.jsx("path",{d:"M7 11.5c0 2.76 2.24 5 5 5s5-2.24 5-5",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"})]})})})});function Hx(){const[e,t]=v.useState("idle"),[n,r]=v.useState(null),[i,a]=v.useState(0),s=v.useRef(null),o=v.useRef(null),u=v.useRef([]),c=v.useRef(null),d=v.useRef(null),f=v.useRef(null),m=v.useRef(null),h=v.useCallback(()=>{m.current!==null&&(cancelAnimationFrame(m.current),m.current=null);try{f.current?.disconnect()}catch{}f.current=null;try{d.current?.disconnect()}catch{}d.current=null;const _=c.current;c.current=null,_&&_.close().catch(()=>{}),a(0)},[]),b=v.useCallback(_=>{try{const S=new AudioContext,D=S.createAnalyser(),I=S.createMediaStreamSource(_);D.fftSize=256,D.smoothingTimeConstant=.85,I.connect(D),c.current=S,d.current=D,f.current=I;const N=new Uint8Array(D.fftSize),G=()=>{const se=d.current;if(!se)return;se.getByteTimeDomainData(N);let ee=0;for(let $=0;$<N.length;$++){const U=(N[$]-128)/128;ee+=U*U}const k=Math.sqrt(ee/N.length),M=Math.min(1,k*6);a(M),m.current=requestAnimationFrame(G)};m.current=requestAnimationFrame(G)}catch{a(0)}},[]),A=v.useCallback(async()=>{r(null),h();try{const _=await navigator.mediaDevices.getUserMedia({audio:!0});o.current=_,b(_);const D=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"].find(N=>MediaRecorder.isTypeSupported(N))||"",I=new MediaRecorder(_,D?{mimeType:D}:void 0);s.current=I,u.current=[],I.ondataavailable=N=>{N.data&&N.data.size>0&&u.current.push(N.data)},I.onerror=()=>{t("error"),r("Recorder error.")},I.onstart=()=>t("recording"),I.onstop=()=>t("stopped"),I.start()}catch(_){h(),t("error"),r(_?.message??"Microphone permission denied.")}},[b,h]),w=v.useCallback(async()=>{const _=s.current,S=o.current;return!_||e!=="recording"?null:new Promise(D=>{_.onstop=()=>{h();const I=_.mimeType||"audio/webm",N=new Blob(u.current,{type:I}),G=I.includes("ogg")?"ogg":"webm",se=new File([N],`voice-message.${G}`,{type:I});S?.getTracks().forEach(ee=>ee.stop()),o.current=null,s.current=null,D({blob:N,file:se})},_.stop()})},[e,h]),y=v.useCallback(()=>{const _=s.current,S=o.current;try{_&&e==="recording"&&_.stop()}catch{}h(),S?.getTracks().forEach(D=>D.stop()),o.current=null,s.current=null,u.current=[],t("idle")},[e,h]);return v.useEffect(()=>()=>{h(),o.current?.getTracks().forEach(_=>_.stop())},[h]),{state:e,error:n,audioLevel:i,start:A,stop:w,cancel:y}}const Ux=()=>{const e=Jt(),t=e.formatMessage({defaultMessage:"Recording...",id:"recordingOverlay.recording"}),n=e.formatMessage({defaultMessage:"Cancel",id:"recordingOverlay.cancel"}),r=e.formatMessage({defaultMessage:"Tap the mic to stop",id:"recordingOverlay.explaination"});return{recordingTranslation:t,cancelTranslation:n,recordingExplainationTranslation:r}},jx=({isOpen:e,onStop:t,onCancel:n,audioLevel:r=0})=>{if(!e)return null;const{recordingTranslation:i}=Ux(),a=v.useMemo(()=>{const s=Math.max(0,Math.min(1,r));return Array.from({length:20},(o,u)=>{const c=Math.sin(u/19*Math.PI*2)*.5+.5,d=u%2===0?.9:.65,f=6+s*(14+c*18)*d;return Math.round(f)})},[r]);return C.jsx("div",{className:"relative mt-3 w-full rounded-lg border border-slate-400 bg-white p-1",role:"group","aria-label":"Recording voice message",children:C.jsxs("div",{className:"flex min-h-[48px] items-center gap-3 px-2",children:[C.jsxs("div",{className:"relative flex h-8 w-8 items-center justify-center",children:[C.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-100 motion-safe:animate-ping","aria-hidden":!0}),C.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-50","aria-hidden":!0}),C.jsx("span",{className:"absolute h-3.5 w-3.5 rounded-full bg-red-200","aria-hidden":!0}),C.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500","aria-hidden":!0})]}),C.jsxs("div",{className:"min-w-0 flex-1",children:[C.jsx("div",{className:"mb-0.5 text-[11px] font-medium leading-3 text-slate-600",children:i}),C.jsx("div",{className:"flex h-5 items-center gap-[3px] overflow-hidden","aria-hidden":"true",children:a.map((s,o)=>C.jsx("span",{className:"block w-1 rounded-full bg-slate-400 transition-[height,background-color] duration-75",style:{height:`${s}px`,backgroundColor:r>.08?"rgb(59 130 246)":"rgb(148 163 184)"}},o))})]}),C.jsx("button",{type:"button",onClick:n,className:"flex h-9 w-9 items-center justify-center rounded-full text-slate-500 hover:bg-slate-100 hover:text-slate-700","aria-label":"Cancel recording",children:C.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:C.jsx("path",{d:"M6 6l12 12M18 6L6 18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),C.jsx("button",{type:"button",onClick:t,className:"flex h-9 w-9 items-center justify-center rounded-full bg-violet-600 text-white hover:bg-violet-700","aria-label":"Validate recording",children:C.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:C.jsx("path",{d:"M5 13l4 4L19 7",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})};let lr=new AbortController;const Cc=({appToken:e,containerClassName:t})=>{const n=Qt();e||n.error("App Token missing");const r=v.useRef(null),{placeholderTranslation:i,genericErrorTranslation:a,tooManyRequestsTranslation:s,discussionFullErrorTranslation:o,infoBannerExplainationTranslation:u,infoBannerTitleTranslation:c}=wf(),{currentConversation:d,addEmptyMessageToCurrentConversation:f,addMessageToCurrentConversation:m,removeEmptyAssistantMessageFromCurrentConversation:h,resetConversation:b,setCurrentConversationId:A,updateCurrentConversationMessageById:w,archivedConversation:y,setArchivedConversationAsMain:_}=Pa(),[S,D]=v.useState("notLoading"),{defaultStartingStep:I,recentMessagesTranslation:N}=yc(),[G,se]=v.useState(null),[ee,k]=v.useState(I),[M,$]=v.useState(null),[U,z]=v.useState(!1),[Q,he]=v.useState(!1),{start:Ee,stop:Le,cancel:Re,audioLevel:g}=Hx(),{companySettings:j}=v.useContext(Pt),{appCurrentLang:J}=v.useContext(xc),[T,K]=v.useState(!0),ne=v.useRef(new Map);v.useEffect(()=>{if(typeof window>"u")return;const V=window.matchMedia("(pointer: coarse)"),L=window.matchMedia("(hover: none)"),P=()=>{K(!(V.matches||L.matches))};return P(),V.addEventListener?(V.addEventListener("change",P),L.addEventListener("change",P)):(V.addListener(P),L.addListener(P)),()=>{V.removeEventListener?(V.removeEventListener("change",P),L.removeEventListener("change",P)):(V.removeListener(P),L.removeListener(P))}},[]);const W=S!=="notLoading"||(d?.items?.length??0)>0,[ae,re]=v.useState(!0),oe=!!y&&(y.items?.length??0)>0,ie=()=>{_(),re(!1)},Se=v.useRef(S);v.useEffect(()=>{const V=Se.current,L=S;V!=="notLoading"&&L==="notLoading"&&d.discussionId!==null&&d?.items.length>0&&Px({conversation:d}),Se.current=L},[S,d?.items.length,d.discussionId]);const Y={...W?{maxHeight:"100vh"}:{height:"250px"}};v.useEffect(()=>{yx(d.items)>=j?.api?.settings?.maxUserMessagesPerDiscussion&&z(!0)},[d.items.length]);const{scrollToBottom:Ne,showScrollButton:$e,messagesContainerRef:lt,removeStickyNess:wt}=vx(d.items),nn=()=>{lr.abort("Cancelling stream on purpose."),n.log("Stream request aborted"),D("notLoading"),h()},He=async V=>{const L=V?.body?.getReader(),P=new TextDecoder;let q=!1;const Z=V.headers.get("discussionId"),fe=parseInt(Z,10);Number.isNaN(fe)||A(fe),await new ReadableStream({start(Ze){return et();async function et(){if(!V.ok){D("notLoading");let tt=a;V.status===409?(tt=o,z(!0)):V.status===429?tt=s:tt=a,m({userType:"assistant",content:tt,metaData:{isErrorMessage:!0},temporaryId:crypto.randomUUID()}),lr=new AbortController;return}return L?.read().then(tt=>{const{done:Ht,value:Ye}=tt,It=P.decode(Ye),ct=kt.transformNDJSONChunkIntoObjects(It);for(const ve of ct)if(kt.isObjectOutputstreamMessageStartDTO(ve))ne.current.set(ve.messageId,{rendered:"",markdownTag:"",isWritingTag:!1,lastStreamSourceUuid:null}),ve.role==="assistant"&&D("loadingDisplayedAnswer"),f({messageStreamId:ve.messageId,role:ve.role});else if(kt.isObjectOutputstreamMessageDeltaDTO(ve)){const{delta:Pe,streamSourceUuid:Jn}=ve;ne.current.get(ve.messageId)||(ne.current.set(ve.messageId,{rendered:"",markdownTag:"",isWritingTag:!1,lastStreamSourceUuid:null}),f({messageStreamId:ve.messageId,role:"assistant"}));const We=ne.current.get(ve.messageId);We.lastStreamSourceUuid&&We.lastStreamSourceUuid!==Jn&&(We.rendered+='<span style="display:block;height:1rem;"></span>'),We.lastStreamSourceUuid=Jn??null,xx(Pe)?(We.markdownTag+=Pe,We.rendered+=We.markdownTag,We.markdownTag="",We.isWritingTag=!1):We.isWritingTag||Tx(Pe)?(We.markdownTag+=Pe,We.isWritingTag=!0):We.rendered+=Pe,w({id:ve.messageId,newContent:We.rendered})}else if(kt.isObjectOutputstreamMessageEndDTO(ve)){const{isLastAnswer:Pe,shouldStopStream:Jn}=ve;(Pe||Jn)&&(q=!0),ne.current.delete(ve.messageId)}else if(kt.isObjectOutputstreamLoadingCurrentStepNumberDTO(ve)){const{content:Pe}=ve;Ze.enqueue(Pe),$(Pe)}else if(kt.isObjectOutputstreamLoadingCurrentStepNameDTO(ve)){const{content:Pe}=ve;Ze.enqueue(Pe),k(Pe)}else if(kt.isObjectOutputstreamLoadingNumberOfStepsDTO(ve)){const{content:Pe}=ve;Ze.enqueue(Pe),se(Pe)}else if(kt.isObjectOutputstreamErrorDTO(ve)){const{message:Pe}=ve;m({userType:"assistant",metaData:{isErrorMessage:!0},content:Pe,temporaryId:crypto.randomUUID()})}else n.warn(`Packet shape not handled - ${ve}`);if(Ht&&q){Ze.close(),D("notLoading"),k(I),$(null);return}return et()})}}}).pipeTo(new WritableStream)},rn=V=>{const P=`${zn.getApiUrl()}/ai/prompt/${e}`,q=lr.signal;if(V.mode==="text"){const fe={query:V.text,language:J.locale};d?.discussionId&&(fe.discussionId=d.discussionId);const qe=zn.getFetchConfig({httpVerb:"POST",body:fe,contentType:"application/json",options:{signal:q}});return{url:P,fetchConfig:qe}}const Z=new FormData;return Z.append("language",J.locale),d?.discussionId&&Z.append("discussionId",String(d.discussionId)),Z.append("audioInput",V.audioFile,V.audioFile.name),{url:P,fetchConfig:{method:"POST",body:Z,signal:q}}},vt=async V=>{D("loadingIntermediaryStates"),requestAnimationFrame(()=>Ne({smooth:!1,sticky:!1}));const{url:L,fetchConfig:P}=rn(V);fetch(L,P).then(async q=>{await He(q)}).catch(q=>{n.error(q),D("notLoading"),lr=new AbortController})},me=async()=>{he(!0),await Ee()},we=async()=>{const V=await Le();he(!1),V&&(n.log("Audio blob:",V.blob),n.log("Audio file:",V.file),vt({mode:"audio",audioFile:V.file}))},ye=()=>{Re(),he(!1)};return C.jsxs("div",{className:["chatbox-root relative p-2","flex flex-col min-h-0 overflow-visible","h-auto",t??"mx-auto"].join(" "),ref:r,style:Y,children:[C.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 messagesContainer",ref:lt,children:[d.items.map((V,L)=>C.jsx(s2,{content:V.content,userType:V.userType,metaData:V.metaData,context:{discussionId:d?.discussionId,messageIndex:L,appToken:e},seenRootEl:lt.current},V.temporaryId)),C.jsx(Sx,{currentStepName:ee,currentStepNumber:M,loadingStatus:S,numberOfSteps:G})]}),$e&&C.jsx(Ox,{label:N,onClick:()=>Ne({smooth:!0,sticky:!0})}),U&&C.jsx(kx,{resetDiscussion:V=>{z(!1),b(V)},companySettings:j}),oe&&ae&&C.jsx(Bx,{actionLabel:c,message:u,onClick:ie}),C.jsx("div",{className:"chatbox-input-wrapper flex-shrink-0",children:Q?C.jsx(jx,{isOpen:Q,onStop:we,onCancel:ye,audioLevel:g}):C.jsx(hx,{classNameTextarea:"",classNameContainer:"relative mt-2 border-slate-400 border-[1px] rounded-lg p-1",SubmitComponent:mx,isDisabled:S!=="notLoading"||U,shouldDisableIfInputIsEmpty:!0,"aria-label":"TextArea For Bot Conversation",onSubmit:V=>{if(re(!1),Ax(V)){const L=_x(V,d.discussionId,b,j);L&&m({userType:"user",content:L,temporaryId:crypto.randomUUID()}),wt(),Ne({smooth:!0,sticky:!1})}else m({userType:"user",content:V,temporaryId:crypto.randomUUID()}),wt(),Ne({smooth:!0,sticky:!1}),vt({mode:"text",text:V})},placeholder:i,autoFocus:T,isLoadingStream:S==="loadingDisplayedAnswer"||S==="loadingIntermediaryStates",LoadingComponent:wx,onPressLoadingButton:nn,onPressMicButton:()=>{me()},MicComponent:Fx,audioEnabled:j?.agent?.isAudioAllowed})})]})};function Ir(){return Ir=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ir.apply(this,arguments)}function Sc(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,a;for(a=0;a<r.length;a++)i=r[a],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function ia(e,t){return ia=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},ia(e,t)}function wc(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,ia(e,t)}var cr={exports:{}};/*
138
+ ${n??""}`,"data-testid":"mic-button",onClick:e,disabled:t,type:"button","aria-label":"Start voice input",children:C.jsx("span",{"data-state":"closed",children:C.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"24",height:"24","aria-hidden":"true",className:"text-white dark:text-black",children:[C.jsx("path",{d:"M12 14.5c1.66 0 3-1.34 3-3V6.5c0-1.66-1.34-3-3-3s-3 1.34-3 3v5c0 1.66 1.34 3 3 3Z",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinejoin:"round"}),C.jsx("path",{d:"M12 14.5V18",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),C.jsx("path",{d:"M8.5 18h7",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),C.jsx("path",{d:"M7 11.5c0 2.76 2.24 5 5 5s5-2.24 5-5",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"})]})})})});function Hx(){const[e,t]=v.useState("idle"),[n,r]=v.useState(null),[i,a]=v.useState(0),s=v.useRef(null),o=v.useRef(null),u=v.useRef([]),c=v.useRef(null),d=v.useRef(null),f=v.useRef(null),m=v.useRef(null),h=v.useCallback(()=>{m.current!==null&&(cancelAnimationFrame(m.current),m.current=null);try{f.current?.disconnect()}catch{}f.current=null;try{d.current?.disconnect()}catch{}d.current=null;const _=c.current;c.current=null,_&&_.close().catch(()=>{}),a(0)},[]),b=v.useCallback(_=>{try{const S=new AudioContext,D=S.createAnalyser(),I=S.createMediaStreamSource(_);D.fftSize=256,D.smoothingTimeConstant=.85,I.connect(D),c.current=S,d.current=D,f.current=I;const N=new Uint8Array(D.fftSize),G=()=>{const se=d.current;if(!se)return;se.getByteTimeDomainData(N);let ee=0;for(let $=0;$<N.length;$++){const U=(N[$]-128)/128;ee+=U*U}const k=Math.sqrt(ee/N.length),M=Math.min(1,k*6);a(M),m.current=requestAnimationFrame(G)};m.current=requestAnimationFrame(G)}catch{a(0)}},[]),A=v.useCallback(async()=>{r(null),h();try{const _=await navigator.mediaDevices.getUserMedia({audio:!0});o.current=_,b(_);const D=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"].find(N=>MediaRecorder.isTypeSupported(N))||"",I=new MediaRecorder(_,D?{mimeType:D}:void 0);s.current=I,u.current=[],I.ondataavailable=N=>{N.data&&N.data.size>0&&u.current.push(N.data)},I.onerror=()=>{t("error"),r("Recorder error.")},I.onstart=()=>t("recording"),I.onstop=()=>t("stopped"),I.start()}catch(_){h(),t("error"),r(_?.message??"Microphone permission denied.")}},[b,h]),w=v.useCallback(async()=>{const _=s.current,S=o.current;return!_||e!=="recording"?null:new Promise(D=>{_.onstop=()=>{h();const I=_.mimeType||"audio/webm",N=new Blob(u.current,{type:I}),G=I.includes("ogg")?"ogg":"webm",se=new File([N],`voice-message.${G}`,{type:I});S?.getTracks().forEach(ee=>ee.stop()),o.current=null,s.current=null,D({blob:N,file:se})},_.stop()})},[e,h]),y=v.useCallback(()=>{const _=s.current,S=o.current;try{_&&e==="recording"&&_.stop()}catch{}h(),S?.getTracks().forEach(D=>D.stop()),o.current=null,s.current=null,u.current=[],t("idle")},[e,h]);return v.useEffect(()=>()=>{h(),o.current?.getTracks().forEach(_=>_.stop())},[h]),{state:e,error:n,audioLevel:i,start:A,stop:w,cancel:y}}const Ux=()=>{const e=Jt(),t=e.formatMessage({defaultMessage:"Recording...",id:"recordingOverlay.recording"}),n=e.formatMessage({defaultMessage:"Cancel",id:"recordingOverlay.cancel"}),r=e.formatMessage({defaultMessage:"Tap the mic to stop",id:"recordingOverlay.explaination"});return{recordingTranslation:t,cancelTranslation:n,recordingExplainationTranslation:r}},jx=({isOpen:e,onStop:t,onCancel:n,audioLevel:r=0})=>{if(!e)return null;const{recordingTranslation:i}=Ux(),a=v.useMemo(()=>{const s=Math.max(0,Math.min(1,r));return Array.from({length:20},(o,u)=>{const c=Math.sin(u/19*Math.PI*2)*.5+.5,d=u%2===0?.9:.65,f=6+s*(14+c*18)*d;return Math.round(f)})},[r]);return C.jsx("div",{className:"relative mt-3 w-full rounded-lg border border-slate-400 bg-white p-1",role:"group","aria-label":"Recording voice message",children:C.jsxs("div",{className:"flex min-h-[48px] items-center gap-3 px-2",children:[C.jsxs("div",{className:"relative flex h-8 w-8 items-center justify-center",children:[C.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-100 motion-safe:animate-ping","aria-hidden":!0}),C.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-50","aria-hidden":!0}),C.jsx("span",{className:"absolute h-3.5 w-3.5 rounded-full bg-red-200","aria-hidden":!0}),C.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500","aria-hidden":!0})]}),C.jsxs("div",{className:"min-w-0 flex-1",children:[C.jsx("div",{className:"mb-0.5 text-[11px] font-medium leading-3 text-slate-600",children:i}),C.jsx("div",{className:"flex h-5 items-center gap-[3px] overflow-hidden","aria-hidden":"true",children:a.map((s,o)=>C.jsx("span",{className:"block w-1 rounded-full bg-slate-400 transition-[height,background-color] duration-75",style:{height:`${s}px`,backgroundColor:r>.08?"rgb(59 130 246)":"rgb(148 163 184)"}},o))})]}),C.jsx("button",{type:"button",onClick:n,className:"flex h-9 w-9 items-center justify-center rounded-full text-slate-500 hover:bg-slate-100 hover:text-slate-700","aria-label":"Cancel recording",children:C.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:C.jsx("path",{d:"M6 6l12 12M18 6L6 18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),C.jsx("button",{type:"button",onClick:t,className:"flex h-9 w-9 items-center justify-center rounded-full bg-violet-600 text-white hover:bg-violet-700","aria-label":"Validate recording",children:C.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:C.jsx("path",{d:"M5 13l4 4L19 7",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})};let lr=new AbortController;const Cc=({appToken:e,containerClassName:t})=>{const n=Qt();e||n.error("App Token missing");const r=v.useRef(null),{placeholderTranslation:i,genericErrorTranslation:a,tooManyRequestsTranslation:s,discussionFullErrorTranslation:o,infoBannerExplainationTranslation:u,infoBannerTitleTranslation:c}=wf(),{currentConversation:d,addEmptyMessageToCurrentConversation:f,addMessageToCurrentConversation:m,removeEmptyAssistantMessageFromCurrentConversation:h,resetConversation:b,setCurrentConversationId:A,updateCurrentConversationMessageById:w,archivedConversation:y,setArchivedConversationAsMain:_}=Pa(),[S,D]=v.useState("notLoading"),{defaultStartingStep:I,recentMessagesTranslation:N}=yc(),[G,se]=v.useState(null),[ee,k]=v.useState(I),[M,$]=v.useState(null),[U,z]=v.useState(!1),[Q,he]=v.useState(!1),{start:Ee,stop:Le,cancel:Re,audioLevel:g}=Hx(),{companySettings:j}=v.useContext(Pt),{appCurrentLang:J}=v.useContext(xc),[T,K]=v.useState(()=>{if(typeof window>"u")return!0;const V=window.matchMedia("(pointer: coarse)"),L=window.matchMedia("(hover: none)");return!(V.matches||L.matches)}),ne=v.useRef(new Map);v.useEffect(()=>{if(typeof window>"u")return;const V=window.matchMedia("(pointer: coarse)"),L=window.matchMedia("(hover: none)"),P=()=>{K(!(V.matches||L.matches))};return P(),V.addEventListener?(V.addEventListener("change",P),L.addEventListener("change",P)):(V.addListener(P),L.addListener(P)),()=>{V.removeEventListener?(V.removeEventListener("change",P),L.removeEventListener("change",P)):(V.removeListener(P),L.removeListener(P))}},[]);const W=S!=="notLoading"||(d?.items?.length??0)>0,[ae,re]=v.useState(!0),oe=!!y&&(y.items?.length??0)>0,ie=()=>{_(),re(!1)},Se=v.useRef(S);v.useEffect(()=>{const V=Se.current,L=S;V!=="notLoading"&&L==="notLoading"&&d.discussionId!==null&&d?.items.length>0&&Px({conversation:d}),Se.current=L},[S,d?.items.length,d.discussionId]);const Y={...W?{maxHeight:"100vh"}:{height:"250px"}};v.useEffect(()=>{yx(d.items)>=j?.api?.settings?.maxUserMessagesPerDiscussion&&z(!0)},[d.items.length]);const{scrollToBottom:Ne,showScrollButton:$e,messagesContainerRef:lt,removeStickyNess:wt}=vx(d.items),nn=()=>{lr.abort("Cancelling stream on purpose."),n.log("Stream request aborted"),D("notLoading"),h()},He=async V=>{const L=V?.body?.getReader(),P=new TextDecoder;let q=!1;const Z=V.headers.get("discussionId"),fe=parseInt(Z,10);Number.isNaN(fe)||A(fe),await new ReadableStream({start(Ze){return et();async function et(){if(!V.ok){D("notLoading");let tt=a;V.status===409?(tt=o,z(!0)):V.status===429?tt=s:tt=a,m({userType:"assistant",content:tt,metaData:{isErrorMessage:!0},temporaryId:crypto.randomUUID()}),lr=new AbortController;return}return L?.read().then(tt=>{const{done:Ht,value:Ye}=tt,It=P.decode(Ye),ct=kt.transformNDJSONChunkIntoObjects(It);for(const ve of ct)if(kt.isObjectOutputstreamMessageStartDTO(ve))ne.current.set(ve.messageId,{rendered:"",markdownTag:"",isWritingTag:!1,lastStreamSourceUuid:null}),ve.role==="assistant"&&D("loadingDisplayedAnswer"),f({messageStreamId:ve.messageId,role:ve.role});else if(kt.isObjectOutputstreamMessageDeltaDTO(ve)){const{delta:Pe,streamSourceUuid:Jn}=ve;ne.current.get(ve.messageId)||(ne.current.set(ve.messageId,{rendered:"",markdownTag:"",isWritingTag:!1,lastStreamSourceUuid:null}),f({messageStreamId:ve.messageId,role:"assistant"}));const We=ne.current.get(ve.messageId);We.lastStreamSourceUuid&&We.lastStreamSourceUuid!==Jn&&(We.rendered+='<span style="display:block;height:1rem;"></span>'),We.lastStreamSourceUuid=Jn??null,xx(Pe)?(We.markdownTag+=Pe,We.rendered+=We.markdownTag,We.markdownTag="",We.isWritingTag=!1):We.isWritingTag||Tx(Pe)?(We.markdownTag+=Pe,We.isWritingTag=!0):We.rendered+=Pe,w({id:ve.messageId,newContent:We.rendered})}else if(kt.isObjectOutputstreamMessageEndDTO(ve)){const{isLastAnswer:Pe,shouldStopStream:Jn}=ve;(Pe||Jn)&&(q=!0),ne.current.delete(ve.messageId)}else if(kt.isObjectOutputstreamLoadingCurrentStepNumberDTO(ve)){const{content:Pe}=ve;Ze.enqueue(Pe),$(Pe)}else if(kt.isObjectOutputstreamLoadingCurrentStepNameDTO(ve)){const{content:Pe}=ve;Ze.enqueue(Pe),k(Pe)}else if(kt.isObjectOutputstreamLoadingNumberOfStepsDTO(ve)){const{content:Pe}=ve;Ze.enqueue(Pe),se(Pe)}else if(kt.isObjectOutputstreamErrorDTO(ve)){const{message:Pe}=ve;m({userType:"assistant",metaData:{isErrorMessage:!0},content:Pe,temporaryId:crypto.randomUUID()})}else n.warn(`Packet shape not handled - ${ve}`);if(Ht&&q){Ze.close(),D("notLoading"),k(I),$(null);return}return et()})}}}).pipeTo(new WritableStream)},rn=V=>{const P=`${zn.getApiUrl()}/ai/prompt/${e}`,q=lr.signal;if(V.mode==="text"){const fe={query:V.text,language:J.locale};d?.discussionId&&(fe.discussionId=d.discussionId);const qe=zn.getFetchConfig({httpVerb:"POST",body:fe,contentType:"application/json",options:{signal:q}});return{url:P,fetchConfig:qe}}const Z=new FormData;return Z.append("language",J.locale),d?.discussionId&&Z.append("discussionId",String(d.discussionId)),Z.append("audioInput",V.audioFile,V.audioFile.name),{url:P,fetchConfig:{method:"POST",body:Z,signal:q}}},vt=async V=>{D("loadingIntermediaryStates"),requestAnimationFrame(()=>Ne({smooth:!1,sticky:!1}));const{url:L,fetchConfig:P}=rn(V);fetch(L,P).then(async q=>{await He(q)}).catch(q=>{n.error(q),D("notLoading"),lr=new AbortController})},me=async()=>{he(!0),await Ee()},we=async()=>{const V=await Le();he(!1),V&&(n.log("Audio blob:",V.blob),n.log("Audio file:",V.file),vt({mode:"audio",audioFile:V.file}))},ye=()=>{Re(),he(!1)};return C.jsxs("div",{className:["chatbox-root relative p-2","flex flex-col min-h-0 overflow-visible","h-auto",t??"mx-auto"].join(" "),ref:r,style:Y,children:[C.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 messagesContainer",ref:lt,children:[d.items.map((V,L)=>C.jsx(s2,{content:V.content,userType:V.userType,metaData:V.metaData,context:{discussionId:d?.discussionId,messageIndex:L,appToken:e},seenRootEl:lt.current},V.temporaryId)),C.jsx(Sx,{currentStepName:ee,currentStepNumber:M,loadingStatus:S,numberOfSteps:G})]}),$e&&C.jsx(Ox,{label:N,onClick:()=>Ne({smooth:!0,sticky:!0})}),U&&C.jsx(kx,{resetDiscussion:V=>{z(!1),b(V)},companySettings:j}),oe&&ae&&C.jsx(Bx,{actionLabel:c,message:u,onClick:ie}),C.jsx("div",{className:"chatbox-input-wrapper flex-shrink-0",children:Q?C.jsx(jx,{isOpen:Q,onStop:we,onCancel:ye,audioLevel:g}):C.jsx(hx,{classNameTextarea:"",classNameContainer:"relative mt-2 border-slate-400 border-[1px] rounded-lg p-1",SubmitComponent:mx,isDisabled:S!=="notLoading"||U,shouldDisableIfInputIsEmpty:!0,"aria-label":"TextArea For Bot Conversation",onSubmit:V=>{if(re(!1),Ax(V)){const L=_x(V,d.discussionId,b,j);L&&m({userType:"user",content:L,temporaryId:crypto.randomUUID()}),wt(),Ne({smooth:!0,sticky:!1})}else m({userType:"user",content:V,temporaryId:crypto.randomUUID()}),wt(),Ne({smooth:!0,sticky:!1}),vt({mode:"text",text:V})},placeholder:i,autoFocus:T,isLoadingStream:S==="loadingDisplayedAnswer"||S==="loadingIntermediaryStates",LoadingComponent:wx,onPressLoadingButton:nn,onPressMicButton:()=>{me()},MicComponent:Fx,audioEnabled:j?.agent?.isAudioAllowed})})]})};function Ir(){return Ir=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ir.apply(this,arguments)}function Sc(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,a;for(a=0;a<r.length;a++)i=r[a],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function ia(e,t){return ia=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},ia(e,t)}function wc(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,ia(e,t)}var cr={exports:{}};/*
139
139
  object-assign
140
140
  (c) Sindre Sorhus
141
141
  @license MIT