orbitchat 3.11.8 → 3.11.9
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/assets/{ChartRenderer-4LQgc_hT.js → ChartRenderer-wxEbPd5g.js} +1 -1
- package/dist/assets/{MermaidRenderer-Cym5GXD0.js → MermaidRenderer-BMEgBeqY.js} +4 -4
- package/dist/assets/{MusicRenderer-I0qFf6Hh.js → MusicRenderer-BMwa1p8w.js} +1 -1
- package/dist/assets/{SVGRenderer-DfC-MRya.js → SVGRenderer-BtiY9l8o.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-CrmTR3bn.js → architectureDiagram-3BPJPVTR-8fDAeSty.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-BTRIXFzA.js → blockDiagram-GPEHLZMM-DjjIkU_V.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-Cr3_VrMd.js → c4Diagram-AAUBKEIU-DPhpjeGs.js} +1 -1
- package/dist/assets/channel-BjJ0j4ky.js +1 -0
- package/dist/assets/{chunk-2J33WTMH-B-71iuuI.js → chunk-2J33WTMH-B9jxVvJD.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-NuqWDbXB.js → chunk-4BX2VUAB-Be2LTDDZ.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-BxsYl4IZ.js → chunk-55IACEB6-CbX0vAQ4.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-C-tI-CGH.js → chunk-727SXJPM-R7lhcdh3.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-D8MYnjVe.js → chunk-AQP2D5EJ-Dzfn3Tu4.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-DrWL2fBK.js → chunk-FMBD7UC4-D4upRD6i.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-Cds3T1WR.js → chunk-ND2GUHAM-BZHjki36.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-ClW_E7Ux.js → chunk-QZHKN3VN-CBtxaJPI.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-CX5VHnPT.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-CX5VHnPT.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-deuY6gCx.js → cose-bilkent-S5V4N54A-CWY9mepe.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-cpSofOiF.js → dagre-BM42HDAG-3sAW_Zso.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-BmD6FAXX.js → diagram-2AECGRRQ-CIvaugjd.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-Dhs-B2QO.js → diagram-5GNKFQAL-DiUrs1k7.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-iY9EY3kU.js → diagram-KO2AKTUF-CvybWAmW.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-8BnNu_Fu.js → diagram-LMA3HP47-BMpzQjf7.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-sgQW4v1A.js → diagram-OG6HWLK6-DxdwVCcp.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-B3hVZc6U.js → erDiagram-TEJ5UH35-BsckieKA.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-B-C_VX5K.js → flowDiagram-I6XJVG4X-QkrIRaVh.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-DechK90j.js → ganttDiagram-6RSMTGT7-BmJWXjKf.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-JXFndHoC.js → gitGraphDiagram-PVQCEYII-C5VXzACD.js} +1 -1
- package/dist/assets/index-DIvm40qq.js +376 -0
- package/dist/assets/index-Do5o2YQv.css +1 -0
- package/dist/assets/{infoDiagram-5YYISTIA-sjx1XvhT.js → infoDiagram-5YYISTIA-3ZefI0By.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-CU3HIun9.js → ishikawaDiagram-YF4QCWOH-CkPahGMo.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-BN6kPPlx.js → journeyDiagram-JHISSGLW-Bh3SbgzJ.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-CAaNWqmT.js → kanban-definition-UN3LZRKU-PW1rLFti.js} +1 -1
- package/dist/assets/{mindmap-definition-RKZ34NQL-B0Q3fxJb.js → mindmap-definition-RKZ34NQL-C3qUsbvW.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-Cd4TWfB8.js → pieDiagram-4H26LBE5-NhwALBxT.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-K1_COFeV.js → quadrantDiagram-W4KKPZXB-DCRqhaIE.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-CmJBeGd_.js → requirementDiagram-4Y6WPE33-BMWJP_JX.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-BvAz6363.js → sankeyDiagram-5OEKKPKP-iAz9Hee0.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-CxmQvvr_.js → sequenceDiagram-3UESZ5HK-HMqFN3v8.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-Y7FIY2F3.js → stateDiagram-AJRCARHV-BPMWDBcG.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-C7Jb-mQ1.js → stateDiagram-v2-BHNVJYJU-D7-ipe-H.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-BsvMErZ_.js → timeline-definition-PNZ67QCA-qHVd0JP4.js} +1 -1
- package/dist/assets/{vennDiagram-CIIHVFJN-BtyekXFx.js → vennDiagram-CIIHVFJN-X2fo2aab.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-pnKWxdyd.js → wardleyDiagram-YWT4CUSO-CrSkg9bp.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-ra8v6JXC.js → xychartDiagram-2RQKCTM6-B7MIKLLH.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/channel-CPqxcwJ9.js +0 -1
- package/dist/assets/classDiagram-4FO5ZUOK-DuHHl1Md.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-DuHHl1Md.js +0 -1
- package/dist/assets/index-Bj4GQU9q.js +0 -376
- package/dist/assets/index-GDO2KFQ0.css +0 -1
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-BMEgBeqY.js","assets/vendor-react-BbEy7z12.js","assets/vendor-syntax-INF7-xC_.js","assets/purify.es-D6gMnemd.js","assets/isPrototype-DezZrpQP.js","assets/graphExportUtils-DrqBjeAI.js","assets/SVGRenderer-BtiY9l8o.js","assets/locales-CcBtm6Ky.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-wxEbPd5g.js","assets/band-CquvqAHh.js","assets/init-Dmth1JHB.js","assets/ordinal-DILIJJjt.js","assets/linear-BGneeY6s.js","assets/defaultLocale-DX6XiGOO.js","assets/time-DJ0lCX4i.js","assets/MusicRenderer-BMwa1p8w.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Po=Object.defineProperty;var Do=(t,e,r)=>e in t?Po(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Qe=(t,e,r)=>Do(t,typeof e!="symbol"?e+"":e,r);import{r as h,j as i,a as Uo,R as pt,b as As,d as Oo}from"./vendor-react-BbEy7z12.js";import{z as zo,p as Bo,j as Ho,f as Vo,e as qo,a as Wo,d as Ko}from"./locales-CcBtm6Ky.js";import{M as Go,r as aa,a as Xo,b as Yo}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Nt,h as Qo,v as Zo,a as Jo}from"./vendor-syntax-INF7-xC_.js";import{u as An,a as Nn,b as el,P as tl,M as rl,A as sl}from"./vendor-auth-aD_bwYde.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(s){if(s.ep)return;s.ep=!0;const a=r(s);fetch(s.href,a)}})();const pi=h.createContext(void 0);function ia({children:t}){const[e,r]=h.useState(()=>{const o=localStorage.getItem("chat-theme");if(o){const l=JSON.parse(o);return{mode:l.mode||"dark",highContrast:!!l.highContrast}}return{mode:"dark",highContrast:!1}}),[n,s]=h.useState(!1);h.useEffect(()=>{const o=()=>{let l=!1;e.mode==="dark"?l=!0:e.mode==="light"?l=!1:l=window.matchMedia("(prefers-color-scheme: dark)").matches,s(l);const c=document.documentElement;l?c.classList.add("dark"):c.classList.remove("dark"),e.highContrast?c.classList.add("high-contrast"):c.classList.remove("high-contrast"),c.classList.remove("text-sm","text-lg"),c.classList.add("text-base")};if(o(),e.mode==="system"){const l=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{o()};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)}},[e]),h.useEffect(()=>{localStorage.setItem("chat-theme",JSON.stringify(e))},[e]);const a=o=>{r(l=>({...l,...o}))};return i.jsx(pi.Provider,{value:{theme:e,updateTheme:a,isDark:n},children:t})}function tr(){const t=h.useContext(pi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const mi=h.createContext(void 0),Gs={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function nl({children:t}){const[e,r]=h.useState(()=>{const s=localStorage.getItem("chat-settings");if(s)try{const a=JSON.parse(s);return{...Gs,...a,voiceEnabled:!1}}catch{return Gs}return Gs});h.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const n=s=>{r(a=>({...a,...s}))};return i.jsx(mi.Provider,{value:{settings:e,updateSettings:n},children:t})}function Ns(){const t=h.useContext(mi);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const pe=t=>typeof t=="string",Ir=()=>{let t,e;const r=new Promise((n,s)=>{t=n,e=s});return r.resolve=t,r.reject=e,r},oa=t=>t==null?"":String(t),al=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},il=/###/g,la=t=>t&&t.includes("###")?t.replace(il,"."):t,ca=t=>!t||pe(t),Tr=(t,e,r)=>{const n=pe(e)?e.split("."):e;let s=0;for(;s<n.length-1;){if(ca(t))return{};const a=la(n[s]);!t[a]&&r&&(t[a]=new r),Object.prototype.hasOwnProperty.call(t,a)?t=t[a]:t={},++s}return ca(t)?{}:{obj:t,k:la(n[s])}},da=(t,e,r)=>{const{obj:n,k:s}=Tr(t,e,Object);if(n!==void 0||e.length===1){n[s]=r;return}let a=e[e.length-1],o=e.slice(0,e.length-1),l=Tr(t,o,Object);for(;l.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),l=Tr(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${a}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${a}`]=r},ol=(t,e,r,n)=>{const{obj:s,k:a}=Tr(t,e,Object);s[a]=s[a]||[],s[a].push(r)},ms=(t,e)=>{const{obj:r,k:n}=Tr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},ll=(t,e,r)=>{const n=ms(t,r);return n!==void 0?n:ms(e,r)},gi=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,n)?pe(t[n])||t[n]instanceof String||pe(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):gi(t[n],e[n],r):t[n]=e[n]);return t},Mt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),cl={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},dl=t=>pe(t)?t.replace(/[&<>"'\/]/g,e=>cl[e]):t;class ul{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const fl=[" ",",","?","!",";"],hl=new ul(20),pl=(t,e,r)=>{e=e||"",r=r||"";const n=fl.filter(o=>!e.includes(o)&&!r.includes(o));if(n.length===0)return!0;const s=hl.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`);let a=!s.test(t);if(!a){const o=t.indexOf(r);o>0&&!s.test(t.substring(0,o))&&(a=!0)}return a},cn=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let s=t;for(let a=0;a<n.length;){if(!s||typeof s!="object")return;let o,l="";for(let c=a;c<n.length;++c)if(c!==a&&(l+=r),l+=n[c],o=s[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<n.length-1)continue;a+=c-a+1;break}s=o}return s},Rr=t=>t==null?void 0:t.replace(/_/g,"-"),ml={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var r,n;(n=(r=console==null?void 0:console[t])==null?void 0:r.apply)==null||n.call(r,console,e)}};class gs{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||ml,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,s){return s&&!this.debug?null:(e=e.map(a=>pe(a)?a.replace(/[\r\n\x00-\x1F\x7F]/g," "):a),pe(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new gs(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new gs(this.logger,e)}}var It=new gs;class Is{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const s=this.observers[n].get(r)||0;this.observers[n].set(r,s+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}once(e,r){const n=(...s)=>{r(...s),this.off(e,n)};return this.on(e,n),this}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([s,a])=>{for(let o=0;o<a;o++)s(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,a])=>{for(let o=0;o<a;o++)s(e,...r)})}}class ua extends Is{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,s={}){var d,u;const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,o=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.includes(".")?l=e.split("."):(l=[e,r],n&&(Array.isArray(n)?l.push(...n):pe(n)&&a?l.push(...n.split(a)):l.push(n)));const c=ms(this.data,l);return!c&&!r&&!n&&e.includes(".")&&(e=l[0],r=l[1],n=l.slice(2).join(".")),c||!o||!pe(n)?c:cn((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[r],n,a)}addResource(e,r,n,s,a={silent:!1}){const o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator;let l=[e,r];n&&(l=l.concat(o?n.split(o):n)),e.includes(".")&&(l=e.split("."),s=r,r=l[1]),this.addNamespaces(r),da(this.data,l,s),a.silent||this.emit("added",e,r,n,s)}addResources(e,r,n,s={silent:!1}){for(const a in n)(pe(n[a])||Array.isArray(n[a]))&&this.addResource(e,r,a,n[a],{silent:!0});s.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,s,a,o={silent:!1,skipCopy:!1}){let l=[e,r];e.includes(".")&&(l=e.split("."),s=n,n=r,r=l[1]),this.addNamespaces(r);let c=ms(this.data,l)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),s?gi(c,n,a):c={...c,...n},da(this.data,l,c),o.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(s=>r[s]&&Object.keys(r[s]).length>0)}toJSON(){return this.data}}var xi={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,s){return t.forEach(a=>{var o;e=((o=this.processors[a])==null?void 0:o.process(e,r,n,s))??e}),e}};const bi=Symbol("i18next/PATH_KEY");function gl(){const t=[],e=Object.create(null);let r;return e.get=(n,s)=>{var a;return(a=r==null?void 0:r.revoke)==null||a.call(r),s===bi?t:(t.push(s),r=Proxy.revocable(n,e),r.proxy)},Proxy.revocable(Object.create(null),e).proxy}function dr(t,e){const{[bi]:r}=t(gl()),n=(e==null?void 0:e.keySeparator)??".",s=(e==null?void 0:e.nsSeparator)??":",a=(e==null?void 0:e.enableSelector)==="strict";if(r.length>1&&s){const o=e==null?void 0:e.ns,l=a?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(l&&(a?l:l.length>1?l.slice(1):[]).includes(r[0]))return`${r[0]}${s}${r.slice(1).join(n)}`}return r.join(n)}const Xs=t=>!pe(t)&&typeof t!="boolean"&&typeof t!="number";class xs extends Is{constructor(e,r={}){super(),al(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=It.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const s=this.resolve(e,n);if((s==null?void 0:s.res)===void 0)return!1;const a=Xs(s.res);return!(n.returnObjects===!1&&a)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const s=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let a=r.ns||this.options.defaultNS||[];const o=n&&e.includes(n),l=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!pl(e,n,s);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:pe(a)?[a]:a};const d=e.split(n);(n!==s||n===s&&this.options.ns.includes(d[0]))&&(a=d.shift()),e=d.join(s)}return{key:e,namespaces:pe(a)?[a]:a}}translate(e,r,n){let s=typeof r=="object"?{...r}:r;if(typeof s!="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),typeof s=="object"&&(s={...s}),s||(s={}),e==null)return"";typeof e=="function"&&(e=dr(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]),e=e.map(M=>typeof M=="function"?dr(M,{...this.options,...s}):String(M));const a=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],s),d=c[c.length-1];let u=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=s.lng||this.language,p=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((f==null?void 0:f.toLowerCase())==="cimode")return p?a?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(s)}:`${d}${u}${l}`:a?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(s)}:l;const g=this.resolve(e,s);let m=g==null?void 0:g.res;const x=(g==null?void 0:g.usedKey)||l,y=(g==null?void 0:g.exactUsedKey)||l,v=["[object Number]","[object Function]","[object RegExp]"],A=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,N=!this.i18nFormat||this.i18nFormat.handleAsObject,C=s.count!==void 0&&!pe(s.count),S=xs.hasDefaultValue(s),E=C?this.pluralResolver.getSuffix(f,s.count,s):"",_=s.ordinal&&C?this.pluralResolver.getSuffix(f,s.count,{ordinal:!1}):"",b=C&&!s.ordinal&&s.count===0,T=b&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${E}`]||s[`defaultValue${_}`]||s.defaultValue;let k=m;N&&!m&&S&&(k=T);const I=Xs(k),P=Object.prototype.toString.apply(k);if(N&&k&&I&&!v.includes(P)&&!(pe(A)&&Array.isArray(k))){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const M=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,k,{...s,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return a?(g.res=M,g.usedParams=this.getUsedParamsDetails(s),g):M}if(o){const M=Array.isArray(k),B=M?[]:{},j=M?y:x;for(const L in k)if(Object.prototype.hasOwnProperty.call(k,L)){const O=`${j}${o}${L}`;S&&!m?B[L]=this.translate(O,{...s,defaultValue:Xs(T)?T[L]:void 0,joinArrays:!1,ns:c}):B[L]=this.translate(O,{...s,joinArrays:!1,ns:c}),B[L]===O&&(B[L]=k[L])}m=B}}else if(N&&pe(A)&&Array.isArray(m))m=m.join(A),m&&(m=this.extendTranslation(m,e,s,n));else{let M=!1,B=!1;!this.isValidLookup(m)&&S&&(M=!0,m=T),this.isValidLookup(m)||(B=!0,m=l);const L=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&B?void 0:m,O=S&&T!==m&&this.options.updateMissing;if(B||M||O){if(this.logger.log(O?"updateKey":"missingKey",f,d,C&&!O?`${l}${this.pluralResolver.getSuffix(f,s.count,s)}`:l,O?T:m),o){const q=this.resolve(l,{...s,keySeparator:!1});q&&q.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let F=[];const X=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&X&&X[0])for(let q=0;q<X.length;q++)F.push(X[q]);else this.options.saveMissingTo==="all"?F=this.languageUtils.toResolveHierarchy(s.lng||this.language):F.push(s.lng||this.language);const G=(q,Q,he)=>{var ee;const z=S&&he!==m?he:L;this.options.missingKeyHandler?this.options.missingKeyHandler(q,d,Q,z,O,s):(ee=this.backendConnector)!=null&&ee.saveMissing&&this.backendConnector.saveMissing(q,d,Q,z,O,s),this.emit("missingKey",q,d,Q,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?F.forEach(q=>{const Q=this.pluralResolver.getSuffixes(q,s);b&&s[`defaultValue${this.options.pluralSeparator}zero`]&&!Q.includes(`${this.options.pluralSeparator}zero`)&&Q.push(`${this.options.pluralSeparator}zero`),Q.forEach(he=>{G([q],l+he,s[`defaultValue${he}`]||T)})}):G(F,l,T))}m=this.extendTranslation(m,e,s,g,n),B&&m===l&&this.options.appendNamespaceToMissingKey&&(m=`${d}${u}${l}`),(B||M)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,M?m:void 0,s))}return a?(g.res=m,g.usedParams=this.getUsedParamsDetails(s),g):m}extendTranslation(e,r,n,s,a){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=pe(e)&&(((d=n==null?void 0:n.interpolation)==null?void 0:d.skipOnVariables)!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const g=e.match(this.interpolator.nestingRegexp);f=g&&g.length}let p=n.replace&&!pe(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,n.lng||this.language||s.usedLng,n),u){const g=e.match(this.interpolator.nestingRegexp),m=g&&g.length;f<m&&(n.nest=!1)}!n.lng&&s&&s.res&&(n.lng=this.language||s.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...g)=>(a==null?void 0:a[0])===g[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${g[0]} in key: ${r[0]}`),null):this.translate(...g,r),n)),n.interpolation&&this.interpolator.reset()}const o=n.postProcess||this.options.postProcess,l=pe(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&n.applyPostProcessor!==!1&&(e=xi.handle(l,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,s,a,o,l;return pe(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?dr(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const d=this.extractFromKey(c,r),u=d.key;s=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=r.count!==void 0&&!pe(r.count),g=p&&!r.ordinal&&r.count===0,m=r.context!==void 0&&(pe(r.context)||typeof r.context=="number")&&r.context!=="",x=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);f.forEach(y=>{var v,A;this.isValidLookup(n)||(l=y,!this.checkedLoadedFor[`${x[0]}-${y}`]&&((v=this.utils)!=null&&v.hasLoadedNamespace)&&!((A=this.utils)!=null&&A.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${y}`]=!0,this.logger.warn(`key "${s}" for languages "${x.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),x.forEach(N=>{var E;if(this.isValidLookup(n))return;o=N;const C=[u];if((E=this.i18nFormat)!=null&&E.addLookupKeys)this.i18nFormat.addLookupKeys(C,u,N,y,r);else{let _;p&&(_=this.pluralResolver.getSuffix(N,r.count,r));const b=`${this.options.pluralSeparator}zero`,T=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(r.ordinal&&_.startsWith(T)&&C.push(u+_.replace(T,this.options.pluralSeparator)),C.push(u+_),g&&C.push(u+b)),m){const k=`${u}${this.options.contextSeparator||"_"}${r.context}`;C.push(k),p&&(r.ordinal&&_.startsWith(T)&&C.push(k+_.replace(T,this.options.pluralSeparator)),C.push(k+_),g&&C.push(k+b))}}let S;for(;S=C.pop();)this.isValidLookup(n)||(a=S,n=this.getResource(N,y,S,r))}))})}),{res:n,usedKey:s,exactUsedKey:a,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,s={}){var a;return(a=this.i18nFormat)!=null&&a.getResource?this.i18nFormat.getResource(e,r,n,s):this.resourceStore.getResource(e,r,n,s)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!pe(e.replace);let s=n?e.replace:e;if(n&&typeof e.count<"u"&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!n){s={...s};for(const a of r)delete s[a]}return s}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith(r)&&e[n]!==void 0)return!0;return!1}}class fa{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=It.create("languageUtils")}getScriptPartFromCode(e){if(e=Rr(e),!e||!e.includes("-"))return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=Rr(e),!e||!e.includes("-"))return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(pe(e)&&e.includes("-")){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const s=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(s))&&(r=s)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const s=this.getScriptPartFromCode(n);if(this.isSupportedCode(s))return r=s;const a=this.getLanguagePartFromCode(n);if(this.isSupportedCode(a))return r=a;r=this.options.supportedLngs.find(o=>o===a?!0:!o.includes("-")&&!a.includes("-")?!1:!!(o.includes("-")&&!a.includes("-")&&o.slice(0,o.indexOf("-"))===a||o.startsWith(a)&&a.length>1))}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),pe(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),s=[],a=o=>{o&&(this.isSupportedCode(o)?s.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return pe(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&a(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&a(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&a(this.getLanguagePartFromCode(e))):pe(e)&&a(this.formatLanguageCode(e)),n.forEach(o=>{s.includes(o)||a(this.formatLanguageCode(o))}),s}}const ha={zero:0,one:1,two:2,few:3,many:4,other:5},pa={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class xl{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=It.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=Rr(e==="dev"?"en":e),s=r.ordinal?"ordinal":"cardinal",a=JSON.stringify({cleanedCode:n,type:s});if(a in this.pluralRulesCache)return this.pluralRulesCache[a];let o;try{o=new Intl.PluralRules(n,{type:s})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),pa;if(!e.match(/-|_/))return pa;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,r)}return this.pluralRulesCache[a]=o,o}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),(n==null?void 0:n.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(s=>`${r}${s}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((s,a)=>ha[s]-ha[a]).map(s=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s}`):[]}getSuffix(e,r,n={}){const s=this.getRule(e,n);return s?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const ma=(t,e,r,n=".",s=!0)=>{let a=ll(t,e,r);return!a&&s&&pe(r)&&(a=cn(t,r,n),a===void 0&&(a=cn(e,r,n))),a},Ys=t=>t.replace(/\$/g,"$$$$");class ga{constructor(e={}){var r;this.logger=It.create("interpolator"),this.options=e,this.format=((r=e==null?void 0:e.interpolation)==null?void 0:r.format)||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:s,prefix:a,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:g,nestingSuffix:m,nestingSuffixEscaped:x,nestingOptionsSeparator:y,maxReplaces:v,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:dl,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=a?Mt(a):o||"{{",this.suffix=l?Mt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?Mt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Mt(u):"",this.nestingPrefix=p?Mt(p):g||Mt("$t("),this.nestingSuffix=m?Mt(m):x||Mt(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=v||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>(r==null?void 0:r.source)===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,s){var g;let a,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=m=>{if(!m.includes(this.formatSeparator)){const A=ma(r,c,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(A,void 0,n,{...s,...r,interpolationkey:m}):A}const x=m.split(this.formatSeparator),y=x.shift().trim(),v=x.join(this.formatSeparator).trim();return this.format(ma(r,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),v,n,{...s,...r,interpolationkey:y})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=(s==null?void 0:s.missingInterpolationHandler)||this.options.missingInterpolationHandler,f=((g=s==null?void 0:s.interpolation)==null?void 0:g.skipOnVariables)!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>Ys(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?Ys(this.escape(m)):Ys(m)}].forEach(m=>{for(l=0;a=m.regex.exec(e);){const x=a[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const v=u(e,a,s);o=pe(v)?v:""}else if(s&&Object.prototype.hasOwnProperty.call(s,x))o="";else if(f){o=a[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!pe(o)&&!this.useRawValueToEscape&&(o=oa(o));const y=m.safeValue(o);if(e=e.replace(a[0],y),f?(m.regex.lastIndex+=o.length,m.regex.lastIndex-=a[0].length):m.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,r,n={}){let s,a,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${Mt(u)}[ ]*{`));let p=`{${f[1]}`;c=f[0],p=this.interpolate(p,o);const g=p.match(/'/g),m=p.match(/"/g);(((g==null?void 0:g.length)??0)%2===0&&!m||((m==null?void 0:m.length)??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{o=JSON.parse(p),d&&(o={...d,...o})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,x),`${c}${u}${p}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;s=this.nestingRegexp.exec(e);){let c=[];o={...n},o=o.replace&&!pe(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(d!==-1&&(c=s[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),s[1]=s[1].slice(0,d)),a=r(l.call(this,s[1].trim(),o),o),a&&s[0]===e&&!pe(a))return a;pe(a)||(a=oa(a)),a||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),a=""),c.length&&(a=c.reduce((u,f)=>this.format(u,f,n.lng,{...n,interpolationkey:s[1].trim()}),a.trim())),e=e.replace(s[0],a),this.regexp.lastIndex=0}return e}}const bl=t=>{let e=t.toLowerCase().trim();const r={};if(t.includes("(")){const n=t.split("(");e=n[0].toLowerCase().trim();const s=n[1].slice(0,-1);e==="currency"&&!s.includes(":")?r.currency||(r.currency=s.trim()):e==="relativetime"&&!s.includes(":")?r.range||(r.range=s.trim()):s.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();r[u]||(r[u]=d),d==="false"&&(r[u]=!1),d==="true"&&(r[u]=!0),isNaN(d)||(r[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:r}},xa=t=>{const e={};return(r,n,s)=>{let a=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(a={...a,[s.interpolationkey]:void 0});const o=n+JSON.stringify(a);let l=e[o];return l||(l=t(Rr(n),s),e[o]=l),l(r)}},yl=t=>(e,r,n)=>t(Rr(r),n)(e);class wl{constructor(e={}){this.logger=It.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?xa:yl;this.formats={number:n((s,a)=>{const o=new Intl.NumberFormat(s,{...a});return l=>o.format(l)}),currency:n((s,a)=>{const o=new Intl.NumberFormat(s,{...a,style:"currency"});return l=>o.format(l)}),datetime:n((s,a)=>{const o=new Intl.DateTimeFormat(s,{...a});return l=>o.format(l)}),relativetime:n((s,a)=>{const o=new Intl.RelativeTimeFormat(s,{...a});return l=>o.format(l,a.range||"day")}),list:n((s,a)=>{const o=new Intl.ListFormat(s,{...a});return l=>o.format(l)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=xa(r)}format(e,r,n,s={}){if(!r||e==null)return e;const a=r.split(this.formatSeparator),o=[];for(let c=0;c<a.length;c++){let d=a[c];for(;d.indexOf("(")>-1&&!d.includes(")")&&c+1<a.length;)d=`${d}${this.formatSeparator}${a[++c]}`;o.push(d)}return o.reduce((c,d)=>{var p;const{formatName:u,formatOptions:f}=bl(d);if(this.formats[u]){let g=c;try{const m=((p=s==null?void 0:s.formatParams)==null?void 0:p[s.interpolationkey])||{},x=m.locale||m.lng||s.locale||s.lng||n;g=this.formats[u](c,x,{...f,...s,...m})}catch(m){this.logger.warn(m)}return g}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const vl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class kl extends Is{constructor(e,r,n,s={}){var a,o;super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=s,this.logger=It.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],(o=(a=this.backend)==null?void 0:a.init)==null||o.call(a,n,s.backend,s)}queueLoad(e,r,n,s){const a={},o={},l={},c={};return e.forEach(d=>{let u=!0;r.forEach(f=>{const p=`${d}|${f}`;!n.reload&&this.store.hasResourceBundle(d,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?o[p]===void 0&&(o[p]=!0):(this.state[p]=1,u=!1,o[p]===void 0&&(o[p]=!0),a[p]===void 0&&(a[p]=!0),c[f]===void 0&&(c[f]=!0)))}),u||(l[d]=!0)}),(Object.keys(a).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(a),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,r,n){const s=e.split("|"),a=s[0],o=s[1];r&&this.emit("failedLoading",a,o,r),!r&&n&&this.store.addResourceBundle(a,o,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const l={};this.queue.forEach(c=>{ol(c.loaded,[a],o),vl(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(f=>{l[d][f]===void 0&&(l[d][f]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(e,r,n,s=0,a=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:s,wait:a,callback:o});return}this.readingCalls++;const l=(d,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(d&&u&&s<this.maxRetries){setTimeout(()=>{this.read(e,r,n,s+1,a*2,o)},a);return}o(d,u)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const d=c(e,r);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,r,l)}prepareLoading(e,r,n={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();pe(e)&&(e=this.languageUtils.toResolveHierarchy(e)),pe(r)&&(r=[r]);const a=this.queueLoad(e,r,n,s);if(!a.toLoad.length)return a.pending.length||s(),null;a.toLoad.forEach(o=>{this.loadOne(o)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),s=n[0],a=n[1];this.read(s,a,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${r}loading namespace ${a} for language ${s} failed`,o),!o&&l&&this.logger.log(`${r}loaded namespace ${a} for language ${s}`,l),this.loaded(e,o,l)})}saveMissing(e,r,n,s,a,o={},l=()=>{}){var c,d,u,f,p;if((d=(c=this.services)==null?void 0:c.utils)!=null&&d.hasLoadedNamespace&&!((f=(u=this.services)==null?void 0:u.utils)!=null&&f.hasLoadedNamespace(r))){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if((p=this.backend)!=null&&p.create){const g={...o,isUpdate:a},m=this.backend.create.bind(this.backend);if(m.length<6)try{let x;m.length===5?x=m(e,r,n,s,g):x=m(e,r,n,s),x&&typeof x.then=="function"?x.then(y=>l(null,y)).catch(l):l(null,x)}catch(x){l(x)}else m(e,r,n,s,l,g)}!e||!e[0]||this.store.addResource(e[0],r,n,s)}}}const Qs=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),pe(t[1])&&(e.defaultValue=t[1]),pe(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ba=t=>(pe(t.ns)&&(t.ns=[t.ns]),pe(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),pe(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),ts=()=>{},Sl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})};class Mr extends Is{constructor(e={},r){if(super(),this.options=ba(e),this.services={},this.logger=It,this.modules={external:[]},Sl(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(pe(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const n=Qs();this.options={...n,...this.options,...ba(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);const s=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?It.init(s(this.modules.logger),this.options):It.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=wl;const u=new fa(this.options);this.store=new ua(this.options.resources,this.options);const f=this.services;f.logger=It,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new xl(u,{prepend:this.options.pluralSeparator}),d&&(f.formatter=s(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new ga(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new kl(s(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.languageDetector&&(f.languageDetector=s(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=s(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new xs(this.services,this.options),this.translator.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,r||(r=ts),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const l=Ir(),c=()=>{const d=(u,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(f),r(u,f)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(e,r=ts){var a,o;let n=r;const s=pe(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if((s==null?void 0:s.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};s?c(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(a=this.options.preload)==null?void 0:a.forEach)==null||o.call(a,d=>c(d)),this.services.backendConnector.load(l,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(d)})}else n(null)}reloadResources(e,r,n){const s=Ir();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=ts),this.services.backendConnector.reload(e,r,a=>{s.resolve(),n(a)}),s}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&xi.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!["cimode","dev"].includes(n)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=Ir();this.emit("languageChanging",e);const s=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},a=(l,c)=>{c?this.isLanguageChangingTo===e&&(s(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...d)=>this.t(...d)),r&&r(l,(...d)=>this.t(...d))},o=l=>{var u,f;!e&&!l&&this.services.languageDetector&&(l=[]);const c=pe(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(pe(l)?[l]:l);d&&(this.language||s(d),this.translator.language||this.translator.changeLanguage(d),(f=(u=this.services.languageDetector)==null?void 0:u.cacheUserLanguage)==null||f.call(u,d)),this.loadResources(d,p=>{a(p,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),n}getFixedT(e,r,n,s){const a=s==null?void 0:s.scopeNs,o=(l,c,...d)=>{let u;typeof c!="object"?u=this.options.overloadTranslationOptionHandler([l,c].concat(d)):u={...c},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const f=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const p={...this.options,...u};Array.isArray(a)&&!f&&(p.ns=a),typeof u.keyPrefix=="function"&&(u.keyPrefix=dr(u.keyPrefix,p));const g=this.options.keySeparator||".";let m;return u.keyPrefix&&Array.isArray(l)?m=l.map(x=>(typeof x=="function"&&(x=dr(x,p)),`${u.keyPrefix}${g}${x}`)):(typeof l=="function"&&(l=dr(l,p)),m=u.keyPrefix?`${u.keyPrefix}${g}${l}`:l),this.t(m,u)};return pe(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){var r;return(r=this.translator)==null?void 0:r.translate(...e)}exists(...e){var r;return(r=this.translator)==null?void 0:r.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,a=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(r.precheck){const l=r.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,e)&&(!s||o(a,e)))}loadNamespaces(e,r){const n=Ir();return this.options.ns?(pe(e)&&(e=[e]),e.forEach(s=>{this.options.ns.includes(s)||this.options.ns.push(s)}),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=Ir();pe(e)&&(e=[e]);const s=this.options.preload||[],a=e.filter(o=>!s.includes(o)&&this.services.languageUtils.isSupportedCode(o));return a.length?(this.options.preload=s.concat(a),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}dir(e){var s,a;if(e||(e=this.resolvedLanguage||(((s=this.languages)==null?void 0:s.length)>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const l=o.getTextInfo();if(l&&l.direction)return l.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=((a=this.services)==null?void 0:a.languageUtils)||new fa(Qs());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new Mr(e,r);return n.createInstance=Mr.createInstance,n}cloneInstance(e={},r=ts){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},a=new Mr(s);if((e.debug!==void 0||e.prefix!==void 0)&&(a.logger=a.logger.clone(e)),["store","services","language"].forEach(l=>{a[l]=this[l]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},n){const l=Object.keys(this.store.data).reduce((c,d)=>(c[d]={...this.store.data[d]},c[d]=Object.keys(c[d]).reduce((u,f)=>(u[f]={...c[d][f]},u),c[d]),c),{});a.store=new ua(l,s),a.services.resourceStore=a.store}if(e.interpolation){const c={...Qs().interpolation,...this.options.interpolation,...e.interpolation},d={...s,interpolation:c};a.services.interpolator=new ga(d)}return a.translator=new xs(a.services,s),a.translator.on("*",(l,...c)=>{a.emit(l,...c)}),a.init(s,r),a.translator.options=s,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Xe=Mr.createInstance();Xe.createInstance;Xe.dir;Xe.init;Xe.loadResources;Xe.reloadResources;Xe.use;Xe.changeLanguage;Xe.getFixedT;Xe.t;Xe.exists;Xe.setDefaultNamespace;Xe.hasLoadedNamespace;Xe.loadNamespaces;Xe.loadLanguages;const jl=(t,e,r,n)=>{var a,o,l,c;const s=[r,{code:e,...n||{}}];if((o=(a=t==null?void 0:t.services)==null?void 0:a.logger)!=null&&o.forward)return t.services.logger.forward(s,"warn","react-i18next::",!0);er(s[0])&&(s[0]=`react-i18next:: ${s[0]}`),(c=(l=t==null?void 0:t.services)==null?void 0:l.logger)!=null&&c.warn?t.services.logger.warn(...s):console!=null&&console.warn&&console.warn(...s)},ya={},dn=(t,e,r,n)=>{er(r)&&ya[r]||(er(r)&&(ya[r]=new Date),jl(t,e,r,n))},yi=(t,e)=>()=>{if(t.isInitialized)e();else{const r=()=>{setTimeout(()=>{t.off("initialized",r)},0),e()};t.on("initialized",r)}},un=(t,e,r)=>{t.loadNamespaces(e,yi(t,r))},wa=(t,e,r,n)=>{if(er(r)&&(r=[r]),t.options.preload&&t.options.preload.indexOf(e)>-1)return un(t,r,n);r.forEach(s=>{t.options.ns.indexOf(s)<0&&t.options.ns.push(s)}),t.loadLanguages(e,yi(t,n))},Cl=(t,e,r={})=>!e.languages||!e.languages.length?(dn(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:r.lng,precheck:(n,s)=>{if(r.bindI18n&&r.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!s(n.isLanguageChangingTo,t))return!1}}),er=t=>typeof t=="string",Al=t=>typeof t=="object"&&t!==null,Nl=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Il={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},Ll=t=>Il[t],El=t=>t.replace(Nl,Ll);let fn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:El,transDefaultProps:void 0};const _l=(t={})=>{fn={...fn,...t}},Tl=()=>fn;let wi;const Ml=t=>{wi=t},Fl=()=>wi,$l={type:"3rdParty",init(t){_l(t.options.react),Ml(t)}},Rl=h.createContext();class Pl{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var Zs={exports:{}},Js={};/**
|
|
3
|
+
* @license React
|
|
4
|
+
* use-sync-external-store-shim.production.js
|
|
5
|
+
*
|
|
6
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
7
|
+
*
|
|
8
|
+
* This source code is licensed under the MIT license found in the
|
|
9
|
+
* LICENSE file in the root directory of this source tree.
|
|
10
|
+
*/var va;function Dl(){if(va)return Js;va=1;var t=Uo();function e(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,s=t.useEffect,a=t.useLayoutEffect,o=t.useDebugValue;function l(f,p){var g=p(),m=n({inst:{value:g,getSnapshot:p}}),x=m[0].inst,y=m[1];return a(function(){x.value=g,x.getSnapshot=p,c(x)&&y({inst:x})},[f,g,p]),s(function(){return c(x)&&y({inst:x}),f(function(){c(x)&&y({inst:x})})},[f]),o(g),g}function c(f){var p=f.getSnapshot;f=f.value;try{var g=p();return!r(f,g)}catch{return!0}}function d(f,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Js.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,Js}var ka;function Ul(){return ka||(ka=1,Zs.exports=Dl()),Zs.exports}var Ol=Ul();const zl=(t,e)=>{if(er(e))return e;if(Al(e)&&er(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const r=t[t.length-1];return typeof r=="function"?"":r}return t},Bl={t:zl,ready:!1},Hl=()=>()=>{},Le=(t,e={})=>{var T,k,I;const{i18n:r}=e,{i18n:n,defaultNS:s}=h.useContext(Rl)||{},a=r||n||Fl();a&&!a.reportNamespaces&&(a.reportNamespaces=new Pl),a||dn(a,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=h.useMemo(()=>{var P;return{...Tl(),...(P=a==null?void 0:a.options)==null?void 0:P.react,...e}},[a,e]),{useSuspense:l,keyPrefix:c}=o,d=s||((T=a==null?void 0:a.options)==null?void 0:T.defaultNS),u=er(d)?[d]:d||["translation"],f=h.useMemo(()=>u,u);(I=(k=a==null?void 0:a.reportNamespaces)==null?void 0:k.addUsedNamespaces)==null||I.call(k,f);const p=h.useRef(0),g=h.useCallback(P=>{if(!a)return Hl;const{bindI18n:M,bindI18nStore:B}=o,j=()=>{p.current+=1,P()};return M&&a.on(M,j),B&&a.store.on(B,j),()=>{M&&M.split(" ").forEach(L=>a.off(L,j)),B&&B.split(" ").forEach(L=>a.store.off(L,j))}},[a,o]),m=h.useRef(),x=h.useCallback(()=>{if(!a)return Bl;const P=!!(a.isInitialized||a.initializedStoreOnce)&&f.every(F=>Cl(F,a,o)),M=e.lng||a.language,B=p.current,j=m.current;if(j&&j.ready===P&&j.lng===M&&j.keyPrefix===c&&j.revision===B)return j;const O={t:a.getFixedT(M,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:P,lng:M,keyPrefix:c,revision:B};return m.current=O,O},[a,f,c,o,e.lng]),[y,v]=h.useState(0),{t:A,ready:N}=Ol.useSyncExternalStore(g,x,x);h.useEffect(()=>{if(a&&!N&&!l){const P=()=>v(M=>M+1);e.lng?wa(a,e.lng,f,P):un(a,f,P)}},[a,e.lng,f,N,l,y]);const C=a||{},S=h.useRef(null),E=h.useRef(),_=P=>{const M=Object.getOwnPropertyDescriptors(P);M.__original&&delete M.__original;const B=Object.create(Object.getPrototypeOf(P),M);if(!Object.prototype.hasOwnProperty.call(B,"__original"))try{Object.defineProperty(B,"__original",{value:P,writable:!1,enumerable:!1,configurable:!1})}catch{}return B},b=h.useMemo(()=>{const P=C,M=P==null?void 0:P.language;let B=P;P&&(S.current&&S.current.__original===P?E.current!==M?(B=_(P),S.current=B,E.current=M):B=S.current:(B=_(P),S.current=B,E.current=M));const j=!N&&!l?(...O)=>(dn(a,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),A(...O)):A,L=[j,B,N];return L.t=j,L.i18n=B,L.ready=N,L},[A,C,N,C.resolvedLanguage,C.language,C.languages]);if(a&&l&&!N)throw new Promise(P=>{const M=()=>P();e.lng?wa(a,e.lng,f,M):un(a,f,M)});return b},Vl={de:{translation:Ko},en:{translation:Wo},es:{translation:qo},fr:{translation:Vo},ja:{translation:Ho},pt:{translation:Bo},zh:{translation:zo}};Xe.use($l).init({resources:Vl,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var ql={agentMode:{mode:"multi",defaultAdapterId:"chat-with-files"},application:{name:"ORBIT Chat",description:"Explore ideas with ORBIT's AI copilots, share context, and build together.",inputPlaceholder:"Message ORBIT...",settingsAboutMsg:"ORBIT Chat",locale:"en-US",favicon:null},i18n:{activeLanguages:["en","fr","es","pt","de","ja","zh"],defaultLanguage:"en"},seo:{includeSitemap:!1,siteUrl:"http://localhost:5173",exposeAgentNotes:!0},debug:{consoleDebug:!1},features:{enableUpload:!0,enableAudioOutput:!0,enableAudioInput:!0,enableFeedbackButtons:!0,enableConversationThreads:!0,enableAutocomplete:!0},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},limits:{files:{perConversation:5,maxSizeMB:50,totalFiles:100},conversations:{maxConversations:10,messagesPerConversation:1e3,messagesPerThread:1e3,totalMessages:1e4},messages:{maxLength:1e4}},guestLimits:{files:{perConversation:1,maxSizeMB:5,totalFiles:1},conversations:{maxConversations:2,messagesPerConversation:5,messagesPerThread:2,totalMessages:10},messages:{maxLength:500},rateLimit:{enabled:!0,windowMs:6e4,maxRequests:60,chat:{windowMs:6e4,maxRequests:10}}},auth:{enabled:!1,provider:"entra"},header:{enabled:!0,logoUrl:"",logoUrlLight:"",logoUrlDark:"",logoHeight:"3.5rem",logoWidth:"auto",bgColor:"",textColor:"",showBorder:!1,navLinks:[{label:"Docs",url:"/"},{label:"About",url:"/about"}]},footer:{enabled:!0,text:"Copyright © 2025 Schmitech Inc.",bgColor:"",textColor:"",showBorder:!1,layout:"stacked",align:"center",topPadding:"large",navLinks:[{label:"Support",url:"/"},{label:"Privacy",url:"/about"}]},adapters:[{id:"simple-chat",name:"Simple AI Chat",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent (Similar to ChatGPT - no files).",inputPlaceholder:"Simple chat, ask anything..."},{id:"web-search",name:"Simple AI Chat (Web Search)",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent with web search supports.",inputPlaceholder:"Simple chat, ask anything..."},{id:"chat-with-files",name:"Simple AI Chat (Multimodal)",apiUrl:"http://localhost:3000",description:"Extract knowledge from PDF, Images, Word, etc. (Similar to ChatGPT Multimodal)",inputPlaceholder:"Files chat, ask anything..."},{id:"image-generator",name:"AI Image Generator",apiUrl:"http://localhost:3000",description:"Generate images from text descriptions using DALL-E 3 or Imagen 3.",inputPlaceholder:"Describe the image you want to create..."},{id:"video-generator",name:"AI Video Generator",apiUrl:"http://localhost:3000",description:"Generate videos from text descriptions.",inputPlaceholder:"Describe the video you want to create..."},{id:"audio-generator",name:"AI Audio Generator",apiUrl:"http://localhost:3000",description:"Convert text to natural-sounding speech using AI voices.",inputPlaceholder:"Type the text you want to convert to speech..."},{id:"qa-sql",name:"City FAQ Assistant (SQLite)",apiUrl:"http://localhost:3000",description:"Quick-test QA assistant over the sample city Q&A SQLite database.",inputPlaceholder:"Ask a city services question..."},{id:"qa-vector-chroma",name:"City FAQ Assistant (Chroma)",apiUrl:"http://localhost:3000",description:"Quick-test semantic QA assistant over the sample city Q&A Chroma collection.",inputPlaceholder:"Ask a city services question..."},{id:"hr-db-chatbot",name:"HR System Assistant",apiUrl:"http://localhost:3000",description:"HR database assistant: natural language queries over SQLite HR data via intent templates.",inputPlaceholder:"Ask HR questions..."},{id:"intent-sql-postgres",name:"Customer Orders Assistant",apiUrl:"http://localhost:3000",description:"Customer orders assistant: natural language queries over PostgreSQL customer orders data."},{id:"ecomm-analytics",name:"Business Analytics Assistant",apiUrl:"http://localhost:3000",description:"DuckDB analytics assistant: natural language analytics queries over the analytics demo. This agent is the perfect example of how to use something like OLAP to quickly discover insigths."},{id:"composite-multi-source-explorer",name:"Multi-Source Explorer",apiUrl:"http://localhost:3000",description:"Multi-domain assistant: natural language over HR (SQLite), customer orders (PostgreSQL), and sales analytics (DuckDB)—one chat, retrieval routes each question to the best source.",inputPlaceholder:"Ask about employees, orders, or sales analytics..."},{id:"intent-http-jsonplaceholder",name:"REST API Chat",apiUrl:"http://localhost:3000",description:"Natural language queries over the fake REST API."},{id:"intent-http-paris-opendata",name:"City of Paris Chat",apiUrl:"http://localhost:3000",description:"Paris open data: events and activities (Que Faire à Paris) via natural language."},{id:"intent-mongodb-mflix",name:"Chat With Movies DB",apiUrl:"http://localhost:3000",description:"MFlix movies assistant: query the sample_mflix MongoDB database via intent templates."},{id:"intent-graphql-spacex",name:"GraphQL Chatbot",apiUrl:"http://localhost:3000",description:"SpaceX GraphQL assistant: natural language queries over the SpaceX API.",inputPlaceholder:"Ask SpaceX questions..."},{id:"audio-transcription",name:"Audio Transcription",apiUrl:"http://localhost:3000",description:"Audio Transcription Test.",inputPlaceholder:"Use the microphone for voice..."},{id:"voice-chat",name:"Voice Chat",apiUrl:"http://localhost:3000",description:"Voice chat adapter test.",inputPlaceholder:"Use the microphone for voice..."},{id:"real-time-voice-chat",name:"Real-Time Voice Chat",apiUrl:"http://localhost:3000",description:"Real-time voice chat adapter test (websocket).",inputPlaceholder:"Use the microphone for voice..."},{id:"intent-elasticsearch-log",name:"Log Analysis Assistant",apiUrl:"http://localhost:3000",description:"Analyze app logs, troubleshoot errors, and monitor performance via Elasticsearch."}]};const hn="http://localhost:3000",Wl="/favicon.svg",Kl="/orbit-logo-light.png",Gl="/orbit-logo-dark.png",Xl={agentMode:{mode:"multi",defaultAdapterId:""},i18n:{activeLanguages:["en"],defaultLanguage:"en"},application:{name:"ORBIT Chat",description:"Explore ideas with ORBIT's AI copilots, share context, and build together.",inputPlaceholder:"Message ORBIT...",settingsAboutMsg:"ORBIT Chat",locale:"en-US",favicon:""},debug:{consoleDebug:!1},seo:{includeSitemap:!1,siteUrl:"",alternateSiteUrls:[],hostPatterns:[],exposeAgentNotes:!0},features:{enableUpload:!1,enableAudioOutput:!1,enableAudioInput:!1,enableFeedbackButtons:!1,enableConversationThreads:!0,enableAutocomplete:!1},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},outOfServiceMessage:null,limits:{files:{perConversation:5,maxSizeMB:50,totalFiles:100},conversations:{maxConversations:10,messagesPerConversation:1e3,messagesPerThread:1e3,totalMessages:1e4},messages:{maxLength:1e3}},guestLimits:{files:{perConversation:1,maxSizeMB:10,totalFiles:2},conversations:{maxConversations:1,messagesPerConversation:10,messagesPerThread:10,totalMessages:10},messages:{maxLength:500}},auth:{enabled:!1,provider:"auth0",domain:"",clientId:"",audience:"",tenantId:"",scopes:[]},header:{enabled:!1,logoUrl:"",logoUrlLight:"",logoUrlDark:"",logoHeight:"",logoWidth:"",bgColor:"",textColor:"",showBorder:!0,navLinks:[]},footer:{enabled:!1,text:"",bgColor:"",textColor:"",showBorder:!1,layout:"stacked",align:"center",topPadding:"large",navLinks:[]},startupScripts:[],adapters:[]};function rs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pn(t,e){if(!rs(t)||!rs(e))return e;const r={...t};return Object.keys(e).forEach(n=>{if(n==="__proto__"||n==="constructor"||n==="prototype")return;const s=r[n],a=e[n];rs(s)&&rs(a)?r[n]=pn(s,a):a!==void 0&&(r[n]=a)}),r}function Yl(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const r=e.toLowerCase();return r==="false"||r==="0"||r==="off"||r==="disabled"?null:e}function Ql(t){return t==="single"?"single":"multi"}function Zl(t){const e=t.trim();if(e.startsWith("["))try{const r=JSON.parse(e);return Array.isArray(r)?r.filter(Boolean):[]}catch{return[]}return e.split(/\s+/).filter(Boolean)}function Jl(){const t=ql||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},r=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let n=pn(Xl,t);return n=pn(n,e),(!r||!n.auth.domain)&&(n.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!r||!n.auth.clientId)&&(n.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!r||n.auth.audience,!r||n.auth.provider,!r||n.auth.tenantId,(!r||n.auth.scopes.length===0)&&(n.auth.scopes=Zl("openid profile email User.Read")),n.outOfServiceMessage=Yl(n.outOfServiceMessage),n.agentMode.mode=Ql(n.agentMode.mode),n.agentMode.defaultAdapterId=typeof n.agentMode.defaultAdapterId=="string"?n.agentMode.defaultAdapterId.trim():"",n}const Y=Jl();function $e(){var e;const t=Y.adapters;if(Array.isArray(t)&&t.length>0){const r=(e=t[0].apiUrl)==null?void 0:e.trim();if(r)return r}return hn}function lt(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:$e()}function ec(){const t=Y.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function tc(){return Y.agentMode.mode}function Ls(){return tc()==="single"}function In(){if(!Ls())return null;const t=Y.agentMode.defaultAdapterId;return t&&Y.adapters.some(r=>{var n;return((n=r==null?void 0:r.id)==null?void 0:n.trim())===t})?t:null}function vi(){const t=Array.isArray(Y.i18n.activeLanguages)?Y.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function rc(){var e;const t=(e=Y.i18n.defaultLanguage)==null?void 0:e.trim();return t&&vi().includes(t)?t:"en"}function Ln(){return Y.application.name}function En(){return Y.application.description}function ki(){return Y.application.inputPlaceholder}function sc(t){var s;const e=t==null?void 0:t.trim();if(!e)return null;const r=Y.adapters.find(a=>{var o;return((o=a==null?void 0:a.id)==null?void 0:o.trim())===e});return((s=r==null?void 0:r.name)==null?void 0:s.trim())||null}function nc(t){var s;const e=t==null?void 0:t.trim();if(!e)return null;const r=Y.adapters.find(a=>{var o;return((o=a==null?void 0:a.id)==null?void 0:o.trim())===e});return((s=r==null?void 0:r.inputPlaceholder)==null?void 0:s.trim())||null}function Si(){return Y.seo.siteUrl.trim()}function ac(){return Array.isArray(Y.seo.alternateSiteUrls)?Y.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function ic(){return Array.isArray(Y.seo.hostPatterns)?Y.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function oc(){return Y.seo.exposeAgentNotes}function lc(){var e;return((e=Y.application.favicon)==null?void 0:e.trim())||Wl}function cc(){return Y.features.enableUpload}function dc(){return Y.features.enableAudioOutput}function uc(){return Y.features.enableAudioInput}function Sa(){return Y.features.enableFeedbackButtons}function fc(){return Y.features.enableConversationThreads}function ji(){return Y.features.enableAutocomplete}function hc(){return Math.max(1e3,Y.voice.silenceTimeoutMs)}function pc(){return Y.voice.recognitionLanguage}function mc(){const t=In();if(t)return t;const e=Y.adapters;if(Array.isArray(e)&&e.length>0)for(const r of e){const n=typeof(r==null?void 0:r.id)=="string"?r.id.trim():"";if(n)return n}return null}function gc(){return Y.outOfServiceMessage}function _n(){return Y.auth.enabled}function tt(){const{enabled:t,provider:e,domain:r,clientId:n,tenantId:s}=Y.auth;return!t||!n?!1:e==="entra"?!!s:!!r}function xc(){return Y.auth.domain}function Ci(){return Y.auth.clientId}function bc(){return Y.auth.audience}function Es(){return Y.auth.provider}function yc(){return Y.auth.tenantId}function Tn(){const t=Y.auth.scopes;return t.length>0?t:["openid","profile","email"]}function mn(){return Y.header.enabled}function wc(){return Y.header.logoUrl}function vc(){var e;return((e=Y.header.logoUrlLight)==null?void 0:e.trim())||Kl}function kc(){var e;return((e=Y.header.logoUrlDark)==null?void 0:e.trim())||Gl}function Sc(){var t;return((t=Y.header.logoHeight)==null?void 0:t.trim())||""}function jc(){var t;return((t=Y.header.logoWidth)==null?void 0:t.trim())||""}function Cc(){return Y.header.bgColor}function Ac(){return Y.header.textColor}function Nc(){return Y.header.showBorder}function Ai(t){if(Array.isArray(t))return t;if(typeof t=="string")try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}return[]}function Ni(){return Ai(Y.header.navLinks)}function Ii(){return Y.footer.enabled}function Ic(){return Y.footer.text}function Lc(){return Y.footer.bgColor}function Ec(){return Y.footer.textColor}function _c(){return Y.footer.showBorder}function Tc(){return Y.footer.layout==="inline"?"inline":"stacked"}function Mc(){return Y.footer.topPadding==="normal"?"normal":"large"}function Fc(){const t=Y.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const r=typeof e.src=="string"?e.src.trim():"",n=typeof e.content=="string"?e.content.trim():"",s=typeof e.id=="string"?e.id.trim():"";return{...e,src:r||void 0,content:n||void 0,id:s||void 0}}).filter(e=>!!(e.src||e.content)):[]}function $c(){return Ai(Y.footer.navLinks)}const Li=["de","en","es","fr","ja","pt","zh"],ss={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function hs(t){return Li.includes(t)}const Ei=h.createContext(void 0),_i="orbit-chat-language";function Rc(){const t=vi().filter(hs);return t.length>0?t:["en"]}function Pc(t){const e=localStorage.getItem(_i);if(e&&hs(e)&&t.includes(e))return e;const r=[...navigator.languages||[],navigator.language].filter(Boolean);for(const s of r){const a=s.split("-")[0].toLowerCase();if(hs(a)&&t.includes(a))return a}const n=rc();return hs(n)&&t.includes(n)?n:t[0]??"en"}function Dc({children:t}){const[e]=h.useState(()=>Rc()),[r,n]=h.useState(()=>Pc(e));h.useEffect(()=>{Xe.changeLanguage(r)},[r]),h.useEffect(()=>{localStorage.setItem(_i,r)},[r]);const s=a=>{Li.includes(a)&&n(a)};return i.jsx(Ei.Provider,{value:{currentLanguage:r,activeLanguages:e,setLanguage:s},children:t})}function Uc(){const t=h.useContext(Ei);if(!t)throw new Error("useLanguage must be used within LanguageProvider");return t}/**
|
|
11
|
+
* @license lucide-react v0.469.0 - ISC
|
|
12
|
+
*
|
|
13
|
+
* This source code is licensed under the ISC license.
|
|
14
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
15
|
+
*/const Oc=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ti=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();/**
|
|
16
|
+
* @license lucide-react v0.469.0 - ISC
|
|
17
|
+
*
|
|
18
|
+
* This source code is licensed under the ISC license.
|
|
19
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
20
|
+
*/var zc={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
21
|
+
* @license lucide-react v0.469.0 - ISC
|
|
22
|
+
*
|
|
23
|
+
* This source code is licensed under the ISC license.
|
|
24
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
25
|
+
*/const Bc=h.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:s="",children:a,iconNode:o,...l},c)=>h.createElement("svg",{ref:c,...zc,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:Ti("lucide",s),...l},[...o.map(([d,u])=>h.createElement(d,u)),...Array.isArray(a)?a:[a]]));/**
|
|
26
|
+
* @license lucide-react v0.469.0 - ISC
|
|
27
|
+
*
|
|
28
|
+
* This source code is licensed under the ISC license.
|
|
29
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
30
|
+
*/const re=(t,e)=>{const r=h.forwardRef(({className:n,...s},a)=>h.createElement(Bc,{ref:a,iconNode:e,className:Ti(`lucide-${Oc(t)}`,n),...s}));return r.displayName=`${t}`,r};/**
|
|
31
|
+
* @license lucide-react v0.469.0 - ISC
|
|
32
|
+
*
|
|
33
|
+
* This source code is licensed under the ISC license.
|
|
34
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
35
|
+
*/const gn=re("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
|
|
36
|
+
* @license lucide-react v0.469.0 - ISC
|
|
37
|
+
*
|
|
38
|
+
* This source code is licensed under the ISC license.
|
|
39
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
40
|
+
*/const ur=re("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
|
|
41
|
+
* @license lucide-react v0.469.0 - ISC
|
|
42
|
+
*
|
|
43
|
+
* This source code is licensed under the ISC license.
|
|
44
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
45
|
+
*/const hr=re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
|
|
46
|
+
* @license lucide-react v0.469.0 - ISC
|
|
47
|
+
*
|
|
48
|
+
* This source code is licensed under the ISC license.
|
|
49
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
50
|
+
*/const ja=re("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
|
|
51
|
+
* @license lucide-react v0.469.0 - ISC
|
|
52
|
+
*
|
|
53
|
+
* This source code is licensed under the ISC license.
|
|
54
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
55
|
+
*/const bs=re("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
|
|
56
|
+
* @license lucide-react v0.469.0 - ISC
|
|
57
|
+
*
|
|
58
|
+
* This source code is licensed under the ISC license.
|
|
59
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
60
|
+
*/const xn=re("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
|
|
61
|
+
* @license lucide-react v0.469.0 - ISC
|
|
62
|
+
*
|
|
63
|
+
* This source code is licensed under the ISC license.
|
|
64
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
65
|
+
*/const Hc=re("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
|
|
66
|
+
* @license lucide-react v0.469.0 - ISC
|
|
67
|
+
*
|
|
68
|
+
* This source code is licensed under the ISC license.
|
|
69
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
70
|
+
*/const Ca=re("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
|
|
71
|
+
* @license lucide-react v0.469.0 - ISC
|
|
72
|
+
*
|
|
73
|
+
* This source code is licensed under the ISC license.
|
|
74
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
75
|
+
*/const Aa=re("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
|
|
76
|
+
* @license lucide-react v0.469.0 - ISC
|
|
77
|
+
*
|
|
78
|
+
* This source code is licensed under the ISC license.
|
|
79
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
80
|
+
*/const _s=re("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
|
|
81
|
+
* @license lucide-react v0.469.0 - ISC
|
|
82
|
+
*
|
|
83
|
+
* This source code is licensed under the ISC license.
|
|
84
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
85
|
+
*/const Vc=re("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
|
|
86
|
+
* @license lucide-react v0.469.0 - ISC
|
|
87
|
+
*
|
|
88
|
+
* This source code is licensed under the ISC license.
|
|
89
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
90
|
+
*/const qc=re("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);/**
|
|
91
|
+
* @license lucide-react v0.469.0 - ISC
|
|
92
|
+
*
|
|
93
|
+
* This source code is licensed under the ISC license.
|
|
94
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
95
|
+
*/const Wc=re("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);/**
|
|
96
|
+
* @license lucide-react v0.469.0 - ISC
|
|
97
|
+
*
|
|
98
|
+
* This source code is licensed under the ISC license.
|
|
99
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
100
|
+
*/const Mi=re("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/**
|
|
101
|
+
* @license lucide-react v0.469.0 - ISC
|
|
102
|
+
*
|
|
103
|
+
* This source code is licensed under the ISC license.
|
|
104
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
105
|
+
*/const Kc=re("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);/**
|
|
106
|
+
* @license lucide-react v0.469.0 - ISC
|
|
107
|
+
*
|
|
108
|
+
* This source code is licensed under the ISC license.
|
|
109
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
110
|
+
*/const Fi=re("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/**
|
|
111
|
+
* @license lucide-react v0.469.0 - ISC
|
|
112
|
+
*
|
|
113
|
+
* This source code is licensed under the ISC license.
|
|
114
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
115
|
+
*/const bn=re("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/**
|
|
116
|
+
* @license lucide-react v0.469.0 - ISC
|
|
117
|
+
*
|
|
118
|
+
* This source code is licensed under the ISC license.
|
|
119
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
120
|
+
*/const Gc=re("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);/**
|
|
121
|
+
* @license lucide-react v0.469.0 - ISC
|
|
122
|
+
*
|
|
123
|
+
* This source code is licensed under the ISC license.
|
|
124
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
125
|
+
*/const Xc=re("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
|
|
126
|
+
* @license lucide-react v0.469.0 - ISC
|
|
127
|
+
*
|
|
128
|
+
* This source code is licensed under the ISC license.
|
|
129
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
130
|
+
*/const Yc=re("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
|
|
131
|
+
* @license lucide-react v0.469.0 - ISC
|
|
132
|
+
*
|
|
133
|
+
* This source code is licensed under the ISC license.
|
|
134
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
135
|
+
*/const Qc=re("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/**
|
|
136
|
+
* @license lucide-react v0.469.0 - ISC
|
|
137
|
+
*
|
|
138
|
+
* This source code is licensed under the ISC license.
|
|
139
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
140
|
+
*/const $i=re("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
|
|
141
|
+
* @license lucide-react v0.469.0 - ISC
|
|
142
|
+
*
|
|
143
|
+
* This source code is licensed under the ISC license.
|
|
144
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
145
|
+
*/const Ri=re("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
|
|
146
|
+
* @license lucide-react v0.469.0 - ISC
|
|
147
|
+
*
|
|
148
|
+
* This source code is licensed under the ISC license.
|
|
149
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
150
|
+
*/const Zc=re("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
|
|
151
|
+
* @license lucide-react v0.469.0 - ISC
|
|
152
|
+
*
|
|
153
|
+
* This source code is licensed under the ISC license.
|
|
154
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
155
|
+
*/const Jc=re("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/**
|
|
156
|
+
* @license lucide-react v0.469.0 - ISC
|
|
157
|
+
*
|
|
158
|
+
* This source code is licensed under the ISC license.
|
|
159
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
160
|
+
*/const ed=re("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
|
|
161
|
+
* @license lucide-react v0.469.0 - ISC
|
|
162
|
+
*
|
|
163
|
+
* This source code is licensed under the ISC license.
|
|
164
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
165
|
+
*/const Na=re("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
|
|
166
|
+
* @license lucide-react v0.469.0 - ISC
|
|
167
|
+
*
|
|
168
|
+
* This source code is licensed under the ISC license.
|
|
169
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
170
|
+
*/const td=re("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
|
|
171
|
+
* @license lucide-react v0.469.0 - ISC
|
|
172
|
+
*
|
|
173
|
+
* This source code is licensed under the ISC license.
|
|
174
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
175
|
+
*/const rd=re("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
|
|
176
|
+
* @license lucide-react v0.469.0 - ISC
|
|
177
|
+
*
|
|
178
|
+
* This source code is licensed under the ISC license.
|
|
179
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
180
|
+
*/const sd=re("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/**
|
|
181
|
+
* @license lucide-react v0.469.0 - ISC
|
|
182
|
+
*
|
|
183
|
+
* This source code is licensed under the ISC license.
|
|
184
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
185
|
+
*/const nd=re("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
186
|
+
* @license lucide-react v0.469.0 - ISC
|
|
187
|
+
*
|
|
188
|
+
* This source code is licensed under the ISC license.
|
|
189
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
190
|
+
*/const ad=re("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
|
|
191
|
+
* @license lucide-react v0.469.0 - ISC
|
|
192
|
+
*
|
|
193
|
+
* This source code is licensed under the ISC license.
|
|
194
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
195
|
+
*/const id=re("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
|
|
196
|
+
* @license lucide-react v0.469.0 - ISC
|
|
197
|
+
*
|
|
198
|
+
* This source code is licensed under the ISC license.
|
|
199
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
200
|
+
*/const od=re("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/**
|
|
201
|
+
* @license lucide-react v0.469.0 - ISC
|
|
202
|
+
*
|
|
203
|
+
* This source code is licensed under the ISC license.
|
|
204
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
205
|
+
*/const ld=re("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);/**
|
|
206
|
+
* @license lucide-react v0.469.0 - ISC
|
|
207
|
+
*
|
|
208
|
+
* This source code is licensed under the ISC license.
|
|
209
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
210
|
+
*/const cd=re("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
|
|
211
|
+
* @license lucide-react v0.469.0 - ISC
|
|
212
|
+
*
|
|
213
|
+
* This source code is licensed under the ISC license.
|
|
214
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
215
|
+
*/const Pi=re("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]);/**
|
|
216
|
+
* @license lucide-react v0.469.0 - ISC
|
|
217
|
+
*
|
|
218
|
+
* This source code is licensed under the ISC license.
|
|
219
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
220
|
+
*/const dd=re("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
|
|
221
|
+
* @license lucide-react v0.469.0 - ISC
|
|
222
|
+
*
|
|
223
|
+
* This source code is licensed under the ISC license.
|
|
224
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
225
|
+
*/const ud=re("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
|
|
226
|
+
* @license lucide-react v0.469.0 - ISC
|
|
227
|
+
*
|
|
228
|
+
* This source code is licensed under the ISC license.
|
|
229
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
230
|
+
*/const Di=re("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/**
|
|
231
|
+
* @license lucide-react v0.469.0 - ISC
|
|
232
|
+
*
|
|
233
|
+
* This source code is licensed under the ISC license.
|
|
234
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
235
|
+
*/const fd=re("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
236
|
+
* @license lucide-react v0.469.0 - ISC
|
|
237
|
+
*
|
|
238
|
+
* This source code is licensed under the ISC license.
|
|
239
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
240
|
+
*/const hd=re("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
|
|
241
|
+
* @license lucide-react v0.469.0 - ISC
|
|
242
|
+
*
|
|
243
|
+
* This source code is licensed under the ISC license.
|
|
244
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
245
|
+
*/const Mn=re("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
|
|
246
|
+
* @license lucide-react v0.469.0 - ISC
|
|
247
|
+
*
|
|
248
|
+
* This source code is licensed under the ISC license.
|
|
249
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
250
|
+
*/const Ia=re("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
|
|
251
|
+
* @license lucide-react v0.469.0 - ISC
|
|
252
|
+
*
|
|
253
|
+
* This source code is licensed under the ISC license.
|
|
254
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
255
|
+
*/const Fn=re("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
|
|
256
|
+
* @license lucide-react v0.469.0 - ISC
|
|
257
|
+
*
|
|
258
|
+
* This source code is licensed under the ISC license.
|
|
259
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
260
|
+
*/const pd=re("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
261
|
+
* @license lucide-react v0.469.0 - ISC
|
|
262
|
+
*
|
|
263
|
+
* This source code is licensed under the ISC license.
|
|
264
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
265
|
+
*/const md=re("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
|
|
266
|
+
* @license lucide-react v0.469.0 - ISC
|
|
267
|
+
*
|
|
268
|
+
* This source code is licensed under the ISC license.
|
|
269
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
270
|
+
*/const Ui=re("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/**
|
|
271
|
+
* @license lucide-react v0.469.0 - ISC
|
|
272
|
+
*
|
|
273
|
+
* This source code is licensed under the ISC license.
|
|
274
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
275
|
+
*/const Oi=re("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
|
|
276
|
+
* @license lucide-react v0.469.0 - ISC
|
|
277
|
+
*
|
|
278
|
+
* This source code is licensed under the ISC license.
|
|
279
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
280
|
+
*/const zi=re("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
|
|
281
|
+
* @license lucide-react v0.469.0 - ISC
|
|
282
|
+
*
|
|
283
|
+
* This source code is licensed under the ISC license.
|
|
284
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
285
|
+
*/const gd=re("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/**
|
|
286
|
+
* @license lucide-react v0.469.0 - ISC
|
|
287
|
+
*
|
|
288
|
+
* This source code is licensed under the ISC license.
|
|
289
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
290
|
+
*/const $n=re("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
|
|
291
|
+
* @license lucide-react v0.469.0 - ISC
|
|
292
|
+
*
|
|
293
|
+
* This source code is licensed under the ISC license.
|
|
294
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
295
|
+
*/const xd=re("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/**
|
|
296
|
+
* @license lucide-react v0.469.0 - ISC
|
|
297
|
+
*
|
|
298
|
+
* This source code is licensed under the ISC license.
|
|
299
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
300
|
+
*/const Rn=re("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/**
|
|
301
|
+
* @license lucide-react v0.469.0 - ISC
|
|
302
|
+
*
|
|
303
|
+
* This source code is licensed under the ISC license.
|
|
304
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
305
|
+
*/const bd=re("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/**
|
|
306
|
+
* @license lucide-react v0.469.0 - ISC
|
|
307
|
+
*
|
|
308
|
+
* This source code is licensed under the ISC license.
|
|
309
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
310
|
+
*/const Ze=re("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
|
|
311
|
+
* @license lucide-react v0.469.0 - ISC
|
|
312
|
+
*
|
|
313
|
+
* This source code is licensed under the ISC license.
|
|
314
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
315
|
+
*/const yd=re("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/**
|
|
316
|
+
* @license lucide-react v0.469.0 - ISC
|
|
317
|
+
*
|
|
318
|
+
* This source code is licensed under the ISC license.
|
|
319
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
320
|
+
*/const wd=re("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function vd(t){const e=t.trim().split(`
|
|
321
|
+
`);if(e.length<2)return!1;const r=e[0].trim();if(!r.startsWith("|")||(r.match(/\|/g)||[]).length<2)return!1;const n=e[1].trim();if(!n.startsWith("|")||!/^[\s|:|-]+$/.test(n)||!n.includes("-"))return!1;for(let s=2;s<e.length;s++){const a=e[s].trim();if(a!==""&&!a.startsWith("|"))return!1}return!0}function kd(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,r,n,s,a)=>vd(s)?`${r}
|
|
322
|
+
${s.trim()}
|
|
323
|
+
${a}`:e)}function Sd(t){const e={};let r=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(n,s)=>{const a=`__DISPLAY_MATH_${r++}__`;return e[a]=`$$${s}$$`,a}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(n,s)=>{const a=`__DISPLAY_MATH_${r++}__`;return e[a]=`$$${s}$$`,a}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(n,s)=>{const a=`__INLINE_MATH_${r++}__`;return e[a]=`$${s}$`,a}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(n,s,a,o,l,c)=>{const d=`__FENCED_CODE_${r++}__`;return e[d]=`${s}${a}${o}
|
|
324
|
+
${l}
|
|
325
|
+
${a}${c}`,d}),t=t.replace(/`([^`]+)`/g,n=>{const s=`__INLINE_CODE_${r++}__`;return e[s]=n,s}),{masked:t,masks:e}}function jd(t){const e={};let r=0;return t=t.replace(new RegExp("(?<!\\$)\\$(?!\\$)([^$\\n]+?)(?<!\\$)\\$(?!\\$)","g"),(n,s)=>{const a=s.trim();if(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:\s?[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion)?$/.test(a))return n;const l=`__INLINE_MATH_${r++}__`;return e[l]=`$${s}$`,l}),{masked:t,masks:e}}const La=/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b/;function Cd(t){const e=/(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)/g,r=/^(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)$/;return t.split(`
|
|
326
|
+
`).map(n=>La.test(n)?n.split(e).map(s=>!s||r.test(s)||!La.test(s)||s.includes("$")?s:s.replace(/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b[^\n]*/g,a=>{const o=a.trimEnd();return o?`$${o}$${a.slice(o.length)}`:a})).join(""):n).join(`
|
|
327
|
+
`)}function Ad(t){return t.replace(/\$([^$\n]*?)\s*=\s*\$([^$\n]+)\$\s*([^$\n]*?)\$/g,(e,r,n,s)=>{const a=String(r).trimEnd(),o=String(n).trim(),l=String(s).trim(),c=[o,l].filter(Boolean).join(" ");return`$${a} = ${c}$`})}function Nd(t){const e=t.split(`
|
|
328
|
+
`);for(let n=0;n<e.length-1;n++){const s=e[n],a=e[n+1]??"";if(!s||!a)continue;const o=a.trim();if(!(o.startsWith("|")&&o.includes("-")))continue;const c=s.indexOf("|");if(c<=0)continue;const d=s.slice(0,c);if(!d||d.trim()==="")continue;const u=d.trim(),f=u.replace(/\s+/g,""),p=f!==""&&/^[>]+$/.test(f),g=/^[-*+]\s*$/.test(u),m=/^\d+\.\s*$/.test(u);if(p||g||m)continue;const x=s.slice(c);if((x.match(/\|/g)||[]).length<2)continue;const v=d.replace(/\s+$/,""),A=x.replace(/^\s+/,"");v&&(e.splice(n,1,v,A),n++)}const r=[];for(let n=0;n<e.length;n++){const s=e[n],a=s.trim(),l=(e[n+1]??"").trim();a.startsWith("|")&&(a.match(/\|/g)||[]).length>=2&&l.startsWith("|")&&/^[\s|:-]+$/.test(l)&&l.includes("-")&&r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push(s)}return r.join(`
|
|
329
|
+
`)}const Ea=["aligned","align","align*","array","cases","pmatrix","bmatrix","vmatrix","Vmatrix","matrix","smallmatrix","gather","gather*","multline","multline*","split","flalign","flalign*","eqnarray","equation","equation*"];function Id(t,e){let r=0,n=`__${e}_${r}__`;for(;Object.prototype.hasOwnProperty.call(t,n);)r++,n=`__${e}_${r}__`;return n}function Ld(t,e){if(!Ea.length)return t;const r=Ea.join("|"),n=new RegExp(String.raw`\\begin\{(${r})\}([\s\S]*?)\\end\{\1\}`,"g");return t.replace(n,(s,a,o,l,c)=>{const d=c.slice(0,l),u=c.slice(l+s.length),f=/(\$\$|\\\[)\s*$/.test(d),p=/^\s*(\$\$|\\\])/.test(u);if(f&&p)return s;const g=d.lastIndexOf("\\["),m=d.lastIndexOf("\\]");if(g>m&&g!==-1&&/\\]/.test(u))return s;const y=/\$\$/g;let v=0;for(;y.exec(d)!==null;)v++;if(v%2===1&&/\$\$/.test(u))return s;if((d.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__").match(/\$/g)||[]).length%2===1){const k=u.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__");if(/^[^$]*\$(?!\$)/.test(k))return s}const _=Id(e,"LATEX_ENV"),b=s.trim();return e[_]=`
|
|
330
|
+
$$
|
|
331
|
+
${b}
|
|
332
|
+
$$
|
|
333
|
+
`,_})}function Ed(t,e){for(const[r,n]of Object.entries(e)){const s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");t=t.replace(s,()=>n)}return t}const _d=t=>{if(!t||typeof t!="string")return"";try{let e=t.replace(/\r\n/g,`
|
|
334
|
+
`).replace(/\r/g,`
|
|
335
|
+
`);e=kd(e);const{masked:r,masks:n}=Sd(e);e=r,e=e.replace(/<br\s*\/?>/gi,`
|
|
336
|
+
`),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=Ad(e),e=Nd(e),e=Ld(e,n);const s=new Map;let a=0;const o=String.raw`-?\$\(?\d{1,3}(?:,\d{3})*(?:\.\d+)?\)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?|\$-?\d+(?:\.\d+)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?`,l=new RegExp(String.raw`(${o})(\s?[–-]\s?)(${o})`,"g");e=e.replace(l,(p,g,m,x)=>{const y=`__CURRENCY_${a++}__`,v=`__CURRENCY_${a++}__`;return s.set(y,g),s.set(v,x),`${y}${m}${v}`});const c=new RegExp(String.raw`-?\$\(?\d{1,3}(?:,\d{3})*(?:\.\d+)?\)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)|\$-?\d+(?:\.\d+)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)`,"g");e=e.replace(c,(p,g,m)=>{if(m.substring(g+p.length).match(/^[a-zA-Z]/)&&!p.match(/[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion$/))return p;const y=`__CURRENCY_${a++}__`;return s.set(y,p),y});const{masked:d,masks:u}=jd(e);return e=d,Object.assign(n,u),e=Cd(e),[/(?:^|\s)([a-zA-Z0-9]+\s*[\^_]\s*[a-zA-Z0-9{}]+(?:\s*[+\-*/]\s*[a-zA-Z0-9]+\s*[\^_]\s*[a-zA-Z0-9{}]+)*\s*=\s*[^$\n]+)(?:\s|$)/g,/(?:^|\s)(\\frac\{[^}]+\}\{[^}]+\})(?:\s|$)/g,/(?:^|\s)(\\(?:sqrt|int|sum|prod|lim|log|ln|sin|cos|tan|exp)\b[^$\n]{0,50})(?:\s|$)/g,/(?:^|\s)([A-Z][a-z]?(?:\d+)?(?:\([A-Z][a-z]?(?:\d+)?\))?(?:\d+)?(?:[+-]\d*)?)+(?:\s|$)/g].forEach(p=>{e=e.replace(p,(g,m)=>{if(g.includes("$")||g.includes("__INLINE_MATH_")||g.includes("__DISPLAY_MATH_")||g.includes("__CURRENCY_"))return g;const x=String(m??"").trim();if(/^[A-Za-z]$/.test(x))return g;const y=/[\\^_+=<>]|\\b(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)\b/.test(x),v=/\d/.test(x),A=/[()]/.test(x),N=(x.match(/[A-Z]/g)||[]).length,C=(x.match(/[a-z]/g)||[]).length,S=N>=2,E=v||A||S&&C>0;return!y&&!E?g:g.replace(m,`$${m}$`)})}),e=e.replace(new RegExp("(?<!\\\\)\\$(?!\\$)([^$\\n]*?)(?<!\\\\)\\$(?!\\$)","g"),(p,g)=>{if(p.includes("__CURRENCY_")||p.includes("__INLINE_MATH_")||p.includes("__DISPLAY_MATH_")||g.trim()==="")return p;const m=/^\d+(?:,\d{3})*(?:\.\d{2})?$/.test(g.trim()),x=/\\/.test(g),y=/[+\-*/=<>^_{}()]/.test(g),v=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(g),A=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(g),N=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(g),C=/^[A-Za-z]$/.test(g.trim());return!m&&(x||y||v||A||N||C||g.length>1)?p:`\\$${g}\\$`}),e=e.split(`
|
|
337
|
+
`).map(p=>{const g=p.indexOf("$$");return g===-1||p.trim()==="$$"||p.indexOf("$$",g+2)!==-1?p:p.replace("$$","\\$\\$")}).join(`
|
|
338
|
+
`),s.forEach((p,g)=>{const m=p.replace(/\$/g,"$");e=e.replace(new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),m)}),e=e.replace(/\\$/g,"$"),e=Ed(e,n),e=e.trimEnd()+`
|
|
339
|
+
`,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},Td=h.lazy(()=>Nt(()=>import("./MermaidRenderer-BMEgBeqY.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),Md=h.lazy(()=>Nt(()=>import("./SVGRenderer-BtiY9l8o.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),Fd=h.lazy(()=>Nt(()=>import("./ChartRenderer-wxEbPd5g.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),$d=h.lazy(()=>Nt(()=>import("./MusicRenderer-BMwa1p8w.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),Rd=t=>{var n,s;if(!t)return typeof window<"u"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light";const e=t.closest(".markdown-content");if(e){if(e.classList.contains("dark"))return"dark";if(e.classList.contains("light"))return"light"}if(t.closest(".dark"))return"dark";if(t.closest(".light"))return"light";const r=t.closest("[data-theme]");if(r){const a=r.getAttribute("data-theme");if(a==="dark")return"dark";if(a==="light")return"light"}return typeof window<"u"&&((s=window.matchMedia)!=null&&s.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Pd=(t,e)=>{const[r,n]=h.useState("light"),s=h.useRef("light");return h.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const a=()=>{const p=Rd(t.current);p!==s.current&&(s.current=p,n(p))};a();const o=((d=window.matchMedia)==null?void 0:d.call(window,"(prefers-color-scheme: dark)"))??null,l=()=>a();o==null||o.addEventListener("change",l);const c=typeof MutationObserver<"u"?new MutationObserver(()=>a()):null;if(c){const p=((f=(u=t.current)==null?void 0:u.closest)==null?void 0:f.call(u,".markdown-content"))??null;p&&c.observe(p,{attributes:!0,attributeFilter:["class","data-theme"]}),document.body&&c.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]})}return()=>{o==null||o.removeEventListener("change",l),c==null||c.disconnect()}},[e,t]),e??r},Dd={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"tsx",sh:"bash",shell:"bash",shellsession:"bash",yml:"yaml",yaml:"yaml",py:"python",rb:"ruby",kt:"kotlin",md:"markdown",csharp:"csharp","c#":"csharp","c++":"cpp",tf:"hcl",terraform:"hcl",docker:"dockerfile",dotenv:"env",env:"env",plaintext:"text",text:"text"},Ud=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const n=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return n?Dd[n]??n:""},Od=t=>pt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),_a=({code:t})=>{const{t:e}=Le(),[r,n]=h.useState(!1),s=async()=>{try{await navigator.clipboard.writeText(t),n(!0),setTimeout(()=>n(!1),2e3)}catch{const a=document.createElement("textarea");a.value=t,a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.select();try{document.execCommand("copy"),n(!0),setTimeout(()=>n(!1),2e3)}catch(o){console.error("Failed to copy code:",o)}document.body.removeChild(a)}};return i.jsxs("button",{className:"code-copy-button",onClick:s,title:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[r?i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M13.5 4.5L6 12L2.5 8.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):i.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M5.5 4.5H3.5C2.94772 4.5 2.5 4.94772 2.5 5.5V12.5C2.5 13.0523 2.94772 13.5 3.5 13.5H10.5C11.0523 13.5 11.5 13.0523 11.5 12.5V10.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),i.jsx("path",{d:"M6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),i.jsx("path",{d:"M9.5 6.5L13.5 2.5L9.5 2.5V6.5Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),i.jsx("span",{className:"code-copy-button-text",children:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},zd=({inline:t,className:e="",children:r,enableGraphs:n=!0,enableMermaid:s=!0,enableSVG:a=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Le(),f=h.useRef(null),p=Pd(f,d),g=i.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return i.jsx("code",{className:e,children:r});const m=Ud(e),x=Od(r);if(o&&(m==="chart"||m==="chart-json"||m==="chart-table"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx(Fd,{code:x,language:m})})});if(l&&(m==="abc"||m==="music"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx($d,{code:x})})});if(n){if(m==="mermaid"&&s)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx(Td,{code:x})})});if(m==="svg"&&a)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx(Md,{code:x})})})}if(c&&m){const y=p==="light"?Zo:Jo;return i.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[i.jsx(_a,{code:x}),i.jsx(Qo,{language:m,style:y,customStyle:{margin:"12px 0",borderRadius:"6px",fontSize:"0.9em"},showLineNumbers:!1,children:x})]})}return i.jsxs("div",{ref:f,className:`markdown-code-block code-block-container ${e}`.trim(),children:[i.jsx(_a,{code:x}),i.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:i.jsx("code",{children:x})})]})},Ta=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),Ma=({children:t,href:e="",className:r="",standalone:n=!1,...s})=>{const a=pt.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&a&&Fa(a)===Fa(e)),c=o?Bd(e):null,d=!!(n&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",r].filter(Boolean).join(" ");return i.jsxs("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",className:u,children:[i.jsx("span",{className:"markdown-link__content",children:d&&c?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"markdown-link__hostname",children:c.hostname}),c.path&&c.path!=="/"&&i.jsx("span",{className:"markdown-link__path",children:c.path})]}):t}),o&&i.jsx("span",{className:"markdown-link__icon","aria-hidden":"true",children:i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M8 16L16 8M16 8H9M16 8V15",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})})})]})};function Fa(t){return t.trim().replace(/\/$/,"")}function Bd(t){try{const e=new URL(t),r=e.hostname.replace(/^www\./i,""),n=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:r,path:n}}catch{return null}}const $t=({content:t,className:e="",disableMath:r=!1,enableGraphs:n=!0,enableMermaid:s=!0,enableSVG:a=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=_d(t);if(!u)return null;const f=r?[aa]:[aa,[Xo,{singleDollarTextMath:!0}]],p=[];r||p.push([Yo,{throwOnError:!1,errorColor:"#cc0000",strict:!1,trust:!0,macros:{"\\RR":"\\mathbb{R}","\\NN":"\\mathbb{N}","\\ZZ":"\\mathbb{Z}","\\QQ":"\\mathbb{Q}","\\CC":"\\mathbb{C}","\\dx":"\\,dx","\\dy":"\\,dy","\\dt":"\\,dt","\\dz":"\\,dz"}}]);const g={table:({children:m,...x})=>i.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:i.jsx("table",{...x,children:m})}),a:Ma,code:m=>{const{className:x,children:y,...v}=m,A=x&&/language-/.test(x),N="inline"in m&&typeof m.inline=="boolean"&&m.inline||!A,C=A;return i.jsx(zd,{inline:N,className:x,enableGraphs:n,enableMermaid:s,enableSVG:a,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":C?"true":void 0,...v,children:y})},p:({node:m,...x})=>{var C;const y=pt.Children.toArray(x.children).filter(S=>!(typeof S=="string"&&S.trim()==="")),v=y.some(S=>{if(!pt.isValidElement(S))return!1;const E=S.props;return(E==null?void 0:E["data-block-code"])==="true"?!0:typeof S.type=="string"?Ta.has(S.type):!1}),A=(C=m==null?void 0:m.children)==null?void 0:C.some(S=>{var E;if(S.type==="code")return!0;if(S.type==="element"){if(S.tagName&&Ta.has(S.tagName))return!0;if(S.tagName==="code"){const _=(E=S.properties)==null?void 0:E.className;return Array.isArray(_)?_.some(b=>typeof b=="string"&&b.startsWith("language-")):!0}}return!1});if(v||A)return i.jsx(i.Fragment,{children:x.children});if(y.length===1&&pt.isValidElement(y[0])&&y[0].type===Ma){const S=y[0];return i.jsx("p",{...x,children:pt.cloneElement(S,{standalone:!0})})}return i.jsx("p",{...x})}};return i.jsx("div",{className:`markdown-content ${e}`,children:i.jsx(Go,{remarkPlugins:f,rehypePlugins:p,components:g,children:u})})},Pn=()=>Y.debug.consoleDebug,U=(...t)=>{Pn()&&console.log(...t)},me=(...t)=>{Pn()&&console.warn(...t)},ge=(...t)=>{Pn()&&console.error(...t)},ze=(...t)=>{console.error(...t)};function $a(t){return t==="mp3"?"audio/mpeg":t==="wav"?"audio/wav":t==="ogg"?"audio/ogg":t==="opus"?"audio/opus":t==="webm"?"audio/webm":`audio/${t}`}function ns({audio:t,audioUrl:e,audioFormat:r="mp3",autoPlay:n=!1,maxSizeMB:s=10,downloadFilename:a}){const{t:o}=Le(),{isDark:l}=tr(),c=h.useRef(null),[d,u]=h.useState(!1),[f,p]=h.useState(0),[g,m]=h.useState(0),[x,y]=h.useState(!0),[v,A]=h.useState(null),[N,C]=h.useState(null),[S,E]=h.useState(null);h.useEffect(()=>{if(!t)return;let L=null,O=!0;return(async()=>{try{y(!0),A(null),C(null);const G=t.length*3/4/(1024*1024);if(G>s)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:G.toFixed(1),maxMB:s}));if(G>2&&(C(o("audio.player.largeAudioWarning",{sizeMB:G.toFixed(1)})),U("[AudioPlayer] Large audio file detected",{sizeMB:G.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(o("audio.player.invalidBase64Error"));const q=atob(t),Q=new Uint8Array(q.length);for(let ee=0;ee<q.length;ee++)Q[ee]=q.charCodeAt(ee);const he=$a(r),z=new Blob([Q],{type:he});if(L=URL.createObjectURL(z),!O){L&&URL.revokeObjectURL(L);return}E(L),y(!1),U("[AudioPlayer] Audio loaded successfully",{format:r,mimeType:he,size:z.size})}catch(X){ge("[AudioPlayer] Failed to load audio:",X),O&&(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{O=!1,L&&URL.revokeObjectURL(L)}},[t,r,s,o]),h.useEffect(()=>{if(t||!e)return;let L=null,O=!1;return(async()=>{try{y(!0),A(null);const X=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,G=await fetch(e,{headers:X?{"X-Adapter-Name":X}:{}});if(!G.ok)throw new Error(`Server returned ${G.status}`);if(O)return;const q=await G.arrayBuffer();if(O)return;const Q=new Blob([q],{type:$a(r)});L=URL.createObjectURL(Q),E(L),y(!1)}catch(X){ge("[AudioPlayer] Failed to fetch audio from",e,X),O||(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{O=!0,L&&URL.revokeObjectURL(L)}},[t,e,r,o]),h.useEffect(()=>{n&&S&&c.current&&c.current.play().catch(L=>{ge("[AudioPlayer] Auto-play failed:",L)})},[n,S]);const _=()=>{c.current&&p(c.current.duration)},b=()=>{c.current&&m(c.current.currentTime)},T=()=>u(!0),k=()=>u(!1),I=()=>{u(!1),m(0)},P=()=>{c.current&&(d?c.current.pause():c.current.play().catch(L=>{ge("[AudioPlayer] Playback failed:",L),A(o("audio.player.playbackFailureError"))}))},M=L=>{if(!c.current)return;const O=parseFloat(L.target.value);c.current.currentTime=O,m(O)},B=()=>{if(!S)return;const L=document.createElement("a");L.href=S,L.download=a||`generated-audio.${r}`,L.click()},j=L=>{if(!isFinite(L))return"0:00";const O=Math.floor(L/60),F=Math.floor(L%60);return`${O}:${F.toString().padStart(2,"0")}`};return v?i.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-700 dark:bg-red-900/20 dark:text-red-400",children:[i.jsx(Rn,{className:"h-4 w-4"}),i.jsx("span",{children:v})]}):i.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[N&&i.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",N]}),i.jsxs("div",{className:"flex items-center gap-3 rounded-md border border-gray-200 bg-white/80 px-3 py-2 dark:border-[#3b3c49] dark:bg-white/5",children:[i.jsx("audio",{ref:c,src:S??void 0,onLoadedMetadata:_,onTimeUpdate:b,onPlay:T,onPause:k,onEnded:I}),i.jsx("button",{onClick:P,disabled:x,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:o(d?"audio.player.pauseTitle":"audio.player.playTitle"),"aria-label":o(d?"audio.player.pauseAriaLabel":"audio.player.playAriaLabel"),children:x?i.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}):d?i.jsx(cd,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):i.jsx(dd,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})}),i.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(g)}),i.jsx("input",{type:"range",min:"0",max:f||0,value:g,onChange:M,disabled:x||!f,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:(()=>{const L=l?"rgb(191 194 205)":"rgb(75 85 99)",O=l?"rgba(255 255 255 / 0.12)":"rgb(229 231 235)",F=f?g/f*100:0;return`linear-gradient(to right, ${L} 0%, ${L} ${F}%, ${O} ${F}%, ${O} 100%)`})()}}),i.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(f)})]}),a&&i.jsx("button",{onClick:B,disabled:x||!S,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:o("audio.player.downloadAudioTooltip"),children:i.jsx(_s,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function Ra({image:t,imageUrl:e,imageFormat:r="png",revisedPrompt:n}){const{t:s}=Le(),[a,o]=h.useState(!1),[l,c]=h.useState(!1),[d,u]=h.useState(null),f=h.useRef(null);h.useEffect(()=>{if(t||!e)return;let x=!1;return(async()=>{try{const y=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,v=await fetch(e,{headers:y?{"X-Adapter-Name":y}:{}});if(!v.ok){console.warn("[ImageDisplay] Server returned",v.status,"for",e);return}if(x)return;const A=await v.arrayBuffer();if(x)return;const N=new Blob([A],{type:`image/${r}`}),C=URL.createObjectURL(N);f.current=C,u(C)}catch(y){console.warn("[ImageDisplay] Failed to fetch image from",e,y)}})(),()=>{x=!0,f.current&&(URL.revokeObjectURL(f.current),f.current=null)}},[e,t,r]);const g=(t?`data:image/${r};base64,${t}`:null)??d;h.useEffect(()=>{if(!a)return;const x=y=>{y.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[a]);const m=x=>{if(x.stopPropagation(),!g)return;const y=document.createElement("a");y.href=g,y.download=`generated-image.${r}`,y.click()};return g?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"generated-image-wrapper",style:{marginTop:"0.75rem"},children:[i.jsxs("div",{className:"generated-image-container",style:{position:"relative",display:"inline-block",cursor:"zoom-in",maxWidth:"100%"},onClick:()=>o(!0),title:n||s("imageDisplay.generatedImageTitle"),children:[i.jsx("img",{src:g,alt:n||s("imageDisplay.generatedImageAlt"),style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",objectFit:"contain"}}),i.jsxs("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[i.jsx("button",{onClick:m,title:s("imageDisplay.downloadImageTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(_s,{size:14})}),i.jsx("button",{onClick:x=>{x.stopPropagation(),o(!0)},title:s("imageDisplay.viewFullSizeTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(wd,{size:14})})]})]}),n&&i.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[i.jsxs("button",{type:"button",onClick:()=>c(x=>!x),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:0,background:"transparent",border:"none",cursor:"pointer",fontSize:"0.75rem",fontWeight:500,opacity:.72},"aria-expanded":l,children:[l?i.jsx(bs,{size:14}):i.jsx(hr,{size:14}),s(l?"imageDisplay.hidePrompt":"imageDisplay.showPrompt")]}),l&&i.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[i.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:s("imageDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),a&&typeof document<"u"&&As.createPortal(i.jsxs("div",{onClick:()=>o(!1),style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.85)",zIndex:9999,overflow:"auto",padding:"56px 24px 24px"},children:[i.jsx("button",{onClick:x=>{x.stopPropagation(),o(!1)},style:{position:"fixed",top:"16px",right:"16px",background:"rgba(255,255,255,0.15)",border:"none",borderRadius:"50%",padding:"8px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(Ze,{size:20})}),i.jsx("img",{src:g,alt:n||s("imageDisplay.generatedImageAlt"),style:{display:"block",width:"auto",height:"auto",maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 80px)",objectFit:"contain",borderRadius:"8px",margin:"0 auto"},onClick:x=>x.stopPropagation()})]}),document.body)]}):null}const en=[750,1500,3e3,5e3],Hd=new Set([403,404,409,425,429,500,502,503,504]),Vd=t=>new Promise(e=>setTimeout(e,t));function Pa({video:t,videoUrl:e,videoFormat:r="mp4",revisedPrompt:n,adapterName:s}){const{t:a}=Le(),[o,l]=h.useState(!1),[c,d]=h.useState(!1),[u,f]=h.useState(null),p=h.useRef(null);h.useEffect(()=>{if(t||!e)return;let y=!1;return(async()=>{try{const v=s||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let A=null;for(let E=0;E<=en.length&&(A=await fetch(e,{headers:v?{"X-Adapter-Name":v}:{}}),!(A.ok||!Hd.has(A.status)||E===en.length));E+=1)if(await Vd(en[E]),y)return;if(!A||!A.ok){console.warn("[VideoDisplay] Server returned",A==null?void 0:A.status,"for",e);return}if(y)return;const N=await A.arrayBuffer();if(y)return;const C=new Blob([N],{type:`video/${r}`}),S=URL.createObjectURL(C);p.current=S,f(S)}catch(v){console.warn("[VideoDisplay] Failed to fetch video from",e,v)}})(),()=>{y=!0,p.current&&(URL.revokeObjectURL(p.current),p.current=null)}},[e,t,r,s]);const m=(t?`data:video/${r};base64,${t}`:null)??u;h.useEffect(()=>{if(!o)return;const y=v=>{v.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);const x=y=>{if(y.stopPropagation(),!m)return;const v=document.createElement("a");v.href=m,v.download=`generated-video.${r}`,v.click()};return m?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"generated-video-wrapper",style:{marginTop:"0.75rem"},children:[i.jsxs("div",{style:{position:"relative",display:"inline-block",maxWidth:"100%"},children:[i.jsx("video",{src:m,controls:!0,style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",backgroundColor:"#000"}}),i.jsxs("div",{style:{position:"absolute",bottom:"48px",right:"8px",display:"flex",gap:"6px"},children:[i.jsx("button",{onClick:x,title:a("videoDisplay.downloadVideoTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(_s,{size:14})}),i.jsx("button",{onClick:y=>{y.stopPropagation(),l(!0)},title:a("videoDisplay.viewFullSizeTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(Jc,{size:14})})]})]}),n&&i.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[i.jsxs("button",{type:"button",onClick:()=>d(y=>!y),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:0,background:"transparent",border:"none",cursor:"pointer",fontSize:"0.75rem",fontWeight:500,opacity:.72},"aria-expanded":c,children:[c?i.jsx(bs,{size:14}):i.jsx(hr,{size:14}),a(c?"videoDisplay.hidePrompt":"videoDisplay.showPrompt")]}),c&&i.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[i.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:a("videoDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),o&&i.jsxs("div",{onClick:()=>l(!1),style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.9)",zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center"},children:[i.jsx("button",{onClick:y=>{y.stopPropagation(),l(!1)},style:{position:"fixed",top:"16px",right:"16px",background:"rgba(255,255,255,0.15)",border:"none",borderRadius:"50%",padding:"8px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(Ze,{size:20})}),i.jsx("video",{src:m,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:y=>y.stopPropagation()})]})]}):null}let ys=null;function Bi(t){ys=t}function Ts(){ys=null}async function Dn(){if(!ys)return null;try{return await ys()}catch{return null}}let yn=!1,Pr=null;const wn=new Set;function Hi(){wn.forEach(t=>t())}function wt(){return yn}function qd(){return Pr}function Ms(t){yn!==t&&(yn=t,!t&&Pr!==null&&(Pr=null),Hi())}function fr(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Pr!==e&&(Pr=e,Hi())}function Wd(t){return wn.add(t),()=>{wn.delete(t)}}const Da="orbitchat-guest-user-id";function as(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function Kd(t){const e=t.split(".");if(e.length<2)return null;try{const r=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"="),s=atob(n);return JSON.parse(s)}catch{return null}}function Gd(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`guest:orbitchat:${t.randomUUID()}`;if(!t||typeof t.getRandomValues!="function")throw new Error("Secure random number generation is unavailable");const e=new Uint8Array(16);return t.getRandomValues(e),`guest:orbitchat:${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}function Xd(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Da);if(t&&t.trim().length>0)return t;const e=Gd();return window.localStorage.setItem(Da,e),e}async function Vi(){const t=qd();if(t)return t;const e=await Dn();if(e){const r=Kd(e),n=as(r==null?void 0:r.sub)||as(r==null?void 0:r.user_id)||as(r==null?void 0:r.preferred_username)||as(r==null?void 0:r.email);if(n)return n}return wt()?"authenticated:orbitchat:unknown":Xd()}const Yd={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",md:"text/markdown",csv:"text/csv"},Ua={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},ps=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,Qd=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function Zd(t){var r;return ps.test(t)?`•${((r=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:r[0])||"\\9"}`:null}function Oa(t){Array.from(t.querySelectorAll("style")).forEach(n=>{const s=n.textContent;!s||!ps.test(s)||(n.textContent=s.replace(Qd,(a,o,l,c)=>{const d=Zd(l);if(!d)return a;const u=c.replace(/\s*font-family\s*:\s*[^;{}]+;?/gi,"");return`${o}content: "${d}";${u}`}))}),Array.from(t.querySelectorAll('span[style*="font-family"]')).forEach(n=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(n.style.fontFamily))return;const s=n.textContent||"";ps.test(s)&&(n.textContent=s.replace(ps,"•"),n.style.fontFamily="")})}function Jd(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function eu(t){const e=window.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r.buffer}function tu(t){return t==="xlsx"||t==="csv"?i.jsx(Fi,{className:"h-5 w-5"}):t==="pptx"?i.jsx(Di,{className:"h-5 w-5"}):t==="md"?i.jsx(Mi,{className:"h-5 w-5"}):i.jsx(bn,{className:"h-5 w-5"})}function za({document:t,documentUrl:e,documentFormat:r="pdf",revisedPrompt:n,adapterName:s}){const{t:a}=Le(),o=Jd(r),[l,c]=h.useState(t||e?"loading":"idle"),[d,u]=h.useState(null),[f,p]=h.useState(null),[g,m]=h.useState([]),[x,y]=h.useState(""),[v,A]=h.useState(null),[N,C]=h.useState([]),[S,E]=h.useState(0),[_,b]=h.useState(!1),[T,k]=h.useState(null),I=h.useRef(null),P=h.useRef(null),M=h.useRef(null),B=n||Ua[o]||a("documentDisplay.generatedDocument"),j=h.useMemo(()=>`generated-document.${o}`,[o]),L=Yd[o]||"application/octet-stream";h.useEffect(()=>{if(!t&&!e)return;let G=!1;return(async()=>{c("loading"),k(null),m([]),y(""),A(null),C([]),E(0);try{const Q=t?eu(t):await(async()=>{const ee=(s==null?void 0:s.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),ce={"X-User-ID":await Vi()};ee&&(ce["X-Adapter-Name"]=ee);const V=await Dn();V&&(ce.Authorization=`Bearer ${V}`);const J=await fetch(e,{headers:ce});if(!J.ok)throw new Error(`Server returned ${J.status}`);return J.arrayBuffer()})();if(G)return;const he=new Blob([Q],{type:L}),z=URL.createObjectURL(he);if(I.current&&URL.revokeObjectURL(I.current),I.current=z,u(z),p(Q.slice(0)),o==="xlsx"){const{default:ee}=await Nt(async()=>{const{default:J}=await import("./index-CZz_ECqk.js");return{default:J}},[]),V=(await ee(he))[0];y((V==null?void 0:V.sheet)||"First sheet"),m(((V==null?void 0:V.data)||[]).slice(0,100).map(J=>J.slice(0,30).map(fe=>fe==null?"":String(fe))))}if(o==="md"&&A(new TextDecoder("utf-8").decode(Q)),o==="csv"){const ee=new TextDecoder("utf-8").decode(Q),{default:ce}=await Nt(async()=>{const{default:J}=await import("./papaparse.min-D13ujVVP.js").then(fe=>fe.p);return{default:J}},__vite__mapDeps([19,1])),V=ce.parse(ee,{skipEmptyLines:!0});E(V.data.length),C(V.data.slice(0,25))}c("ready")}catch(Q){if(G)return;console.warn("[DocumentDisplay] Failed to load document from",e,Q),k(Q instanceof Error?Q.message:"Unable to load document"),c("error")}})(),()=>{G=!0,I.current&&(URL.revokeObjectURL(I.current),I.current=null)}},[s,t,e,o,L]),h.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!P.current)return;const G=P.current;G.replaceChildren(),Nt(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:q})=>{await q(f.slice(0),G,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Oa(G)}).catch(q=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",q),k("Unable to render document preview")})},[f,o,l]),h.useEffect(()=>{if(!_||o!=="docx"||!f||!M.current)return;const G=M.current;G.replaceChildren(),Nt(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:q})=>{await q(f.slice(0),G,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Oa(G)}).catch(q=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",q)})},[f,o,_]),h.useEffect(()=>{if(!_)return;const G=q=>{q.key==="Escape"&&b(!1)};return window.document.addEventListener("keydown",G),()=>window.document.removeEventListener("keydown",G)},[_]);const O=G=>{if(G==null||G.stopPropagation(),!d)return;const q=window.document.createElement("a");q.href=d,q.download=j,q.click()},F=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),X=F&&o!=="xlsx"&&o!=="csv";return l==="idle"?null:i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mt-3 max-w-full overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm dark:border-[#3b3c49] dark:bg-[#202123]",children:[i.jsxs("div",{className:"flex items-center gap-3 border-b border-gray-100 px-3 py-2.5 dark:border-[#3b3c49]",children:[i.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-300",children:tu(o)}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:B}),i.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[Ua[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${a("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${T||a("documentDisplay.previewUnavailableShort")}`:""]})]}),X&&i.jsx("button",{type:"button",onClick:()=>b(!0),className:"rounded-md p-2 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:a("documentDisplay.openPreviewTooltip"),"aria-label":a("documentDisplay.openPreviewTooltip"),children:i.jsx(Vc,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:O,disabled:!d,className:"rounded-md p-2 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:a("documentDisplay.downloadDocumentTooltip"),"aria-label":a("documentDisplay.downloadDocumentTooltip"),children:i.jsx(_s,{className:"h-4 w-4"})})]}),F&&i.jsxs("div",{className:"max-h-[460px] overflow-auto bg-gray-50 dark:bg-[#171717]",children:[o==="pdf"&&d&&i.jsx("iframe",{src:d,title:B,className:"block h-[460px] w-full border-0 bg-white"}),o==="docx"&&i.jsx("div",{ref:P,className:"min-h-[240px] bg-white p-5 text-sm text-[#111827] dark:bg-white dark:text-[#111827]"}),o==="xlsx"&&i.jsxs("div",{className:"p-3",children:[x&&i.jsx("p",{className:"mb-2 text-xs font-medium text-gray-500 dark:text-[#bfc2cd]",children:x}),i.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:i.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:i.jsx("tbody",{children:g.length>0?g.map((G,q)=>i.jsx("tr",{className:q===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((Q,he)=>i.jsx("td",{className:"max-w-[220px] truncate border-b border-r border-gray-100 px-2 py-1.5 text-[#353740] dark:border-[#3b3c49] dark:text-[#ececf1]",children:Q},he))},q)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:a("documentDisplay.noSheetDataFound")})})})})})]}),o==="md"&&v!==null&&i.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:i.jsx($t,{content:v,disableMath:!0})}),o==="csv"&&i.jsxs("div",{className:"p-3",children:[S>25&&i.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:a("documentDisplay.csvRowsPreviewMessage",{count:S})}),i.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:i.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:i.jsx("tbody",{children:N.length>0?N.map((G,q)=>i.jsx("tr",{className:q===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((Q,he)=>i.jsx("td",{className:"max-w-[220px] truncate border-b border-r border-gray-100 px-2 py-1.5 text-[#353740] dark:border-[#3b3c49] dark:text-[#ececf1]",children:Q},he))},q)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:a("documentDisplay.noDataFound")})})})})})]})]}),l==="ready"&&!F&&i.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:a("documentDisplay.previewUnavailable")})]}),_&&d&&i.jsxs("div",{onClick:()=>b(!1),className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/85 p-4",children:[i.jsx("button",{onClick:G=>{G.stopPropagation(),b(!1)},className:"fixed right-4 top-4 flex items-center rounded-full border-0 bg-white/15 p-2 text-white",title:a("common.close"),"aria-label":a("common.close"),children:i.jsx(Ze,{className:"h-5 w-5"})}),i.jsxs("div",{onClick:G=>G.stopPropagation(),className:"h-[92vh] w-[92vw] overflow-auto rounded-lg bg-white",children:[o==="pdf"&&i.jsx("iframe",{src:d,title:B,className:"h-full w-full border-0"}),o==="docx"&&i.jsx("div",{ref:M,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&v!==null&&i.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:i.jsx($t,{content:v,disableMath:!0})})]})]})]})}const ru=["a[href]","area[href]",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(",");function Dr(t,{enabled:e,onEscape:r}){h.useEffect(()=>{if(!e||!t.current)return;const n=t.current,s=document.activeElement,a=Array.from(n.querySelectorAll(ru)).filter(d=>d.tabIndex!==-1),o=a[0]||n,l=a[a.length-1]||n;o.focus({preventScroll:!0});const c=d=>{if(d.key==="Escape"){r==null||r();return}if(d.key!=="Tab")return;if(a.length===0){d.preventDefault(),n.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!n.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!n.contains(u))&&(d.preventDefault(),o.focus({preventScroll:!0}))};return document.addEventListener("keydown",c),()=>{var d;document.removeEventListener("keydown",c),(d=s==null?void 0:s.focus)==null||d.call(s,{preventScroll:!0})}},[e,r,t])}function ws({isOpen:t,onClose:e,onConfirm:r,title:n,message:s,confirmText:a,cancelText:o,type:l="danger",isLoading:c=!1}){const d=h.useRef(null);Dr(d,{enabled:t,onEscape:e});const{t:u}=Le(),f=a??u("common.confirm"),p=o??u("common.cancel");if(!t)return null;const g=()=>{c||r()},x=(()=>{switch(l){case"danger":return{icon:"text-red-500",iconBg:"bg-red-100 dark:bg-red-900/20",confirmButton:"bg-red-600 hover:bg-red-700 focus:ring-red-500",border:"border-red-200 dark:border-red-800"};case"warning":return{icon:"text-amber-500",iconBg:"bg-amber-100 dark:bg-amber-900/20",confirmButton:"bg-amber-600 hover:bg-amber-700 focus:ring-amber-500",border:"border-amber-200 dark:border-amber-800"};default:return{icon:"text-blue-500",iconBg:"bg-blue-100 dark:bg-blue-900/20",confirmButton:"bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",border:"border-blue-200 dark:border-blue-800"}}})(),y=i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/60 p-4 backdrop-blur-sm animate-fadeIn",children:i.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"confirm-title",tabIndex:-1,className:"w-full max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto rounded-2xl bg-white shadow-2xl transform animate-fadeIn dark:bg-[#1a1b1e]",children:[i.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full ${x.iconBg} flex items-center justify-center`,children:i.jsx($n,{className:`w-5 h-5 ${x.icon}`})}),i.jsx("h2",{id:"confirm-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:n})]}),i.jsx("button",{type:"button",onClick:e,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors","aria-label":u("common.close"),children:i.jsx(Ze,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),i.jsx("div",{className:"p-6",children:i.jsx("p",{className:"text-gray-600 dark:text-gray-300 leading-relaxed",children:s})}),i.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-[#2d2f39] bg-gray-50 dark:bg-[#131416] rounded-b-2xl",children:[i.jsx("button",{type:"button",onClick:e,disabled:c,className:"px-4 py-3 md:py-2.5 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:p}),i.jsx("button",{type:"button",onClick:g,disabled:c,className:`px-4 py-3 md:py-2.5 text-white rounded-lg transition-all font-medium shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none ${x.confirmButton}`,children:c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}),u("confirmationModal.loadingLabel")]}):f})]})]})});return typeof document>"u"?y:As.createPortal(y,document.body)}const su=["#","*","`","[","]","(",")","{","}","|","<",">"],qi=t=>su.some(e=>t.includes(e));function Wi(t){if(!t||t.length<1e3)return!1;const e=/^[A-Za-z0-9+/=]+$/,r=t.replace(/\s+/g,"");if(r.length>1e4&&e.test(r)){const n=/\b(the|and|for|are|but|not|you|all|can|function|const|let|var|class|return|import|export|async|await|if|else|while|true|false|null|undefined|http|https|www|error|data|response|request|api|json|xml|html|css|js|py|java|cpp|def|print|console|log)\b/i.test(t),s=qi(t),a=/[-.,;:!?'"()]/.test(t);if(!n&&!s&&!a)return!0}return!!(r.length>5e4&&e.test(r)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const nu=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Ur(t){if(!t)return t;let e=t.replace(nu," ");if(Wi(e))return"";const r=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(r,n=>{const s=n.replace(/\s+/g,"");if(s.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(s)){const a=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(n),o=qi(n),l=/[-.,;:!?'"()]/.test(n);if(!a&&!o&&!l)return""}return n}),e}function vn(t,e=5e4){return!t||t.length<=e?t:Wi(t)?"":t.substring(0,e)+`
|
|
340
|
+
|
|
341
|
+
... (content truncated due to length)`}const au={maxFilesPerConversation:Y.limits.files.perConversation,maxFileSizeMB:Y.limits.files.maxSizeMB,maxTotalFiles:Y.limits.files.totalFiles,maxConversations:Y.limits.conversations.maxConversations,maxMessagesPerConversation:Y.limits.conversations.messagesPerConversation,maxMessagesPerThread:Y.limits.conversations.messagesPerThread,maxTotalMessages:Y.limits.conversations.totalMessages,maxMessageLength:Y.limits.messages.maxLength};function iu(t){const e=Y.guestLimits;switch(t){case"maxConversations":return e.conversations.maxConversations;case"maxMessagesPerConversation":return e.conversations.messagesPerConversation;case"maxMessagesPerThread":return e.conversations.messagesPerThread;case"maxTotalMessages":return e.conversations.totalMessages;case"maxFilesPerConversation":return e.files.perConversation;case"maxTotalFiles":return e.files.totalFiles;case"maxMessageLength":return e.messages.maxLength;case"maxFileSizeMB":return e.files.maxSizeMB;default:return}}const le=new Proxy(au,{get(t,e){if(tt()&&!wt()){const r=iu(e);if(r!==void 0)return r}return t[e]}});function pr(){return h.useSyncExternalStore(Wd,wt,wt)}class Ki extends Error{constructor(r,n){super(r);Qe(this,"status");Qe(this,"statusText");this.name="ApiRequestError",this.status=n.status,this.statusText=n.statusText}}async function Oe(t={}){const e={"X-User-ID":await Vi(),...t},r=await Dn();return r&&(e.Authorization=`Bearer ${r}`),e}function jt(t){return encodeURIComponent(t)}function ou(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function Lr(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const n=await t.json(),s=typeof n.detail=="string"&&n.detail.trim()||typeof n.error=="string"&&n.error.trim()||typeof n.message=="string"&&n.message.trim();if(s)return`${e}: ${s}`}else{const n=(await t.text()).trim();if(n)return`${e}: ${n}`}}catch{}return e}function Ba(t){if(!t.startsWith("data: "))return null;try{const e=JSON.parse(t.substring(6));return e.request_id&&!e.response&&!e.done?{text:"",done:!1,request_id:e.request_id}:{text:e.text||e.content||e.message||e.response||"",done:e.done||!1,request_id:e.request_id,audio:e.audio,audioFormat:e.audio_format||e.audioFormat,audio_chunk:e.audio_chunk,chunk_index:e.chunk_index,image:e.image,image_format:e.image_format,image_revised_prompt:e.image_revised_prompt,image_url:e.image_url,video:e.video,video_format:e.video_format,video_revised_prompt:e.video_revised_prompt,video_url:e.video_url,document:e.document,document_format:e.document_format,document_revised_prompt:e.document_revised_prompt,document_url:e.document_url,generated_audio_url:e.generated_audio_url,generated_audio_format:e.generated_audio_format,generated_audio_revised_prompt:e.generated_audio_revised_prompt,assistant_message_id:e.assistant_message_id,threading:e.threading}}catch{return null}}let is=null;function lu(){let t=null,e=null;const r=(s,a,o)=>{t=a||null,e=o||null},n=(s,a)=>({async*streamChat(o,l,c,d,u,f,p,g,m,x,y,v,A,N){var E,_;const C={messages:[{role:"user",content:o}],stream:l!==!1};c&&c.length>0&&(C.file_ids=c),d&&(C.thread_id=d),u&&(C.audio_input=u),f&&(C.audio_format=f),p&&(C.language=p),g!==void 0&&(C.return_audio=g),m&&(C.tts_voice=m),x&&(C.source_language=x),y&&(C.target_language=y),v&&(C.model=v),A&&(C.skill=A),N&&(C.regenerate_of_message_id=N);const S=await fetch("/api/v1/chat",{method:"POST",headers:await Oe({"Content-Type":"application/json","X-Adapter-Name":s,...a?{"X-Session-ID":a}:{}}),body:JSON.stringify(C)});if(!S.ok)throw new Error(await Lr(S));if((E=S.headers.get("content-type"))!=null&&E.includes("text/event-stream")){const b=(_=S.body)==null?void 0:_.getReader(),T=new TextDecoder;let k="";if(!b)throw new Error("Response body is not readable");for(;;){const{done:I,value:P}=await b.read();if(I)break;k+=T.decode(P,{stream:!0});const M=k.split(`
|
|
342
|
+
`);k=M.pop()||"";for(const B of M){const j=Ba(B);j&&(yield j)}}if(k.trim())for(const I of k.split(`
|
|
343
|
+
`)){const P=Ba(I);P&&(yield P)}}else{const b=await S.json();yield{text:b.message||b.response||"",done:!0,audio:b.audio,audioFormat:b.audio_format||b.audioFormat,image:b.image,image_format:b.image_format,image_revised_prompt:b.image_revised_prompt,image_url:b.image_url,video:b.video,video_format:b.video_format,video_revised_prompt:b.video_revised_prompt,video_url:b.video_url,document:b.document,document_format:b.document_format,document_revised_prompt:b.document_revised_prompt,document_url:b.document_url,generated_audio_url:b.generated_audio_url,generated_audio_format:b.generated_audio_format,generated_audio_revised_prompt:b.generated_audio_revised_prompt,assistant_message_id:b.assistant_message_id,threading:b.threading}}},async createThread(o,l){const c=await fetch("/api/threads",{method:"POST",headers:await Oe({"Content-Type":"application/json","X-Adapter-Name":s,"X-Session-ID":l}),body:JSON.stringify({message_id:o,session_id:l})});if(!c.ok)throw new Error(`Failed to create thread: ${c.statusText}`);return c.json()},async getThreadInfo(o){const l=await fetch(`/api/threads/${jt(o)}`,{headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get thread info: ${l.statusText}`);return l.json()},async deleteThread(o){const l=await fetch(`/api/threads/${jt(o)}`,{method:"DELETE",headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to delete thread: ${l.statusText}`);return l.json()},async submitFeedback(o,l,c){const d=await fetch("/api/feedback",{method:"POST",headers:await Oe({"Content-Type":"application/json","X-Adapter-Name":s,"X-Session-ID":l}),body:JSON.stringify({message_id:o,session_id:l,feedback_type:c})});if(!d.ok)throw new Error(`Failed to submit feedback: ${d.statusText}`);return d.json()},async getSessionFeedback(o){const l=await fetch(`/api/feedback/${jt(o)}`,{headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get feedback: ${l.statusText}`);return l.json()},async clearConversationHistory(o){const l=o||a;if(!l)throw new Error("No session ID available for clearing conversation history");const c=await fetch(`/api/admin/chat-history/${jt(l)}`,{method:"DELETE",headers:await Oe({"X-Adapter-Name":s})});if(!c.ok)throw new Error(`Failed to clear history: ${c.statusText}`);return c.json()},async getConversationHistory(o,l){const c=o||a;if(!c)throw new Error("No session ID available for conversation history");const d=typeof l=="number"&&Number.isFinite(l)&&l>0?`?limit=${Math.floor(l)}`:"",u=await fetch(`/api/admin/chat-history/${jt(c)}${d}`,{headers:await Oe({"X-Adapter-Name":s})});if(!u.ok)throw new Error(`Failed to load history: ${u.statusText}`);return u.json()},async deleteConversationWithFiles(o,l){const c=o||a;if(!c)throw new Error("No session ID available for deleting conversation");const d=ou(l),u=await fetch(`/api/admin/conversations/${jt(c)}${d}`,{method:"DELETE",headers:await Oe({"X-Adapter-Name":s})});if(!u.ok)throw new Error(`Failed to delete conversation: ${u.statusText}`);return u.json()},getSessionId:()=>a,async uploadFile(o){const l=new FormData;l.append("file",o);const c=await fetch("/api/files/upload",{method:"POST",headers:await Oe({"X-Adapter-Name":s}),body:l});if(!c.ok)throw new Error(`Failed to upload file: ${c.statusText}`);return c.json()},async listFiles(){const o=await fetch("/api/files",{headers:await Oe({"X-Adapter-Name":s})});if(!o.ok)throw new Error(`Failed to list files: ${o.statusText}`);const l=await o.json();return Array.isArray(l)?l:l.files||[]},async getFileInfo(o){const l=await fetch(`/api/files/${jt(o)}`,{headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get file info: ${l.statusText}`);return l.json()},async queryFile(o,l,c){const d=await fetch(`/api/files/${jt(o)}/query`,{method:"POST",headers:await Oe({"Content-Type":"application/json","X-Adapter-Name":s}),body:JSON.stringify({query:l,max_results:c})});if(!d.ok)throw new Error(`Failed to query file: ${d.statusText}`);return d.json()},async deleteFile(o){const l=await fetch(`/api/files/${jt(o)}`,{method:"DELETE",headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to delete file: ${l.statusText}`);return l.json()},async validateApiKey(){const o=await fetch(`/api/admin/api-keys/${jt(s)}/status`,{headers:await Oe({"X-Adapter-Name":s})});if(!o.ok)throw new Error(`Failed to validate API key: ${o.statusText}`);return o.json()},async getAdapterInfo(){const o="/api/admin/adapters/info",l=f=>{if(!f)return 0;const p=Number(f);if(Number.isFinite(p)&&p>0)return Math.min(p*1e3,3e4);const g=Date.parse(f);if(!Number.isNaN(g)){const m=g-Date.now();if(m>0)return Math.min(m,3e4)}return 0},c=f=>new Promise(p=>setTimeout(p,f)),d=async()=>fetch(o,{headers:await Oe({"X-Adapter-Name":s})});let u=await d();if(u.status===429){const f=l(u.headers.get("Retry-After"));f>0&&(await c(f),u=await d())}if(!u.ok){const f=await u.text(),p=`${u.status} ${u.statusText}`.trim(),g=u.status===401?`Adapter info request was unauthorized for '${s}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${p}) for '${s}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:s,status:u.status,statusText:u.statusText,details:f||void 0}),new Ki(g,u)}return u.json()},async stopChat(o,l){const c=await fetch("/api/v1/chat/stop",{method:"POST",headers:await Oe({"Content-Type":"application/json","X-Adapter-Name":s}),body:JSON.stringify({session_id:o,request_id:l})});return c.ok?(await c.json()).status==="cancelled":(console.warn(`[ProxyApi] stopChat failed: ${c.status} ${c.statusText}`),!1)},async getAdapterModels(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/models`,{headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(await Lr(l));return l.json()},async getAllModels(){const o=await fetch("/api/admin/models",{headers:await Oe({"X-Adapter-Name":s})});if(!o.ok)throw new Error(await Lr(o));return o.json()},async getAdapterSkills(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/skills`,{headers:await Oe({"X-Adapter-Name":s})});if(!l.ok)throw new Error(await Lr(l));return l.json()},async getAllSkills(){const o=await fetch("/api/admin/skills",{headers:await Oe({"X-Adapter-Name":s})});if(!o.ok)throw new Error(await Lr(o));return o.json()}});return{configureApi:r,streamChat:async function*(s,a,o,l,c,d,u,f,p,g,m,x,y,v){if(!e)throw new Error("Adapter name is required");yield*n(e,t).streamChat(s,a,o,l,c,d,u,f,p,g,m,x,y,v)},stopChat:async(s,a)=>{if(!e)throw new Error("Adapter name is required");return n(e,t).stopChat(s,a)},ApiClient:class{constructor(a){Qe(this,"client");const o=a.adapterName||null,l=a.sessionId||null;if(!o)throw new Error("Adapter name is required");this.client=n(o,l)}async*streamChat(...a){yield*this.client.streamChat(...a)}get createThread(){var a;return(a=this.client.createThread)==null?void 0:a.bind(this.client)}get getThreadInfo(){var a;return(a=this.client.getThreadInfo)==null?void 0:a.bind(this.client)}get deleteThread(){var a;return(a=this.client.deleteThread)==null?void 0:a.bind(this.client)}get submitFeedback(){var a;return(a=this.client.submitFeedback)==null?void 0:a.bind(this.client)}get getSessionFeedback(){var a;return(a=this.client.getSessionFeedback)==null?void 0:a.bind(this.client)}get clearConversationHistory(){var a;return(a=this.client.clearConversationHistory)==null?void 0:a.bind(this.client)}get getConversationHistory(){var a;return(a=this.client.getConversationHistory)==null?void 0:a.bind(this.client)}get deleteConversationWithFiles(){var a;return(a=this.client.deleteConversationWithFiles)==null?void 0:a.bind(this.client)}get getSessionId(){var a;return(a=this.client.getSessionId)==null?void 0:a.bind(this.client)}get uploadFile(){var a;return(a=this.client.uploadFile)==null?void 0:a.bind(this.client)}get listFiles(){var a;return(a=this.client.listFiles)==null?void 0:a.bind(this.client)}get getFileInfo(){var a;return(a=this.client.getFileInfo)==null?void 0:a.bind(this.client)}get queryFile(){var a;return(a=this.client.queryFile)==null?void 0:a.bind(this.client)}get deleteFile(){var a;return(a=this.client.deleteFile)==null?void 0:a.bind(this.client)}get validateApiKey(){var a;return(a=this.client.validateApiKey)==null?void 0:a.bind(this.client)}get getAdapterInfo(){var a;return(a=this.client.getAdapterInfo)==null?void 0:a.bind(this.client)}get stopChat(){var a;return(a=this.client.stopChat)==null?void 0:a.bind(this.client)}get getAdapterModels(){var a;return(a=this.client.getAdapterModels)==null?void 0:a.bind(this.client)}get getAllModels(){var a;return(a=this.client.getAllModels)==null?void 0:a.bind(this.client)}get getAdapterSkills(){var a;return(a=this.client.getAdapterSkills)==null?void 0:a.bind(this.client)}get getAllSkills(){var a;return(a=this.client.getAllSkills)==null?void 0:a.bind(this.client)}}}}async function cu(){return is||(U("Loading API via Express proxy"),is=lu(),U("API loaded successfully"),is)}async function Fe(){return await cu()}class Ha{static async getAdapterSkills(e,r){const n=await Fe(),s=new n.ApiClient({apiUrl:"",adapterName:r});return s.getAdapterSkills?(await s.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const r=await Fe(),n=new r.ApiClient({apiUrl:"",adapterName:e});return n.getAllSkills?(await n.getAllSkills()).skills:[]}}const du=6e4;function Gi(t={}){const{adapterName:e,enabled:r=!0,selectionScopeKey:n,supportsThreading:s=!1}=t,a=r&&!!e&&!s,o=n??e??"__default__",[l,c]=h.useState([]),[d,u]=h.useState(!1),[f,p]=h.useState(null),[g,m]=h.useState({}),x=h.useRef(null),y=h.useRef(new Map),v=h.useCallback(async S=>{var b,T;const E=S,_=y.current.get(E);if(_&&_.expiresAt>Date.now()){c(_.skills),p(S);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[k,I]=await Promise.all([Ha.getAdapterSkills(S,S),Ha.getAllSkills(S)]);if((b=x.current)!=null&&b.signal.aborted)return;const P=I.filter(M=>k.includes(M.name)&&M.enabled);y.current.set(E,{skills:P,expiresAt:Date.now()+du}),c(P),p(S),U("[useSkills] Loaded",P.length,"skills for adapter",S)}catch(k){if(k instanceof Error&&k.name==="AbortError")return;me("[useSkills] Failed to load skills:",k instanceof Error?k.message:String(k)),c([]),p(S)}finally{(T=x.current)!=null&&T.signal.aborted||u(!1)}},[]);h.useEffect(()=>{if(!a||!e)return;const S=window.setTimeout(()=>{v(e)},0);return()=>{var E;window.clearTimeout(S),(E=x.current)==null||E.abort()}},[a,e,v]);const A=h.useCallback(S=>{m(E=>{const _=E[o]??null;if(_===S||(_==null?void 0:_.name)===(S==null?void 0:S.name))return E;const b={...E};return S?b[o]=S:delete b[o],b})},[o]),N=h.useCallback(()=>{m(S=>{if(!S[o])return S;const E={...S};return delete E[o],E})},[o]),C=a?g[o]??null:null;return{skills:a&&f===e?l:[],isLoading:a?d||f!==e:!1,selectedSkill:C,selectSkill:A,clearSkill:N}}const Va=t=>{let e;const r=new Set,n=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const p=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),r.forEach(g=>g(e,p))}},s=()=>e,l={setState:n,getState:s,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=e=t(n,s,l);return l},uu=(t=>t?Va(t):Va),fu=t=>t;function hu(t,e=fu){const r=pt.useSyncExternalStore(t.subscribe,pt.useCallback(()=>e(t.getState()),[t,e]),pt.useCallback(()=>e(t.getInitialState()),[t,e]));return pt.useDebugValue(r),r}const qa=t=>{const e=uu(t),r=n=>hu(e,n);return Object.assign(r,e),r},Xi=(t=>t?qa(t):qa),rt=Xi(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),os=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)};class Or{static async uploadFile(e,r,n,s,a){try{const o=le.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${le.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","image/webp","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(e.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|webp|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(e.name)||(e.type==="application/x-zip-compressed"||e.type==="application/zip")&&/\.xlsx$/i.test(e.name)))throw new Error(`File type not supported: ${e.type||"unknown"}`);r&&r({filename:e.name,progress:0,status:"uploading"});const d=await Fe(),u=(s==null?void 0:s.trim())||$e(),f=os(a);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");U(`Using adapter: ${f}`);const p=new d.ApiClient({apiUrl:u,sessionId:null,adapterName:f});if(!p.uploadFile)throw new Error("File upload is not available.");const g=await p.uploadFile(e);r&&r({filename:e.name,progress:75,status:"processing",fileId:g.file_id});let m;try{m=await this.pollFileStatus(g.file_id,30,2e3,void 0,u,f)}catch(x){const y=x instanceof Error?x.message:String(x);if(y.includes("was deleted"))throw new Error(`File ${g.file_id} was deleted during upload`);me(`File status polling failed for ${g.file_id}:`,x);const v=y.includes("processing failed")||y.includes("timeout");m={file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,processing_status:v?"failed":g.status||"processing",chunk_count:g.chunk_count,error_message:v?y:void 0}}return r&&r({filename:e.name,progress:100,status:m.processing_status==="completed"?"completed":"processing",fileId:g.file_id}),m}catch(o){let l=o instanceof Error?o.message:"Upload failed";throw l.includes("401")&&(l="Authentication failed. Please check your adapter configuration."),r&&r({filename:e.name,progress:0,status:"error",error:l}),new Error(l)}}static async uploadFiles(e,r){const s=[],a=[];for(let o=0;o<e.length;o+=3){const l=e.slice(o,o+3),c=await Promise.allSettled(l.map(async(d,u)=>{const f=o+u;return this.uploadFile(d,p=>{r&&r(f,p)})}));for(let d=0;d<c.length;d++){const u=c[d],f=o+d;u.status==="fulfilled"?s.push(u.value):(ze(`Failed to upload file ${e[f].name}:`,u.reason),a.push({index:f,file:e[f].name,error:u.reason}))}}if(s.length===0&&a.length>0){const o=a[0].error;throw o instanceof Error?o:new Error(`All ${a.length} file uploads failed`)}return a.length>0&&me(`[FileUploadService] ${a.length} of ${e.length} files failed to upload:`,a.map(o=>o.file)),s}static async listFiles(e,r,n){try{const s=await Fe(),a=(r==null?void 0:r.trim())||$e(),o=os(n);if(!o)throw new Error("Adapter not configured");const l=new s.ApiClient({apiUrl:a,sessionId:null,adapterName:o});if(!l.listFiles)throw new Error("File listing is not available.");const c=await l.listFiles();return(Array.isArray(c)?c:Array.isArray(c.files)?c.files:[]).map(u=>({file_id:u.file_id,filename:u.filename,mime_type:u.mime_type,file_size:u.file_size,upload_timestamp:u.upload_timestamp,processing_status:u.processing_status,chunk_count:u.chunk_count,error_message:u.error_message}))}catch(s){ze("Failed to list files:",s);const a=s instanceof Error?s.message:"Failed to list files";throw new Error(a)}}static async getFileInfo(e,r,n,s){try{const a=await Fe(),o=(n==null?void 0:n.trim())||$e(),l=os(s);if(!l)throw new Error("Adapter not configured");const c=new a.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.getFileInfo)throw new Error("File info retrieval is not available.");const d=await c.getFileInfo(e);return{file_id:d.file_id,filename:d.filename,mime_type:d.mime_type,file_size:d.file_size,upload_timestamp:d.upload_timestamp,processing_status:d.processing_status,chunk_count:d.chunk_count,error_message:d.error_message}}catch(a){if(a instanceof Error&&(a.message.includes("404")||a.message.includes("File not found")))throw new Error(`File ${e} was deleted`);ze(`Failed to get file info for ${e}:`,a);const o=a instanceof Error?a.message:`Failed to get file info: ${e}`;throw new Error(o)}}static async pollFileStatus(e,r=30,n=2e3,s,a,o){for(let l=0;l<r;l++)try{if(s&&!s())throw new Error("Polling cancelled - component unmounted");const c=await this.getFileInfo(e,void 0,a,o);if(c.processing_status==="completed")return c;if(c.processing_status==="error"||c.processing_status==="failed"){const d=c.error_message;throw new Error(d||`File processing failed for ${e}`)}l<r-1&&await new Promise(d=>setTimeout(d,n))}catch(c){const d=c instanceof Error?c.message:String(c);if(d.includes("404")||d.includes("File not found")||d.includes("was deleted"))throw new Error(`File ${e} was deleted during upload`);if(d.includes("component unmounted")||d.includes("processing failed")||d.includes("processing_status")||d.includes("401")||d.includes("403")||d.includes("500")||d.includes("502")||d.includes("503")||d.includes("Authentication")||d.includes("Adapter not configured"))throw c;if(l<r-1){await new Promise(u=>setTimeout(u,n));continue}throw c}throw new Error(`File processing timeout: ${e} did not complete within ${r*n/1e3} seconds`)}static async deleteFile(e,r,n,s){try{const a=await Fe(),o=(n==null?void 0:n.trim())||$e(),l=os(s);if(!l)throw new Error("Adapter not configured");const c=new a.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available.");return await c.deleteFile(e)}catch(a){if(a instanceof Error&&(a.message.includes("404")||a.message.includes("File not found")||a.message.includes("Not Found")))return U(`File ${e} was already deleted from server`),{message:"File already deleted",file_id:e};ze(`Failed to delete file ${e}:`,a);const o=a instanceof Error?a.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class pu{constructor(){Qe(this,"audioQueue",[]);Qe(this,"isPlaying",!1);Qe(this,"currentAudio",null);Qe(this,"audioContext",null);Qe(this,"isEnabled",!1);Qe(this,"onPlaybackStart",null);Qe(this,"onPlaybackEnd",null);Qe(this,"mimeTypeCache",new Map);Qe(this,"onChunkPlayed",null);Qe(this,"blobUrls",[]);Qe(this,"suppressPlaybackErrors",!1)}async enableAudio(){var e,r;try{if(!this.audioContext){const a=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;a&&(this.audioContext=new a)}const n=((e=this.audioContext)==null?void 0:e.state)==="suspended"?this.audioContext.resume():Promise.resolve();let s=Promise.resolve();try{const a=this.createSilentWavBlob(),o=URL.createObjectURL(a),l=new Audio;l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),l.src=o,l.volume=0,s=l.play().then(()=>{l.pause()}).catch(()=>{U("[AudioStreamManager] HTMLAudioElement silent unlock failed (will retry on next gesture)")}).finally(()=>{URL.revokeObjectURL(o)})}catch{U("[AudioStreamManager] Could not create silent audio element")}if(await n,this.audioContext&&this.audioContext.state==="running"){const a=this.audioContext.createBuffer(1,1,22050),o=this.audioContext.createBufferSource();o.buffer=a,o.connect(this.audioContext.destination),o.start(0)}return await s,this.isEnabled=!0,U("[AudioStreamManager] Audio playback enabled",{audioContextState:(r=this.audioContext)==null?void 0:r.state}),!0}catch(n){return ge("[AudioStreamManager] Failed to enable audio:",n),!1}}createSilentWavBlob(){const o=new ArrayBuffer(844),l=new DataView(o),c=(d,u)=>{for(let f=0;f<u.length;f++)l.setUint8(d+f,u.charCodeAt(f))};return c(0,"RIFF"),l.setUint32(4,836,!0),c(8,"WAVE"),c(12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,1,!0),l.setUint16(22,1,!0),l.setUint32(24,8e3,!0),l.setUint32(28,8e3*2,!0),l.setUint16(32,2,!0),l.setUint16(34,16,!0),c(36,"data"),l.setUint32(40,800,!0),new Blob([o],{type:"audio/wav"})}disableAudio(){!this.isEnabled&&!this.isPlaying||(this.isEnabled=!1,this.stop(),U("[AudioStreamManager] Audio playback disabled"))}async ensureAudioContext(){var e;if(!this.audioContext){const r=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;if(r)try{this.audioContext=new r}catch(n){return ge("[AudioStreamManager] Failed to create AudioContext:",n),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(r){return U("[AudioStreamManager] AudioContext resume deferred",r),!1}return!0}resolveMimeType(e){const r=this.mimeTypeCache.get(e);if(r)return r;let n;switch(e){case"mp3":n="audio/mpeg";break;case"wav":n="audio/wav";break;case"webm":n="audio/webm";break;case"ogg":n="audio/ogg";break;case"opus":{const s=typeof document<"u"?document.createElement("audio"):null;s!=null&&s.canPlayType("audio/ogg; codecs=opus")?n="audio/ogg; codecs=opus":s!=null&&s.canPlayType("audio/webm; codecs=opus")?n="audio/webm; codecs=opus":n="audio/mp4";break}default:n=`audio/${e}`}return this.mimeTypeCache.set(e,n),U(`[AudioStreamManager] Resolved MIME type for "${e}": ${n}`),n}isAudioEnabled(){return this.isEnabled}setOnPlaybackStart(e){this.onPlaybackStart=e}setOnPlaybackEnd(e){this.onPlaybackEnd=e}setOnChunkPlayed(e){this.onChunkPlayed=e}async addChunk(e){if(!this.isEnabled){U(`[AudioStreamManager] Audio disabled, dropping chunk ${e.chunkIndex}`);return}U(`[AudioStreamManager] Adding chunk ${e.chunkIndex} to queue`),this.audioQueue.push(e),this.audioQueue.sort((r,n)=>r.chunkIndex-n.chunkIndex),this.isPlaying||this.playNextChunk().catch(r=>{ge("[AudioStreamManager] Playback chain error:",r)})}async playNextChunk(){var r,n;if(this.audioQueue.length===0){this.isPlaying=!1,U("[AudioStreamManager] Queue empty, playback complete"),this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){U("[AudioStreamManager] Audio not enabled, skipping playback"),this.audioQueue=[],this.isPlaying=!1;return}this.suppressPlaybackErrors=!1,await this.ensureAudioContext(),this.isPlaying=!0;const e=this.audioQueue.shift();try{if(!this.isPlaying)return;if(this.onPlaybackStart&&e.chunkIndex===0&&this.onPlaybackStart(),U(`[AudioStreamManager] Playing chunk ${e.chunkIndex}`),!e.audio||e.audio.length===0)throw new Error(`Empty audio data for chunk ${e.chunkIndex}`);let s;try{s=atob(e.audio)}catch(f){throw new Error(`Failed to decode base64 audio for chunk ${e.chunkIndex}: ${f instanceof Error?f.message:String(f)}`)}if(s.length===0)throw new Error(`Decoded audio data is empty for chunk ${e.chunkIndex}`);const a=new Uint8Array(s.length);for(let f=0;f<s.length;f++)a[f]=s.charCodeAt(f);const o=this.resolveMimeType(e.audioFormat),l=new Blob([a],{type:o}),c=URL.createObjectURL(l);this.blobUrls.push(c);const d=()=>{if(this.currentAudio){try{this.currentAudio.pause()}catch{}this.currentAudio.removeAttribute("src"),this.currentAudio.load()}URL.revokeObjectURL(c),this.blobUrls=this.blobUrls.filter(f=>f!==c)};let u=!1;try{u=await this.playViaAudioElement(c,e,d)}catch{u=!1}if(!u&&!this.suppressPlaybackErrors&&this.audioContext){U(`[AudioStreamManager] HTMLAudioElement failed for chunk ${e.chunkIndex}, trying AudioContext fallback`);try{u=await this.playViaAudioContext(a.buffer,e.chunkIndex)}catch(f){ge(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{ge("[AudioStreamManager] Playback chain error:",f)})}catch(s){if(this.suppressPlaybackErrors){U("[AudioStreamManager] Playback stopped, suppressing audio error");return}const a=s instanceof Error?s.message:String(s);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,a,s,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(r=e.audio)==null?void 0:r.length,audioContextState:(n=this.audioContext)==null?void 0:n.state,isEnabled:this.isEnabled}),ge(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,s),this.playNextChunk().catch(o=>{ge("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,r,n){return new Promise(s=>{const a=new Audio;a.setAttribute("playsinline",""),a.setAttribute("webkit-playsinline",""),a.src=e,this.currentAudio=a;let o=!1;const l=u=>{o||(o=!0,s(u))},c=()=>{if(this.suppressPlaybackErrors){n(),l(!0);return}const u=a.error;ge(`[AudioStreamManager] Media error on chunk ${r.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),n(),l(!1)};a.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{a.addEventListener("ended",()=>{o||(U(`[AudioStreamManager] Chunk ${r.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(r.chunkIndex),n(),l(!0))},{once:!0}),await a.play()}catch(u){if(this.suppressPlaybackErrors){n(),l(!0);return}U(`[AudioStreamManager] audio.play() rejected for chunk ${r.chunkIndex}:`,u),n(),l(!1)}};a.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():a.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,r){return new Promise((n,s)=>{if(!this.audioContext){s(new Error("No AudioContext"));return}const a=e.slice(0);this.audioContext.decodeAudioData(a,o=>{if(!this.audioContext||this.suppressPlaybackErrors){n(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{U(`[AudioStreamManager] Chunk ${r} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(r),n(!0)},l.start(0)},o=>{s(o)})})}stop(){U("[AudioStreamManager] Stopping playback"),this.suppressPlaybackErrors=!0,this.isPlaying=!1,this.audioQueue=[],this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.blobUrls.forEach(e=>URL.revokeObjectURL(e)),this.blobUrls=[]}reset(){this.stop(),U("[AudioStreamManager] Manager reset")}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const qt=new pu,mu=[{extensions:["pdf"],Icon:bn,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:bn,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:Fi,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:Di,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:Kc,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:Wc,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:Gc,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:qc,colorClass:"bg-amber-600"},{extensions:["js","mjs","ts","tsx","py","java","sql","cpp","cxx","cc","c","h","hpp","go","rs","rb","php","sh","bash","zsh","yaml","yml","xml","css","scss","sass","less","json","html","vtt"],Icon:Mi,colorClass:"bg-slate-500"}],gu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function xu(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function bu(t){const e=xu(t),r=mu.find(n=>n.extensions.includes(e));return{Icon:(r==null?void 0:r.Icon)??Xc,colorClass:(r==null?void 0:r.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:gu.has(e)}}const zr=new Map;function Yi(t,e){const r=zr.get(t);r&&r!==e&&URL.revokeObjectURL(r),zr.set(t,e)}function yu(t){return zr.get(t)}function kn(t){const e=zr.get(t);e&&(URL.revokeObjectURL(e),zr.delete(t))}const wu=mc()||ec(),Qi=()=>{if(Ls())return In()||void 0},Fr="",vu=["New Chat","New Conversation"],ku=t=>t&&!vu.includes(t)?t:Fr,$r=(t,e,r)=>({id:t,sessionId:e,title:Fr,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:r,adapterName:Qi(),adapterLoadError:null}),vs=()=>{const t=localStorage.getItem("chatbot-session-id");if(t)return t;const e=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return localStorage.setItem("chatbot-session-id",e),e},Su=t=>{localStorage.setItem("chatbot-session-id",t)};let ju=0;const lr=t=>{const e=Date.now(),r=++ju,n=Math.random().toString(36).substr(2,9);return`msg_${e}_${r}_${n}_${t}`},Wt=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},Zi=t=>{const e=new Set;let r=!1;const n=t.map(s=>{if(!e.has(s.id))return e.add(s.id),s;r=!0;const a={...s,id:lr(s.role)};return e.add(a.id),me(`[chatStore] Re-keyed duplicate message id ${s.id}`),a});return r?n:t},Wa=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,Ka=t=>t.flatMap(r=>[r.imageUrl,r.videoUrl,r.documentUrl]).map(r=>{var n;return((n=r==null?void 0:r.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:n[1])??null}).filter(r=>r!==null),Cu=(t,e)=>{if(t instanceof Date)return new Date(t);if(typeof t=="number"&&Number.isFinite(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r}if(typeof t=="string"){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r}return e?new Date(e):new Date},Au=(t,e)=>{const r=new Map;e.forEach((s,a)=>{s.databaseMessageId&&r.set(s.databaseMessageId,{message:s,index:a})});const n=new Set;return t.map((s,a)=>{var f;const o=s.role==="user"?"user":"assistant",l=typeof s.message_id=="string"&&s.message_id.length>0?s.message_id:void 0;let c;if(l&&r.has(l)){const p=r.get(l);c=p.message,n.add(p.index)}else{const p=a<e.length?a:0;if(!n.has(p)&&((f=e[p])==null?void 0:f.role)===o)c=e[p],n.add(p);else for(let g=1;g<e.length;g++){const m=(p+g)%e.length;if(!n.has(m)&&e[m].role===o){c=e[m],n.add(m);break}}}const d=s.timestamp?Cu(s.timestamp,c==null?void 0:c.timestamp):c!=null&&c.timestamp?new Date(c.timestamp):new Date,u=c?{...c,content:s.content??c.content,timestamp:d}:{id:l?`srv_${l}`:lr(o),content:s.content||"",role:o,timestamp:d};if(u.isStreaming=!1,l&&(u.databaseMessageId=l),!u.supportsThreading&&s.metadata&&typeof s.metadata=="object"){const p=s.metadata,g=p==null?void 0:p.retrieved_docs;Array.isArray(g)&&g.length>0&&(u.supportsThreading=!0)}return u})},Nu=(t,e)=>{if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){const n=t[r],s=e[r];if(n.role!==s.role||n.content!==s.content||(n.databaseMessageId||null)!==(s.databaseMessageId||null)||+n.timestamp!=+s.timestamp)return!1}return!0},Ji=t=>{var s,a,o,l,c,d;const e=((a=(s=t.adapterInfo)==null?void 0:s.adapter_name)==null?void 0:a.includes("voice"))||((l=(o=t.adapterInfo)==null?void 0:o.adapter_name)==null?void 0:l.includes("audio"))||((d=(c=t.adapterInfo)==null?void 0:c.adapter_name)==null?void 0:d.includes("multilingual"));let r=!1;try{const u=localStorage.getItem("chat-settings");u&&(r=JSON.parse(u).voiceEnabled===!0)}catch{me("Failed to read global voice setting")}const n=t.audioSettings;return{returnAudio:(n==null?void 0:n.enabled)??r??!!e,ttsVoice:(n==null?void 0:n.ttsVoice)||void 0,language:(n==null?void 0:n.language)||"en-US",audioFormat:n==null?void 0:n.audioFormat}},Iu=300;let ls=null;const Ke=t=>{ls&&clearTimeout(ls),ls=setTimeout(()=>{ls=null;try{const e=t(),r=e.conversations.map(n=>({...n,messages:n.messages.map(s=>s.audio||s.image||s.video||s.document?Object.fromEntries(Object.entries(s).filter(([o])=>o!=="audio"&&o!=="image"&&o!=="video"&&o!=="document")):s)}));localStorage.setItem("chat-state",JSON.stringify({conversations:r,currentConversationId:e.currentConversationId}))}catch(e){e instanceof DOMException&&e.name==="QuotaExceededError"?me("[chatStore] localStorage quota exceeded — skipping save"):ze("[chatStore] Failed to save state to localStorage:",e)}},Iu)},Lu=32,cr=new Map;let Vt=null,ct=null,Ft=null,Jt=null;const Sn=(t,e)=>{const r=cr.get(t);if(r){if(r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=null),r.content){const n=r.content,s=r.messageId;r.content="",e(a=>({conversations:a.conversations.map(o=>{if(o.id!==t)return o;const l=[...o.messages],c=s?l.findIndex(u=>u.id===s):l.length-1,d=c!==-1?l[c]:void 0;return d&&d.role==="assistant"&&d.isStreaming&&(l[c]={...d,content:d.content+n}),{...o,messages:l,updatedAt:new Date}})}))}cr.delete(t)}},At=(t,e,r,n)=>({conversations:t.conversations.map(s=>{var l;if(s.id!==e)return s;const a=[...s.messages],o=n?a.findIndex(c=>c.id===n):a.length-1;return o!==-1&&((l=a[o])==null?void 0:l.role)==="assistant"&&(a[o]={...a[o],...r(a[o])}),{...s,messages:a,updatedAt:new Date}})});let ks=!1,Ss="";async function Er(){if(ks&&Ss)return!0;try{const t=await Fe(),e=localStorage.getItem("chat-api-url");e&&e===hn&&localStorage.removeItem("chat-api-url");const r=e&&e!==hn?e:$e(),n=vs(),s=localStorage.getItem("chat-adapter-name")||wu;return t.configureApi(r,n,s),Ss=r,ks=!0,!0}catch(t){return ze("Failed to configure API:",t),!1}}async function Ga(t,e,r,n,s,a,o,l,c){let d=!1;const u=new AbortController;Vt=u,Jt=n,ct=null;try{const f=t().conversations.find(y=>y.id===n);if(!f)throw new Error("Conversation not found");if(!f.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.");Ft=f.sessionId,f.sessionId&&(await Fe()).configureApi(lt(f.apiUrl),f.sessionId,f.adapterName);const p=await Fe(),{returnAudio:g,ttsVoice:m,language:x}=Ji(f);for await(const y of p.streamChat(s,!0,a.length>0?a:void 0,void 0,void 0,void 0,x,g,m,void 0,void 0,o,void 0,c)){if(y.request_id&&!ct&&(ct=y.request_id,U(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${y.request_id}`)),y.text){const v=Ur(y.text);v?(t().appendToLastMessage(v,n,r),d=!0):y.text.length>100&&me("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(y.audio&&y.done&&e(v=>At(v,n,()=>({audio:y.audio,audioFormat:y.audioFormat||"mp3"}),r)),y.image&&y.done&&(d=!0,e(v=>At(v,n,()=>({image:y.image,imageFormat:y.image_format||"png",imageRevisedPrompt:y.image_revised_prompt,imageUrl:y.image_url}),r))),(y.video||y.video_url)&&y.done&&(d=!0,e(v=>At(v,n,()=>({video:y.video,videoFormat:y.video_format||"mp4",videoRevisedPrompt:y.video_revised_prompt,videoUrl:y.video_url}),r))),(y.document||y.document_url)&&y.done&&(d=!0,e(v=>At(v,n,()=>({document:y.document,documentFormat:y.document_format||"pdf",documentRevisedPrompt:y.document_revised_prompt,documentUrl:y.document_url}),r))),y.generated_audio_url&&y.done&&(d=!0,e(v=>At(v,n,()=>({generatedAudioFormat:y.generated_audio_format||"mp3",generatedAudioRevisedPrompt:y.generated_audio_revised_prompt,generatedAudioUrl:y.generated_audio_url}),r))),y.done){const v=y.threading;v!=null&&v.supports_threading&&e(A=>({conversations:A.conversations.map(N=>N.id!==n?N:{...N,messages:N.messages.map(C=>C.id===r?{...C,supportsThreading:!0,databaseMessageId:v.message_id}:C),updatedAt:new Date})})),y.assistant_message_id&&e(A=>({conversations:A.conversations.map(N=>N.id!==n?N:{...N,messages:N.messages.map(C=>C.id===r&&!C.databaseMessageId?{...C,databaseMessageId:y.assistant_message_id}:C),updatedAt:new Date})}));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",n,r)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Stream cancelled by user"||f.message.includes("aborted")))U(`[chatStore] ${l==="edit-regenerate"?"Edit-regenerate":"Regeneration"} stream was cancelled by user`),d=!0;else{ze(`${l==="edit-regenerate"?"Edit-regenerate":"Regenerate"} API error:`,f);let g="Sorry, there was an error regenerating the response.";f instanceof Error&&(f.message.startsWith("Server error:")?g=f.message.substring(14):(f.message.includes("Could not connect")||f.message.includes("timed out"))&&(g=f.message)),t().appendToLastMessage(g,n,r)}}Vt=null,ct=null,Ft=null,Jt=null,Sn(n,e),e(f=>{const p=f.conversations.map(m=>m.id===n?{...m,messages:m.messages.map(x=>x.id===r?{...x,isStreaming:!1}:x),updatedAt:new Date}:m),g=p.find(m=>m.id===f.currentConversationId);return{conversations:p,isLoading:g?g.messages.some(m=>m.role==="assistant"&&m.isStreaming):!1}})}const be=Xi((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:vs(),getSessionId:()=>e().sessionId,configureApiSettings:async(r,n,s)=>{const a=e(),o=a.conversations.find(c=>c.id===a.currentConversationId),l=(o==null?void 0:o.sessionId)||n||vs();n&&Su(n),t({sessionId:l});try{const c=await Fe();if(!s||!s.trim())throw new Error("Adapter name is required");c.configureApi(r,l,s),Ss=r,ks=!0;let d;try{const u=new c.ApiClient({apiUrl:r,sessionId:null,adapterName:s});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),U("Adapter info loaded:",d))}catch(u){me("Failed to load adapter info:",u)}if(o)t(u=>({conversations:u.conversations.map(f=>f.id===o.id?{...f,adapterName:s,apiUrl:r,adapterInfo:d,adapterLoadError:null,updatedAt:new Date}:f)}));else if(s&&s.trim()){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Wt();t(p=>({conversations:[...p.conversations,{id:u,sessionId:f,title:Fr,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:s,apiUrl:r,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw ge("Failed to configure API:",c),t({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}s?localStorage.setItem("chat-adapter-name",s):localStorage.removeItem("chat-adapter-name"),t({isLoading:!1})},createConversation:()=>{var u;const r=e(),n=le.maxConversations,s=r.conversations.length,a=r.currentConversationId?r.conversations.find(f=>f.id===r.currentConversationId):null;if(n!==null&&s>=n){if(tt()&&!wt()){const p=`You've reached the guest limit of ${n} conversation${n===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:p}),rt.getState().openLoginPrompt(p),new Error("Guest conversation limit reached")}const f=`Maximum of ${n} conversations reached. Please delete an existing conversation before starting a new one.`;throw t({error:f}),new Error(f)}const o=!!a&&(a.messages.length>0||(((u=a.attachedFiles)==null?void 0:u.length)||0)>0);if(a&&!o){const f="Finish or delete the current conversation before starting a new one.";throw t({error:f}),new Error(f)}const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=Wt(),d={id:l,sessionId:c,title:Fr,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:$e(),adapterName:Qi(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),Ke(e),l},selectConversation:async r=>{const n=e().conversations.find(s=>s.id===r);if(n){const s=n.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:r,sessionId:n.sessionId,isLoading:s});const a=n.apiUrl||$e(),o=n.adapterName;if(await Er()&&o){const c=await Fe();if(c.configureApi(a,n.sessionId,o),!n.adapterInfo)try{const d=new c.ApiClient({apiUrl:a,sessionId:null,adapterName:o});if(typeof d.getAdapterInfo=="function"){const u=await d.getAdapterInfo();U("Adapter info loaded for conversation:",u),t(f=>({conversations:f.conversations.map(p=>p.id===r?{...p,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:p)})),Ke(e)}}catch(d){me("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(n.sessionId).catch(()=>{})}Ke(e)},deleteConversation:async r=>{var a,o;const n=e(),s=n.conversations.find(l=>l.id===r);if(U(`🗑️ Deleting conversation ${r}:`,{conversationId:r,sessionId:s==null?void 0:s.sessionId,title:s==null?void 0:s.title,messageCount:s==null?void 0:s.messages.length,fileCount:((a=s==null?void 0:s.attachedFiles)==null?void 0:a.length)||0}),n.currentConversationId===r&&qt.stop(),s){const l=(s.attachedFiles||[]).map(d=>d.file_id),c=(s.messages||[]).flatMap(d=>(d.attachments||[]).map(u=>u.file_id));[...l,...c].forEach(kn)}if(s!=null&&s.sessionId)try{if(!await Er())ze("Failed to configure API for conversation deletion");else{const c=s.apiUrl||$e(),d=s.adapterName;d?U(`Using conversation's adapter for deletion: ${d} (conversation: ${r})`):me(`Skipping server deletion for conversation ${r}: adapter not configured`);const u=await Fe(),f=new u.ApiClient({apiUrl:c,sessionId:s.sessionId,adapterName:d}),p=((o=s.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],g=Ka(s.messages||[]),m=[...p,...g];if(U(`🔧 Calling deleteConversationWithFiles for session: ${s.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(s.sessionId,m);U(`✅ Deleted conversation and files for session: ${s.sessionId}`,x),U(` - Deleted ${x.deleted_messages} messages`),U(` - Deleted ${x.deleted_files} files`),x.file_deletion_errors&&x.file_deletion_errors.length>0&&me(` - Errors deleting files: ${x.file_deletion_errors.join(", ")}`)}else me("⚠️ deleteConversationWithFiles method not available on API client")}}catch(l){ze("Failed to clear conversation history from server:",l)}else me(`⚠️ No session ID found for conversation ${r}, skipping server-side deletion`);t(l=>{var u;const c=l.conversations.filter(f=>f.id!==r),d=l.currentConversationId===r?((u=c[0])==null?void 0:u.id)||null:l.currentConversationId;if(c.length===0){const f=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=Wt(),g=$r(f,p,$e());return Ke(e),{conversations:[g],currentConversationId:f,sessionId:p}}return Ke(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const n=[...e().conversations];U(`🗑️ Deleting all conversations (${n.length} total)`),qt.stop();const s=n.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await Er()){ze("Failed to configure API for conversation deletion");return}const g=u.adapterName;if(!g){U(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const m=await Fe(),x=new m.ApiClient({apiUrl:lt(u.apiUrl),sessionId:u.sessionId,adapterName:g}),y=[...((f=u.attachedFiles)==null?void 0:f.map(v=>v.file_id))||[],...Ka(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,y),U(`✅ Deleted conversation ${u.id} and files`)):me(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(p){ze(`Failed to delete conversation ${u.id} from server:`,p)}}),o=(await Promise.allSettled(s)).filter(u=>u.status==="rejected");o.length>0&&ze(`Some conversations failed to delete from server: ${o.length}`,o);const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=Wt(),d=$r(l,c,$e());t({conversations:[d],currentConversationId:l,sessionId:c}),Ke(e)},deleteThread:async(r,n,s)=>{const a=e().conversations.find(f=>f.id===r);if(!a)throw new Error("Conversation not found");if(!a.adapterName)throw new Error("Adapter not configured for this conversation");const o=a.messages.find(f=>f.id===n);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==s)throw new Error("Thread not found for this message");const l=lt(a.apiUrl||$e()),c=await Fe(),d=new c.ApiClient({apiUrl:l,sessionId:a.sessionId,adapterName:a.adapterName});await new(await Nt(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(s),t(f=>({conversations:f.conversations.map(p=>{var x;if(p.id!==r)return p;const g=p.messages.filter(y=>y.isThreadMessage?!(y.threadId===s||y.parentMessageId===n):!0).map(y=>y.id!==n?y:{...y,threadInfo:void 0,supportsThreading:!0}),m=p.currentThreadId===s||p.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...p,messages:g,currentThreadId:m?void 0:p.currentThreadId,currentThreadSessionId:m?void 0:p.currentThreadSessionId,updatedAt:new Date}})})),Ke(e)},sendMessage:async(r,n,s,a,o)=>{var c;let l=null;try{if(e().isLoading){me("Another request is already in progress");return}if(!await Er())throw new Error("API not properly configured. Please configure API settings first.");let u=e().currentConversationId;u||(u=e().createConversation());const f=e().conversations.find(b=>b.id===u);if(!f)throw new Error("Conversation not found");const p=le.maxConversations;if(tt()&&!wt()&&p!==null&&e().conversations.length>p){rt.getState().openLoginPrompt(`You've reached the guest limit of ${p} conversation${p===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const g=n?n.map(b=>{var k;const T=(k=f==null?void 0:f.attachedFiles)==null?void 0:k.find(I=>I.file_id===b);return T||{file_id:b,filename:"",mime_type:"",file_size:0}}).filter(b=>b!==void 0):[];g.length>0&&g.forEach(b=>{e().addFileToConversation(u,b)});const m=s||null;let x,y=null;if(m){if(x=f.messages.find(b=>{var T;return((T=b.threadInfo)==null?void 0:T.thread_id)===m}),!x)throw new Error("Thread metadata not found. Please recreate the thread from this message.");if(y=((c=x.threadInfo)==null?void 0:c.thread_session_id)||null,!y)throw new Error("Thread session is missing. Please recreate the thread from this message.")}const v=Wa(f.messages),A=le.maxMessagesPerConversation;if(A!==null&&v>=A){tt()&&!wt()&&rt.getState().openLoginPrompt(`You've reached the guest limit of ${A} messages per conversation. Sign in to send more messages, or delete conversations to start over.`),me(`[chatStore] Conversation ${u} reached the message limit (${A}).`),t({isLoading:!1});return}const N=le.maxTotalMessages;if(N!==null&&e().conversations.reduce((T,k)=>T+Wa(k.messages),0)>=N){tt()&&!wt()&&rt.getState().openLoginPrompt(`You've reached the guest limit of ${N} total messages. Sign in to continue chatting, or delete conversations to start over.`),me(`[chatStore] Workspace reached the total message limit (${N}).`),t({isLoading:!1});return}const C={id:lr("user"),content:r,role:"user",timestamp:new Date,attachments:g.length>0?g:void 0},S=lr("assistant"),E={id:S,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:a};if(m&&x){C.isThreadMessage=!0,C.threadId=m,C.parentMessageId=x.id,E.isThreadMessage=!0,E.threadId=m,E.parentMessageId=x.id;const b=le.maxMessagesPerThread;if(b!==null&&f.messages.filter(k=>k.isThreadMessage?(k.threadId===m||k.parentMessageId===x.id)&&!(k.role==="assistant"&&k.isStreaming):!1).length>=b){tt()&&!wt()&&rt.getState().openLoginPrompt(`You've reached the guest limit of ${b} messages per thread. Sign in to continue this thread, or delete conversations to start over.`),me(`[chatStore] Thread ${m} reached the message limit (${b}).`),t({isLoading:!1});return}}t(b=>{const T=b.conversations.find(I=>I.id===u),k=(T==null?void 0:T.messages.filter(I=>I.role==="assistant"&&I.isStreaming))||[];return k.length>0&&me(`Cleaning up ${k.length} existing streaming messages`),{conversations:b.conversations.map(I=>{if(I.id!==u)return I;const P=I.messages.filter(M=>!(M.role==="assistant"&&M.isStreaming));return{...I,messages:[...P,C,E],updatedAt:new Date,title:I.messages.length===0?r.slice(0,50)+(r.length>50?"...":""):I.title}}),isLoading:!0,error:null}}),l=u;let _=!1;qt.reset();try{const b=e().conversations.find(F=>F.id===l);if(!b)throw new Error("Conversation not found");if(!b.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.");const T=lt(b.apiUrl),k=b.adapterName,I=y||b.sessionId,P=await Fe();P.configureApi(T,I,k),m&&I!==b.sessionId&&U(`[chatStore] Thread mode: using thread session ${I} (original: ${b.sessionId})`);const{returnAudio:M,ttsVoice:B,language:j,audioFormat:L}=Ji(b);U("[chatStore] Audio settings:",{returnAudio:M,ttsVoice:B,language:j,audioFormat:L});const O=new AbortController;Vt=O,Ft=I,Jt=l,ct=null;for await(const F of P.streamChat(r,!0,n,m||void 0,void 0,void 0,j,M,B,void 0,void 0,a,o)){if(F.request_id&&!ct&&(ct=F.request_id,U(`[chatStore] >>> CAPTURED request_id for stop: ${F.request_id}`)),F.audio_chunk&&qt.addChunk({audio:F.audio_chunk,audioFormat:F.audioFormat||"opus",chunkIndex:F.chunk_index??0}),F.text){const X=Ur(F.text);X?(e().appendToLastMessage(X,l,S),_=!0):F.text.length>100&&me("[chatStore] Filtered out potential base64 audio data from message content")}if(F.audio&&F.done&&t(X=>At(X,l,()=>({audio:F.audio,audioFormat:F.audioFormat||"mp3"}),S)),F.image&&F.done&&(_=!0,t(X=>At(X,l,()=>({image:F.image,imageFormat:F.image_format||"png",imageRevisedPrompt:F.image_revised_prompt,imageUrl:F.image_url}),S))),(F.video||F.video_url)&&F.done&&(_=!0,t(X=>At(X,l,()=>({video:F.video,videoFormat:F.video_format||"mp4",videoRevisedPrompt:F.video_revised_prompt,videoUrl:F.video_url}),S))),(F.document||F.document_url)&&F.done&&(_=!0,t(X=>At(X,l,()=>({document:F.document,documentFormat:F.document_format||"pdf",documentRevisedPrompt:F.document_revised_prompt,documentUrl:F.document_url}),S))),F.generated_audio_url&&F.done&&(_=!0,t(X=>At(X,l,()=>({generatedAudioFormat:F.generated_audio_format||"mp3",generatedAudioRevisedPrompt:F.generated_audio_revised_prompt,generatedAudioUrl:F.generated_audio_url}),S))),F.done){U("[chatStore] Stream completed, receivedAnyText:",_);const X=F.threading;X!=null&&X.supports_threading&&t(G=>({conversations:G.conversations.map(q=>q.id!==l?q:{...q,messages:q.messages.map(Q=>Q.id===S?{...Q,supportsThreading:!0,databaseMessageId:X.message_id}:Q),updatedAt:new Date})})),F.assistant_message_id&&t(G=>({conversations:G.conversations.map(q=>q.id!==l?q:{...q,messages:q.messages.map(Q=>Q.id===S&&!Q.databaseMessageId?{...Q,databaseMessageId:F.assistant_message_id}:Q),updatedAt:new Date})}));break}}!_&&!O.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,S)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message==="Stream cancelled by user"||b.message.includes("aborted")))U("[chatStore] Stream was cancelled by user"),_=!0;else{ze("Chat API error:",b);let k="Sorry, there was an error processing your request.";b instanceof Error&&(b.message.startsWith("Server error:")?k=b.message.substring(14):(b.message.includes("Could not connect")||b.message.includes("timed out"))&&(k=b.message)),e().appendToLastMessage(k,l,S)}}Vt=null,ct=null,Ft=null,Jt=null,Sn(l,t),t(b=>{const T=b.conversations.map(I=>I.id===l?{...I,messages:I.messages.map(P=>P.id===S?{...P,isStreaming:!1}:P),updatedAt:new Date}:I),k=T.find(I=>I.id===b.currentConversationId);return{conversations:T,isLoading:k?k.messages.some(I=>I.role==="assistant"&&I.isStreaming):!1}}),Ke(e)}catch(d){ze("Chat store error:",d),t(u=>({isLoading:!1,...u.currentConversationId===l&&{error:`Failed to send message: ${d instanceof Error?d.message:"Unknown error"}`}}))}},createThread:async(r,n)=>{try{const s=e().conversations.find(p=>p.sessionId===n);if(!s)throw new Error("Conversation not found for session");if(!s.adapterName)throw new Error("Adapter not configured for this conversation");const a=s.messages.find(p=>p.id===r);if(!a)throw new Error("Message not found");const o=a.databaseMessageId||r,l=lt(s.apiUrl||$e()),c=await Fe(),d=new c.ApiClient({apiUrl:l,sessionId:n,adapterName:s.adapterName}),f=await new(await Nt(async()=>{const{ThreadService:p}=await import("./threadService-B9Db3n0J.js");return{ThreadService:p}},[])).ThreadService(d).createThread(o,n);t(p=>({conversations:p.conversations.map(g=>g.sessionId!==n?g:{...g,messages:g.messages.map(m=>m.id===r?{...m,threadInfo:f,supportsThreading:!0}:m),currentThreadId:void 0,currentThreadSessionId:void 0})})),U(`[chatStore] Created thread ${f.thread_id} for message ${r}`)}catch(s){throw ze("Failed to create thread:",s),s}},appendToLastMessage:(r,n,s)=>{const a=Ur(r);if(!a&&r){me("[chatStore] Filtered out base64 audio data from message content");return}const o=vn(a),l=n||e().currentConversationId;if(!l)return;const c=l,d=cr.get(c);d?(d.content+=o,d.messageId=s,d.timeoutId&&clearTimeout(d.timeoutId)):cr.set(c,{content:o,timeoutId:null,messageId:s});const u=()=>{const p=cr.get(c);if(!p||!p.content)return;const g=p.content,m=p.messageId;p.content="",p.timeoutId=null,t(x=>({conversations:x.conversations.map(y=>{if(y.id!==l)return y;const v=[...y.messages],A=m?v.findIndex(C=>C.id===m):v.length-1,N=A!==-1?v[A]:void 0;return N&&N.role==="assistant"&&N.isStreaming&&(v[A]={...N,content:N.content+g}),{...y,messages:v,updatedAt:new Date}})}))},f=cr.get(c);f.timeoutId=setTimeout(u,Lu)},regenerateResponse:async(r,n)=>{let s=null;try{if(e().isLoading){me("Another request is already in progress");return}if(!await Er())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(g=>g.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(g=>g.id===r);if(c===-1)return;const d=l.messages[c];if(!d||d.role!=="assistant")return;const u=l.messages[c-1];if(!u||u.role!=="user")return;const f=(u.attachments||[]).map(g=>g.file_id).filter(g=>typeof g=="string"&&g.length>0),p=lr("assistant");if(t(g=>({conversations:g.conversations.map(m=>m.id===g.currentConversationId?{...m,messages:[...m.messages.slice(0,c),{id:p,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:n,supportsThreading:d.supportsThreading,databaseMessageId:d.databaseMessageId,threadInfo:d.threadInfo,threadId:d.threadId,parentMessageId:d.parentMessageId,isThreadMessage:d.isThreadMessage},...m.messages.slice(c+1)],updatedAt:new Date}:m),isLoading:!0,error:null})),s=o.currentConversationId,!s)throw new Error("No conversation selected");await Ga(e,t,p,s,u.content,f,n,"regenerate",d.databaseMessageId)}catch(a){ze("Regenerate error:",a),t(o=>({isLoading:!1,...o.currentConversationId===s&&{error:`Failed to regenerate response: ${a instanceof Error?a.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(r,n,s)=>{let a=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&Sn(x,t)}const o=e(),l=o.conversations.find(x=>x.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(x=>x.id===r);if(c===-1)return;const d=l.messages[c];if(d.role!=="user")return;const u=(d.attachments||[]).map(x=>x.file_id).filter(x=>typeof x=="string"&&x.length>0),f=lr("assistant"),p=l.messages[c+1],g=(p==null?void 0:p.role)==="assistant",m=g?c+2:c+1;if(t(x=>({conversations:x.conversations.map(y=>y.id===x.currentConversationId?{...y,messages:[...y.messages.slice(0,c),{...d,content:n,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:s,supportsThreading:g?p.supportsThreading:void 0,databaseMessageId:g?p.databaseMessageId:void 0,threadInfo:g?p.threadInfo:void 0,threadId:g?p.threadId:void 0,parentMessageId:g?p.parentMessageId:void 0,isThreadMessage:g?p.isThreadMessage:void 0},...y.messages.slice(m)],updatedAt:new Date}:y),isLoading:!0,error:null})),a=o.currentConversationId,!a)throw new Error("No conversation selected");await Ga(e,t,f,a,n,u,s,"edit-regenerate",g?p.databaseMessageId:void 0),Ke(e)}catch(o){ze("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===a&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(r,n)=>{t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,title:n,updatedAt:new Date}:a)})),Ke(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const r=Jt;t(n=>{let s=!1;return{conversations:n.conversations.map(o=>o.id===r?(o.messages.some(c=>c.role==="assistant"&&c.isStreaming)&&(s=!0),o):o.messages.some(c=>c.role==="assistant"&&c.isStreaming)?{...o,messages:o.messages.filter(c=>!(c.role==="assistant"&&c.isStreaming)),updatedAt:new Date}:o),isLoading:s}})},canCreateNewConversation:()=>{var o;const r=e(),n=le.maxConversations;if(!r.currentConversationId)return n===null||r.conversations.length<n;const s=r.conversations.find(l=>l.id===r.currentConversationId);return!!s&&(s.messages.length>0||(((o=s.attachedFiles)==null?void 0:o.length)||0)>0)?n===null||r.conversations.length<n:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(r,n)=>{U("[chatStore] addFileToConversation called",{conversationId:r,fileId:n.file_id,filename:n.filename}),t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,attachedFiles:[...(a.attachedFiles||[]).filter(o=>o.file_id!==n.file_id),n],updatedAt:new Date}:a)})),Ke(e)},removeFileFromConversation:async(r,n)=>{U("[chatStore] removeFileFromConversation called",{conversationId:r,fileId:n});try{const s=e().conversations.find(a=>a.id===r);if(!s)throw new Error("Conversation not found");if(!s.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await Or.deleteFile(n,void 0,lt(s.apiUrl),s.adapterName),U(`[chatStore] Successfully deleted file ${n} from server`)}catch(s){s instanceof Error&&(s.message.includes("404")||s.message.includes("File not found"))?U(`[chatStore] File ${n} was already deleted from server`):ge(`[chatStore] Failed to delete file ${n} from server:`,s)}kn(n),t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,attachedFiles:(a.attachedFiles||[]).filter(o=>o.file_id!==n),updatedAt:new Date}:a)})),Ke(e)},loadConversationFiles:async r=>{try{const n=e().conversations.find(l=>l.id===r);if(!n)return;if(!n.adapterName){U(`Skipping file load for conversation ${r}: adapter not configured`);return}if(new Set((n.attachedFiles||[]).map(l=>l.file_id)).size===0){U(`No files to sync for conversation ${r}`);return}const a=await Or.listFiles(void 0,lt(n.apiUrl),n.adapterName),o=new Map(a.map(l=>[l.file_id,{file_id:l.file_id,filename:l.filename,mime_type:l.mime_type,file_size:l.file_size,upload_timestamp:l.upload_timestamp,processing_status:l.processing_status,chunk_count:l.chunk_count}]));t(l=>{const c=l.conversations.find(u=>u.id===r);if(!c)return l;const d=(c.attachedFiles||[]).map(u=>o.get(u.file_id)||u).filter(u=>o.has(u.file_id)||!u.processing_status||u.processing_status==="processing");return{conversations:l.conversations.map(u=>u.id===r?{...u,attachedFiles:d,updatedAt:new Date}:u)}}),Ke(e)}catch(n){ze(`Failed to load files for conversation ${r}:`,n)}},syncConversationFiles:async r=>{await e().loadConversationFiles(r)},syncConversationsWithBackend:async()=>{try{const r=e();if(r.conversations.length===0)return;const n=await Fe(),s=le.maxMessagesPerConversation!==null&&le.maxMessagesPerConversation||void 0;let a=!1;const l=(await Promise.all(r.conversations.map(async c=>{var d;if(!c.sessionId)return null;if(!c.adapterName)return me(`[chatStore] Skipping backend sync for conversation ${c.id} - adapter not configured`),null;if(c.messages.length===0)return null;try{const u=new n.ApiClient({apiUrl:lt(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return a||(a=!0,me("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,s),p=Array.isArray(f==null?void 0:f.messages)?f.messages:[];if(p.length===0)return c.messages.length===0?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:[],cleared:!0,updatedAt:new Date};const g=Au(p,c.messages),m=c.messages.filter(y=>y.isThreadMessage),x=Zi(m.length>0?[...g,...m]:g);return Nu(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=g[g.length-1])==null?void 0:d.timestamp)||new Date}}catch(u){return me(`[chatStore] Failed to sync session ${c.sessionId}:`,u),null}}))).filter(c=>!!c);if(l.length===0)return;t(c=>{const d=new Map(l.map(u=>[u.id,u]));return{conversations:c.conversations.map(u=>{const f=d.get(u.id);return f?f.cleared?{...u,sessionId:f.sessionId||u.sessionId,messages:[],attachedFiles:[],title:Fr,updatedAt:f.updatedAt,adapterLoadError:null}:{...u,sessionId:f.sessionId||u.sessionId,messages:f.messages,updatedAt:f.updatedAt,adapterLoadError:null}:u}),currentConversationId:c.currentConversationId}}),Ke(e)}catch(r){me("Failed to synchronize conversations with backend:",r)}},stopStreaming:async()=>{var n;if(!e().isLoading){U("[chatStore] stopStreaming called but not currently loading");return}if(U("[chatStore] Stopping stream...",{hasAbortController:!!Vt,requestId:ct,sessionId:Ft}),Vt&&Vt.abort(),ct&&Ft)try{const s=await Fe(),a=await((n=s.stopChat)==null?void 0:n.call(s,Ft,ct));U(`[chatStore] Server-side cancellation result: ${a}`)}catch(s){me("[chatStore] Failed to cancel server-side stream:",s)}else me(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ct}, sessionId=${Ft}`);const r=Jt||e().currentConversationId;t(r?s=>({conversations:s.conversations.map(a=>a.id!==r?a:{...a,messages:a.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),Vt=null,ct=null,Ft=null,Jt=null,U("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const r=e().currentConversationId;r&&(t(n=>({conversations:n.conversations.map(s=>s.id===r?{...s,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:s)})),Ke(e))},submitFeedback:async(r,n)=>{const s=e(),a=s.conversations.find(l=>l.id===s.currentConversationId);if(!a)return;const o=a.messages.find(l=>l.id===r);if(!(o!=null&&o.databaseMessageId)){me("[chatStore] Cannot submit feedback: no databaseMessageId on message");return}if(a.adapterName)try{const l=await Fe(),u=(await new l.ApiClient({apiUrl:lt(a.apiUrl||$e()),sessionId:a.sessionId,adapterName:a.adapterName}).submitFeedback(o.databaseMessageId,a.sessionId,n)).feedback_type;t(f=>({conversations:f.conversations.map(p=>p.id!==s.currentConversationId?p:{...p,messages:p.messages.map(g=>g.id===r?{...g,feedback:u}:g),updatedAt:new Date})})),Ke(e)}catch(l){ge("[chatStore] Failed to submit feedback:",l)}},loadFeedbackForConversation:async r=>{var a;const s=e().conversations.find(o=>o.sessionId===r);if(s!=null&&s.adapterName)try{const o=await Fe(),l=new o.ApiClient({apiUrl:lt(s.apiUrl||$e()),sessionId:s.sessionId,adapterName:s.adapterName}),c=new Set([r]);for(const f of s.messages)(a=f.threadInfo)!=null&&a.thread_session_id&&c.add(f.threadInfo.thread_session_id);const d=await Promise.all(Array.from(c).map(f=>l.getSessionFeedback(f).catch(()=>({feedbacks:[]})))),u=new Map;for(const f of d)if(f!=null&&f.feedbacks)for(const p of f.feedbacks)u.set(p.message_id,p.feedback_type);if(u.size===0)return;t(f=>({conversations:f.conversations.map(p=>p.sessionId!==r?p:{...p,messages:p.messages.map(g=>g.databaseMessageId&&u.has(g.databaseMessageId)?{...g,feedback:u.get(g.databaseMessageId)}:g)})}))}catch(o){ge("[chatStore] Failed to load feedback:",o)}}})),Eu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=$e(),r=!!localStorage.getItem("chat-api-url");let n=vs(),s=!1;if(t)try{const d=JSON.parse(t),u=g=>{if(g instanceof Date)return g;const m=g?new Date(g):new Date;return Number.isNaN(m.getTime())?new Date:m},p=(Array.isArray(d.conversations)?d.conversations:[]).map(g=>{const x=(Array.isArray(g.messages)?g.messages:[]).filter(N=>!(N.role==="assistant"&&N.isStreaming)).map(N=>({...N,timestamp:u(N.timestamp),isStreaming:!1})),y=Zi(x),v={id:g.id,sessionId:g.sessionId||Wt(),title:ku(g.title),messages:y,createdAt:u(g.createdAt),updatedAt:u(g.updatedAt),attachedFiles:g.attachedFiles||[],adapterName:g.adapterName,apiUrl:g.apiUrl,adapterInfo:g.adapterInfo,adapterLoadError:g.adapterLoadError||null,audioSettings:g.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},A=v.messages.length===0&&!v.adapterName;return{...v,apiUrl:A&&!r?e:lt(g.apiUrl)}});if(s=p.length>0,d.currentConversationId&&p.length>0){const g=p.find(m=>m.id===d.currentConversationId);g!=null&&g.sessionId&&(n=g.sessionId)}if(p.length===0){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,m=Wt(),x=$r(g,m,$e());be.setState({conversations:[x],currentConversationId:g,sessionId:m}),n=m}else be.setState({conversations:p,currentConversationId:d.currentConversationId||((c=p[0])==null?void 0:c.id)||null,sessionId:n}),!d.currentConversationId&&p.length>0&&(be.setState({currentConversationId:p[0].id,sessionId:p[0].sessionId||n}),n=p[0].sessionId||n);U("📋 Loaded conversations:",be.getState().conversations.map(g=>{var m;return{id:g.id,title:g.title,sessionId:g.sessionId,messageCount:((m=g.messages)==null?void 0:m.length)||0}})),setTimeout(()=>be.getState().cleanupStreamingMessages(),100)}catch(d){ze("Failed to load chat state:",d);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Wt(),p=$r(u,f,$e());be.setState({conversations:[p],currentConversationId:u,sessionId:f}),n=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=Wt(),f=$r(d,u,$e());be.setState({conversations:[f],currentConversationId:d,sessionId:u}),n=u}localStorage.removeItem("chat-api-key");const a=be.getState(),o=a.currentConversationId?a.conversations.find(d=>d.id===a.currentConversationId):null,l=s&&(o!=null&&o.apiUrl)?o.apiUrl:$e();try{const d=await Fe(),u=o==null?void 0:o.adapterName;if(!u)U("No adapter selected yet. Waiting for user selection before configuring API.");else if(d.configureApi(l,n,u),Ss=l,ks=!0,!(o!=null&&o.adapterInfo))try{const f=new d.ApiClient({apiUrl:l,sessionId:null,adapterName:u});if(typeof f.getAdapterInfo=="function"){const p=await f.getAdapterInfo();U("Adapter info loaded for existing adapter:",p);const g=be.getState();g.currentConversationId&&(be.setState({conversations:g.conversations.map(m=>m.id===g.currentConversationId?{...m,adapterInfo:p,adapterLoadError:null,updatedAt:new Date}:m)}),setTimeout(()=>{const m=be.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:m.conversations,currentConversationId:m.currentConversationId}))},0))}}catch(f){me("Failed to load adapter info for existing adapter:",f)}}catch(d){ze("Failed to initialize API:",d)}try{await be.getState().syncConversationsWithBackend()}catch(d){me("Conversation history sync skipped:",d)}};typeof window<"u"&&Eu();function _u(t){return t.includes("image")?i.jsx(Yc,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?i.jsx(yd,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):i.jsx(Fn,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function Tu(t){return t.replace(/-/g," ")}function eo({skills:t,isLoading:e,selectedSkill:r,activeSkillName:n,query:s="",onSelect:a,onActiveSkillChange:o}){const{t:l}=Le(),c=pt.useRef(null),d=s.toLowerCase().replace(/-/g," "),u=d?t.filter(f=>f.name.replace(/-/g," ").toLowerCase().includes(d)||f.description.toLowerCase().includes(d)):t;return pt.useEffect(()=>{var p;const f=(p=c.current)==null?void 0:p.querySelector('[data-active="true"]');f==null||f.scrollIntoView({block:"nearest"})},[n,u.length]),!e&&t.length===0?i.jsx("div",{className:"w-full overflow-hidden rounded-xl border border-gray-200 bg-white shadow-lg shadow-black/5 dark:border-[#242424] dark:bg-[#101010] dark:shadow-black/30",children:i.jsx("p",{className:"px-4 py-3 text-sm text-gray-500 dark:text-[#bfc2cd]",children:l("skillPicker.noSkillsAvailable")})}):i.jsx("div",{className:"w-full overflow-hidden rounded-xl border border-gray-200 bg-white shadow-lg shadow-black/5 dark:border-[#242424] dark:bg-[#101010] dark:shadow-black/30",children:e?i.jsx("div",{className:"px-4 py-3.5",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-[#bfc2cd]",children:[i.jsx("div",{className:"h-3.5 w-3.5 rounded-full border-2 border-current border-t-transparent animate-spin","aria-hidden":"true"}),l("skillPicker.loadingLabel")]})}):u.length===0?i.jsx("div",{className:"px-4 py-3.5",children:i.jsx("p",{className:"text-sm text-gray-500 dark:text-[#bfc2cd]",children:d?l("skillPicker.noMatchingSkills",{query:s}):l("skillPicker.noMatchingSkillsGeneric")})}):i.jsx("div",{ref:c,role:"listbox","aria-label":l("skillPicker.listboxLabel"),className:"max-h-72 overflow-y-auto p-1.5",children:u.map((f,p)=>{const g=(r==null?void 0:r.name)===f.name,m=n===f.name||!n&&(g||!r&&p===0);return i.jsxs("button",{id:`skill-option-${f.name}`,type:"button",role:"option","aria-selected":m,"data-active":m?"true":void 0,onMouseEnter:()=>o==null?void 0:o(f),onClick:()=>a(f),className:`group flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:focus-visible:ring-gray-600 ${m?"bg-gray-100 text-gray-950 dark:bg-[#242424] dark:text-white":"text-gray-900 hover:bg-gray-50 dark:text-gray-100 dark:hover:bg-[#1a1a1a]"}`,children:[i.jsx("div",{className:`mt-0.5 flex h-5 w-5 flex-shrink-0 items-center justify-center transition-colors ${m?"text-gray-900 dark:text-white":"text-gray-500 group-hover:text-gray-700 dark:text-[#bfc2cd] dark:group-hover:text-gray-200"}`,children:_u(f.name)}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex min-w-0 items-center gap-2",children:i.jsx("span",{className:"truncate text-sm font-medium capitalize leading-5 text-current",children:Tu(f.name)})}),f.description&&i.jsx("p",{className:"mt-0.5 line-clamp-2 text-xs leading-5 text-gray-500 dark:text-[#bfc2cd]",children:f.description})]}),g&&i.jsx("span",{className:"mt-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-gray-900 text-white dark:bg-white dark:text-gray-900",children:i.jsx(ur,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function to({availableModels:t,defaultModel:e,selectedModel:r,onSelect:n,wrapperClassName:s="relative hidden md:block",maxWidthClass:a="max-w-[200px]",triggerTitle:o,listboxLabel:l,staticPaddingClass:c="px-3 py-1.5",triggerPaddingClass:d="px-3 py-1.5"}){const{t:u}=Le(),f=o??u("modelPicker.selectModel"),p=l??u("modelPicker.selectModel"),[g,m]=h.useState(!1),[x,y]=h.useState(""),[v,A]=h.useState(null),N=h.useRef(null),C=h.useRef(null),S=h.useRef(null),E=h.useRef(null),_=r??e,b=x.trim()?t.filter(M=>M.name.toLowerCase().includes(x.trim().toLowerCase())):t,T=h.useCallback(()=>{if(!C.current)return;const M=C.current.getBoundingClientRect();A({bottom:window.innerHeight-M.top+8,right:window.innerWidth-M.right})},[]),k=h.useCallback(()=>{m(!1),y("")},[]),I=()=>{if(g){k();return}T(),m(!0)};if(h.useEffect(()=>{if(!g)return;const M=setTimeout(()=>{var O;return(O=S.current)==null?void 0:O.focus()},10),B=O=>{var q,Q;const F=O.target,X=((q=N.current)==null?void 0:q.contains(F))??!1,G=((Q=E.current)==null?void 0:Q.contains(F))??!1;!X&&!G&&k()},j=O=>{var F;O.key==="Escape"&&(O.preventDefault(),k(),(F=C.current)==null||F.focus())},L=new ResizeObserver(T);return C.current&&L.observe(C.current),window.addEventListener("resize",T,{passive:!0}),document.addEventListener("scroll",T,{capture:!0,passive:!0}),document.addEventListener("pointerdown",B),document.addEventListener("keydown",j),()=>{clearTimeout(M),L.disconnect(),window.removeEventListener("resize",T),document.removeEventListener("scroll",T,{capture:!0}),document.removeEventListener("pointerdown",B),document.removeEventListener("keydown",j)}},[k,g,T]),!e&&t.length===0)return null;const P=g&&v&&typeof document<"u"?As.createPortal(i.jsxs("div",{ref:E,style:{position:"fixed",bottom:v.bottom,right:v.right,width:288,zIndex:9999},className:"rounded-xl border border-gray-200 bg-white shadow-xl dark:border-[#2f303d] dark:bg-[#111111]",children:[i.jsx("div",{className:"p-2 border-b border-gray-100 dark:border-[#222222]",children:i.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-gray-50 px-3 py-1.5 dark:bg-[#1a1a1a]",children:[i.jsx(Mn,{className:"h-3.5 w-3.5 flex-shrink-0 text-gray-400 dark:text-[#6b6f7a]","aria-hidden":"true"}),i.jsx("input",{ref:S,type:"text",value:x,onChange:M=>y(M.target.value),placeholder:u("modelPicker.searchPlaceholder"),className:"flex-1 bg-transparent pl-1 text-xs text-gray-700 placeholder-gray-400 focus:outline-none dark:text-[#ececf1] dark:placeholder-[#6b6f7a]","aria-label":u("modelPicker.searchAriaLabel")})]})}),i.jsx("div",{role:"listbox","aria-label":p,className:"max-h-60 overflow-y-auto py-1",children:b.length===0?i.jsx("div",{className:"px-3 py-5 text-center text-xs text-gray-400 dark:text-[#6b6f7a]",children:u("modelPicker.noModelsMatch",{query:x})}):b.map(M=>{const B=_===M.name;return i.jsxs("button",{role:"option","aria-selected":B,type:"button",onClick:()=>{var j;n(M.name),k(),(j=C.current)==null||j.focus()},className:`flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs transition-colors ${B?"bg-gray-100 text-gray-900 dark:bg-[#1f1f1f] dark:text-[#ececf1]":"text-gray-700 hover:bg-gray-50 dark:text-[#bfc2cd] dark:hover:bg-[#1a1a1a]"}`,children:[i.jsx("span",{className:`flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded-full border ${B?"border-blue-500 bg-blue-500 dark:border-blue-400 dark:bg-blue-400":"border-gray-300 dark:border-[#5a5b65]"}`,children:B&&i.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-white"})}),i.jsx("span",{className:"truncate font-medium normal-case tracking-normal",children:M.name})]},M.name)})}),t.length>8&&i.jsx("div",{className:"border-t border-gray-100 px-3 py-1.5 dark:border-[#222222]",children:i.jsx("span",{className:"text-[10px] text-gray-400 dark:text-[#6b6f7a]",children:u("modelPicker.modelCountHint",{filtered:b.length,total:t.length})})})]}),document.body):null;return i.jsx("div",{ref:N,className:s,children:t.length>1?i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:C,type:"button",onClick:I,className:`inline-flex min-w-[100px] ${a} items-center gap-1.5 rounded-full border border-gray-200 bg-gray-100 ${d} text-xs font-medium text-gray-700 transition-colors hover:bg-gray-200 dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#bfc2cd] dark:hover:bg-[#3a3b48]`,"aria-haspopup":"listbox","aria-expanded":g,title:f,children:[i.jsx("span",{className:"truncate flex-1",children:_}),i.jsx(hr,{className:`h-3.5 w-3.5 flex-shrink-0 text-gray-400 transition-transform duration-150 dark:text-[#6b6f7a] ${g?"rotate-180":""}`,"aria-hidden":"true"})]}),P]}):i.jsx("div",{className:`inline-flex min-w-[100px] ${a} items-center rounded-full border border-gray-200 bg-gray-100 ${c} text-xs text-gray-500 dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#bfc2cd]`,title:_??void 0,children:i.jsx("span",{className:"truncate",children:_})})})}function js({filename:t,fileId:e,status:r,statusText:n,errorMessage:s,onRemove:a,removeTitle:o,className:l=""}){const c=r==="uploading"||r==="processing",d=r==="error",u=bu(t),f=e?yu(e):void 0,p=u.Icon,g=d?s||n:n||u.label;return i.jsxs("div",{className:`group relative flex w-full min-w-[168px] max-w-[240px] items-center gap-2.5 rounded-xl border p-2 transition-colors ${d?"border-red-200 bg-red-50 dark:border-red-500/30 dark:bg-[#1a1010]":"border-gray-200 bg-gray-50 dark:border-[#242424] dark:bg-[#101010]"} ${l}`,children:[i.jsx("div",{className:`flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg text-white ${d?"bg-red-500":u.colorClass}`,children:f&&!d?i.jsx("img",{src:f,alt:"",className:"h-full w-full object-cover"}):c?i.jsx($i,{className:"h-[18px] w-[18px] animate-spin"}):d?i.jsx(xn,{className:"h-[18px] w-[18px]"}):i.jsx(p,{className:"h-[18px] w-[18px]"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`truncate text-sm font-medium leading-tight ${d?"text-red-700 dark:text-red-300":"text-[#353740] dark:text-[#ececf1]"}`,title:t,children:t}),g&&i.jsx("p",{className:`truncate text-xs leading-tight mt-0.5 ${d?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-[#8e8ea0]"}`,children:g})]}),a&&i.jsx("button",{type:"button",onClick:a,title:o,"aria-label":o,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-500 shadow-sm transition-colors hover:text-red-600 dark:border-[#3c3f4a] dark:bg-[#2d2f39] dark:text-[#bfc2cd] dark:hover:text-red-400",children:i.jsx(Ze,{className:"h-3 w-3"})})]})}const Mu=[],Fu=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},$u=(t,e)=>{const r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return new Blob([n],{type:e})},Ru=async t=>{const e=URL.createObjectURL(t);try{const r=new Image;r.decoding="async";const n=new Promise((o,l)=>{r.onload=()=>o(r),r.onerror=()=>l(new Error("Failed to load generated image for clipboard copy"))});r.src=e,await n;const s=document.createElement("canvas");s.width=r.naturalWidth,s.height=r.naturalHeight;const a=s.getContext("2d");if(!a)throw new Error("Could not create canvas context for image clipboard copy");return a.drawImage(r,0,0),await new Promise((o,l)=>{s.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},Pu=async(t,e)=>{const r=Fu(t.imageFormat);if(t.image)return $u(t.image,r);if(!t.imageUrl)return null;const n=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!n.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${n.status}`);const s=await n.blob();return s.type?s:new Blob([s],{type:r})},Du=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function Xa({size:t="md"}){const e=t==="sm"?"h-2 w-2":"h-2.5 w-2.5";return i.jsx("div",{className:"flex items-center gap-1.5 py-1",children:[0,150,300].map(r=>i.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${r}ms`}},r))})}function Uu({reply:t}){const{t:e}=Le(),[r,n]=h.useState(!1),[s,a]=h.useState(!1),o=h.useRef(null),l=be(d=>d.submitFeedback);h.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const c=async d=>{if(!t.databaseMessageId||r)return;const u=t.feedback!==d;n(!0);try{await l(t.id,d),u?(a(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a(!1),o.current=null},2e3)):a(!1)}catch(f){ge("Failed to submit thread reply feedback:",f)}finally{n(!1)}};return i.jsxs("div",{className:"mt-0.5 flex items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0]",children:[i.jsx("button",{onClick:()=>c("up"),disabled:r,className:`rounded-md p-1.5 transition-colors ${r?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.good"),"aria-label":e("message.feedback.good"),children:i.jsx(Oi,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>c("down"),disabled:r,className:`rounded-md p-1.5 transition-colors ${r?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.poor"),"aria-label":e("message.feedback.poor"),children:i.jsx(Ui,{className:"h-4 w-4"})}),s&&i.jsxs("span",{className:"ml-1 inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg bg-emerald-500 px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm animate-fadeIn dark:bg-emerald-600",children:[i.jsx(ur,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]})}function Ou({message:t,onRegenerate:e,onEdit:r,onStartThread:n,onClearThread:s,onSendThreadMessage:a,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null}){var bt,yr,wr;const{t:p}=Le(),[g,m]=h.useState(!1),[x,y]=h.useState(t.content||""),[v,A]=h.useState(!1),N=h.useRef(null),[C,S]=h.useState(!1),[E,_]=h.useState(!1),[b,T]=h.useState(!1),[k,I]=h.useState(""),[P,M]=h.useState(!1),[B,j]=h.useState(!1),[L,O]=h.useState(!1),[F,X]=h.useState(0),[G,q]=h.useState(!1),[Q,he]=h.useState(!1),[z,ee]=h.useState(()=>f??u),ce=h.useRef(f),V=h.useRef(((bt=t.threadInfo)==null?void 0:bt.thread_id)||null),J=h.useRef(null),fe=h.useRef(null),Se=h.useRef(null),H=h.useRef(!1),se=h.useRef(0),ne=h.useRef(""),je=h.useRef(!1),te=h.useRef(!0),Z=h.useRef(!1),oe=h.useRef(null),_e=h.useRef(null),xe=t.role==="assistant",De=o??Mu,Ie=De.filter($=>!($.role==="assistant"&&$.isStreaming)).length,D=De.some($=>$.isStreaming),K=pr(),Ee=tt()&&!K,ue=be($=>$.conversations.find(we=>we.id===$.currentConversationId)),Ae=!!((t.image||t.imageUrl)&&xe&&!t.isStreaming),st=!!((t.video||t.videoUrl)&&xe&&!t.isStreaming),mt=p(Ae?"message.copyImageLabel":"message.copyLabel"),qe=fc(),vt=le.maxMessageLength,Rt=le.maxMessagesPerThread,kt=Rt!==null&&Ie>=Rt,Pt=kt?Ee?p("message.thread.limitReachedGuest",{count:Rt}):p("message.thread.limitReachedUser",{count:Rt}):null,{theme:Kt,isDark:nt}=tr(),Dt=p("message.thread.placeholder"),Ut=`thread-input-${t.id}`,{skills:ke,isLoading:gt,selectedSkill:ie,selectSkill:ye,clearSkill:Te}=Gi({adapterName:ue==null?void 0:ue.adapterName,enabled:qe&&!!t.threadInfo,selectionScopeKey:((yr=t.threadInfo)==null?void 0:yr.thread_id)||t.id}),Me=k.startsWith("/")?k.slice(1):"",ae=Me.toLowerCase().replace(/-/g," "),Be=ae?ke.filter($=>$.name.replace(/-/g," ").toLowerCase().includes(ae)||$.description.toLowerCase().includes(ae)):ke,Fs=Be.length>0?Math.min(F,Be.length-1):0,at=Be[Fs]??null,Gt=(at==null?void 0:at.name.replace(/-/g," "))??"",Br=L&&at&&k.startsWith("/")&&Gt.toLowerCase().startsWith(Me.toLowerCase())&&Gt.length>Me.length?Gt.slice(Me.length):null,rr=Kt.mode==="dark"?"dark":Kt.mode==="light"?"light":"",sr=nt?"dark":"light",dt=h.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",rr].filter(Boolean).join(" "),[rr]),Hr=h.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",rr].filter(Boolean).join(" "),[rr]),mr=xe?dt:Hr,gr=`${dt} text-sm leading-6`,Xt=`${Hr} text-sm leading-6`;h.useEffect(()=>{var $,we;!V.current&&(($=t.threadInfo)!=null&&$.thread_id)&&M(!0),V.current=((we=t.threadInfo)==null?void 0:we.thread_id)||null},[(wr=t.threadInfo)==null?void 0:wr.thread_id]),h.useEffect(()=>{t.threadInfo||setTimeout(()=>{I(""),M(!1),j(!1),O(!1),Te()},0)},[t.threadInfo,Te]),h.useEffect(()=>{Ie>0&&setTimeout(()=>{M(!0)},0)},[Ie]),h.useEffect(()=>()=>{oe.current&&clearTimeout(oe.current),_e.current&&clearTimeout(_e.current)},[]),h.useEffect(()=>{if(!g||!N.current)return;const $=N.current;$.focus(),$.setSelectionRange($.value.length,$.value.length)},[g]),h.useEffect(()=>{if(!g||!N.current)return;const $=N.current;$.style.height="auto",$.style.height=`${$.scrollHeight}px`},[g,x]);const xr=h.useCallback(()=>{const $=x.trim();if(!$||$===t.content){m(!1);return}r==null||r(t.id,$),m(!1)},[x,t.content,t.id,r]),it=h.useCallback(()=>{requestAnimationFrame(()=>{Se.current&&(Se.current.scrollTop=Se.current.scrollHeight)})},[]);h.useEffect(()=>{if(!P)return;const $=De.length,we=$>se.current,W=De[De.length-1],Ne=(W==null?void 0:W.content)||"",Je=Ne!==ne.current,We=(W==null?void 0:W.isStreaming)??!1,vr=je.current&&!We;we||We&&Je||vr?(it(),te.current=!0):te.current&&Je&&it(),se.current=$,ne.current=Ne,je.current=We},[P,De,it]),h.useEffect(()=>{P&&(it(),te.current=!0)},[P,it]);const nr=xe?"message-bubble message-bubble-assistant min-w-0 break-words leading-relaxed text-[#353740] dark:text-[#ececf1]":"message-bubble message-bubble-user inline-block min-w-0 break-words leading-relaxed rounded-[1.75rem] border border-black/[0.06] bg-[#f4f4f4] px-4 py-3 text-[#111827] shadow-[0_1px_2px_rgba(16,24,40,0.06)] dark:border-white/[0.08] dark:bg-[#2a2a2a] dark:text-[#f5f5f5] dark:shadow-[0_1px_3px_rgba(0,0,0,0.3)]",St=h.useCallback(()=>{S(!0),oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>{S(!1),oe.current=null},2e3)},[]),Vr=async()=>{try{if(Ae){if("ClipboardItem"in window&&navigator.clipboard.write)try{const we=(ue==null?void 0:ue.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),W=await Pu(t,we);if(W){const Ne=W.type==="image/png"?W:await Ru(W);await navigator.clipboard.write([new ClipboardItem({[Ne.type||"image/png"]:Ne})]),St();return}}catch(we){ge("Failed to copy generated image, falling back to text:",we)}const $=Du(t);if($){await navigator.clipboard.writeText($),St();return}return}await navigator.clipboard.writeText(t.content),St()}catch($){ge(Ae?"Failed to copy generated image:":"Failed to copy text:",$)}},$s=be($=>$.submitFeedback),Lt=async $=>{if(!t.databaseMessageId||E)return;const we=t.feedback!==$;_(!0);try{await $s(t.id,$),we?(T(!0),_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>{T(!1),_e.current=null},2e3)):T(!1)}catch(W){ge("Failed to submit feedback:",W)}finally{_(!1)}},qr=async()=>{if(!a||!t.threadInfo||kt)return;const $=k.trim();if(!$)return;const we=k,W=ie,Ne=ie==null?void 0:ie.name;I(""),j(!0),O(!1),Ne&&Te();try{await a(t.threadInfo.thread_id,t.id,$,Ne,z??u??void 0),setTimeout(()=>{J.current&&J.current.focus()},100)}catch(Je){ge("Failed to send thread message:",Je),I(we),W&&ye(W),setTimeout(()=>{J.current&&J.current.focus()},100)}finally{j(!1)}},He=h.useCallback($=>{var we;ye($),O(!1),I(""),X(0),(we=J.current)==null||we.focus()},[ye]),br=h.useCallback(()=>{var $;O(!1),I(""),X(0),($=J.current)==null||$.focus()},[]),ar=h.useCallback(()=>{var $;I("/"),O(!0),X(0),($=J.current)==null||$.focus()},[]),Rs=$=>{if(L){if($.key==="ArrowDown"){$.preventDefault(),X(we=>Be.length===0?0:(we+1)%Be.length);return}if($.key==="ArrowUp"){$.preventDefault(),X(we=>Be.length===0?0:(we-1+Be.length)%Be.length);return}if($.key==="Home"){$.preventDefault(),X(0);return}if($.key==="End"){$.preventDefault(),X(Math.max(Be.length-1,0));return}if(($.key==="Enter"&&!$.shiftKey||$.key==="Tab")&&at){$.preventDefault(),He(at);return}if($.key==="Escape"){$.preventDefault(),br();return}}$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),qr())},ut=!t.threadInfo||!a||c||D||B||kt,xt=!!t.threadInfo&&!!s&&Ie>0&&!D&&!B&&!c,Ps=async()=>{if(!(!t.threadInfo||!s)){he(!0);try{await s(t.id,t.threadInfo.thread_id),q(!1),M(!1),I("")}catch($){ge("Failed to clear thread:",$)}finally{he(!1)}}};h.useEffect(()=>{ce.current=f},[f]),h.useEffect(()=>{ee(ce.current??u)},[u]),h.useEffect(()=>{if(!P||ut){Z.current=B;return}const $=J.current;if(!$){Z.current=B;return}if(!(H.current||Z.current)){Z.current=B;return}const W=requestAnimationFrame(()=>{var Je;H.current&&((Je=fe.current)==null||Je.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),$.focus();const Ne=$.value.length;$.setSelectionRange(Ne,Ne),H.current=!1,Z.current=B});return()=>{cancelAnimationFrame(W),Z.current=B}},[P,ut,B]),h.useEffect(()=>{if(J.current){const we=J.current;we.style.height="auto";const W=we.scrollHeight;we.style.height=`${Math.min(W,120)}px`,we.style.overflowY=W>120?"auto":"hidden"}},[k]);const Ds=h.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return i.jsx("div",{className:mr,children:i.jsx(Xa,{})});const $=t.isStreaming&&xe?" streaming-cursor":"";return i.jsx("div",{className:$||void 0,children:i.jsx($t,{content:vn(Ur(t.content||"")),className:mr,syntaxTheme:sr})})},[mr,t.content,t.isStreaming,xe,sr]),Us=h.useMemo(()=>{const $=W=>W instanceof Date?W.getTime():new Date(W).getTime();return[...De].sort((W,Ne)=>$(W.timestamp)-$(Ne.timestamp)).map(W=>{const Ne=W.role==="assistant",Je=Ne?gr:Xt,We=W.isStreaming&&Ne?" streaming-cursor":"",vr=W.isStreaming&&(!W.content||W.content==="…")?i.jsx("div",{className:Je,children:i.jsx(Xa,{size:"sm"})}):i.jsx("div",{className:We||void 0,children:i.jsx($t,{content:vn(Ur(W.content||"")),className:Je,syntaxTheme:sr})});return i.jsx("div",{className:`min-w-0 flex ${Ne?"justify-start":"justify-end"}`,children:i.jsxs("div",{className:Ne?"min-w-0 w-full max-w-full":"min-w-0 max-w-[85%]",children:[i.jsxs("div",{className:Ne?"thread-markdown-wrapper overflow-x-visible text-sm text-[#353740] dark:text-[#ececf1]":"thread-markdown-wrapper overflow-x-visible text-sm rounded-[1.75rem] bg-[#f4f4f4] px-4 py-3 text-[#111827] dark:bg-[#2a2a2a] dark:text-[#f5f5f5]",children:[vr,W.audio&&Ne&&!W.isStreaming&&i.jsx(ns,{audio:W.audio,audioFormat:W.audioFormat,autoPlay:!1}),(W.image||W.imageUrl)&&Ne&&!W.isStreaming&&i.jsx(Ra,{image:W.image,imageUrl:W.imageUrl,imageFormat:W.imageFormat,revisedPrompt:W.imageRevisedPrompt}),(W.video||W.videoUrl)&&Ne&&!W.isStreaming&&i.jsx(Pa,{video:W.video,videoUrl:W.videoUrl,videoFormat:W.videoFormat,revisedPrompt:W.videoRevisedPrompt,adapterName:ue==null?void 0:ue.adapterName}),(W.document||W.documentUrl)&&Ne&&!W.isStreaming&&i.jsx(za,{document:W.document,documentUrl:W.documentUrl,documentFormat:W.documentFormat,revisedPrompt:W.documentRevisedPrompt,adapterName:ue==null?void 0:ue.adapterName}),W.generatedAudioUrl&&Ne&&!W.isStreaming&&i.jsx(ns,{audioUrl:W.generatedAudioUrl,audioFormat:W.generatedAudioFormat,downloadFilename:`generated-audio.${W.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ne&&!W.isStreaming&&W.model&&i.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:p("message.generatedBy",{model:W.model})}),Ne&&!W.isStreaming&&Sa()&&i.jsx(Uu,{reply:W})]})},W.id)})},[ue==null?void 0:ue.adapterName,sr,p,gr,De,Xt]);return i.jsxs("div",{className:"group animate-fadeIn min-w-0 w-full px-0",children:[i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsxs("div",{className:xe?void 0:"flex flex-col items-end",children:[i.jsxs("div",{className:nr,children:[g?i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx("textarea",{ref:N,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:x,onChange:$=>y($.target.value),onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&!v&&($.preventDefault(),$.stopPropagation(),xr()),$.key==="Escape"&&($.stopPropagation(),m(!1),y(t.content||""))},maxLength:le.maxMessageLength,rows:1,style:{minHeight:"24px"}}),i.jsxs("div",{className:"flex items-center justify-between gap-2 mt-1",children:[i.jsx("span",{className:"text-xs text-gray-400 dark:text-[#6e6e80]",children:p("message.edit.willRegenerateHint")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{m(!1),y(t.content||"")},className:"px-3 py-1.5 text-xs font-medium rounded-full bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-[#4a4b54] dark:text-gray-200 dark:hover:bg-[#565869] transition-colors",children:p("common.cancel")}),i.jsxs("button",{onClick:xr,className:"px-3 py-1.5 text-xs font-medium rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-1.5",children:[i.jsx(gn,{className:"w-3.5 h-3.5"}),p("common.send")]})]})]})]}):Ds,t.attachments&&t.attachments.length>0&&i.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map($=>i.jsx(js,{filename:$.filename,fileId:$.file_id,status:"completed",statusText:`${($.file_size/1024).toFixed(1)} KB`},$.file_id))}),t.audio&&xe&&!t.isStreaming&&i.jsx(ns,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&xe&&!t.isStreaming&&i.jsx(Ra,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&xe&&!t.isStreaming&&i.jsx(Pa,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:ue==null?void 0:ue.adapterName}),(t.document||t.documentUrl)&&xe&&!t.isStreaming&&i.jsx(za,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:ue==null?void 0:ue.adapterName}),t.generatedAudioUrl&&xe&&!t.isStreaming&&i.jsx(ns,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!xe&&!g&&i.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[i.jsx("button",{onClick:Vr,className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:mt,"aria-label":mt,children:C?i.jsx(ur,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Aa,{className:"h-4 w-4"})}),r&&i.jsx("button",{onClick:()=>{y(t.content||""),m(!0)},className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:p("message.editAriaLabel"),"aria-label":p("message.editAriaLabel"),children:i.jsx(Pi,{className:"h-4 w-4"})})]})]}),xe&&!t.isStreaming&&t.model&&i.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:p("message.generatedBy",{model:t.model})}),xe&&!t.isStreaming&&i.jsxs("div",{className:"py-1 flex flex-nowrap items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0] transition-opacity",children:[!st&&i.jsx("button",{onClick:Vr,className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:mt,"aria-label":mt,children:C?i.jsx(ur,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Aa,{className:"h-4 w-4"})}),Sa()&&i.jsxs("div",{className:"relative flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>Lt("up"),disabled:E,className:`rounded-md p-1.5 transition-colors ${E?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:p("message.feedback.good"),"aria-label":p("message.feedback.good"),children:i.jsx(Oi,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>Lt("down"),disabled:E,className:`rounded-md p-1.5 transition-colors ${E?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:p("message.feedback.poor"),"aria-label":p("message.feedback.poor"),children:i.jsx(Ui,{className:"h-4 w-4"})}),b&&i.jsxs("div",{className:"absolute bottom-full left-1/2 mb-2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-emerald-500 px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm animate-fadeIn dark:bg-emerald-600",children:[i.jsx("div",{className:"absolute left-1/2 top-full h-2.5 w-2.5 -translate-x-1/2 -translate-y-1/2 rotate-45 bg-emerald-500 dark:bg-emerald-600"}),i.jsxs("div",{className:"relative flex items-center gap-1.5",children:[i.jsx(ur,{className:"h-3.5 w-3.5"}),i.jsx("span",{children:p("message.feedback.thanks")})]})]})]}),e&&i.jsx("button",{onClick:()=>e(t.id),className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:p("message.regenerateTitle"),"aria-label":p("message.regenerateAriaLabel"),children:i.jsx(hd,{className:"h-4 w-4"})}),qe&&t.supportsThreading&&!t.threadInfo&&n&&l&&i.jsxs("button",{type:"button",onClick:()=>{H.current=!0,M(!0),n(t.id,l)},className:"ml-1 inline-flex items-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1.5 text-xs text-blue-700 shadow-sm transition-all hover:border-blue-300 hover:bg-blue-100 hover:text-blue-800 hover:shadow-md dark:border-blue-500/30 dark:bg-blue-500/10 dark:text-blue-200 dark:hover:border-blue-400/50 dark:hover:bg-blue-500/20 dark:hover:text-blue-100 animate-follow-up-enter whitespace-nowrap",title:p("message.thread.continueDiscussionTitle"),"aria-label":p("message.thread.continueDiscussionAriaLabel"),children:[i.jsx(Na,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:p("message.thread.continueLabel")})]}),qe&&t.threadInfo&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-4 shrink-0 bg-gray-200 dark:bg-[#3c3f4a] mx-1"}),i.jsxs("button",{onClick:()=>M($=>!$),className:"inline-flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1] transition-colors text-xs",children:[i.jsx(Na,{className:"h-4 w-4"}),i.jsx("span",{className:"truncate",children:p("message.thread.replyCount",{count:Ie})}),P?i.jsx(bs,{className:"h-3 w-3"}):i.jsx(hr,{className:"h-3 w-3"})]}),xt&&i.jsx("button",{type:"button",onClick:()=>q(!0),className:"inline-flex items-center rounded-md px-2 py-1 text-xs font-medium text-red-600 transition-colors hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900/30",title:p("message.thread.clearTitle"),"aria-label":p("message.thread.clearAriaLabel"),children:p("common.clear")})]})]}),qe&&t.threadInfo&&P&&i.jsxs("div",{className:"thread-panel mt-3 md:mt-3 border-l-2 border-gray-200 pl-3 sm:pl-4 dark:border-[#3b3c49]",children:[i.jsx("div",{ref:Se,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!Se.current)return;const{scrollTop:$,scrollHeight:we,clientHeight:W}=Se.current;te.current=we-$-W<100},children:Ie>0?Us:null}),Pt&&i.jsxs("div",{className:"mt-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-500/30 dark:bg-[#2f2410] dark:text-amber-100",children:[Pt,Ee&&i.jsx("div",{className:"mt-2",children:i.jsx("button",{type:"button",onClick:()=>rt.getState().openLoginPrompt(p("message.thread.signInPromptMessage")),className:"inline-flex items-center gap-1 rounded-md bg-blue-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",children:p("message.thread.signInForHigherLimits")})})]}),i.jsxs("div",{ref:fe,className:"mt-1 w-full max-w-[64rem] bg-transparent pt-1",children:[i.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2 dark:border-[#242424] dark:bg-[#101010]",children:[ie&&i.jsxs("div",{className:"flex h-8 shrink-0 items-center gap-1.5 self-center rounded-full border border-gray-300 bg-white px-2.5 text-xs text-gray-700 shadow-sm dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-200",children:[i.jsx(Fn,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:ie.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>Te(),className:"-mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-100","aria-label":p("message.thread.removeSkillAriaLabel"),children:i.jsx(Ze,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!ie&&ke.length>0&&k.length===0&&!ut&&i.jsxs("button",{type:"button",onClick:ar,className:"flex h-8 shrink-0 items-center gap-1.5 self-center rounded-full border border-gray-300 bg-white px-2.5 text-xs font-medium text-gray-600 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-300 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600","aria-label":p("message.thread.skillsHintAriaLabel"),title:p("message.thread.skillsHint"),children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded bg-gray-200 font-mono text-[10px] leading-none text-gray-600 dark:bg-[#2a2a2a] dark:text-gray-300","aria-hidden":"true",children:"/"}),p("messageInput.skillsHint.text")]}),i.jsxs("div",{className:"relative flex min-h-8 flex-1 items-center min-w-0",children:[i.jsx("label",{htmlFor:Ut,className:"sr-only",children:p("message.thread.placeholder")}),Br&&i.jsxs("div",{className:"pointer-events-none absolute inset-0 whitespace-pre-wrap px-0 py-0 text-base leading-8 text-gray-400 dark:text-[#8e8ea0] sm:text-sm sm:leading-8","aria-hidden":"true",children:[i.jsx("span",{className:"invisible",children:k}),i.jsx("span",{children:Br})]}),i.jsx("textarea",{id:Ut,ref:J,className:"relative z-10 block h-8 w-full min-w-0 resize-none overflow-hidden bg-transparent px-0 py-0 text-base leading-8 text-[#353740] placeholder-slate-500 outline-none transition focus:outline-none disabled:opacity-60 dark:text-[#ececf1] dark:placeholder-[#70707c] sm:text-sm sm:leading-8",placeholder:Dt,"aria-label":p("message.thread.placeholder"),value:k,onChange:$=>{const we=$.target.value;I(we),we.startsWith("/")&&X(0),O(we.startsWith("/"))},onKeyDown:Rs,disabled:ut,rows:1,maxLength:vt,style:{minHeight:"32px",maxHeight:"120px",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none"}})]}),i.jsxs("div",{className:"flex items-center justify-between sm:justify-end gap-2",children:[i.jsx(to,{availableModels:d,defaultModel:u,selectedModel:z,onSelect:ee,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:p("message.thread.selectModelTitle"),listboxLabel:p("message.thread.selectModelTitle")}),k.trim().length>0&&i.jsx("button",{type:"button",onClick:qr,disabled:ut||k.trim().length===0,className:"flex h-10 w-10 sm:h-8 sm:w-8 items-center justify-center rounded-full transition active:scale-95 bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 disabled:cursor-not-allowed",title:p("message.thread.sendMessageTitle"),children:i.jsx(gn,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),L&&i.jsx("div",{className:"w-full pt-1",children:i.jsx(eo,{skills:ke,isLoading:gt,selectedSkill:ie,activeSkillName:at==null?void 0:at.name,query:Me,onActiveSkillChange:$=>{const we=Be.findIndex(W=>W.name===$.name);we>=0&&X(we)},onSelect:He,onClose:br})})]}),Ie>0&&i.jsx("div",{className:"mt-2 flex justify-end",children:i.jsxs("button",{type:"button",onClick:()=>M(!1),className:"inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-[#bfc2cd] dark:hover:bg-[#2f313a] dark:hover:text-white","aria-label":p("message.thread.hideRepliesAriaLabel"),children:[i.jsx(bs,{className:"h-3 w-3"}),i.jsx("span",{children:p("message.thread.hideRepliesLabel")})]})})]})]}),i.jsx(ws,{isOpen:G,onClose:()=>{Q||q(!1)},onConfirm:Ps,title:p("message.confirmation.clearRepliesTitle"),message:p("message.confirmation.clearRepliesMessage"),confirmText:p("common.clear"),cancelText:p("common.cancel"),type:"danger",isLoading:Q})]})}let or=null;function zu(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!or||or.state==="closed")&&(or=new t),or.state==="suspended"&&or.resume(),or):(U("[SoundEffects] AudioContext not supported in this browser"),null)}function Bu(t){const e=zu();if(!e)return;const r=e.currentTime;for(const n of t){const s=e.createOscillator(),a=e.createGain();s.connect(a),a.connect(e.destination),s.frequency.value=n.frequency,s.type=n.type;const o=r+n.startTime,l=o+n.duration;a.gain.setValueAtTime(.001,o),a.gain.linearRampToValueAtTime(n.gain,o+.008),a.gain.exponentialRampToValueAtTime(.001,l),s.start(o),s.stop(l+.01)}}const Hu={messageSent:[{frequency:1046,startTime:0,duration:.08,gain:.15,type:"sine"},{frequency:1397,startTime:.07,duration:.11,gain:.18,type:"sine"}],messageReceived:[{frequency:988,startTime:0,duration:.12,gain:.16,type:"sine"},{frequency:1319,startTime:.13,duration:.12,gain:.18,type:"sine"},{frequency:1568,startTime:.26,duration:.18,gain:.14,type:"sine"}],success:[{frequency:784,startTime:0,duration:.1,gain:.14,type:"sine"},{frequency:1175,startTime:.11,duration:.18,gain:.18,type:"sine"}],error:[{frequency:330,startTime:0,duration:.15,gain:.16,type:"sine"},{frequency:262,startTime:.18,duration:.22,gain:.13,type:"sine"}],notification:[{frequency:880,startTime:0,duration:.1,gain:.14,type:"sine"},{frequency:1109,startTime:.12,duration:.16,gain:.17,type:"sine"}]};function _r(t,e){if(!e)return;const r=Hu[t];if(!r){U(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{Bu(r),U(`[SoundEffects] Playing ${t} sound effect`)}catch(n){U(`[SoundEffects] Failed to play ${t} sound effect:`,n)}}function Vu({messages:t,onRegenerate:e,onEditMessage:r,onStartThread:n,onClearThread:s,onSendThreadMessage:a,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f}){const p=h.useRef(null),g=h.useRef(null),m=h.useRef(t.length),x=h.useRef(""),y=h.useRef(l),v=h.useRef(!0),{settings:A}=Ns(),{t:N}=Le(),{topLevelMessages:C,threadLookup:S}=h.useMemo(()=>{const b=new Map,T=[];return t.forEach(k=>{if(k.isThreadMessage&&k.parentMessageId){const I=b.get(k.parentMessageId)||[];b.set(k.parentMessageId,[...I,k]);return}T.push(k)}),{topLevelMessages:T,threadLookup:b}},[t]),E=()=>{if(!g.current)return;const{scrollTop:b,scrollHeight:T,clientHeight:k}=g.current,P=T-b-k<200;v.current=P},_=h.useCallback(()=>{requestAnimationFrame(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)})},[]);return h.useEffect(()=>{const b=t.length,T=m.current,k=b>T,I=t[t.length-1],P=(I==null?void 0:I.content)||"",M=P!==x.current,B=(I==null?void 0:I.isStreaming)??!1;k||B&&M?(_(),v.current=!0):v.current&&M&&_(),m.current=b,x.current=P},[t,_]),h.useEffect(()=>{l&&(_(),v.current=!0)},[l,_]),h.useEffect(()=>{if(y.current&&!l){const b=t[t.length-1];(b==null?void 0:b.role)==="assistant"&&b.content&&_r("messageReceived",A.soundEnabled)}y.current=l},[l,t,A.soundEnabled]),C.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center px-4 sm:px-6",children:i.jsxs("div",{className:"text-center text-lg text-gray-500 dark:text-[#bfc2cd]",children:[i.jsx("p",{className:"text-xl",children:N("messageList.emptyStateHeading")}),i.jsx("p",{className:"mt-1 text-lg",children:N("messageList.emptyStateSubheading")})]})}):i.jsx("div",{ref:g,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:E,children:i.jsx("div",{className:"mx-auto w-full max-w-[96rem] px-3 sm:px-5 md:px-6 lg:px-8 xl:px-10",children:i.jsxs("div",{className:`message-list__rail mx-auto w-full space-y-7 ${c}`,children:[C.map(b=>i.jsx("div",{className:`flex w-full ${b.role==="user"?"justify-end":"justify-start"}`,style:{contentVisibility:"auto",containIntrinsicSize:"420px"},children:i.jsx(Ou,{message:b,onRegenerate:e,onEdit:r,onStartThread:n,onClearThread:s,onSendThreadMessage:a,threadMessages:S.get(b.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f})},b.id)),i.jsx("div",{ref:p,className:"h-8"})]})})})}const qu=4e3;function Wu(t,e,r={}){var T;const{t:n}=Le(),[s,a]=h.useState(!1),[o,l]=h.useState(null),c=h.useRef(null),d=h.useRef(""),u=h.useRef(""),f=h.useRef(!1),p=h.useRef(null),g=typeof navigator<"u"?navigator.language:"en-US",m=Number.isFinite(r.silenceTimeoutMs)?Math.max(Math.floor(r.silenceTimeoutMs),1e3):qu,x=((T=r.language)==null?void 0:T.trim())||g||"en-US",y=h.useCallback(k=>k.replace(/\s+/g," ").trim(),[]),v=h.useCallback(k=>{const I=y(k);I&&I!==u.current&&(u.current=I,t(I))},[y,t]),A=h.useCallback(()=>{if(!d.current)return;const k=d.current;d.current="",v(k)},[v]),N=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),C=h.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),S=h.useCallback(()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]),E=h.useCallback(()=>{S(),p.current=setTimeout(()=>{U("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():C()},m)},[S,C,m]),_=h.useCallback(()=>{if(!N){l(n("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const k=window.SpeechRecognition||window.webkitSpeechRecognition,I=new k;I.continuous=!0,I.interimResults=!0,I.lang=x,I.maxAlternatives=1,I.onstart=()=>{a(!0),l(null),d.current="",u.current="",U("Speech recognition started"),E()},I.onresult=P=>{let M="",B="";for(let j=P.resultIndex;j<P.results.length;j++){const L=P.results[j][0].transcript;P.results[j].isFinal?M+=L:B+=L}B&&(d.current=y(B)),M&&(d.current="",v(M)),E()},I.onend=()=>{S(),A(),a(!1),c.current=null,U("Speech recognition ended"),C()},I.onerror=P=>{switch(S(),ge("Speech recognition error:",P.error),a(!1),c.current=null,d.current="",C(),P.error){case"no-speech":l(n("voice.error.noSpeech"));break;case"audio-capture":l(n("voice.error.audioCapture"));break;case"not-allowed":l(n("voice.error.notAllowed"));break;case"network":l(n("voice.error.network"));break;default:l(n("voice.error.generic",{error:P.error}))}},I.start(),c.current=I}catch(k){ge("Failed to start speech recognition:",k),l(n("voice.error.startFailed")),a(!1)}},[N,A,C,E,S,x,y,v,n]),b=h.useCallback(()=>{if(U("Stopping speech recognition..."),c.current){const k=c.current;k.onstart=null,k.onerror=null;try{k.stop()}catch(I){U("Recognition already stopped or error stopping:",I),S(),A(),k.onend=null,k.onresult=null,c.current=null,a(!1),C()}}S(),a(!1),l(null),U("Speech recognition stopped, isListening set to false")},[S,A,C]);return{isListening:s,isSupported:N,startListening:_,stopListening:b,error:o}}const Ku=300,Ya=3,cs=5,Gu=6e4;function Qa(t){if(typeof t!="string")return null;const e=t.replace(/[\r\n\u2028\u2029]+/g," ").replace(/\s{2,}/g," ").trim();return e?{text:e}:null}function Xu(t,e={}){const{enabled:r=ji(),adapterName:n,sessionId:s,adapterSupportsAutocomplete:a,skill:o,inputRef:l}=e,[c,d]=h.useState([]),[u,f]=h.useState(!1),[p,g]=h.useState(-1),m=h.useRef(null),x=h.useRef(null),y=h.useRef(null),v=h.useRef(null),A=h.useRef(null),N=h.useRef(0),C=h.useRef([]),S=h.useRef([]),E=h.useRef(new Map);h.useEffect(()=>{C.current=c},[c]);const _=h.useCallback(j=>{const L=E.current.get(j);return L?L<=Date.now()?(E.current.delete(j),!1):!0:!1},[]),b=h.useCallback((j,L=!0)=>{const O=j.toLowerCase().trim(),F=S.current.length>0?S.current:C.current;if(!O)return F.slice(0,cs);const X=F.filter(G=>G.text.toLowerCase().includes(O));return X.length>0?X.slice(0,cs):L?F.slice(0,cs):[]},[]),T=h.useCallback(async j=>{if(!r||j.length<Ya){d([]),S.current=[],x.current&&clearTimeout(x.current),y.current&&clearTimeout(y.current),f(!1);return}if(!n){d([]),S.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(a===!1||_(n)){d([]),S.current=[],x.current&&clearTimeout(x.current),f(!1);return}v.current&&v.current.abort(),v.current=new AbortController;const L=N.current+1;N.current=L,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{L===N.current&&f(!0)},150);try{const O={"X-Adapter-Name":n};s&&(O["X-Session-ID"]=s);const F=new URLSearchParams;F.set("q",j),F.set("limit",String(cs)),o&&F.set("skill",o);const X=`/api/v1/autocomplete?${F.toString()}`,G=await fetch(X,{method:"GET",headers:O,signal:v.current.signal});if(!G.ok){me("[useAutocomplete] Request failed:",G.status),[404,405,501].includes(G.status)?(E.current.set(n,Date.now()+Gu),d([]),S.current=[]):d(b(j));return}const q=await G.json(),Q=Array.isArray(q==null?void 0:q.suggestions)?q.suggestions.map(he=>Qa(typeof he=="string"?he:he==null?void 0:he.text)).filter(he=>he!==null):[];if(L!==N.current)return;Q.length===0?d(b(j,!1)):(d(Q),S.current=Q),g(-1),U("[useAutocomplete] Received",Q.length,"suggestions")}catch(O){if(O instanceof Error&&O.name==="AbortError")return;me("[useAutocomplete] Error:",O instanceof Error?O.message:String(O)),L===N.current&&d(b(j))}finally{L===N.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[r,n,s,a,o,b,_]);h.useEffect(()=>{m.current&&clearTimeout(m.current);const j=()=>{v.current&&v.current.abort(),x.current&&clearTimeout(x.current),f(!1)},L=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,d([]),j()},0)};if(!r||t.length<Ya||a===!1||n&&_(n)){L();return}if(A.current){if(t===A.current){L();return}A.current=null}return m.current=setTimeout(()=>{T(t)},Ku),()=>{m.current&&clearTimeout(m.current),y.current&&(clearTimeout(y.current),y.current=null)}},[t,T,r,n,a,_]),h.useEffect(()=>()=>{v.current&&v.current.abort(),x.current&&clearTimeout(x.current)},[]);const k=h.useCallback(()=>{g(j=>{const L=C.current.length;return L===0?-1:j<L-1?j+1:0})},[]),I=h.useCallback(()=>{g(j=>{const L=C.current.length;return L===0?-1:j>0?j-1:L-1})},[]),P=h.useCallback(()=>{d([]),S.current=[],g(-1),v.current&&v.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),M=h.useCallback(j=>{if(!(l!=null&&l.current))return;const L=()=>{const O=l.current;if(!O)return;const F=typeof j=="string"?j.length:O.value.length;O.focus({preventScroll:!0}),typeof O.setSelectionRange=="function"&&O.setSelectionRange(F,F)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(L):setTimeout(L,0)},[l]),B=h.useCallback(j=>{A.current=j},[]);return{suggestions:c,isLoading:u,selectedIndex:p,setSelectedIndex:g,selectNext:k,selectPrevious:I,clearSuggestions:P,focusInputAfterSelection:M,suppressUntilQueryChange:B}}const Bt=new Map,Yu=new Map,Qu=new Map,Zu=new Set,Ju=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},ro=t=>typeof t=="object"&&t!==null&&"message"in t,ef=t=>t instanceof Error?t.message:typeof t=="string"?t:ro(t)?t.message??"Unknown error":"Unknown error";function tf({conversationId:t,onFilesSelected:e,onUploadError:r,onClose:n,onUploadingChange:s,onUploadSuccess:a,maxFiles:o=le.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Le(),[d,u]=h.useState(!1),[f,p]=h.useState(0),g=h.useRef(null),m=h.useRef(Qu),x=h.useRef(Zu),y=h.useRef(new Map),v=h.useRef(!0),A=h.useRef(Yu),N=h.useRef(t),C=be(z=>z.conversations),S=h.useMemo(()=>{if(!t)return new Map;const z=Bt.get(t);return z?new Map(z):new Map},[t,f]),E=h.useCallback(z=>{if(!z){s==null||s(null,!1),p(J=>J+1);return}const ee=Bt.get(z)||new Map,ce=C.find(J=>J.id===z),V=new Map(ee);if(ce!=null&&ce.attachedFiles){const J=new Set(ce.attachedFiles.filter(fe=>fe.processing_status==="completed"||fe.processing_status==="failed"||fe.processing_status==="error").map(fe=>fe.file_id));V.forEach((fe,Se)=>{fe.fileId&&J.has(fe.fileId)&&V.delete(Se)})}V.size>0?(Bt.set(z,V),s==null||s(z,!0)):(Bt.delete(z),s==null||s(z,!1)),p(J=>J+1)},[C,s]);h.useEffect(()=>{N.current=t,setTimeout(()=>{E(t)},0)},[t,E]),h.useEffect(()=>{t&&setTimeout(()=>{E(t)},0)},[C,t,E]);const _=h.useCallback((z,ee)=>{if(!z)return;const ce=Bt.get(z)||new Map,V=ee(new Map(ce));V.size>0?Bt.set(z,V):Bt.delete(z),s==null||s(z,V.size>0),p(J=>J+1)},[s]),b=h.useCallback((z,ee)=>{if(!z)return;const ce=A.current.get(z)||[],V=ee([...ce||[]]),J=new Set(ce.map(fe=>fe.file_id));if(A.current.set(z,V),e(z,V),a){const fe=V.filter(Se=>!J.has(Se.file_id));fe.length>0&&a(z,fe)}p(fe=>fe+1)},[e,a]),T=be(z=>z.removeFileFromConversation),k=be(z=>z.addFileToConversation);h.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const I=h.useCallback(()=>{v.current=!1,new Map(y.current).forEach(ee=>ee.abort()),setTimeout(()=>{const ee=be.getState(),ce=new Map(ee.conversations.map(J=>[J.id,J])),V=[];m.current.forEach((J,fe)=>{var Se;if(J){const H=ce.get(J);if(new Set(((Se=H==null?void 0:H.attachedFiles)==null?void 0:Se.map(ne=>ne.file_id))||[]).has(fe)){x.current.add(fe),m.current.delete(fe);return}}if(x.current.has(fe)){U(`[FileUpload] Skipping cleanup delete for ${fe}; file was previously attached and already handled`),m.current.delete(fe),x.current.delete(fe);return}V.push({fileId:fe,conversationId:J||null})}),V.length>0&&(n==null||n(),V.forEach(async({fileId:J,conversationId:fe})=>{try{if(fe)await T(fe,J);else{const Se=Ju();await Or.deleteFile(J,void 0,void 0,Se??void 0),kn(J)}}catch(Se){if(ro(Se)){const H=Se.message??"";!H.includes("404")&&!H.includes("File not found")&&me(`Failed to cleanup file ${J} during component unmount:`,Se)}else me(`Failed to cleanup file ${J} during component unmount`,Se)}}))},300)},[n,T]);h.useEffect(()=>I,[I]);const P=h.useCallback(async z=>{if(!z||z.length===0)return;const ee=Array.from(z),ce=be.getState(),V=t||ce.currentConversationId;if(!V){r==null||r(c("fileUpload.selectBeforeUpload"));return}const J=ce.conversations.find(te=>te.id===V);if(!J){r==null||r(c("fileUpload.conversationNotFound"));return}const fe=J.attachedFiles||[],Se=[],H=ee.filter(te=>fe.some(oe=>oe.filename===te.name&&oe.file_size===te.size)?(Se.push(te.name),!1):!0);if(Se.length>0&&(r==null||r(Se.length===1?c("fileUpload.duplicateFileError",{filename:Se[0]}):c("fileUpload.duplicateFilesError",{count:Se.length}))),H.length===0)return;if((A.current.get(V)||[]).length+H.length>o){const te=c("fileUpload.maxFilesPerConversationError",{count:o});tt()&&!wt()&&rt.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),r==null||r(te);return}if(le.maxTotalFiles!==null&&ce.conversations.reduce((oe,_e)=>{var xe;return oe+(((xe=_e.attachedFiles)==null?void 0:xe.length)||0)},0)+H.length>le.maxTotalFiles){const oe=c("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles});tt()&&!wt()&&rt.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),r==null||r(oe);return}if(!J.adapterName){r==null||r(c("fileUpload.adapterNotConfigured"));return}const ne=J.adapterName,je=lt(J.apiUrl);for(let te=0;te<H.length;te++){const Z=H[te],oe=new AbortController;y.current.set(Z.name,oe);const _e=`${V}-${Z.name}-${Date.now()}-${te}`;let xe=null;const De=Z.type.startsWith("image/")?URL.createObjectURL(Z):null;try{const Ie=await Or.uploadFile(Z,D=>{if(_(V,K=>(K.set(_e,D),K)),D.fileId&&!xe){xe=D.fileId,m.current.set(D.fileId,V),x.current.add(D.fileId),De&&Yi(D.fileId,De);const K={file_id:D.fileId,filename:Z.name,mime_type:Z.type||"application/octet-stream",file_size:Z.size,processing_status:D.status==="uploading"?"uploading":D.status==="processing"?"processing":D.status==="completed"?"completed":void 0};U(`[FileUpload] Adding file ${D.fileId} to conversation ${V} immediately (status: ${K.processing_status})`),k(V,K)}},void 0,je,ne).catch(D=>{if(D.message&&D.message.includes("was deleted")){xe&&m.current.delete(xe);const K=D.message.match(/File\s+([\w-]+)\s+was deleted/);return K&&K[1]&&m.current.delete(K[1]),U(`File ${Z.name} was deleted during upload`),null}throw D});Ie?(m.current.set(Ie.file_id,V),x.current.add(Ie.file_id),U(`[FileUpload] Updating file ${Ie.file_id} in conversation ${V} with final status`),k(V,Ie),Ie.processing_status==="completed"||Ie.processing_status==="failed"||Ie.processing_status==="error"?_(V,K=>(K.delete(_e),K)):_(V,K=>{const Ee=K.get(_e);return Ee&&K.set(_e,{...Ee,progress:90,status:"processing",fileId:Ie.file_id}),K}),b(V,K=>{if(new Set(K.map(Ae=>Ae.file_id)).has(Ie.file_id))return K;const ue=[...K,Ie];return U(`[FileUpload] Updated uploadedFiles for ${V}: ${ue.length} files`,ue),ue})):(me(`Upload completed for ${Z.name} but uploadedAttachment is null`),_(V,D=>(D.delete(_e),D)))}catch(Ie){const D=ef(Ie);if(Ie instanceof DOMException&&Ie.name==="AbortError"||oe.signal.aborted){U(`Upload cancelled for ${Z.name}`),xe?m.current.delete(xe):De&&URL.revokeObjectURL(De);continue}if(D.includes("was deleted")){U(`File ${Z.name} was deleted during upload`),xe&&m.current.delete(xe);const ue=D.match(/File\s+([\w-]+)\s+was deleted/);ue&&ue[1]&&m.current.delete(ue[1]);continue}v.current?(ge(`Failed to upload file ${Z.name}:`,Ie),ge(`File type: ${Z.type}, File name: ${Z.name}`),r==null||r(D||`Failed to upload ${Z.name}`)):me(`Upload error for ${Z.name} (component unmounted):`,D),xe?m.current.delete(xe):De&&URL.revokeObjectURL(De);const K=_e,Ee=V;setTimeout(()=>{_(Ee,ue=>(ue.delete(K),ue))},5e3)}finally{y.current.delete(Z.name)}}},[k,t,o,r,c,b,_]),M=h.useCallback(z=>{z.preventDefault(),z.stopPropagation(),l||u(!0)},[l]),B=h.useCallback(z=>{z.preventDefault(),z.stopPropagation(),u(!1)},[]),j=h.useCallback(z=>{if(z.preventDefault(),z.stopPropagation(),u(!1),l)return;const ee=z.dataTransfer.files;P(ee)},[l,P]),L=h.useCallback(z=>{const ee=z.target.files;P(ee),g.current&&(g.current.value="")},[P]),O=h.useCallback(()=>{!l&&g.current&&g.current.click()},[l]),F=h.useCallback(z=>{l||(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),O())},[l,O]),X=S.size>0,G=h.useMemo(()=>{const z=new Map;return C.forEach(ee=>{z.set(ee.id,ee.title||c("chatInterface.newChatTitle"))}),z},[C,c]),q=h.useMemo(()=>{const z=[];return Bt.forEach((ee,ce)=>{ce!==t&&ee.size>0&&z.push({conversationId:ce,uploads:Array.from(ee.entries()).map(([V,J])=>({key:V,progress:J}))})}),z},[t,f]),Q=(z,ee)=>{const ce=z.status==="uploading"?c("fileUpload.uploadingStatus"):z.status==="processing"?c("fileUpload.processingStatus"):z.status==="completed"?c("fileUpload.completedStatus"):void 0;return i.jsx(js,{filename:z.filename,fileId:z.fileId,status:z.status,statusText:ce,errorMessage:z.error||(z.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},ee)},he=i.jsx("div",{className:"w-full max-w-full overflow-hidden flex flex-wrap gap-2",role:"status","aria-live":"polite",children:Array.from(S.entries()).map(([z,ee])=>Q(ee,z))});return i.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[X&&he,!X&&i.jsxs("button",{type:"button",onClick:O,onKeyDown:F,onDragOver:M,onDragLeave:B,onDrop:j,disabled:l,className:`
|
|
344
|
+
group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
|
|
345
|
+
${d?"border-blue-300 bg-blue-50 ring-2 ring-blue-400 ring-inset dark:border-blue-500/40 dark:bg-[#101010] dark:ring-blue-500":l?"border-gray-200 bg-gray-50 cursor-not-allowed opacity-50 dark:border-[#242424] dark:bg-[#101010]":"border-gray-200 bg-gray-50 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 focus-visible:ring-inset dark:border-[#242424] dark:bg-[#101010] dark:hover:bg-[#1a1a1a]"}
|
|
346
|
+
`,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[i.jsx("input",{ref:g,type:"file",multiple:!0,onChange:L,className:"hidden",disabled:l,accept:".pdf,.doc,.docx,.txt,.md,.csv,.json,.html,.pptx,.xlsx,.py,.java,.sql,.js,.mjs,.ts,.tsx,.cpp,.cxx,.cc,.c,.h,.hpp,.go,.rs,.rb,.php,.sh,.bash,.zsh,.yaml,.yml,.xml,.css,.scss,.sass,.less,.png,.jpg,.jpeg,.tiff,.webp,.wav,.mp3,.mp4,.ogg,.flac,.webm,.m4a,.aac,.vtt"}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg transition-colors duration-200 ${d?"bg-blue-100 dark:bg-blue-500/15":"bg-gray-200/70 dark:bg-[#1a1a1a] group-hover:bg-blue-100 dark:group-hover:bg-[#242424]"}`,children:i.jsx(xd,{className:`h-5 w-5 transition-colors duration-200 ${d?"text-blue-600 dark:text-blue-400":"text-gray-400 dark:text-[#8e8ea0] group-hover:text-blue-500 dark:group-hover:text-blue-400"}`})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:`text-sm font-medium transition-colors duration-200 ${d?"text-blue-700 dark:text-blue-300":"text-[#353740] dark:text-[#ececf1]"}`,children:c(l?"fileUpload.disabledAriaLabel":d?"fileUpload.draggingText":"fileUpload.dragDropText")}),i.jsx("p",{className:"text-xs text-gray-400 dark:text-[#8e8ea0] mt-0.5",children:c("fileUpload.fileTypesAndLimit",{count:o})})]})]})]}),q.length>0&&i.jsxs("div",{className:"w-full max-w-full space-y-2 rounded-lg border border-gray-200 bg-gray-50 p-2.5 dark:border-[#242424] dark:bg-[#101010]",children:[i.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] px-1",children:c("fileUpload.otherConversationsLabel")}),q.map(({conversationId:z,uploads:ee})=>i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"text-[11px] font-medium text-gray-400 dark:text-[#6b6f7a] px-1",children:G.get(z)||"Conversation"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:ee.map(({key:ce,progress:V})=>Q(V,ce))})]},z))]})]})}const Za={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/tiff":"tiff","image/tif":"tif","image/gif":"gif","image/webp":"webp","application/pdf":"pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/msword":"doc","text/plain":"txt","text/markdown":"md","application/json":"json"},tn=4,ds=3,rf=0,sf=0,rn=2;function nf(t){if(!t||typeof t!="object")return null;const e=t,r=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const a of r)if(typeof e[a]=="boolean")return e[a];const n=["capabilities","features"],s=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const a of n){const o=e[a];if(!o||typeof o!="object")continue;const l=o;for(const c of s)if(typeof l[c]=="boolean")return l[c]}return null}function af(t){if(!t)return"bin";if(Za[t])return Za[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function of(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function lf(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function cf(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function sn(t){return!t||t==="processing"||t==="uploading"}function df(t,e){const r=Date.now(),n=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",s=of(cf(n)),o=lf(n)||af(t.type),l=`${s}-${r}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function Ja({onSend:t,disabled:e=!1,placeholder:r=ki(),autoFocusEnabled:n=!0,suppressMobileAutoFocus:s=!1,desktopOnlyAutoFocus:a=!1,isCentered:o=!1,maxWidthClass:l="max-w-5xl",adapterNotes:c,skillState:d,availableModels:u=[],defaultModel:f=null,selectedModel:p=null,onSelectModel:g}){var ra;const{t:m}=Le(),[x,y]=h.useState(""),[v,A]=h.useState(!1),[N,C]=h.useState(!1),[S,E]=h.useState(!1),[_,b]=h.useState(!1),[T,k]=h.useState([]),[I,P]=h.useState({}),[M,B]=h.useState(new Map),[j,L]=h.useState(!1),[O,F]=h.useState(!1),[X,G]=h.useState(null),[q,Q]=h.useState(null),[he,z]=h.useState(null),[ee,ce]=h.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),V=h.useRef(null),J=h.useRef(null),fe=h.useRef(null),Se=h.useRef(null),H=h.useRef(null),se=h.useRef(new Set),ne=h.useRef(""),je=h.useRef(!1),te=h.useRef(0),Z=h.useRef(null),{settings:oe,updateSettings:_e}=Ns(),{theme:xe,isDark:De}=tr(),Ie=xe.mode==="dark"?"dark":xe.mode==="light"?"light":"",D=De?"dark":"light";Dr(J,{enabled:S,onEscape:()=>E(!1)});const K=h.useCallback((w,R)=>{w&&P(de=>{if(de[w]===R)return de;const ve={...de};return R?ve[w]=!0:delete ve[w],ve})},[]),[Ee,ue]=h.useState(0),[Ae,st]=h.useState(!1),[mt,qe]=h.useState(0),[vt,Rt]=h.useState(()=>({top:tn+ds,bottom:Math.max(tn-ds,0)})),[kt,Pt]=h.useState(null),Kt=pr(),nt=tt()&&!Kt,Dt=rt(w=>w.showLoginPrompt),{createConversation:Ut,currentConversationId:ke,conversations:gt,isLoading:ie,syncConversationFiles:ye,stopStreaming:Te,removeFileFromConversation:Me}=be(),ae=gt.find(w=>w.id===ke),Be=ae?ae.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,Fs=gt.reduce((w,R)=>w+R.messages.filter(de=>!(de.role==="assistant"&&de.isStreaming)).length,0),at=!!ae&&le.maxMessagesPerConversation!==null&&Be>=le.maxMessagesPerConversation,Gt=le.maxTotalMessages!==null&&Fs>=le.maxTotalMessages,Br=h.useCallback(()=>{ue(w=>w+1)},[]),rr=hc(),sr=pc(),{isListening:dt,isSupported:Hr,startListening:mr,stopListening:gr,error:Xt}=Wu(w=>{y(R=>{const de=R.length>0&&!/\s$/.test(R)?" ":"",ve=(R+de+w).slice(0,le.maxMessageLength);return ne.current=ve,ve})},Br,{silenceTimeoutMs:rr,language:sr||void 0}),xr=dc(),it=uc(),nr=it&&Hr,St=cc(),Vr=ji(),$s=nf(ae==null?void 0:ae.adapterInfo),{skills:Lt,isLoading:qr,selectedSkill:He,selectSkill:br,clearSkill:ar}=d,Rs=(ae==null?void 0:ae.adapterName)||null,{suggestions:ut,selectedIndex:xt,setSelectedIndex:Ps,selectNext:Ds,selectPrevious:Us,clearSuggestions:bt,focusInputAfterSelection:yr,suppressUntilQueryChange:wr}=Xu(x,{enabled:Vr&&!dt,apiUrl:ae==null?void 0:ae.apiUrl,adapterName:Rs,sessionId:ae==null?void 0:ae.sessionId,adapterSupportsAutocomplete:$s,skill:(He==null?void 0:He.name)||null,inputRef:V}),$=ut.length>0,we=!dt,W=we&&$&&!Ae,Ne=x.startsWith("/")?x.slice(1):"",Je=Ne.toLowerCase().replace(/-/g," "),We=Je?Lt.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(Je)||w.description.toLowerCase().includes(Je)):Lt,vr=We.length>0?Math.min(mt,We.length-1):0,Et=We[vr]??null,Os=(Et==null?void 0:Et.name.replace(/-/g," "))??"",po=Ae&&Et&&x.startsWith("/")&&Os.toLowerCase().startsWith(Ne.toLowerCase())&&Os.length>Ne.length?Os.slice(Ne.length):null,mo=xt>=0?xt:0,kr=$?ut[mo]:null,Bn=h.useMemo(()=>{if(!kr)return null;const w=kr.text||"";if(!x)return w;const R=x;return w.toLowerCase().startsWith(R.toLowerCase())&&w.length>R.length?w.slice(R.length):null},[kr,x]),zs=po??Bn,go=x.trim().length===0&&!zs,xo=h.useCallback(w=>{if(!x)return i.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(x.toLowerCase()))return i.jsx("span",{className:"line-clamp-1 text-current",children:w});const R=w.slice(0,x.length),de=w.slice(x.length);return i.jsxs("span",{className:"line-clamp-1",children:[i.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:R}),i.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:de})]})},[x]),Hn=h.useCallback(w=>{var R;br(w),st(!1),y(""),bt(),qe(0),(R=V.current)==null||R.focus()},[bt,br]),bo=h.useCallback(()=>{var w;y("/"),st(!0),qe(0),(w=V.current)==null||w.focus()},[]),Vn=h.useCallback(()=>{var w;st(!1),y(""),qe(0),(w=V.current)==null||w.focus()},[]),Ot=h.useCallback(()=>{const w=V.current;if(!w||typeof window>"u")return;const R=Ce=>{const Ve=Ce+ds,Pe=Math.max(Ce-ds,0);w.style.paddingTop=`${Ve}px`,w.style.paddingBottom=`${Pe}px`,Rt({top:Ve,bottom:Pe})},de=window.getComputedStyle(w),ve=parseFloat(de.lineHeight||"0");!Number.isNaN(ve)&&ve>0?Pt(Ce=>Ce===ve?Ce:ve):Pt(Ce=>Ce===null?Ce:null),R(tn)},[]),yo=()=>{const w=V.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===x.length:!1},qn=(ae==null?void 0:ae.attachedFiles)||[],ir=ke?qn:T,wo=gt.reduce((w,R)=>{var de;return w+(((de=R.attachedFiles)==null?void 0:de.length)||0)},0),Wn=le.maxFilesPerConversation!==null&&le.maxFilesPerConversation>0&&qn.length>=le.maxFilesPerConversation,Kn=le.maxTotalFiles!==null&&wo>=le.maxTotalFiles,Sr=((ra=ae==null?void 0:ae.adapterInfo)==null?void 0:ra.isFileSupported)??!1,Bs=ir.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),yt=ke?!!I[ke]:!1,Wr=Object.values(I).some(Boolean),Hs=x.trim().length>0,Gn=at||Gt,Ue=e||Bs||yt||Gn,Xn=St&&Sr,Kr=Wn||Kn,jr=!Xn||Ue||Kr;h.useLayoutEffect(()=>{if(V.current){const w=V.current,R=120;if(x.length===0){w.style.height="32px",w.style.overflowY="hidden",Ot();return}w.style.height="auto";const de=w.scrollHeight;w.style.height=`${Math.min(de,R)}px`,w.style.overflowY=de>R?"auto":"hidden",Ot()}},[x,Ot]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=V.current;if(!w)return;const R=new ResizeObserver(()=>{Ot()});return R.observe(w),()=>{R.disconnect()}},[Ot]);const Yn=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},Gr=h.useCallback(()=>typeof window>"u"?!1:!!(a&&!window.matchMedia("(min-width: 1024px)").matches||s&&window.matchMedia("(max-width: 767px)").matches),[a,s]),Xr=h.useCallback(()=>{var w;(w=V.current)==null||w.focus({preventScroll:a})},[a]);h.useEffect(()=>{Gr()||n&&!Ue&&V.current&&!Yn()&&Xr()},[n,Ue,Gr,Xr]);const Qn=!!He||Lt.length>0&&x.length===0&&!Ue;h.useEffect(()=>{if(typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches||!Qn||document.activeElement!==V.current)return;const w=window.requestAnimationFrame(()=>{const R=V.current;!R||document.activeElement!==R||(R.blur(),R.focus({preventScroll:!0}))});return()=>window.cancelAnimationFrame(w)},[Qn]);const Vs=h.useRef(ie);h.useEffect(()=>{if(Gr()){Vs.current=ie;return}n&&Vs.current&&!ie&&!Ue&&V.current&&setTimeout(()=>{V.current&&!Yn()&&Xr()},100),Vs.current=ie},[n,ie,Ue,Gr,Xr]),h.useEffect(()=>{if(!nr||(Ee>te.current&&(je.current=!0,te.current=Ee),!je.current||Ee===0))return;const w=ne.current.trim(),R=be.getState();if(U("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:Ue,isComposing:v,isLoading:R.isLoading}),je.current=!1,!w)return;if(Ue||v){U("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const de=R.conversations.find(Pe=>Pe.id===R.currentConversationId),Ce=((de==null?void 0:de.attachedFiles)||[]).map(Pe=>Pe.file_id),Ve=He==null?void 0:He.name;U("[MessageInput] Auto-sending voice message immediately:",w),t(w,Ce.length>0?Ce:void 0,void 0,Ve),Ve&&ar(),setTimeout(()=>{st(!1)},0),bt(),setTimeout(()=>{y("")},0),ne.current="",V.current&&(V.current.style.height="auto",V.current.style.overflowY="hidden",Ot())},[nr,Ee,Ue,v,t,He,ar,Ot,bt]),h.useEffect(()=>{yt&&_&&setTimeout(()=>{b(!1)},0)},[yt,_]);const Yr=h.useCallback((w,R)=>{setTimeout(()=>{let de=be.getState(),ve=R||de.currentConversationId;if(ve||(ve=Ut(),de=be.getState(),ve=de.currentConversationId||ve),!ve){ge("[MessageInput] Unable to sync files: conversation ID missing");return}const Ce=new Set(w.map(Pe=>Pe.file_id)),Ve=[];se.current.forEach((Pe,Re)=>{const[,...Ge]=Re.split("-"),Qt=Ge.join("-");Ce.has(Qt)||Ve.push(Re)}),Ve.forEach(Pe=>se.current.delete(Pe)),w.forEach(Pe=>{const Re=`${ve}-${Pe.file_id}`;se.current.has(Re)||(se.current.add(Re),U(`[MessageInput] Adding file ${Pe.file_id} to conversation ${ve}`),de.addFileToConversation(ve,Pe))})},0)},[Ut]);h.useEffect(()=>{if(ke!==Z.current)if(Z.current=ke||null,ke&&ae){const w=ae.attachedFiles||[];setTimeout(()=>{k(w.map(R=>({...R})))},0)}else setTimeout(()=>{k([])},0)},[ke,ae]),h.useEffect(()=>{if(ke&&ae){const w=ae.attachedFiles||[];w.length>0?setTimeout(()=>{k(R=>{const de=new Set(R.map(Ce=>Ce.file_id)),ve=w.filter(Ce=>!de.has(Ce.file_id));return ve.length>0?(U(`[MessageInput] Syncing ${ve.length} missing files from conversation to UI`),[...R,...ve]):R})},0):w.length===0&&T.length>0&&setTimeout(()=>{k([])},0)}},[ke,ae,gt,T.length]);const qs=h.useRef(null),Ws=h.useRef(""),Qr=(ae==null?void 0:ae.attachedFiles)||[],Zr=Qr.length>0?`${Qr.length}:${Qr.map(w=>w.file_id).join("|")}`:"",Zn=Qr.some(w=>sn(w.processing_status));h.useEffect(()=>{if(!ke||!(ae!=null&&ae.adapterName))return;const w=Zr!=="";if(w&&(qs.current!==ke||Ws.current!==Zr)?(U(`[MessageInput] Syncing files for conversation ${ke}...`),qs.current=ke,Ws.current=Zr,ye(ke).catch(ve=>{ge("[MessageInput] Failed to sync conversation files:",ve)})):w||(qs.current=ke,Ws.current=""),!Zn)return;U("[MessageInput] Files still processing, starting poll...");const de=setInterval(async()=>{const Ce=be.getState().conversations.find(Re=>Re.id===ke);if(!Ce){clearInterval(de);return}if((Ce.attachedFiles||[]).filter(Re=>sn(Re.processing_status)).length===0){U("[MessageInput] All files completed processing, stopping poll"),clearInterval(de);return}try{await ye(ke)}catch(Re){ge("[MessageInput] Failed to poll file status:",Re)}},3e3);return()=>{clearInterval(de)}},[ke,ae==null?void 0:ae.adapterName,Zr,Zn,ye]),h.useEffect(()=>{setTimeout(()=>{P(w=>{const R=new Set(gt.map(Ce=>Ce.id));let de=!1;const ve={...w};return Object.keys(ve).forEach(Ce=>{R.has(Ce)||(delete ve[Ce],de=!0)}),de?ve:w})},0)},[gt]);const Jn=w=>{if(w.preventDefault(),Hs&&!Ue&&!v){dt&&gr();const de=((ae==null?void 0:ae.attachedFiles)||[]).map(Ce=>Ce.file_id),ve=He==null?void 0:He.name;t(x.trim(),de.length>0?de:void 0,void 0,ve),ve&&ar(),st(!1),_r("messageSent",oe.soundEnabled),y(""),ne.current="",k([]),b(!1),V.current&&(V.current.style.height="auto",V.current.style.overflowY="hidden",Ot())}},Jr=h.useCallback(w=>{if(!w||w.length===0)return;const R=w.length===1?m("messageInput.uploadSuccess.single",{filename:w[0].filename}):m("messageInput.uploadSuccess.multiple",{count:w.length});_r("success",oe.soundEnabled),Q(R),setTimeout(()=>{Q(null)},6e3)},[oe.soundEnabled,m]),vo=h.useCallback((w,R)=>{U(`[MessageInput] handleFilesSelected called with ${R.length} files for conversation ${w}:`,R),w&&(w===ke&&k(R),Yr(R,w))},[ke,Yr]),ko=h.useCallback((w,R)=>{w===ke&&Jr(R)},[ke,Jr]),So=h.useCallback(w=>{ce({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),jo=h.useCallback(()=>{ce(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),Co=h.useCallback(async()=>{if(!(!ke||!ee.fileId)){ce(w=>({...w,isDeleting:!0}));try{await Me(ke,ee.fileId),k(w=>w.filter(R=>R.file_id!==ee.fileId)),ce({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const R=w instanceof Error?w.message:m("messageInput.fileRemoveFailed");ge("[MessageInput] Failed to remove file:",w),z(R),ce({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[ke,ee.fileId,Me,m]),ea=h.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),es=h.useCallback(w=>{const R=ea(w);y(R),bt(),wr(R),yr(R)},[bt,yr,ea,wr]),Ks=h.useCallback(w=>{if(w<0)return;const R=ut[w]||ut[0];R&&es(R.text)},[ut,es]),Ao=w=>{if(Ae){if(w.key==="ArrowDown"){w.preventDefault(),qe(R=>We.length===0?0:(R+1)%We.length);return}if(w.key==="ArrowUp"){w.preventDefault(),qe(R=>We.length===0?0:(R-1+We.length)%We.length);return}if(w.key==="Home"){w.preventDefault(),qe(0);return}if(w.key==="End"){w.preventDefault(),qe(Math.max(We.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&Et){w.preventDefault(),Hn(Et);return}if(w.key==="Escape"){w.preventDefault(),Vn();return}}if($&&we){if(w.key==="ArrowDown"){w.preventDefault(),Ds();return}if(w.key==="ArrowUp"){w.preventDefault(),Us();return}if(w.key==="Tab"){w.preventDefault();const R=xt>=0?xt:0;Ks(R);return}if(w.key==="ArrowRight"&&yo()){if(Bn&&kr){w.preventDefault(),es(kr.text);return}if(xt>=0){w.preventDefault(),Ks(xt);return}}if(w.key==="Enter"&&xt>=0){w.preventDefault(),Ks(xt);return}if(w.key==="Escape"){w.preventDefault(),bt();return}}w.key==="Enter"&&!w.shiftKey&&!v&&(w.preventDefault(),Jn(w))},No=()=>{dt?gr():(bt(),mr())},Io=()=>{const w=!oe.voiceEnabled;_e({voiceEnabled:w}),w&&qt.enableAudio()},Lo=h.useCallback(async w=>{if(!St||!N||!Sr||Ue)return;const R=w.clipboardData;if(!R||!R.items)return;const ve=Array.from(R.items).filter(Re=>Re.kind==="file");if(ve.length===0)return;const Ce=[];if(ve.forEach((Re,Ge)=>{const Qt=Re.getAsFile();Qt&&Ce.push(df(Qt,Ge))}),Ce.length===0)return;w.preventDefault(),G(null),Q(null);let Ve=null;const Pe=new Set;try{const Re=be.getState(),Ge=Re.conversations.find(ot=>ot.id===Re.currentConversationId);if(((Ge==null?void 0:Ge.attachedFiles)||[]).length+Ce.length>le.maxFilesPerConversation)throw nt&&rt.getState().openLoginPrompt(m("fileUpload.maxFilesGuestLimitMessage",{count:le.maxFilesPerConversation})),new Error(m("fileUpload.maxFilesPerConversationError",{count:le.maxFilesPerConversation}));if(le.maxTotalFiles!==null&&Re.conversations.reduce((ft,Tt)=>{var Ye;return ft+(((Ye=Tt.attachedFiles)==null?void 0:Ye.length)||0)},0)+Ce.length>le.maxTotalFiles)throw nt&&rt.getState().openLoginPrompt(m("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),new Error(m("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles}));if(!Ge)throw new Error(m("messageInput.conversationNotFoundShort"));if(!Ge.adapterName)throw new Error(m("fileUpload.adapterNotConfigured"));const To=lt(Ge.apiUrl),Mo=Ge.adapterName;Ve=Ge.id,K(Ve,!0);const Cr=[],sa=[];for(let ot=0;ot<Ce.length;ot++){const ft=Ce[ot],Tt=ft.name||`Clipboard file ${ot+1}`,Ye=`${Tt}-${Date.now()}-${ot}`,Ar=ft.type.startsWith("image/")?URL.createObjectURL(ft):null;Ar&&Pe.add(Ar);let na=null;B(et=>{const zt=new Map(et);return zt.set(Ye,{filename:Tt,progress:0,status:"uploading"}),zt});const Fo=et=>{et.fileId&&!na&&(na=et.fileId,Ar&&(Yi(et.fileId,Ar),Pe.delete(Ar))),B(zt=>{const ht=new Map(zt),Nr=ht.get(Ye);return Nr&&ht.set(Ye,{...Nr,filename:Tt,progress:et.progress,status:et.status,fileId:et.fileId}),ht})},$o=()=>new Promise(et=>{B(zt=>{const ht=new Map(zt),Nr=ht.get(Ye);return Nr&&ht.set(Ye,{...Nr,progress:100,status:"completed"}),ht}),setTimeout(()=>{B(zt=>{const ht=new Map(zt);return ht.delete(Ye),ht}),et()},2500)});U(`[MessageInput] Pasting file: ${ft.name}, type: ${ft.type||"unknown"}, size: ${ft.size}`);const Ro=await Or.uploadFile(ft,et=>{U(`[MessageInput] Paste upload progress for ${ft.name}: ${et.progress}% - ${et.status}`),Fo(et)},void 0,To,Mo);Cr.push(Ro),sa.push($o())}if(Cr.length>0){let ot=Cr;if(Ve&&Ve===ke){const ft=new Set(T.map(Ye=>Ye.file_id)),Tt=Cr.filter(Ye=>!ft.has(Ye.file_id));Tt.length>0?(k(Ye=>[...Ye,...Tt]),ot=Tt):ot=[]}ot.length>0&&Yr(ot,Ve),await Promise.all(sa),Jr(Cr)}}catch(Re){const Ge=Re instanceof Error?Re.message:"Failed to paste file";ge("[MessageInput] Paste error:",Re),_r("error",oe.soundEnabled),G(Ge),Ge.toLowerCase().includes("maximum")&&z(Ge),setTimeout(()=>{G(null)},5e3),B(new Map),Pe.forEach(Qt=>URL.revokeObjectURL(Qt))}finally{K(Ve,!1)}},[T,ke,N,Sr,nt,Ue,K,oe.soundEnabled,Jr,Yr,St,m]),ta=nc(ae==null?void 0:ae.adapterName);let _t;Gt?_t=nt?m("messageInput.placeholder.guestLimitTotal",{count:le.maxTotalMessages}):m("messageInput.placeholder.workspaceLimitTotal",{count:le.maxTotalMessages}):at?_t=nt?m("messageInput.placeholder.guestLimitPerConversation",{count:le.maxMessagesPerConversation}):m("messageInput.placeholder.conversationLimitReached",{count:le.maxMessagesPerConversation}):Bs||yt?_t=m("messageInput.placeholder.filesUploading"):ta?_t=ta:Xn?_t=m("messageInput.placeholder.messageOrbit"):_t=r;const Yt=[];Gt&&le.maxTotalMessages!==null&&(nt?Dt&&Yt.push(m("messageInput.limitWarning.guestTotalMessages",{count:le.maxTotalMessages})):Yt.push(m("messageInput.limitWarning.workspaceTotalMessages",{count:le.maxTotalMessages}))),at&&le.maxMessagesPerConversation!==null&&(nt?Dt&&Yt.push(m("messageInput.limitWarning.guestPerConversation",{count:le.maxMessagesPerConversation})):Yt.push(m("messageInput.limitWarning.conversationLimitReached",{count:le.maxMessagesPerConversation}))),he&&Yt.push(he),h.useEffect(()=>{!it||!Xt||_r("error",oe.soundEnabled)},[it,oe.soundEnabled,Xt]),h.useEffect(()=>{if(!he)return;const w=setTimeout(()=>z(null),5e3);return()=>clearTimeout(w)},[he]),h.useEffect(()=>{var w;(_||yt||M.size>0||Wr)&&((w=fe.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[_,yt,M.size,Wr]),h.useEffect(()=>{var w;W&&((w=Se.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[W]),h.useEffect(()=>{var w;Ae&&((w=H.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[Ae,We.length]);const Eo=l,_o=o?"flex justify-center":"";return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`bg-transparent px-2 py-1.5 md:bg-transparent md:px-0 md:pt-4 md:pb-2 md:dark:bg-transparent sm:px-4 ${_o}`,children:i.jsxs("div",{className:`mx-auto w-full ${Eo}`,children:[Xt&&it&&i.jsxs("div",{role:"alert","aria-live":"assertive",className:"mb-2.5 w-full flex items-start gap-2.5 rounded-lg bg-red-50 dark:bg-red-950/40 px-3.5 py-2.5 animate-fadeIn",children:[i.jsx(xn,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),i.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:Xt})]}),X&&i.jsxs("div",{role:"alert","aria-live":"assertive",className:"mb-2.5 w-full flex items-start gap-2.5 rounded-lg bg-red-50 dark:bg-red-950/40 px-3.5 py-2.5 animate-fadeIn",children:[i.jsx(xn,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),i.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:X})]}),q&&i.jsxs("div",{role:"status","aria-live":"polite",className:"mb-2.5 w-full flex items-center gap-2.5 rounded-lg bg-gray-50 dark:bg-[#1f1f24] px-3.5 py-2.5 animate-fadeIn",children:[i.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/40",children:i.jsx(Hc,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"})}),i.jsx("span",{className:"text-sm text-[#353740] dark:text-[#ececf1]",children:q})]}),Yt.length>0&&i.jsxs("div",{role:"status","aria-live":"polite",className:"mb-2.5 w-full flex items-start gap-2.5 rounded-lg bg-amber-50 dark:bg-amber-950/30 px-3.5 py-2.5 animate-fadeIn",children:[i.jsx($n,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-amber-500 dark:text-amber-400"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("ul",{className:"list-none space-y-0.5",children:Yt.map((w,R)=>i.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${R}`))}),nt&&(Gn||Kr)&&Dt&&i.jsx("button",{type:"button",onClick:()=>rt.getState().openLoginPrompt(m("messageInput.signInPrompt.message")),className:"mt-2 inline-flex items-center gap-1.5 rounded-md bg-[#353740] px-3 py-1.5 text-xs font-medium text-white hover:bg-[#40414f] dark:bg-white dark:text-[#353740] dark:hover:bg-gray-200 transition-colors",children:m("messageInput.signInPrompt.button")})]})]}),i.jsxs("div",{className:"relative w-full",children:[i.jsxs("form",{onSubmit:Jn,className:"flex w-full flex-col gap-2 md:gap-3",children:[i.jsxs("div",{className:`grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1.5 md:flex md:flex-row md:flex-nowrap md:gap-2 rounded-xl md:rounded-lg border px-2.5 py-1.5 md:px-4 md:py-3 shadow-sm transition-all ${N?"border-gray-400 shadow-md dark:border-[#3a3a3a] dark:shadow-lg":"border-gray-300 dark:border-[#242424]"} bg-gray-50 dark:bg-[#111111]`,children:[He&&i.jsx("div",{className:"col-span-2 flex w-full shrink-0 basis-full md:contents",children:i.jsxs("div",{className:"flex h-8 max-w-[45%] shrink-0 items-center gap-1.5 rounded-full border border-gray-300 bg-white px-2.5 text-xs text-gray-700 shadow-sm dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-200 sm:max-w-[38%] md:self-center md:max-w-[32%]",children:[i.jsx(Fn,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:He.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>{var w;ar(),(w=V.current)==null||w.focus()},className:"-mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600","aria-label":m("messageInput.selectedSkill.removeAriaLabel"),children:i.jsx(Ze,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})}),!He&&Lt.length>0&&x.length===0&&!Ue&&i.jsx("div",{className:"col-span-2 flex w-full shrink-0 basis-full md:contents",children:i.jsxs("button",{type:"button",onClick:bo,className:"flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-gray-300 bg-white px-2.5 text-xs font-medium text-gray-600 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-300 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600 md:self-center","aria-label":m("messageInput.skillsHint.ariaLabel"),title:m("messageInput.skillsHint.title"),children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded bg-gray-200 font-mono text-[10px] leading-none text-gray-600 dark:bg-[#2a2a2a] dark:text-gray-300","aria-hidden":"true",children:"/"}),m("messageInput.skillsHint.text")]})}),i.jsxs("div",{className:"relative flex-1 w-full min-w-0 md:translate-y-0.5",children:[go&&_t&&i.jsx("div",{className:"pointer-events-none absolute inset-0 truncate whitespace-nowrap text-base md:text-sm text-gray-500 dark:text-[#8e8ea0]",style:{paddingTop:Math.max(vt.top-rf,0),paddingBottom:vt.bottom,paddingLeft:`${rn}px`,paddingRight:0,lineHeight:kt?`${kt}px`:void 0},"aria-hidden":"true",children:_t}),zs&&N&&i.jsxs("div",{className:"pointer-events-none absolute inset-0 whitespace-pre-wrap text-base md:text-sm text-gray-400 dark:text-[#8e8ea0]",style:{paddingTop:Math.max(vt.top-sf,0),paddingBottom:vt.bottom,paddingLeft:`${rn}px`,paddingRight:0,lineHeight:kt?`${kt}px`:void 0},"aria-hidden":"true",children:[i.jsx("span",{className:"invisible",children:x}),i.jsx("span",{children:zs})]}),i.jsx("textarea",{ref:V,"aria-label":m("messageInput.textarea.ariaLabel"),value:x,onChange:w=>{const R=w.target.value;y(R),R.startsWith("/")&&qe(0),st(R.startsWith("/")&&Lt.length>0)},onKeyDown:Ao,onPaste:Lo,onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onFocus:()=>C(!0),onBlur:()=>C(!1),placeholder:_t,disabled:Ue,rows:1,maxLength:le.maxMessageLength,className:"relative z-10 flex-1 w-full min-w-0 resize-none bg-transparent py-0 text-base md:text-sm text-[#353740] placeholder-transparent focus:outline-none dark:text-[#ececf1] dark:placeholder-transparent",style:{minHeight:"24px",maxHeight:"120px",paddingTop:`${vt.top}px`,paddingBottom:`${vt.bottom}px`,paddingLeft:`${rn}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:x.trim()||N?"inherit":"transparent"}})]}),i.jsxs("div",{className:"flex items-center justify-end gap-1 md:gap-2 flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[o&&!St&&i.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),St&&i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),jr||b(!_)},disabled:jr,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${_||ir.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":jr?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:Sr?Kr&&Wn&&le.maxFilesPerConversation!==null?m("messageInput.fileUpload.titleLimitPerConversation",{count:le.maxFilesPerConversation}):Kr&&Kn&&le.maxTotalFiles!==null?m("messageInput.fileUpload.titleLimitWorkspace",{count:le.maxTotalFiles}):Ue?m("messageInput.fileUpload.titleUploading"):ir.length>0?m("messageInput.fileUpload.titleAttached",{count:ir.length}):m("messageInput.fileUpload.attachAriaLabel"):m("messageInput.fileUpload.titleNotSupported"),"aria-label":m("messageInput.fileUpload.attachAriaLabel"),children:jr&&j?i.jsx(Ze,{className:"h-4 w-4"}):i.jsx(ld,{className:"h-4 w-4"})}),x.length>0&&i.jsx("div",{className:"hidden md:block px-2 text-xs text-gray-500 dark:text-[#bfc2cd] md:min-w-[72px] md:text-right",children:i.jsxs("span",{className:x.length>=le.maxMessageLength?"text-red-600 font-semibold":"",children:[x.length,"/",le.maxMessageLength]})})]}),i.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[i.jsx(to,{availableModels:u,defaultModel:f,selectedModel:p,onSelect:w=>g==null?void 0:g(w)}),(xr||it)&&i.jsxs(i.Fragment,{children:[xr&&i.jsx("button",{type:"button",onClick:Io,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${oe.voiceEnabled?"bg-blue-100 text-blue-600 dark:bg-blue-900/40 dark:text-blue-300":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:oe.voiceEnabled?m("messageInput.voiceOutput.titleEnabled"):m("messageInput.voiceOutput.titleDisabled"),"aria-label":oe.voiceEnabled?m("messageInput.voiceOutput.ariaLabelEnabled"):m("messageInput.voiceOutput.ariaLabelDisabled"),children:oe.voiceEnabled?i.jsx(Rn,{className:"h-5 w-5"}):i.jsx(bd,{className:"h-5 w-5"})}),nr&&i.jsx("button",{type:"button",onClick:No,disabled:Ue,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${dt?"!flex bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":Ue?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:m(Ue?"messageInput.voiceInput.titleUploading":dt?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":m(dt?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:dt||Ue&&O?i.jsx(td,{className:"h-5 w-5"}):i.jsx(rd,{className:"h-5 w-5"})})]}),c&&i.jsx("button",{type:"button",onClick:()=>E(!0),className:"hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]",title:m("messageInput.agentInfo.title"),"aria-label":m("messageInput.agentInfo.ariaLabel"),children:i.jsx(Ca,{className:"h-5 w-5"})}),(Bs||yt)&&i.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:i.jsx($i,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),ie?i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Te()},className:"flex h-9 w-9 md:h-8 md:w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700",title:m("messageInput.stop.title"),"aria-label":m("messageInput.stop.ariaLabel"),children:i.jsx(pd,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):i.jsx("button",{type:"submit",disabled:!Hs||Ue||v,className:`flex h-9 w-9 md:h-8 md:w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${Hs&&!Ue&&!v?"bg-black text-white hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200":"bg-gray-300 text-gray-500 dark:bg-[#565869] dark:text-[#6b6f7a]"}`,title:m("messageInput.submit.title"),"aria-label":m("messageInput.submit.ariaLabel"),children:i.jsx(gn,{className:"h-4 w-4"})})]})]})]}),ir.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2",children:ir.map(w=>{const R=sn(w.processing_status),de=w.processing_status==="failed"||w.processing_status==="error",ve=de?"error":R?w.processing_status==="uploading"?"uploading":"processing":"completed",Ce=R?w.processing_status==="uploading"?m("messageInput.attachedFile.uploadingStatus"):m("messageInput.attachedFile.processingStatus"):void 0;return i.jsx(js,{filename:w.filename,fileId:w.file_id,status:ve,statusText:Ce,errorMessage:de?w.error_message||m("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{de?(ke&&Me(ke,w.file_id),k(Ve=>Ve.filter(Pe=>Pe.file_id!==w.file_id))):So(w)},removeTitle:m(de?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),St&&(Sr||Wr)&&i.jsxs("div",{ref:fe,className:`rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32] transition-all duration-200 ${!_&&!yt&&M.size===0&&!Wr?"hidden":""}`,children:[_&&i.jsxs("div",{className:"mb-2 flex items-center justify-between px-1",children:[i.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:m("messageInput.uploadPanel.headingAttach")}),i.jsx("button",{type:"button",onClick:()=>b(!1),className:"flex h-6 w-6 items-center justify-center rounded-md text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:text-[#6b6f7a] dark:hover:bg-[#3c3f4a] dark:hover:text-[#bfc2cd] transition-colors",title:m("messageInput.uploadPanel.closeTitle"),children:i.jsx(Ze,{className:"h-3.5 w-3.5"})})]}),(yt||M.size>0)&&!_&&M.size===0&&i.jsx("div",{className:"mb-2 px-1",children:i.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:m("messageInput.uploadPanel.headingUploading")})}),M.size>0&&i.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(M.entries()).map(([w,R])=>i.jsx(js,{filename:R.filename,fileId:R.fileId,status:R.status,statusText:R.status==="uploading"?m("messageInput.uploadProgress.statusUploading"):R.status==="processing"?m("messageInput.uploadProgress.statusProcessing"):R.status==="completed"?m("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:R.error},w))}),i.jsx("div",{className:`${_||yt?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!(_||yt),children:i.jsx(tf,{conversationId:ke,onFilesSelected:vo,onUploadError:w=>{ge("File upload error:",w),z(w)},onUploadingChange:K,onUploadSuccess:ko,maxFiles:le.maxFilesPerConversation,disabled:jr})})]}),i.jsx("div",{className:"h-3 md:h-1",children:nr&&dt&&i.jsxs("span",{className:"flex items-center gap-2 text-sm md:text-xs text-gray-500 dark:text-[#bfc2cd]",children:[i.jsx("span",{className:"h-2.5 w-2.5 md:h-2 md:w-2 animate-pulse rounded-full bg-red-500"}),m("messageInput.listeningIndicator")]})})]}),Ae&&i.jsx("div",{ref:H,className:"w-full pt-1",children:i.jsx(eo,{skills:Lt,isLoading:qr,selectedSkill:He,activeSkillName:Et==null?void 0:Et.name,query:Ne,onActiveSkillChange:w=>{const R=We.findIndex(de=>de.name===w.name);R>=0&&qe(R)},onSelect:Hn,onClose:Vn})}),W&&i.jsx("div",{ref:Se,role:"listbox","aria-label":m("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:ut.map((w,R)=>{const de=R===xt;return i.jsx("button",{type:"button",role:"option","aria-selected":de,className:`flex w-full items-center gap-3 px-3 py-3 md:py-2.5 text-left text-[15px] md:text-sm transition-colors ${de?"bg-gray-100 dark:bg-[#2d2f39]":"hover:bg-gray-50 dark:hover:bg-[#2d2f39]/60"}`,onClick:()=>es(w.text),onMouseEnter:()=>Ps(R),children:xo(w.text)},R)})}),i.jsx(ws,{isOpen:ee.isOpen,onClose:jo,onConfirm:Co,title:m("messageInput.fileDelete.title"),message:m("messageInput.fileDelete.message",{filename:ee.filename}),confirmText:m("messageInput.fileDelete.confirmText"),cancelText:m("common.cancel"),type:"danger",isLoading:ee.isDeleting})]})]})}),S&&c&&typeof document<"u"&&As.createPortal(i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/60 p-4 backdrop-blur-sm animate-fadeIn",children:i.jsxs("div",{ref:J,role:"dialog","aria-modal":"true","aria-labelledby":"agent-info-title",tabIndex:-1,className:"w-full max-w-2xl max-h-[calc(100vh-2rem)] overflow-y-auto rounded-2xl bg-white shadow-2xl transform animate-fadeIn dark:bg-[#1a1b1e]",children:[i.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/20 flex items-center justify-center",children:i.jsx(Ca,{className:"w-5 h-5 text-blue-500"})}),i.jsx("h2",{id:"agent-info-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:m("messageInput.agentInfoModal.title")})]}),i.jsx("button",{type:"button",onClick:()=>E(!1),className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":m("messageInput.agentInfoModal.closeAriaLabel"),children:i.jsx(Ze,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),i.jsx("div",{className:"p-6",children:i.jsx($t,{content:c,className:`message-markdown w-full min-w-0 prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${Ie}`,syntaxTheme:D})}),i.jsx("div",{className:"flex items-center justify-end p-6 border-t border-gray-200 dark:border-[#2d2f39] bg-gray-50 dark:bg-[#111113] rounded-b-2xl",children:i.jsx("button",{type:"button",onClick:()=>E(!1),className:"px-4 py-3 md:py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium shadow-sm hover:shadow-md",children:m("messageInput.agentInfoModal.confirmButton")})})]})}),document.body)]})}function ei({adapter:t,onSelect:e}){var l;const{t:r}=Le(),n=(l=t.description)==null?void 0:l.trim(),{isDark:s}=tr(),a=s?"dark":"light",o=()=>e(t);return i.jsxs("div",{tabIndex:0,role:"button","data-agent-card":"true",onClick:o,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),o())},className:"group relative flex w-full cursor-pointer flex-col rounded-2xl border border-slate-200 bg-white px-4 py-3.5 text-left shadow-sm transition-colors duration-150 hover:border-slate-300 hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/30 dark:border-[#242424] dark:bg-[#080808] dark:hover:border-[#333333] dark:hover:bg-[#111111] dark:focus-visible:ring-sky-400/30 md:px-5 md:py-4",children:[i.jsx("div",{className:"relative",children:i.jsx("div",{className:"min-w-0",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"truncate text-[15px] font-semibold text-blue-700 dark:text-blue-300 md:text-base",children:t.name}),n?i.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:i.jsx($t,{content:n,className:"prose prose-slate max-w-none text-inherit dark:prose-invert [&>*]:mb-0 [&>*]:mt-0 [&_p]:overflow-hidden [&_p]:text-ellipsis [&_p]:[display:-webkit-box] [&_p]:[-webkit-box-orient:vertical] [&_p]:[-webkit-line-clamp:4]",syntaxTheme:a})}):i.jsx("p",{className:"mt-1 text-sm leading-5 text-slate-500 dark:text-slate-400",children:r("agentCard.configureMessage")})]}),i.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),o()},className:"hidden h-8 w-8 flex-shrink-0 items-center justify-center self-start rounded-full text-slate-700 transition-all duration-150 hover:bg-slate-100 group-hover:translate-x-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/30 dark:text-slate-200 dark:hover:bg-white/10 dark:focus-visible:ring-sky-400/30 md:inline-flex","aria-label":r("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(ja,{className:"h-4 w-4","aria-hidden":"true"})})]})})}),i.jsx("div",{className:"mt-3 flex items-center justify-end gap-3 border-t border-slate-200 pt-2.5 text-xs text-slate-500 dark:border-white/10 dark:text-slate-400 md:hidden",children:i.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),o()},className:"inline-flex h-8 w-8 items-center justify-center rounded-full text-slate-700 transition-all duration-150 hover:bg-slate-100 group-hover:translate-x-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/30 dark:text-slate-200 dark:hover:bg-white/10 dark:focus-visible:ring-sky-400/30","aria-label":r("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(ja,{className:"h-4 w-4","aria-hidden":"true"})})})]})}const Zt=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},uf=t=>{if(!t||typeof t!="object")return null;const e=t,r=Zt(e.name);if(!r)return null;const n=Zt(e.id);if(!n)return console.warn(`[middlewareConfig] Adapter "${r}" is missing a required 'id' field — skipping.`),null;const s=Zt(e.apiUrl),a=Zt(e.model),o=Zt(e.inputPlaceholder),l=typeof e.notes=="string"?e.notes.trim():void 0;let c=Zt(e.description)||Zt(e.summary);if(!c&&typeof l=="string"){const u=l.split(/\r?\n/).find(f=>f.trim().length>0);c=u?u.trim():void 0}const d={id:n,name:r};return s&&(d.apiUrl=s),c&&(d.description=c),l&&(d.notes=l),a&&(d.model=a),o&&(d.inputPlaceholder=o),d},so=t=>Array.isArray(t)?t.map(uf).filter(e=>e!==null):[];let Ht=null,nn=0;const ff=3e4;function hf(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){U("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=so(t.adapters);if(e.length===0)return null;const r=`{
|
|
347
|
+
"simple-chat": "default-key",
|
|
348
|
+
"dialoga": "orbit_PswAO5TJgX0yWEVdjOmuxwLLBpk0S74O",
|
|
349
|
+
"web-search": "orbit_XfxmYoTZgnp7zoMTKsIBfMBuYwj6U21P",
|
|
350
|
+
"chat-with-files": "multimodal",
|
|
351
|
+
"hr-db-chatbot": "human-resources",
|
|
352
|
+
"intent-sql-sqlite-classified": "classified",
|
|
353
|
+
"ecomm-analytics": "analytical",
|
|
354
|
+
"intent-duckdb-ev-population": "electric-vehicle",
|
|
355
|
+
"intent-http-jsonplaceholder": "rest-json-api",
|
|
356
|
+
"intent-http-paris-opendata": "paris-opendata",
|
|
357
|
+
"intent-mongodb-mflix": "mongodb-mflix",
|
|
358
|
+
"intent-graphql-spacex": "graphql-spacex",
|
|
359
|
+
"intent-sql-postgres": "postgres-customer-orders",
|
|
360
|
+
"open-ai-real-time-voice-chat": "open-ai-real-time-voice-chat",
|
|
361
|
+
"composite-multi-source-explorer": "composite-multi-source-explorer",
|
|
362
|
+
"math-teacher-quadratic": "math-teacher-trig-identities",
|
|
363
|
+
"qa-sql": "orbit_g6QuN5sPUh3fI2v0njoOJroXbAh1ILGP",
|
|
364
|
+
"qa-vector-chroma": "orbit_Rxm90sh85f8l5bzOLJpqpMUP9HcoNAX3",
|
|
365
|
+
"image-generator": "orbit_bZQ0h6kvpTphfCr9QgrCP13dkVclAsKQ",
|
|
366
|
+
"video-generator": "orbit_9P1vnx1GNMvVNyNCKF71VvVvcYx9duuo",
|
|
367
|
+
"intent-elasticsearch-log": "orbit_Ghpo8Q9mRdvVIODdw97ht7lBPpYBAzb6",
|
|
368
|
+
"audio-transcription": "orbit_RTBIwFoB6DA2mBuuHfnKf0xabwE6XKs2",
|
|
369
|
+
"voice-chat": "orbit_WjrkTqVjHE7mBa2ri8sAjENEVnLT9wbO",
|
|
370
|
+
"real-time-voice-chat": "orbit_xkvziKTXpZ1ufHWKg76pUDPbMDBRSRqC",
|
|
371
|
+
"tender-notices": "tender-notices",
|
|
372
|
+
"award-notices": "award-notices",
|
|
373
|
+
"contract-history": "contract-history",
|
|
374
|
+
"standing-offers": "standing-offers"
|
|
375
|
+
}`;if(!r.trim())return[];try{const n=JSON.parse(r),s=new Set(Object.entries(n).filter(([,a])=>{if(typeof a=="string")return a.trim().length>0;if(a&&typeof a=="object"){const o=a;if(typeof o.apiKey=="string"&&o.apiKey.trim().length>0||typeof o.key=="string"&&o.key.trim().length>0)return!0}return!1}).map(([a])=>a));return e.filter(a=>s.has(a.id))}catch{return[]}}}return null}async function Un(){if(Ht&&Date.now()-nn<ff)return Ht;try{const e=await fetch("/api/adapters?refresh=1",{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(e.ok){const r=await e.json(),n=so(r.adapters);if(n.length>0)return Ht=n,nn=Date.now(),U("Fetched adapters from /api/adapters:",Ht),Ht;U("/api/adapters response did not contain valid adapters, trying fallback")}U(`/api/adapters returned ${e.status}, trying fallback`)}catch(e){U("Could not fetch from /api/adapters, trying fallback:",e)}const t=hf();if(t&&t.length>0)return Ht=t,nn=Date.now(),U("Loaded adapters from config:",Ht),Ht;throw ge("No adapters available from API or config"),new Error("No adapters available. Define adapters in orbitchat.yaml and provide matching ids in VITE_ADAPTER_KEYS.")}const pf="h-[96px]";function mf({onAdapterSelect:t,className:e="",title:r="",subtitle:n="",eyebrow:s=""}){const{t:a}=Le(),[o,l]=h.useState([]),[c,d]=h.useState(!0),[u,f]=h.useState(null),p=h.useRef(null),g=h.useRef(null),[m,x]=h.useState(""),[y,v]=h.useState(!1),A=h.useCallback(()=>{const j=p.current;if(!j){v(!1);return}v(j.scrollHeight-j.scrollTop-j.clientHeight>20)},[]),N=()=>typeof window<"u"&&window.matchMedia("(min-width: 768px)").matches,C=()=>{var j;return Array.from(((j=p.current)==null?void 0:j.querySelectorAll('[data-agent-card="true"]'))??[])},S=j=>{const O=C()[j]??null;O&&(O.focus(),O.scrollIntoView({block:"nearest"}))},E=()=>{S(0)},_=()=>{const j=C();j.length!==0&&S(j.length-1)},b=j=>{if(!c&&!u&&I.length>0&&N()){if(j.key==="Tab"&&!j.shiftKey){j.preventDefault(),E();return}if(j.key==="ArrowDown"){j.preventDefault(),E();return}j.key==="ArrowUp"&&(j.preventDefault(),_())}},T=j=>{var X;if(!P||!N()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const L=document.activeElement;if(!(L instanceof HTMLElement)||L.dataset.agentCard!=="true")return;const O=C(),F=O.indexOf(L);if(F!==-1){if(j.preventDefault(),j.key==="ArrowDown"){S((F+1)%O.length);return}if(F===0){(X=g.current)==null||X.focus();return}S(F-1)}},k=m.trim().toLowerCase(),I=k?o.filter(j=>{var X,G;const L=j.name.toLowerCase().includes(k),O=((X=j.description)==null?void 0:X.toLowerCase().includes(k))??!1,F=((G=j.model)==null?void 0:G.toLowerCase().includes(k))??!1;return L||O||F}):o,P=m.trim().length>0,M=P||I.length===1;h.useEffect(()=>{const j=p.current;if(j)return A(),j.addEventListener("scroll",A,{passive:!0}),()=>j.removeEventListener("scroll",A)},[A,I]),h.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const F=(await Un()).slice().sort((X,G)=>X.name.localeCompare(G.name,void 0,{sensitivity:"base"}));j&&l(F)}catch(O){ge("[AgentSelectionList] Failed to load adapters",O),j&&f(a("agentSelectionList.unableToLoad"))}finally{j&&d(!1)}})(),()=>{j=!1}},[a]),h.useEffect(()=>{var j;c||u||o.length===0||(j=g.current)==null||j.focus()},[c,u,o.length]);const B=()=>c?i.jsx("div",{className:"grid gap-4",children:Array.from({length:3}).map((j,L)=>i.jsx("div",{className:`${pf} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},L))}):u?i.jsx("div",{className:"rounded-2xl border border-red-200 bg-transparent px-4 py-6 text-sm text-red-700 dark:border-red-900 dark:text-red-200",children:u}):o.length===0?i.jsx("div",{className:"rounded-2xl border border-gray-200 bg-transparent px-4 py-6 text-sm text-gray-600 dark:border-[#3b3c49] dark:text-gray-300",children:a("agentSelectionList.noAgentsAvailable")}):I.length===0?i.jsx("div",{className:"rounded-2xl border border-gray-200 bg-transparent px-4 py-6 text-sm text-gray-600 dark:border-[#3b3c49] dark:text-gray-300",children:a("agentSelectionList.noSearchResults")}):i.jsxs("div",{className:"relative flex flex-col h-full min-h-0",children:[i.jsx("div",{ref:p,onKeyDown:T,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:M?i.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:I.map(j=>i.jsx(ei,{adapter:j,onSelect:L=>t(L.id)},j.id))}):i.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:I.map(j=>i.jsx(ei,{adapter:j,onSelect:L=>t(L.id)},j.id))})}),y&&i.jsx("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-12 md:hidden bg-gradient-to-t from-white dark:from-[#212121] to-transparent","aria-hidden":"true"})]});return i.jsxs("div",{className:`flex w-full flex-col gap-4 md:gap-6 ${e}`,children:[(s||r||n)&&i.jsxs("div",{className:"flex-shrink-0",children:[s&&i.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:s}),r&&i.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:r}),n&&i.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:n})]}),i.jsx("div",{className:"flex w-full flex-shrink-0 justify-center",children:i.jsx("div",{className:"w-full max-w-xl lg:max-w-2xl",children:i.jsxs("div",{className:"relative overflow-hidden rounded-[1.75rem] border border-slate-300/90 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(248,250,252,0.94))] shadow-[0_10px_28px_rgba(15,23,42,0.05)] dark:border-white/20 dark:bg-[linear-gradient(180deg,rgba(37,39,49,0.95),rgba(29,31,39,0.92))] dark:shadow-[0_12px_30px_rgba(0,0,0,0.2)]",children:[i.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[inherit] bg-[linear-gradient(180deg,rgba(255,255,255,0.45),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"}),i.jsx(Mn,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 dark:text-slate-500"}),i.jsx("input",{ref:g,type:"text",placeholder:a("agentSelectionList.searchPlaceholder"),value:m,maxLength:100,disabled:c||!!u||o.length===0,onChange:j=>x(j.target.value),onKeyDown:b,className:"relative z-10 w-full bg-transparent py-3 pl-11 pr-11 text-sm font-medium text-slate-700 placeholder:font-normal placeholder:text-slate-400 focus:outline-none focus:ring-0 focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-60 dark:text-slate-100 dark:placeholder:text-slate-400"}),m&&i.jsx("button",{type:"button",onClick:()=>x(""),className:"absolute right-3 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200/80 bg-white/90 text-slate-400 transition-colors hover:border-slate-300 hover:text-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-200 dark:border-white/10 dark:bg-white/5 dark:text-slate-500 dark:hover:border-white/20 dark:hover:text-slate-200 dark:focus:ring-sky-500/20","aria-label":a("agentSelectionList.clearSearchAriaLabel"),children:i.jsx(Ze,{className:"h-3.5 w-3.5"})})]})})}),i.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:B()})]})}function jn(){return _n()?Es()==="entra"?i.jsx(xf,{}):i.jsx(gf,{}):null}function gf(){const{user:t,logout:e,loginWithRedirect:r}=Nn();if(!pr()||!t)return i.jsx(no,{onClick:()=>r()});const s=t.name||t.email||"User";return i.jsx(ao,{displayName:s,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function xf(){const{instance:t,accounts:e}=An();if(!pr()||e.length===0)return i.jsx(no,{onClick:()=>t.loginRedirect({scopes:Tn()}).catch(()=>{})});const n=e[0],s=n.name||n.username||"User";return i.jsx(ao,{displayName:s,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function no({onClick:t}){const{t:e}=Le();return i.jsxs("button",{onClick:t,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-blue-400/70 bg-blue-600 px-3 py-2 text-xs font-semibold text-white shadow-sm active:scale-[0.97] transition-all duration-150 hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600",children:[i.jsx(Ri,{className:"h-4 w-4"}),i.jsx("span",{children:e("common.signIn")})]})}function ao({displayName:t,onClick:e}){const{t:r}=Le();return i.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm text-gray-600 dark:text-[#bfc2cd]",children:[i.jsx("span",{className:"hidden max-w-[170px] truncate font-medium md:block",title:t,children:t}),i.jsxs("button",{onClick:e,className:"inline-flex min-h-10 items-center justify-center gap-1.5 rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600 shadow-sm transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-400 dark:border-[#454755] dark:text-[#c4c8d4] dark:hover:border-red-900/40 dark:hover:bg-red-900/20 dark:hover:text-red-300 md:rounded-full md:text-sm md:font-medium",title:r("authStatus.signOutButton.title"),"aria-label":r("authStatus.signOutButton.ariaLabel"),children:[i.jsx(Zc,{className:"h-4 w-4"}),i.jsx("span",{className:"hidden md:inline",children:r("common.logOut")})]})]})}function io({placement:t="default",compact:e=!1}){const{t:r}=Le();if(!Ii())return null;const n=Ic(),s=Lc(),a=Ec(),o=_c(),l=Tc(),c=Mc(),d=$c(),u=o?"border-t border-slate-200/80 dark:border-[#333645]":"",f=e?t==="sidebar"?"pt-4 pb-2":"pt-2 pb-2":c==="normal"?"pt-3 pb-3":"pt-5 pb-3",p=l==="inline"?"flex w-full flex-col gap-1 items-center justify-center text-center sm:flex-row sm:items-center sm:justify-center":"flex w-full flex-col items-center justify-center gap-1 text-center",g="justify-center",m=t==="sidebar"?"w-full px-2":"w-full px-3 sm:px-6",x=t==="sidebar"?"w-full":"mx-auto w-full max-w-7xl",y=e?"inline-flex min-h-8 items-center rounded px-1.5 text-xs font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300":"inline-flex min-h-10 items-center rounded-md px-2.5 text-sm font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300 sm:text-base";return i.jsx("footer",{className:`shrink-0 bg-white dark:bg-black text-sm ${f} ${u}`.trim(),style:{backgroundColor:s||void 0,color:a||void 0},children:i.jsx("div",{className:m,children:i.jsx("div",{className:x,children:i.jsxs("div",{className:p,children:[n&&i.jsx("p",{className:`${e?"text-xs leading-snug":"text-sm"} text-slate-700 dark:text-slate-200 ${t==="sidebar"?"pt-0.5":""}`.trim(),children:n}),d.length>0&&i.jsx("nav",{"aria-label":r("appFooter.navLinksAriaLabel"),children:i.jsx("ul",{className:`flex flex-wrap items-center ${g} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((v,A)=>{const N=l==="inline"&&A>0;return i.jsxs("li",{className:"flex items-center",children:[N&&i.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),i.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:y,style:{color:a||void 0},children:v.label})]},v.url)})})})]})})})})}const bf=60*1e3;let an=null,ti=0;const on=t=>{if(!t||t==="/")return"/";const e=t.trim();if(!e)return"/";const r=e.startsWith("/")?e:`/${e}`;return r==="/"?"/":r.endsWith("/")?r.slice(0,-1):r},oo=()=>{if(typeof window>"u")return on("/");const t=on("/");if(typeof document>"u")return t;const e=document.querySelector("base[href]");if(!e)return t;try{const r=new URL(e.getAttribute("href")||"/",window.location.origin);return on(r.pathname||t)}catch{return t}},Cs=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),yf=async()=>{const t=Date.now();if(an&&t-ti<bf)return an;let e=[];try{e=await Un()}catch(n){me("[agentRouting] Unable to load adapters for slug resolution",n)}const r=new Map;return e.forEach(n=>{const s=Cs(n.name);s&&r.set(s,n.id);const a=Cs(n.id);a&&a!==s&&r.set(a,n.id)}),an=r,ti=t,r},Cn=t=>{var a;const e=oo(),r=t.startsWith("/")?t:`/${t}`;let n=r;if(e!=="/"){if(!r.startsWith(e))return null;n=r.slice(e.length)}const s=n.split("/").filter(Boolean);return s.length===0?null:((a=s[0])==null?void 0:a.toLowerCase())||null},lo=t=>{const e=oo();if(!t)return e;const r=t.replace(/^\/+|\/+$/g,"");return e==="/"?r?`/${r}`:"/":`${e}/${r}`.replace(/\/{2,}/g,"/")},Ct=t=>{if(typeof window>"u")return;const e=lo(t),r=window.location.pathname;if(e===r)return;const n=window.location.search||"",s=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${n}${s}`)},wf=()=>lo(null),vf=async t=>{const e=t.trim().toLowerCase();return e&&(await yf()).get(e)||null};function kf({currentConversation:t,showEmptyState:e,createConversation:r,configureApiSettings:n,clearError:s,clearCurrentConversationAdapter:a}){var Se;const{t:o}=Le(),l=o("agent.error.singleAdapterMissing"),[c,d]=h.useState(!1),[u,f]=h.useState(null),p=Ls(),g=In(),m=typeof window<"u"?Cn(window.location.pathname):null,[x,y]=h.useState(m),[v,A]=h.useState(()=>!p&&e&&!m),N=h.useRef(null),C=h.useRef(new Map),S=h.useRef(0),E=3e4,_=!!t,b=(t==null?void 0:t.messages.length)??0,T=((Se=t==null?void 0:t.attachedFiles)==null?void 0:Se.length)??0,k=h.useMemo(()=>_&&(b>0||T>0),[T,b,_]),I=h.useCallback(()=>{Ke(()=>be.getState())},[]),P=h.useCallback((H,se)=>{if(!H)return;const ne=se||o("agent.error.configurationFailed");let je=!1;be.setState(te=>{const Z=te.conversations.find(oe=>oe.id===H);return!Z||Z.messages.length>0?te:(je=!0,{conversations:te.conversations.map(oe=>oe.id===H?{...oe,adapterLoadError:ne}:oe)})}),je&&I()},[I,o]),M=h.useCallback(H=>{if(!H)return;let se=!1;be.setState(ne=>{const je=ne.conversations.find(te=>te.id===H);return!je||!je.adapterLoadError?ne:(se=!0,{conversations:ne.conversations.map(te=>te.id===H?{...te,adapterLoadError:null}:te)})}),se&&I()},[I]),B=h.useCallback(H=>H instanceof Ki?H.status===401?o("agent.error.authenticationFailed"):H.status===404?o("agent.error.notFound"):H.message:H instanceof Error?H.message:o("agent.error.loadFailed"),[o]),j=h.useCallback(()=>{const H=be.getState(),se=H.currentConversationId?H.conversations.find(ne=>ne.id===H.currentConversationId):null;if(!se||se.messages.length>0)try{return r()}catch(ne){me("Cannot create a new conversation for agent selection:",ne instanceof Error?ne.message:"Unknown error")}return(se==null?void 0:se.id)||null},[r]),L=h.useCallback(async H=>{if(!(H!=null&&H.adapterName))return{ok:!1};try{const se=await Fe(),ne=new se.ApiClient({apiUrl:H.apiUrl||$e(),sessionId:null,adapterName:H.adapterName});if(typeof ne.getAdapterInfo!="function")return{ok:!1};const je=await ne.getAdapterInfo();return be.setState(te=>({conversations:te.conversations.map(Z=>Z.id===H.id?{...Z,adapterInfo:je,adapterLoadError:null,updatedAt:new Date}:Z)})),be.getState().currentConversationId===H.id&&f(null),I(),{ok:!0}}catch(se){const ne=B(se),je=be.getState();je.currentConversationId===H.id&&f({conversationId:H.id,message:ne});const te=je.conversations.find(Z=>Z.id===H.id);return te&&te.messages.length===0&&P(H.id,ne),{ok:!1,error:se}}},[B,P,I]),O=h.useCallback(async H=>{if(!H)return;const se=be.getState(),ne=se.currentConversationId?se.conversations.find(je=>je.id===se.currentConversationId):null;if(ne){d(!0),f(null),M(ne.id);try{const je=ne.apiUrl||$e();await n(je,void 0,H),s();const te=be.getState(),Z=te.conversations.find(oe=>oe.id===te.currentConversationId);if((Z==null?void 0:Z.adapterName)===H&&(!Z.adapterInfo||Z.adapterInfo.notes===void 0)){const oe=await L(Z);!oe.ok&&oe.error&&ge("Failed to load adapter info after selecting adapter:",oe.error)}}catch(je){ge("Failed to configure adapter from empty state:",je);const te=B(je);f({conversationId:ne.id,message:te}),P(ne.id,te)}finally{d(!1)}}},[M,s,n,L,B,P]),F=h.useCallback(H=>{p||(j(),A(!1),Ct(Cs(H)),O(H))},[j,O,p]),X=h.useCallback(()=>{p||(a(),Ct(null),A(!0))},[a,p]),G=h.useCallback(()=>{var je,te;if(p){const Z=be.getState(),oe=Z.currentConversationId?Z.conversations.find(xe=>xe.id===Z.currentConversationId):null;if(!!oe&&(oe.messages.length>0||(((je=oe.attachedFiles)==null?void 0:je.length)||0)>0))try{r()}catch(xe){me("Cannot go home (new conversation):",xe instanceof Error?xe.message:"Unknown error")}Ct(null),A(!1);return}y(null);const H=be.getState(),se=H.currentConversationId?H.conversations.find(Z=>Z.id===H.currentConversationId):null;if(!!se&&(se.messages.length>0||(((te=se.attachedFiles)==null?void 0:te.length)||0)>0))try{r()}catch(Z){me("Cannot go home (new conversation):",Z instanceof Error?Z.message:"Unknown error");return}else se!=null&&se.adapterName&&a();Ct(null),A(!0)},[a,r,p]),Q=!p&&e&&!x&&!(t!=null&&t.adapterName)&&!k||!p&&e&&v&&!(t!=null&&t.adapterName)&&!k;h.useEffect(()=>{if(p){Ct(null);return}if(!x){if(Q||!(t!=null&&t.adapterName)){Ct(null);return}Ct(Cs(t.adapterName))}},[t==null?void 0:t.adapterName,p,x,Q]);const he=h.useCallback(async()=>{if(typeof window>"u")return;const H=++S.current;if(p){Ct(null),y(null);return}const se=Cn(window.location.pathname);if(!se)return;const ne=await vf(se);if(H===S.current){if(!ne){j(),Ct(null),a(),A(!0),y(null);return}j(),A(!1),Ct(se),await O(ne),y(null)}},[a,j,O,p]),z=h.useRef(he);h.useEffect(()=>{z.current=he},[he]),h.useEffect(()=>{const H=window.setTimeout(()=>{z.current()},0),se=()=>{z.current()};return window.addEventListener("popstate",se),()=>{window.clearTimeout(H),S.current+=1,window.removeEventListener("popstate",se)}},[]);const ee=t==null?void 0:t.id,ce=t==null?void 0:t.adapterName,V=t==null?void 0:t.apiUrl,J=!!(t!=null&&t.adapterInfo);h.useEffect(()=>{if(!p||!g||!e||!ee||k||c)return;const H=(ce==null?void 0:ce.trim())||g,se=(ce==null?void 0:ce.trim())!==H||!J;if(!H||!se)return;let ne=!1;return(async()=>{d(!0),f(null),M(ee);try{const te=V||$e();await n(te,void 0,H),s()}catch(te){if(!ne){const Z=B(te);f({conversationId:ee,message:Z}),P(ee,Z)}}finally{ne||d(!1)}})(),()=>{ne=!0}},[M,s,n,k,B,c,p,P,e,ce,V,J,ee,g]),h.useEffect(()=>{(async()=>{const se=t==null?void 0:t.adapterName,ne=t?`${t.id}:${se}`:null;if(!(!ne||N.current===ne))if(se){N.current=ne,U("[ChatInterface] Refreshing adapter info from the backend - adapterName:",se);const je=await L(t);if(je.ok)U("[ChatInterface] Adapter info loaded successfully");else{const te=je.error;ge("[ChatInterface] Failed to load adapter info:",te);const Z=te instanceof Error?te.message:String(te);if((Z.includes("429")||Z.includes("Too Many Requests"))&&se){const _e=C.current.get(ne);_e&&clearTimeout(_e);const xe=setTimeout(()=>{N.current===ne&&(N.current=null),C.current.delete(ne)},E);C.current.set(ne,xe),me(`[ChatInterface] Adapter info request rate-limited; retrying in ${E/1e3}s`)}else N.current=null}}else U("[ChatInterface] Skipping adapter info refresh: no adapter selected")})()},[L,t]),h.useEffect(()=>{const H=C.current;return()=>{H.forEach(se=>clearTimeout(se)),H.clear()}},[]);const fe=p&&!g?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:fe,handleAgentCardSelection:F,handleChangeAgent:X,goToAgentSelectionHome:G,hasAdapterConfigurationError:!!fe,isAgentSelectionVisible:v,isConfiguringAdapter:c,isSingleAdapterMode:p,setIsAgentSelectionVisible:A,shouldShowAgentSelectionList:Q}}const co=h.createContext(null),Sf={registerGoHome:()=>{},goHome:()=>{}};function uo(){return h.useContext(co)??Sf}function jf({adapter:t,syntaxTheme:e,forcedThemeClass:r=""}){var s;const n=(s=t.notes)==null?void 0:s.trim();return n?i.jsxs("section",{"aria-labelledby":"agent-seo-content-title",className:"mx-auto w-full max-w-[56rem] px-1 text-left sm:px-0",children:[i.jsx("h2",{id:"agent-seo-content-title",className:"sr-only",children:t.name}),i.jsx("div",{children:i.jsx($t,{content:n,className:`message-markdown prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${r}`,syntaxTheme:e})})]}):null}const Cf='meta[name="description"]',Af='meta[property="og:title"]',Nf='meta[property="og:description"]',If='meta[property="og:type"]',Lf='link[rel="canonical"]';function ri(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ef(t){return t.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/^>\s?/gm,"").replace(/[*_~]/g,"").replace(/\s+/g," ").trim()}function _f(t,e){const r=t==null?void 0:t.trim();if(r)return r;if(!e)return En();const n=Ef(e);return n.length>160?`${n.slice(0,157).trimEnd()}...`:n}function Tf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mf(t){const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Ff(t){const e=t.trim();if(!e)return null;const r=`^${Tf(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(r,"i")}catch{return null}}function $f(t){return[Si(),...ac()].map(Mf).filter(r=>!!r).includes(t)?!0:ic().some(r=>{const n=Ff(r);return n?n.test(t):!1})}function Rf(t){var n,s,a;const e=t==null?void 0:t.trim();if(!e)return null;const r=Y.adapters.find(o=>{var l;return((l=o==null?void 0:o.id)==null?void 0:l.trim())===e});return r?{id:r.id,name:((n=r.name)==null?void 0:n.trim())||r.id,description:((s=r.description)==null?void 0:s.trim())||void 0,notes:((a=r.notes)==null?void 0:a.trim())||void 0}:null}function Pf(t){var n,s,a;if(typeof window>"u")return null;const e=Cn(window.location.pathname);if(!e)return null;const r=Y.adapters.find(o=>{const l=ri(o.name||""),c=ri(o.id||"");return e===l||e===c});return r?{id:r.id,name:((n=r.name)==null?void 0:n.trim())||r.id,description:((s=r.description)==null?void 0:s.trim())||void 0,notes:((a=r.notes)==null?void 0:a.trim())||void 0}:null}function us(t,e,r){if(typeof document>"u")return null;const n=document.querySelector(t);if(n)return n;const s=document.createElement("meta");return s.setAttribute(e,r),document.head.appendChild(s),s}function Df(){if(typeof document>"u")return null;const t=document.querySelector(Lf);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function fo(t){if(typeof document>"u")return;const e=Ln(),r=t?`${t.name} | ${e}`:e,n=t?_f(t.description,t.notes):En();document.title=r;const s=us(Cf,"name","description");s&&(s.content=n);const a=us(Af,"property","og:title");a&&(a.content=r);const o=us(Nf,"property","og:description");o&&(o.content=n);const l=us(If,"property","og:type");l&&(l.content="website");const c=Df();if(c&&typeof window<"u"){const d=Si(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",g=`${u&&$f(u)?u:f||u}${window.location.pathname}`;c.href=g}}function Uf(){return oc()}class On{static async getAdapterModels(e,r){const n=await Fe(),s=new n.ApiClient({apiUrl:"",adapterName:r});if(!s.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return s.getAdapterModels(e)}static async getAllModels(e){const r=await Fe(),n=new r.ApiClient({apiUrl:"",adapterName:e});if(!n.getAllModels)throw new Error("getAllModels is not available on this API client");return n.getAllModels()}static async listAdapterModels(e,r){return(await On.getAdapterModels(e,r)).models}}const Of="rounded-t-[32px] border border-white/40 bg-transparent px-4 pb-4 pt-[max(env(safe-area-inset-top),1rem)] shadow-none backdrop-blur-0 dark:border-[#2f303d] dark:bg-transparent md:rounded-none md:border-0 md:bg-transparent md:px-0 md:pb-0 md:pt-3 md:shadow-none md:backdrop-blur-0 md:dark:bg-transparent md:dark:border-0",zf="shrink-0 sticky bottom-[calc(var(--app-footer-height,0px)+0.25rem)] z-10 -mx-4 mt-auto overflow-visible bg-transparent pb-[max(env(safe-area-inset-bottom),0.5rem)] shadow-none backdrop-blur-0 transition-all duration-200 dark:bg-transparent md:bottom-[calc(var(--app-footer-height,0px)+0.5rem)] md:z-10 md:mx-0 md:mt-0 md:overflow-visible md:rounded-none md:border-0 md:bg-transparent md:pb-0 md:shadow-none md:backdrop-blur-0 md:dark:bg-transparent md:dark:border-0 [&>div]:bg-transparent md:[&>div]:rounded-none md:[&>div]:px-0",Bf="relative z-20 shrink-0 -mx-4 px-4 pt-2 pb-2 bg-transparent border-b border-transparent dark:border-transparent dark:bg-transparent md:static md:mx-0 md:px-0 md:pt-6 md:pb-6 md:bg-transparent md:border-gray-200 md:dark:border-[#4a4b54] md:dark:bg-transparent";function Hf({onOpenSettings:t,onOpenSidebar:e}){var Pt,Kt,nt,Dt,Ut,ke,gt;const{t:r}=Le(),{conversations:n,currentConversationId:s,createConversation:a,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:p,clearError:g,createThread:m,clearCurrentConversationAdapter:x}=be(),{settings:y}=Ns(),v=pr(),A=tt()&&!v,{theme:N,isDark:C}=tr(),S=N.mode==="dark"?"dark":N.mode==="light"?"light":"",E=C?"dark":"light",_=["application-description agent-home-markdown prose prose-slate dark:prose-invert max-w-none text-sm md:text-base leading-relaxed","text-[#4a4c5a] dark:text-[#bfc2cd]","[&>:first-child]:mt-0 [&>:last-child]:mb-0",S].filter(Boolean).join(" "),b=n.find(ie=>ie.id===s),T=n.some(ie=>{var ye;return(ie.messages.length>0||(((ye=ie.attachedFiles)==null?void 0:ye.length)||0)>0)&&!ie.adapterLoadError}),k=!b||b.messages.length===0,I=((Pt=b==null?void 0:b.adapterInfo)==null?void 0:Pt.supportsThreading)===!0,P=!!(b!=null&&b.adapterName&&(b!=null&&b.adapterInfo))&&!I,M=Gi({adapterName:b==null?void 0:b.adapterName,enabled:P,selectionScopeKey:s,supportsThreading:I}),B=ki(),j=Ln(),L=En().trim(),O=L.length>0,{registerGoHome:F}=uo(),[X,G]=h.useState([]),[q,Q]=h.useState(null);h.useEffect(()=>{const ie=b==null?void 0:b.adapterName;let ye=!1;async function Te(){if(Q(null),!ie){G([]);return}try{const Me=await On.listAdapterModels(ie,ie);if(ye)return;G(Me),Q(Me.length>0?Me[0].name:null)}catch{ye||(G([]),Q(null))}}return Te(),()=>{ye=!0}},[b==null?void 0:b.adapterName]);const{adapterNotesError:he,handleAgentCardSelection:z,handleChangeAgent:ee,goToAgentSelectionHome:ce,hasAdapterConfigurationError:V,isAgentSelectionVisible:J,isConfiguringAdapter:fe,isSingleAdapterMode:Se,shouldShowAgentSelectionList:H}=kf({currentConversation:b,showEmptyState:k,createConversation:a,configureApiSettings:f,clearError:g,clearCurrentConversationAdapter:x});h.useLayoutEffect(()=>(F(()=>ce()),()=>F(null)),[F,ce]);const se="max-w-[96rem]",ne="max-w-[64rem]",je="max-w-[56rem]",te=`mx-auto w-full ${se}`,Z=o(),oe=!!(b!=null&&b.adapterName)&&((b==null?void 0:b.messages.length)||0)===0,_e=r(Z?"chatInterface.newConversation.tooltipCanStart":A?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),xe=!!(b&&!H),De=H?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",Ie=!mn()&&H?"pt-0 pb-0 md:pt-0 md:pb-1":"",K=`${Bf} ${De} ${Ie}`.trim(),Ee=Ii(),ue=n.some(ie=>{var ye;return(ie.messages.length>0||(((ye=ie.attachedFiles)==null?void 0:ye.length)??0)>0)&&!ie.adapterLoadError}),Ae=Ee&&!ue,st=H?"pt-0 md:pt-0":"pt-4 md:pt-6",mt=h.useMemo(()=>{var Me,ae,Be;if(H)return null;const ie=Rf(b==null?void 0:b.adapterName)||Pf();if(!ie&&!(b!=null&&b.adapterName))return null;const ye=(Me=b==null?void 0:b.adapterName)==null?void 0:Me.trim(),Te=(Be=(ae=b==null?void 0:b.adapterInfo)==null?void 0:ae.notes)==null?void 0:Be.trim();return ie?{...ie,notes:Te||ie.notes}:ye?{id:ye,name:ye,notes:Te||void 0}:null},[(Kt=b==null?void 0:b.adapterInfo)==null?void 0:Kt.notes,b==null?void 0:b.adapterName,H]);h.useEffect(()=>{fo(mt)},[mt]),h.useEffect(()=>{let ie=null;const ye=()=>{ie&&(ie(),ie=null)};if(y.voiceEnabled){if(qt.isAudioEnabled())return U("[ChatInterface] Audio streaming already enabled"),ye;const Te=()=>{ye();const Me=async()=>{ye(),await qt.enableAudio()?U("[ChatInterface] Audio streaming enabled after user gesture"):(me("[ChatInterface] User gesture did not enable audio streaming"),Te())};document.addEventListener("pointerdown",Me,{once:!0}),document.addEventListener("keydown",Me,{once:!0}),ie=()=>{document.removeEventListener("pointerdown",Me),document.removeEventListener("keydown",Me)},U("[ChatInterface] Waiting for user gesture to enable audio streaming")};return Te(),ye}return ye(),qt.disableAudio(),U("[ChatInterface] Audio streaming disabled via settings"),ye},[y.voiceEnabled]);const qe=(ie,ye,Te,Me)=>{var ae;l(ie,ye,Te,q??((ae=b==null?void 0:b.adapterInfo)==null?void 0:ae.model)??void 0,Me)},vt=async(ie,ye,Te,Me,ae)=>{var Be;await l(Te,void 0,ie,ae??q??((Be=b==null?void 0:b.adapterInfo)==null?void 0:Be.model)??void 0,Me)},Rt=()=>{try{a()}catch(ie){me("Cannot create new conversation:",ie instanceof Error?ie.message:"Unknown error")}},kt=h.useCallback(async(ie,ye)=>{if(b)try{await be.getState().deleteThread(b.id,ie,ye)}catch(Te){ge("Failed to clear thread:",Te)}},[b]);return i.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":r("chatInterface.workspace.ariaLabel"),children:i.jsx("div",{className:"flex h-full w-full flex-col overflow-hidden px-3 sm:px-5 lg:px-8",children:i.jsxs("div",{className:`mx-auto flex h-full w-full ${se} flex-col overflow-hidden md:pb-4 ${Of}`,children:[p&&i.jsx("div",{role:"alert",className:"mt-6 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsx("p",{children:p}),i.jsx("button",{onClick:g,className:"ml-4 rounded p-1 text-red-500 hover:bg-red-100 hover:text-red-700 dark:text-red-200 dark:hover:bg-red-800/40","aria-label":r("chatInterface.error.dismissAriaLabel"),children:"×"})]})}),i.jsxs("div",{className:K,children:[e&&i.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2 md:hidden",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("button",{onClick:e,disabled:!T,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-semibold shadow-sm transition-all duration-150 ${T?"border-white/50 bg-white/80 text-gray-800 active:scale-[0.97] hover:bg-white dark:border-[#2f303d] dark:bg-[#232430] dark:text-[#ececf1]":"cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400 shadow-none dark:border-[#2f303d] dark:bg-[#181922] dark:text-[#6b6f7a]"}`,"aria-label":r("chatInterface.mobile.openChatsMenuAriaLabel"),children:[i.jsx(ed,{className:"h-4 w-4"}),r("chatInterface.mobile.chatsButton")]}),i.jsxs("button",{onClick:t,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-white/50 bg-[#11121a]/90 px-3 py-2 text-xs font-semibold text-white shadow-sm active:scale-[0.97] transition-all duration-150 hover:bg-[#0c0d14] dark:border-[#3b3c49] dark:bg-[#565869] dark:hover:bg-[#6b6f7a]","aria-label":r("chatInterface.mobile.openSettingsAriaLabel"),children:[i.jsx(Ia,{className:"h-4 w-4"}),r("chatInterface.mobile.settingsButton")]})]}),i.jsx("div",{className:"ml-auto flex-shrink-0",children:i.jsx(jn,{})})]}),i.jsxs("div",{className:"flex flex-col gap-2 md:gap-4 sm:flex-row sm:items-end sm:justify-between",children:[i.jsx("div",{className:"min-w-0 flex-1",children:xe&&i.jsx("div",{className:"space-y-1.5 md:space-y-3",children:i.jsxs("div",{className:"md:space-y-1",children:[i.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[i.jsx("h1",{className:"min-w-0 truncate text-lg md:text-2xl font-semibold text-[#353740] dark:text-[#ececf1]",children:(b==null?void 0:b.title)||r("chatInterface.newChatTitle")}),b&&i.jsx("span",{className:"flex-shrink-0 text-xs md:hidden text-gray-500 dark:text-[#bfc2cd]",children:b.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),b&&i.jsx("div",{className:"hidden md:flex items-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:i.jsx("span",{children:r("chatInterface.updatedAt",{time:b.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})})})]})})}),i.jsxs("div",{className:"flex w-full flex-wrap items-center gap-2 my-2 md:my-0 sm:w-auto md:justify-end md:gap-3",children:[i.jsx("div",{className:"hidden flex-shrink-0 items-center md:inline-flex",children:i.jsx("button",{onClick:t,className:"inline-flex h-[42px] w-[42px] items-center justify-center rounded-full border border-gray-200 text-gray-500 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/50 dark:border-[#3c3f4a] dark:text-[#9aa1bc] dark:hover:border-[#4d5166] dark:hover:bg-[#2d2f39] dark:hover:text-[#ececf1]","aria-label":r("chatInterface.settings.ariaLabel"),title:r("chatInterface.settings.title"),children:i.jsx(Ia,{className:"h-4 w-4"})})}),!Se&&!H&&!!(b!=null&&b.adapterName)&&i.jsx("button",{type:"button",onClick:()=>{oe&&ee()},disabled:!oe,className:`order-2 sm:order-1 inline-flex h-8 md:h-[42px] w-[calc(50%-0.25rem)] min-w-[140px] md:w-[190px] items-center justify-center gap-1 md:gap-2 rounded-full border px-2.5 md:px-3.5 py-1.5 md:py-2.5 text-[11px] md:text-[13px] font-medium tracking-[0.01em] transition-colors focus-visible:outline-none focus-visible:ring-2 ${oe?"border-blue-300 text-blue-700 hover:bg-blue-50 hover:border-blue-400 focus-visible:ring-blue-500 dark:border-blue-500/40 dark:text-blue-300 dark:hover:bg-blue-900/20 dark:hover:border-blue-400/60 dark:focus-visible:ring-blue-400/60":"cursor-not-allowed border-gray-200 text-gray-400 bg-transparent dark:border-[#3c3f4a] dark:text-[#6b6f7a]"}`,title:r(oe?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:r("chatInterface.changeAgent.button")}),!H&&i.jsxs("button",{onClick:Rt,disabled:!Z,className:`order-3 sm:order-2 inline-flex h-8 md:h-[42px] w-[calc(50%-0.25rem)] min-w-[160px] md:w-[220px] md:min-w-[220px] items-center justify-center gap-1 md:gap-2 rounded-full border px-2.5 md:px-3.5 py-1.5 md:py-2.5 text-[11px] md:text-[13px] font-medium tracking-[0.01em] whitespace-nowrap ${Z?"border-[#1f2937] bg-[#1f2937] text-white shadow-[0_2px_8px_rgba(15,23,42,0.12)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1f2937]/40 dark:border-[#4b5568] dark:bg-[#2f3747] dark:text-[#e9edf8] dark:shadow-[0_2px_8px_rgba(0,0,0,0.25)] dark:focus-visible:ring-[#6f809f]/35":"cursor-not-allowed border-gray-200 text-gray-400 bg-white/40 dark:border-[#3c3f4a] dark:text-[#6b6f7a] dark:bg-transparent"}`,title:_e,children:[i.jsx(ud,{className:"h-3.5 w-3.5"}),r("chatInterface.newConversation.button")]}),!mn()&&i.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:i.jsx(jn,{})})]})]})]}),k?i.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${st} ${H?"overflow-hidden":""}`,children:[H?i.jsx("div",{className:"flex-1 flex flex-col md:justify-start min-h-0 overflow-hidden",children:i.jsx("div",{className:"w-full flex flex-col min-h-0 overflow-hidden flex-1",children:i.jsxs("div",{className:"flex flex-col min-h-0 flex-1 gap-3 overflow-hidden md:gap-6",children:[i.jsx("div",{className:`${te} flex-shrink-0 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between`,children:i.jsxs("div",{className:"flex-1",children:[i.jsx($t,{content:j,className:"agent-home-markdown prose prose-slate dark:prose-invert max-w-none [&>:first-child]:mt-0 [&>:last-child]:mb-0 text-2xl font-semibold text-[#11111b] dark:text-white text-center md:text-left [&_p]:text-2xl [&_p]:font-semibold [&_p]:leading-tight [&_p]:m-0",syntaxTheme:E}),O&&i.jsx("div",{className:"mt-2",children:i.jsx($t,{content:L,className:_,syntaxTheme:E})})]})}),i.jsx(mf,{onAdapterSelect:z,className:`${te} md:flex-1 md:min-h-0 md:overflow-hidden`})]})})}):i.jsx("div",{className:"flex flex-1 w-full min-h-0 flex-col overflow-y-auto pt-4 md:pt-6",children:i.jsxs("div",{className:`mx-auto flex w-full ${je} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[he?i.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:he}):b!=null&&b.adapterName?i.jsx("h2",{className:"w-full text-center text-xl font-semibold tracking-tight text-[#353740] dark:text-[#ececf1] md:text-2xl",style:{fontFamily:'-apple-system, "SF Pro Display", BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},children:sc(b.adapterName)||b.adapterName}):fe?i.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:r("chatInterface.empty.configuringAgent")}):null,mt&&Uf()&&i.jsx(jf,{adapter:mt,syntaxTheme:E,forcedThemeClass:S}),i.jsx("div",{className:"w-full min-w-0",children:i.jsx(Ja,{onSend:qe,disabled:u||!b||!(b!=null&&b.adapterName)||V,autoFocusEnabled:!0,desktopOnlyAutoFocus:Se,placeholder:B,isCentered:!0,maxWidthClass:je,adapterNotes:(nt=b==null?void 0:b.adapterInfo)==null?void 0:nt.notes,skillState:M,availableModels:X,defaultModel:((Dt=b==null?void 0:b.adapterInfo)==null?void 0:Dt.model)??null,selectedModel:q,onSelectModel:Q})})]})}),Ae&&i.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:i.jsx(io,{compact:!0})})]}):i.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[i.jsx(Vu,{messages:b.messages,onRegenerate:ie=>{var ye;return c(ie,q??((ye=b==null?void 0:b.adapterInfo)==null?void 0:ye.model)??void 0)},onEditMessage:(ie,ye)=>{var Te;return d(ie,ye,q??((Te=b==null?void 0:b.adapterInfo)==null?void 0:Te.model)??void 0)},onStartThread:async(ie,ye)=>{try{await m(ie,ye)}catch(Te){ge("Failed to create thread:",Te)}},onClearThread:kt,onSendThreadMessage:vt,sessionId:b.sessionId,isLoading:u,contentMaxWidthClass:ne,availableModels:X,defaultModel:((Ut=b==null?void 0:b.adapterInfo)==null?void 0:Ut.model)??null,selectedModel:q}),i.jsx("div",{className:zf,children:i.jsx("div",{className:"mx-auto w-full max-w-[96rem] px-3 sm:px-5 md:px-6 lg:px-8 xl:px-10",children:i.jsx(Ja,{onSend:qe,disabled:u||!b||!b.adapterName||J||V,autoFocusEnabled:!0,placeholder:r("chatInterface.docked.placeholder"),maxWidthClass:ne,isCentered:!1,adapterNotes:(ke=b==null?void 0:b.adapterInfo)==null?void 0:ke.notes,skillState:M,availableModels:X,defaultModel:((gt=b==null?void 0:b.adapterInfo)==null?void 0:gt.model)??null,selectedModel:q,onSelectModel:Q})})})]})]})})})}function Vf({selectedAdapter:t,onAdapterChange:e,disabled:r,showDescriptions:n=!1,variant:s="sidebar",label:a,showLabel:o}){const{t:l}=Le(),[c,d]=h.useState([]),[u,f]=h.useState(!0),[p,g]=h.useState(null),[m,x]=h.useState(!1);h.useEffect(()=>{let T=!0;async function k(){try{f(!0),g(null);const I=await Un();T&&d(I)}catch(I){ge("Failed to load adapters:",I),T&&g(l("adapterSelector.failedToLoad"))}finally{T&&f(!1)}}return k(),()=>{T=!1}},[l]);const y=c.find(T=>T.id===t),v=typeof o=="boolean"?o:s==="prominent",A=a||l(s==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),N=h.useMemo(()=>s==="prominent"?"relative w-full text-left":"relative w-full",[s]),C=h.useMemo(()=>{const T="w-full rounded-md border bg-white px-4 py-3 text-left text-sm text-[#353740] focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 dark:bg-[#343541] dark:text-[#ececf1]";return s==="prominent"?[T,"border-gray-300 shadow-sm transition-all duration-200 focus-visible:ring-blue-500 dark:border-[#4a4b54] dark:focus-visible:ring-blue-400"].join(" "):["w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-left text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1] dark:focus:border-[#6b6f7a]"].join(" ")},[s]),S=h.useMemo(()=>s==="prominent"?"absolute z-20 mt-2 w-full rounded-xl border border-gray-200 bg-white shadow-xl ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]":"absolute z-20 mt-1 w-full rounded-md border border-gray-200 bg-white shadow-lg ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]",[s]),b=v?`mb-2 block text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-[#bfc2cd] ${s==="prominent"?"!text-sm !font-semibold !text-gray-700 dark:!text-white":""}`:"sr-only";return i.jsxs("div",{className:N,children:[i.jsx("label",{className:b,children:A}),i.jsxs("div",{className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>!r&&x(!m),disabled:r||u||c.length===0,className:`${C} disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":A,children:i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex flex-col min-w-0",children:[i.jsx("span",{className:`truncate font-medium ${y?"text-[#11121a] dark:text-white":"text-gray-500 dark:text-gray-400"}`,children:u?l("adapterSelector.loadingAgents"):p?l("adapterSelector.errorLoadingAgents"):y?y.name:c.length===0?l("adapterSelector.noAgentsAvailable"):l("adapterSelector.selectAnAgent")}),s==="prominent"&&(y==null?void 0:y.description)&&i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:y.description})]}),i.jsx(hr,{className:`h-4 w-4 flex-shrink-0 transition-transform text-gray-400 dark:text-gray-300 ${m?"rotate-180":""}`})]})}),m&&!r&&c.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),i.jsx("div",{className:S,children:i.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map(T=>{const k=T.id===t;return i.jsx("button",{type:"button",onClick:()=>{k||e(T.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${k?"bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200":"text-[#353740] hover:bg-gray-50 dark:text-[#ececf1] dark:hover:bg-[#2a2d35]"}`,children:i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"font-medium truncate",children:T.name}),n&&T.description&&i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:T.description})]})},T.id)})})})]})]}),p&&i.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:p})]})}const fs=100;function si({onClick:t,label:e,hoverClassName:r,icon:n}){return i.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${r}`,"aria-label":e,children:n})}function qf(t,e){const r=new Date(e.getFullYear(),e.getMonth(),e.getDate()),n=new Date(r);n.setDate(n.getDate()-1);const s=new Date(r);s.setDate(s.getDate()-r.getDay());const a=new Date(e.getFullYear(),e.getMonth(),1);return t>=r?"today":t>=n?"yesterday":t>=s?"thisWeek":t>=a?"thisMonth":"earlier"}function Wf(t){const e=new Date,r=["today","yesterday","thisWeek","thisMonth","earlier"],n=new Map;for(const s of t){const a=qf(s.updatedAt,e),o=n.get(a);o?o.push(s):n.set(a,[s])}return r.filter(s=>n.has(s)).map(s=>({label:s,conversations:n.get(s)}))}function ni({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:r}=Le(),n=Ls(),{conversations:s,currentConversationId:a,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:p}=be(),g=s.find(D=>D.id===a),[m,x]=h.useState(""),[y,v]=h.useState(null),[A,N]=h.useState(""),[C,S]=h.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[E,_]=h.useState({isOpen:!1,isDeleting:!1}),[b,T]=h.useState(!1),[k,I]=h.useState(null),[P,M]=h.useState(!1),[B,j]=h.useState(null),L=h.useRef(null),O=h.useRef(null),F=h.useRef(null),X=!g||g.messages.length===0,G=(k==null?void 0:k.conversationId)===a?k.adapterName:(g==null?void 0:g.adapterName)??null,q=(B==null?void 0:B.conversationId)===a?B.message:null,Q=h.useMemo(()=>s.filter(D=>{var K;return(D.messages.length>0||(((K=D.attachedFiles)==null?void 0:K.length)||0)>0)&&!D.adapterLoadError}),[s]),he=h.useMemo(()=>{if(!m)return Q;const D=m.toLowerCase();return Q.filter(K=>(K.title||r("chatInterface.newChatTitle")).toLowerCase().includes(D)||K.messages.some(Ee=>Ee.content.toLowerCase().includes(D))||(K.attachedFiles||[]).some(Ee=>Ee.filename.toLowerCase().includes(D)))},[Q,m,r]),z=h.useMemo(()=>Wf(he),[he]),ee=u(),ce=m.length>0,V=Q.length>0;h.useEffect(()=>{if(!a||!O.current)return;const D=O.current.querySelector('[aria-current="true"]');D&&D.scrollIntoView({block:"nearest",behavior:"smooth"})},[a]);const J=h.useCallback(D=>{var st;if(D.key!=="ArrowDown"&&D.key!=="ArrowUp")return;D.preventDefault();const K=(st=O.current)==null?void 0:st.querySelectorAll('[role="option"]');if(!K||K.length===0)return;const Ee=document.activeElement,ue=Array.from(K).indexOf(Ee);let Ae;D.key==="ArrowDown"?Ae=ue<K.length-1?ue+1:0:Ae=ue>0?ue-1:K.length-1,K[Ae].focus()},[]),fe=async D=>{if(!(!X||!D)){I({conversationId:a??null,adapterName:D}),j(null),M(!0);try{const K=(g==null?void 0:g.apiUrl)||$e();await f(K,void 0,D),p(),T(!1)}catch(K){ge("Failed to configure adapter:",K),j({conversationId:a??null,message:K instanceof Error?K.message:r("sidebar.adapterConfigureFailed")})}finally{M(!1)}}},Se=async D=>{try{await o(D),t==null||t()}catch(K){ge("Failed to select conversation:",K)}},H=(D,K)=>{D.stopPropagation(),S({isOpen:!0,conversationId:K.id,conversationTitle:K.title||r("chatInterface.newChatTitle"),isDeleting:!1})},se=async()=>{S(D=>({...D,isDeleting:!0}));try{await l(C.conversationId)}catch(D){ge("Failed to delete conversation:",D)}S({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ne=()=>{S({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},je=(D,K)=>{D.stopPropagation(),v(K.id),N((K.title||r("chatInterface.newChatTitle")).slice(0,fs))},te=D=>{const K=A.slice(0,fs).trim();K&&d(D,K),v(null),N("")},Z=()=>{v(null),N("")},oe=()=>{_({isOpen:!0,isDeleting:!1})},_e=async()=>{_(D=>({...D,isDeleting:!0}));try{await c()}catch(D){ge("Failed to clear all conversations:",D)}_({isOpen:!1,isDeleting:!1})},xe=()=>{_({isOpen:!1,isDeleting:!1})},De=D=>{var K,Ee,ue;return(K=D.adapterName)!=null&&K.trim()?D.adapterName:(ue=(Ee=D.adapterInfo)==null?void 0:Ee.adapter_name)!=null&&ue.trim()?D.adapterInfo.adapter_name:null};Dr(L,{enabled:b,onEscape:()=>T(!1)});const Ie=D=>{const K=a===D.id,Ee=n?null:De(D),ue=D.title||r("chatInterface.newChatTitle");return i.jsxs("div",{role:"option","aria-selected":K,tabIndex:0,onKeyDown:Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),Se(D.id))},onClick:()=>Se(D.id),className:`group relative flex w-full cursor-pointer items-center overflow-hidden rounded-xl border px-3 py-2 text-left text-sm transition-all duration-150
|
|
376
|
+
${K?"border-slate-200/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.97),rgba(248,250,252,0.94))] shadow-[0_1px_2px_rgba(15,23,42,0.04),0_2px_10px_rgba(15,23,42,0.06)] dark:border-white/10 dark:bg-[linear-gradient(180deg,rgba(50,52,65,0.95),rgba(38,39,49,0.92))] dark:shadow-[0_2px_16px_rgba(0,0,0,0.32)]":"border-transparent hover:border-slate-200/60 hover:bg-slate-50 dark:hover:border-white/[0.05] dark:hover:bg-[#212228]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/50 dark:focus-visible:ring-sky-400/40`,"aria-current":K?"true":void 0,"aria-label":r("sidebar.conversationCard.openAriaLabel",{title:ue}),children:[K&&i.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0.4),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(255,255,255,0))]"}),i.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 w-[3px] transition-opacity duration-150 ${K?"bg-sky-500 opacity-100 dark:bg-sky-400":"opacity-0"}`}),y===D.id?i.jsx("input",{type:"text",value:A,onChange:Ae=>N(Ae.target.value.slice(0,fs)),onKeyDown:Ae=>{Ae.key==="Enter"&&te(D.id),Ae.key==="Escape"&&Z(),Ae.stopPropagation()},onBlur:()=>te(D.id),maxLength:fs,className:"relative z-10 flex-1 rounded-lg border border-sky-300 bg-white px-2 py-1 text-sm text-[#353740] focus:outline-none focus:ring-2 focus:ring-sky-400/50 dark:border-sky-500/40 dark:bg-[#1a1b1e] dark:text-[#ececf1]",autoFocus:!0,"aria-label":r("sidebar.conversationCard.editInputAriaLabel")}):i.jsxs("div",{className:"relative z-10 flex min-w-0 flex-1 flex-col gap-1",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[i.jsx("h3",{className:`flex-1 truncate text-sm leading-snug tracking-[-0.006em] ${K?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:ue}),i.jsxs("div",{className:"ml-1 flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-100 group-hover:opacity-100 group-focus-within:opacity-100",children:[i.jsx(si,{onClick:Ae=>je(Ae,D),label:r("sidebar.conversationCard.editAriaLabel",{title:ue}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:i.jsx(Pi,{className:"h-3.5 w-3.5"})}),i.jsx(si,{onClick:Ae=>H(Ae,D),label:r("sidebar.conversationCard.deleteAriaLabel",{title:ue}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:i.jsx(zi,{className:"h-3.5 w-3.5"})})]})]}),Ee&&i.jsx("span",{className:"block max-w-full truncate text-left text-xs font-medium tracking-wide text-blue-700 dark:text-blue-300",children:Ee})]})]},D.id)};return i.jsxs(i.Fragment,{children:[!n&&b&&i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm px-4",children:i.jsxs("div",{ref:L,role:"dialog","aria-modal":"true","aria-labelledby":"select-agent-title",tabIndex:-1,className:"w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-2xl dark:border-[#3d4050] dark:bg-[#1a1b1e]",children:[i.jsx("h2",{id:"select-agent-title",className:"mb-4 text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:r("sidebar.selectAgent.title")}),i.jsxs("div",{className:"space-y-5",children:[i.jsx(Vf,{selectedAdapter:G,onAdapterChange:fe,disabled:P,variant:"prominent",showDescriptions:!0,showLabel:!1}),q&&i.jsx("div",{role:"alert",className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:q}),i.jsx("div",{className:"flex justify-end gap-3 pt-2",children:i.jsx("button",{type:"button",onClick:()=>{j(null),T(!1)},className:"rounded-lg px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 dark:text-[#d1d5db] dark:hover:bg-[#2d2f39]",disabled:P,children:r("common.cancel")})})]})]})}),i.jsxs("nav",{"aria-label":r("sidebar.navAriaLabel"),className:"flex h-full md:h-[calc(100%-2rem)] md:mt-4 w-full md:w-72 flex-col border-r border-b border-gray-200 md:border-l md:border-t md:rounded-2xl md:overflow-hidden bg-transparent dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"bg-transparent px-4 pb-4 pt-4 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"flex items-center gap-2 pb-3",children:[s.length>0&&s.some(D=>D.messages.length>0)&&i.jsxs("button",{onClick:oe,className:"flex flex-1 items-center justify-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm font-medium text-red-600 transition-all duration-150 hover:bg-red-50 hover:border-red-300 hover:shadow-sm dark:border-red-500/25 dark:text-red-400 dark:hover:bg-red-950/20 dark:hover:border-red-500/40",title:r("sidebar.deleteAllConversations.title"),children:[i.jsx(gd,{className:"h-4 w-4"}),r("sidebar.deleteAllConversations.button")]}),e&&i.jsx("button",{type:"button",onClick:e,className:"ml-auto hidden shrink-0 md:inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-200/80 bg-white text-slate-600 transition-colors hover:border-slate-300 hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-[#333645] dark:bg-[#161616] dark:text-[#d1d5db] dark:hover:border-[#43465a] dark:hover:bg-[#202020] dark:hover:text-white","aria-label":r("sidebar.collapse.ariaLabel"),title:r("sidebar.collapse.title"),children:i.jsx(id,{className:"h-4 w-4"})})]}),q&&!b&&i.jsx("p",{role:"alert",className:"mt-2 text-xs text-red-600 dark:text-red-400",children:q}),V&&i.jsxs("div",{className:"border-t border-gray-200 pt-4 mt-4 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"relative overflow-hidden rounded-[1.75rem] border border-slate-200/85 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(248,250,252,0.94))] shadow-[0_10px_28px_rgba(15,23,42,0.05)] transition-all duration-200 focus-within:border-sky-300/90 focus-within:shadow-[0_0_0_1px_rgba(125,211,252,0.55),0_10px_28px_rgba(15,23,42,0.05)] dark:border-white/10 dark:bg-[linear-gradient(180deg,rgba(37,39,49,0.95),rgba(29,31,39,0.92))] dark:shadow-[0_12px_30px_rgba(0,0,0,0.2)] dark:focus-within:border-sky-400/30 dark:focus-within:shadow-[0_0_0_1px_rgba(56,189,248,0.22),0_12px_30px_rgba(0,0,0,0.2)]",children:[i.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[inherit] bg-[linear-gradient(180deg,rgba(255,255,255,0.45),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"}),i.jsx(Mn,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 dark:text-slate-500"}),i.jsx("input",{ref:F,type:"text",role:"searchbox","aria-label":r("sidebar.search.ariaLabel"),placeholder:r("sidebar.search.placeholder"),value:m,onChange:D=>x(D.target.value),className:"relative z-10 w-full bg-transparent py-3 pl-11 pr-11 text-sm font-medium text-slate-700 placeholder:font-normal placeholder:text-slate-400 focus:outline-none dark:text-slate-100 dark:placeholder:text-slate-500"}),m&&i.jsx("button",{type:"button",onClick:()=>{var D;x(""),(D=F.current)==null||D.focus()},className:"absolute right-3 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200/80 bg-white/90 text-slate-400 transition-colors hover:border-slate-300 hover:text-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-200 dark:border-white/10 dark:bg-white/5 dark:text-slate-500 dark:hover:border-white/20 dark:hover:text-slate-200 dark:focus:ring-sky-500/20","aria-label":r("sidebar.search.clearAriaLabel"),children:i.jsx(Ze,{className:"h-3.5 w-3.5"})})]}),ce&&i.jsx("p",{"aria-live":"polite",className:"mt-2 text-center text-[11px] tabular-nums text-gray-400 dark:text-[#6e7490]",children:he.length===0?r("sidebar.resultsNone"):r("sidebar.results",{count:he.length})})]})]}),i.jsx("div",{ref:O,role:"listbox","aria-label":r("sidebar.conversations.ariaLabel"),onKeyDown:J,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:he.length===0?null:ce?i.jsx("div",{className:"space-y-1.5",children:he.map(Ie)}):i.jsx("div",{className:"space-y-4",children:z.map(D=>i.jsxs("section",{"aria-label":r(`sidebar.timeGroups.${D.label}`),children:[i.jsx("h4",{className:"sticky top-0 z-10 mb-1 bg-transparent px-1 pb-1 pt-0.5 text-[11px] font-semibold uppercase tracking-wider text-gray-400 backdrop-blur-sm dark:text-[#6e7490]",children:r(`sidebar.timeGroups.${D.label}`)}),i.jsx("div",{className:"space-y-1.5",children:D.conversations.map(Ie)})]},D.label))})}),(()=>{const D=Ni();return D.length===0?null:i.jsx("div",{className:"shrink-0 border-t border-gray-200/80 px-4 py-3 md:hidden dark:border-[#2d2f39]",children:i.jsx("nav",{"aria-label":r("appHeader.navLinksAriaLabel"),children:i.jsx("ul",{className:"flex flex-wrap gap-2",children:D.map(K=>i.jsx("li",{children:i.jsx("a",{href:K.url,className:"inline-flex items-center rounded-md px-2.5 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-100 dark:text-[#d1d5db] dark:hover:bg-[#2b2d39]",children:K.label})},K.url))})})})})(),i.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:i.jsx(io,{placement:"sidebar",compact:!0})})]}),i.jsx(ws,{isOpen:C.isOpen,onClose:ne,onConfirm:se,title:r("sidebar.deleteConfirm.title"),message:r("sidebar.deleteConfirm.message",{title:C.conversationTitle}),confirmText:r("sidebar.deleteConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:C.isDeleting}),i.jsx(ws,{isOpen:E.isOpen,onClose:xe,onConfirm:_e,title:r("sidebar.clearAllConfirm.title"),message:r("sidebar.clearAllConfirm.message",{count:ee}),confirmText:r("sidebar.clearAllConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:E.isDeleting})]})}const Kf="3.11.9",Gf={version:Kf},zn=Gf.version,Xf=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function Yf(t){const e=t.toLowerCase();return Xf.some(r=>e.includes(r.toLowerCase()))}function Qf(t){const e=[];for(let r=0;r<t.length;r++){const n=t.key(r);n&&Yf(n)&&e.push(n)}e.forEach(r=>t.removeItem(r))}function ai(t){try{Qf(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function Zf(){if(typeof document>"u"||!document.cookie)return;const t=new Set([void 0]),e=window.location.hostname;e&&e!=="localhost"&&!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)&&(t.add(e),t.add(`.${e}`)),document.cookie.split(";").forEach(n=>{const s=n.indexOf("="),a=(s>-1?n.slice(0,s):n).trim();a&&t.forEach(o=>{const l=o?`;domain=${o}`:"";document.cookie=`${a}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${l}`})})}function Jf(){ai(localStorage),ai(sessionStorage),Zf()}function eh({isOpen:t,onClose:e}){const{t:r}=Le(),{theme:n,updateTheme:s}=tr(),{settings:a,updateSettings:o}=Ns(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=Uc(),[u,f]=h.useState(!1),[p,g]=h.useState(!1),m=h.useRef(null),x=h.useRef(null),y=h.useMemo(()=>[...l].sort((E,_)=>ss[E].localeCompare(ss[_])),[l]);h.useEffect(()=>{if(!p)return;const E=_=>{_.key==="Escape"&&(_.stopPropagation(),g(!1))};return document.addEventListener("keydown",E,{capture:!0}),()=>document.removeEventListener("keydown",E,{capture:!0})},[p]);const v=E=>{s({mode:E})},A=()=>{o({soundEnabled:!a.soundEnabled})},N=()=>{f(!0)},C=()=>{f(!1)},S=()=>{C(),Ts(),Ms(!1),fr(null),rt.getState().closeLoginPrompt(),Jf(),window.location.reload()};return Dr(m,{enabled:t&&!u,onEscape:e}),Dr(x,{enabled:u,onEscape:C}),t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-end md:items-center justify-center overflow-y-auto bg-black/50 p-0 md:p-4",children:[i.jsx("button",{type:"button",onClick:e,"aria-label":r("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),i.jsxs("div",{onClick:E=>E.stopPropagation(),ref:m,role:"dialog","aria-modal":"true","aria-labelledby":"settings-title",tabIndex:-1,className:"relative flex h-[100dvh] w-full max-w-none flex-col overflow-hidden bg-white shadow-2xl dark:bg-[#1a1b1e] md:h-auto md:max-h-[90vh] md:max-w-md md:rounded-2xl",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between border-b border-gray-200 px-6 pb-4 pt-[max(env(safe-area-inset-top),1rem)] dark:border-[#2d2f39] md:p-6",children:[i.jsx("h2",{id:"settings-title",className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:r("settings.dialog.title")}),i.jsx("button",{onClick:e,className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":r("settings.dialog.closeButtonAriaLabel"),children:i.jsx(Ze,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),i.jsxs("div",{className:"flex-1 min-h-0 space-y-6 overflow-y-auto px-6 pb-[max(env(safe-area-inset-bottom),1.25rem)] pt-6 md:p-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[i.jsx(ad,{className:"w-5 h-5"}),r("settings.appearance.heading")]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r("settings.appearance.themeLabel")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:r("settings.appearance.themeLight"),icon:md},{value:"dark",label:r("settings.appearance.themeDark"),icon:nd},{value:"system",label:r("settings.appearance.themeSystem"),icon:sd}].map(({value:E,label:_,icon:b})=>i.jsxs("button",{onClick:()=>v(E),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${n.mode===E?"border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300":"border-gray-200 dark:border-[#2d2f39] hover:border-gray-300 dark:hover:border-[#43465a] text-gray-700 dark:text-gray-300"}`,children:[i.jsx(b,{className:"w-5 h-5"}),i.jsx("span",{className:"text-sm font-medium",children:_})]},E))})]}),l.length>1&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[i.jsx(Qc,{className:"w-4 h-4"}),r("settings.language.label")]}),i.jsxs("div",{className:"relative",children:[i.jsxs("button",{type:"button",onClick:()=>g(E=>!E),"aria-haspopup":"listbox","aria-expanded":p,className:`flex w-full items-center justify-between gap-2 rounded-lg border-2 px-3 py-2.5 text-left text-sm transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 dark:focus-visible:ring-blue-400/40 ${p?"border-blue-500":"border-gray-200 dark:border-[#2d2f39] hover:border-gray-300 dark:hover:border-[#43465a]"}`,children:[i.jsx("span",{className:"font-medium text-gray-900 dark:text-gray-100",children:ss[c]}),i.jsx(hr,{className:`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-200 dark:text-gray-500 ${p?"rotate-180":""}`})]}),p&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),i.jsx("div",{role:"listbox","aria-label":r("settings.language.label"),className:"absolute z-20 mt-2 max-h-60 w-full overflow-y-auto rounded-lg border border-gray-200 bg-white p-1 shadow-lg ring-1 ring-black/5 dark:border-[#2d2f39] dark:bg-[#1a1b1e] dark:ring-white/5",children:y.map(E=>{const _=E===c;return i.jsxs("button",{type:"button",role:"option","aria-selected":_,onClick:()=>{d(E),g(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${_?"bg-blue-50 font-medium text-blue-700 dark:bg-blue-900/20 dark:text-blue-300":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-[#25262f]"}`,children:[i.jsx("span",{className:"truncate",children:ss[E]}),_&&i.jsx(ur,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},E)})})]})]})]})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:r("settings.chat.heading")}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Rn,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r("settings.soundEffects.label")}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("settings.soundEffects.description")})]})]}),i.jsx("button",{onClick:A,role:"switch","aria-checked":a.soundEnabled,"aria-label":r("settings.soundEffects.toggleAriaLabel"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${a.soundEnabled?"bg-blue-600":"bg-gray-200 dark:bg-[#3c3f4a]"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${a.soundEnabled?"translate-x-6":"translate-x-1"}`})})]})]}),i.jsxs("div",{className:"space-y-4 pt-4 border-t border-gray-200 dark:border-[#2d2f39]",children:[i.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[i.jsx(zi,{className:"w-5 h-5"}),r("settings.dataManagement.heading")]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.dataManagement.description")}),i.jsx("button",{onClick:N,className:"w-full px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:r("settings.reset.button")})]})]}),i.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",zn]})]}),u&&i.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:i.jsxs("div",{ref:x,role:"dialog","aria-modal":"true","aria-labelledby":"reset-dialog-title",tabIndex:-1,className:"max-h-[calc(100dvh-2rem)] w-full max-w-sm overflow-y-auto rounded-2xl border border-red-100 bg-white p-6 shadow-2xl dark:border-red-800/60 dark:bg-[#111113]",children:[i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-10 w-10 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/40",children:i.jsx($n,{className:"w-5 h-5 text-red-600 dark:text-red-400"})}),i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("p",{id:"reset-dialog-title",className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:r("settings.reset.confirmTitle")}),i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.reset.confirmMessage")})]})]}),i.jsxs("div",{className:"mt-4 flex gap-2 pt-2",children:[i.jsx("button",{onClick:C,className:"flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-[#2d2f39] rounded-lg hover:bg-gray-50 dark:hover:bg-[#1a1b1e] transition-colors",children:r("common.cancel")}),i.jsx("button",{onClick:S,className:"flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600",children:r("settings.reset.confirmButton")})]})]})})]})]}):null}function th({message:t}){const{t:e}=Le(),r=Ln();return i.jsx("main",{className:"min-h-dvh bg-white px-4 py-6 text-slate-950 dark:bg-black dark:text-slate-100 sm:px-6 lg:px-8",children:i.jsxs("div",{className:"mx-auto flex min-h-[calc(100dvh-3rem)] w-full max-w-5xl flex-col",children:[i.jsxs("header",{className:"flex items-center justify-between gap-4",children:[i.jsx("p",{className:"min-w-0 truncate text-lg font-semibold tracking-tight sm:text-xl",children:r}),i.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",zn]})]}),i.jsx("section",{className:"flex flex-1 items-center justify-center py-12",children:i.jsxs("div",{className:"w-full max-w-lg space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"relative flex h-2.5 w-2.5 shrink-0",children:[i.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-60 dark:bg-amber-500"}),i.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-amber-500 dark:bg-amber-400"})]}),i.jsx("span",{className:"text-xs font-semibold uppercase tracking-widest text-amber-700 dark:text-amber-400",children:e("outOfService.statusBadge")})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-950 dark:text-white sm:text-4xl",children:e("outOfService.heading")}),i.jsx("p",{className:"max-w-md whitespace-pre-wrap text-base leading-relaxed text-slate-500 dark:text-slate-400",children:t})]}),i.jsx("div",{className:"border-t border-slate-200 dark:border-[#242424]"}),i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[i.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"inline-flex items-center justify-center gap-2 rounded-lg bg-slate-950 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-slate-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-white dark:text-slate-950 dark:hover:bg-slate-200",children:[i.jsx(fd,{className:"h-4 w-4","aria-hidden":"true"}),e("outOfService.retryButton")]}),i.jsx("span",{className:"hidden text-slate-300 dark:text-slate-700 sm:block","aria-hidden":"true",children:"·"})]})]})})]})})}function rh({children:t}){const{instance:e,accounts:r}=An(),n=el();return h.useEffect(()=>{Ms(n)},[n]),h.useEffect(()=>{if(!n||r.length===0){fr(null);return}const s=r[0];fr(s.username||s.name||s.localAccountId||null)},[n,r]),h.useEffect(()=>{if(!n||r.length===0)return;const s=r[0],a=Tn();return Bi(async()=>(await e.acquireTokenSilent({scopes:a,account:s})).accessToken),()=>Ts()},[n,r,e]),i.jsx(i.Fragment,{children:t})}function sh({children:t}){return i.jsx(rh,{children:t})}function nh({children:t}){const{isLoading:e,isAuthenticated:r,getAccessTokenSilently:n,user:s}=Nn();return h.useEffect(()=>{Ms(r)},[r]),h.useEffect(()=>{if(!r){fr(null);return}const a=(s==null?void 0:s.sub)||(s==null?void 0:s.email)||(s==null?void 0:s.nickname)||(s==null?void 0:s.name)||null;fr(a)},[r,s]),h.useEffect(()=>(r&&Bi(()=>n()),()=>Ts()),[r,n]),e?i.jsx("div",{className:"flex items-center justify-center h-screen bg-white dark:bg-[#212121]",children:i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-gray-100"})}):i.jsx(i.Fragment,{children:t})}function ah({children:t}){return h.useEffect(()=>{Ms(!1),fr(null),Ts()},[]),i.jsx(i.Fragment,{children:t})}function ih({children:t}){return tt()?Es()==="entra"?i.jsx(sh,{children:t}):i.jsx(nh,{children:t}):i.jsx(ah,{children:t})}function oh(){const t=_n(),e=tt(),r=pr(),{showLoginPrompt:n,promptMessage:s,closeLoginPrompt:a}=rt();return h.useEffect(()=>{n&&(!t||!e||r)&&a()},[n,t,e,r,a]),!t||!e||r||!n?null:Es()==="entra"?i.jsx(ch,{message:s,onClose:a}):i.jsx(lh,{message:s,onClose:a})}function lh({message:t,onClose:e}){const{loginWithRedirect:r}=Nn();return i.jsx(ho,{message:t,onClose:e,onLogin:()=>r()})}function ch({message:t,onClose:e}){const{instance:r}=An();return i.jsx(ho,{message:t,onClose:e,onLogin:()=>r.loginRedirect({scopes:Tn()}).catch(()=>{})})}function ho({message:t,onClose:e,onLogin:r}){const{t:n}=Le();return i.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:e,"aria-hidden":"true"}),i.jsxs("div",{className:"relative z-10 mx-4 w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-2xl dark:border-[#4a4b54] dark:bg-[#2d2f39]",children:[i.jsx("button",{onClick:e,className:"absolute right-3 top-3 rounded-full p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]","aria-label":n("common.close"),children:i.jsx(Ze,{className:"h-4 w-4"})}),i.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[i.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/40",children:i.jsx(Ri,{className:"h-5 w-5 text-blue-600 dark:text-blue-300"})}),i.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:n("loginPrompt.heading")})]}),i.jsx("p",{className:"mb-6 text-sm leading-relaxed text-gray-600 dark:text-[#bfc2cd]",children:t}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx("button",{onClick:r,className:"flex-1 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600",children:n("common.signIn")}),i.jsx("button",{onClick:e,className:"flex-1 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 dark:border-[#4a4b54] dark:bg-[#2d2f39] dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a]",children:n("common.cancel")})]})]})]})}function dh(){const{t}=Le(),{goHome:e}=uo(),{isDark:r}=tr(),n=wf(),s=h.useRef(!1),a=wc(),o=vc(),l=kc(),c=r?l:o,d=Sc(),u=jc(),f=!!(d||u),p=Cc(),g=Ac(),m=Nc(),x=Ni(),y=m?"border-b border-slate-200/80 dark:border-[#333645]":"",v="inline-flex min-h-10 items-center rounded-md px-2.5 text-sm font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300";return h.useEffect(()=>{s.current},[l,a,o]),mn()?i.jsx("header",{className:`relative z-30 shrink-0 bg-white px-3 pb-1 pt-2 dark:bg-black sm:px-5 sm:pb-2 sm:pt-3 lg:px-8 md:pt-5 ${y}`.trim(),style:{backgroundColor:p||void 0,color:g||void 0},children:i.jsxs("div",{className:"mx-auto flex w-full max-w-[96rem] items-center justify-between gap-3",children:[i.jsx("div",{className:"flex min-w-0 flex-1 items-center justify-center gap-2 md:justify-start md:gap-3",children:i.jsx("a",{href:n,"aria-label":t("appHeader.homeLinkAriaLabel"),onClick:A=>{A.preventDefault(),e()},className:"inline-flex items-center rounded-sm px-1 py-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:focus-visible:ring-blue-300 dark:focus-visible:ring-offset-black md:-ml-1",children:i.jsx("img",{src:c,alt:t("appHeader.logoAlt"),draggable:!1,className:`block max-w-full flex-shrink-0 select-none ${f?"":"h-8 w-auto sm:h-10 md:h-11"}`.trim(),style:{WebkitUserDrag:"none",...d?{height:d}:{},...u?{width:u}:{}}})})}),i.jsxs("div",{className:"hidden min-w-0 flex-1 items-center justify-end gap-2 sm:gap-4 md:flex",children:[x.length>0&&i.jsx("nav",{"aria-label":t("appHeader.navLinksAriaLabel"),className:"hidden sm:block",children:i.jsx("ul",{className:"flex items-center gap-1.5 sm:gap-2",children:x.map(A=>i.jsx("li",{children:i.jsx("a",{href:A.url,target:"_blank",rel:"noopener noreferrer",className:v,style:{color:g||void 0},children:A.label})},A.url))})}),i.jsx(jn,{})]})]})}):null}function uh({children:t}){const e=h.useRef(null),r=h.useCallback(s=>{e.current=s},[]),n=h.useCallback(()=>{var s;(s=e.current)==null||s.call(e)},[]);return i.jsx(co.Provider,{value:{registerGoHome:r,goHome:n},children:t})}function fh(){const{t}=Le(),[e,r]=h.useState(!1),[n,s]=h.useState(!1),[a,o]=h.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=be(u=>u.conversations),c=gc();if(h.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(a))},[a]),c)return i.jsx(ia,{children:i.jsx(th,{message:c})});const d=l.some(u=>{var f;return(u.messages.length>0||(((f=u.attachedFiles)==null?void 0:f.length)??0)>0)&&!u.adapterLoadError});return i.jsx(ia,{children:i.jsx(nl,{children:i.jsx(Dc,{children:i.jsx(ih,{children:i.jsx(uh,{children:i.jsxs("div",{className:"h-dvh flex flex-col bg-white dark:bg-black text-slate-900 dark:text-slate-100",children:[i.jsxs("div",{className:"flex-1 flex flex-col md:flex-row md:pl-4 min-h-0",children:[d&&(a?i.jsx("div",{className:"hidden md:flex md:w-16 md:h-full shrink-0 items-start justify-center pt-8",children:i.jsx("button",{type:"button",onClick:()=>o(!1),className:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-200/80 bg-white text-slate-600 transition-colors hover:border-slate-300 hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-[#333645] dark:bg-[#161616] dark:text-[#d1d5db] dark:hover:border-[#43465a] dark:hover:bg-[#202020] dark:hover:text-white","aria-label":t("app.sidebar.openAriaLabel"),title:t("app.sidebar.openTitle"),children:i.jsx(od,{className:"h-4 w-4"})})}):i.jsx("div",{className:"hidden md:h-full md:flex",children:i.jsx(ni,{onToggleDesktopSidebar:()=>o(!0)})})),i.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[i.jsx(dh,{}),i.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:i.jsx(Hf,{onOpenSettings:()=>r(!0),onOpenSidebar:()=>s(!0)})})]})]}),i.jsx(oh,{}),i.jsx(eh,{isOpen:e,onClose:()=>r(!1)}),n&&i.jsxs("div",{className:"fixed inset-0 z-50 flex md:hidden",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>s(!1),"aria-hidden":"true"}),i.jsxs("div",{className:"relative z-10 h-full w-[min(20rem,90vw)] animate-slideIn bg-white dark:bg-black",children:[i.jsx(ni,{onRequestClose:()=>s(!1)}),i.jsx("button",{onClick:()=>s(!1),className:"absolute -right-3 top-[max(env(safe-area-inset-top),0.75rem)] rounded-full bg-white/95 p-3 text-gray-600 shadow-lg active:scale-95 transition-transform dark:bg-[#2d2f39] dark:text-[#ececf1]","aria-label":t("app.menu.closeAriaLabel"),children:i.jsx(Ze,{className:"h-5 w-5"})})]})]})]})})})})})})}const ln=new tl({auth:{clientId:Ci(),authority:`https://login.microsoftonline.com/${yc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function hh({children:t}){const[e,r]=h.useState(!1);return h.useEffect(()=>{ln.initialize().then(()=>ln.handleRedirectPromise()).catch(n=>{console.error("[EntraAuth] Redirect processing failed:",n)}).finally(()=>r(!0))},[]),e?i.jsx(rl,{instance:ln,children:t}):null}function ph({children:t}){if(!_n()||!tt())return i.jsx(i.Fragment,{children:t});if(Es()==="entra")return i.jsx(hh,{children:t});const r=xc(),n=Ci(),s=bc();return!r||!n?i.jsx(i.Fragment,{children:t}):i.jsx(sl,{domain:r,clientId:n,authorizationParams:{redirect_uri:window.location.origin,...s?{audience:s}:{}},cacheLocation:"memory",children:t})}fo(null);const ii=lc(),oi=document.querySelector('link[rel="icon"]');if(oi)oi.href=ii;else{const t=document.createElement("link");t.rel="icon",t.href=ii,document.head.appendChild(t)}const mh=Fc();var li,ci,di,ui,fi,hi;for(const t of mh){const e=((li=t.src)==null?void 0:li.trim())||"",r=((ci=t.content)==null?void 0:ci.trim())||"",n=((di=t.id)==null?void 0:di.trim())||"";if(!e&&!r||n&&document.querySelector(`script[data-orbitchat-startup-script-id="${n}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=r&&(o.textContent||"").trim()===r;return!!(l||c)}))continue;const a=document.createElement("script");e&&(a.src=e),r&&(a.text=r),a.async=t.async??!0,t.defer!==void 0&&(a.defer=t.defer),(ui=t.type)!=null&&ui.trim()&&(a.type=t.type.trim()),(fi=t.integrity)!=null&&fi.trim()&&(a.integrity=t.integrity.trim()),t.crossOrigin&&(a.crossOrigin=t.crossOrigin),(hi=t.referrerPolicy)!=null&&hi.trim()&&(a.referrerPolicy=t.referrerPolicy.trim()),a.dataset.orbitchatStartupScript="true",n&&(a.dataset.orbitchatStartupScriptId=n),e&&(a.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(a)}U("🚀 AI Chat Application started");U(`📱 App Version: v${zn}`);Oo.createRoot(document.getElementById("root")).render(i.jsx(h.StrictMode,{children:i.jsx(ph,{children:i.jsx(fh,{})})}));export{Ul as r,Le as u};
|